lundi 30 novembre 2015

IF Statement Checking (Not Working Properly)

randomEmpty() returns a random coordinate on the n x n grid that is empty (Method works). randomAdjacent() uses randomEmpty() to select an EMPTY coordinate on the map. Comparisons are then made to see if this coordinate has an VALID adjacent coordinate that is NON-EMPTY. The PROBLEM is that randomAdjacent does not always return the coordinates of space with an adjacent NON-EMPTY space. It will always return valid coordinates but not the latter. I can't spot the problem. Can someone help me identify the problem?

public int[] randomEmpty()
{
    Random r = new Random();
    int[] random = new int[2];
    int row = r.nextInt(array.length);
    int column = r.nextInt(array.length);
    while(!(isEmpty(row,column)))
    {
        row = r.nextInt(array.length);
        column = r.nextInt(array.length);
    }
    random[0] = row+1;
    random[1] = column+1;
    return random;        
}

public int[] randomAdjacent()
{
    int[] adjacentToX = new int[8];
    int[] adjacentToY = new int[8];
    int[] adjacentFrom = randomEmpty();
    int count;
    boolean isTrue = false;
    boolean oneAdjacentNotEmpty = false;

    while(!(oneAdjacentNotEmpty))
    {
        count = 0;

        if(validIndex(adjacentFrom,1,-1))
        {
            adjacentToX[count] = adjacentFrom[0]+1;
            adjacentToY[count] = adjacentFrom[1]-1;
            count++;
        }
        if(validIndex(adjacentFrom,0,-1))
        {               
            adjacentToX[count] = adjacentFrom[0];
            adjacentToY[count] = adjacentFrom[1]-1;
            count++;
        }
        if(validIndex(adjacentFrom,-1,-1))
        {          
            adjacentToX[count] = adjacentFrom[0]-1;
            adjacentToY[count] = adjacentFrom[1]-1;
            count++;
        }
        if(validIndex(adjacentFrom,-1,0))
        {        
            adjacentToX[count] = adjacentFrom[0]-1;
            adjacentToY[count] = adjacentFrom[1];
            count++;
        }
        if(validIndex(adjacentFrom,-1,1))
        {       
            adjacentToX[count] = adjacentFrom[0]-1;
            adjacentToY[count] = adjacentFrom[1]+1;
            count++;
        }
        if(validIndex(adjacentFrom,0,1))
        {         
            adjacentToX[count] = adjacentFrom[0];
            adjacentToY[count] = adjacentFrom[1]+1;
            count++;
        }
        if(validIndex(adjacentFrom,1,1))
        {         
            adjacentToX[count] = adjacentFrom[0]+1;
            adjacentToY[count] = adjacentFrom[1]+1;
            count++;
        }
        if(validIndex(adjacentFrom,1,0))
        {        
            adjacentToX[count] = adjacentFrom[0]+1;
            adjacentToY[count] = adjacentFrom[1];
            count++;
        }
        for(int i = 0; i < count; i++)
        {
            if(!(isEmpty(adjacentToX[i],adjacentToY[i])))  
            {
                oneAdjacentNotEmpty = true;
                isTrue = true;
            }
        }
        if(isTrue)
            break;
        else
            adjacentFrom = randomEmpty();           
    }
    return adjacentFrom;
}

public boolean validIndex(int[] a,int i, int j)
{
    try
    {
        Pebble aPebble = array[a[0]+i][a[1]+j];
        return true;
    }
    catch(ArrayIndexOutOfBoundsException e)
    {
        return false;
    }
}
public void setCell(int xPos, int yPos, Pebble aPebble)
{
    array[xPos-1][yPos-1] = aPebble;
}

public Pebble getCell(int xPos, int yPos)
{
    return array[xPos-1][yPos-1];
}

JUNIT Test Performed:

@Test
public void testRandomAdjacent() {
    final int size = 5;
    final Board board2 = new Board(size);
    board2.setCell(1, 1, Pebble.O);
    board2.setCell(5, 5, Pebble.O);
    int[] idx = board2.randomAdjacent();
    int x = idx[0];
    int y = idx[1];
    boolean empty = true;
    for (int i = x - 1; i <= x + 1; i++) {
        for (int j = y - 1; j <= y + 1; j++) {
            if ((i == x && j == y) || i < 1 || j < 1 || i > size || j > size) {
                continue;
            }
            if (board2.getCell(i, j) != Pebble.EMPTY)
                empty = false;
        }

    }
    assertFalse(empty);// NEVER gets SET TO FALSE
    assertEquals(Pebble.EMPTY, board2.getCell(x, y));
}

Simplify logic statement

I am having a brain fart

I have this

if(!A or (A and B))   //pseudocode

I want to negate that if-statement

this should work:

if(!(!A or (A and B))  //pseudocode

but I believe there is a way to simplify it and it's escaping me at the moment

thanks

C++ Visual Studio compare string in structure

I have a structure which contain information like name, first name, id, etc. I am creating a fonction to search by name into the structure tabStudent[i].name I am not sure why it's not working can you please help?

  void recherchename(Student tabStudent[], int nbrStudent, int name)
    {
    for (int i = 0; i < nbrStudent; i++)
    {
    if (nbrStudent == tabStudent[i].name)
    {
    //code
    }

VBA Run-time Error 1004 Nested If statement

The purpose of my code is to determine if a cell falls within a 'feasible region'. If it does, apply a formula based on the location of the cell, and if it does not, put a "|" into the cell.

I have run this same code at a smaller scale and had no problems. I have stepped into the code and it allows the For loop to run hundreds of times before returning a "Run-time error '1004': Application-defined or object defined error"

Sub DPCalc()

Dim Pur As Integer
Dim ws As Worksheet
Dim LookUpRange As Range
Dim State As Integer

Set ws = ThisWorkbook.Sheets("DPExpansion")

 For C = 5 To 74
    For r = 6 To 278
    Pur = Cells(1, C).Value
        If Pur <= Cells(r, 4).Value And Pur >= Cells(r, 3).Value Then
' Year 2055
            If r <= 10 Then
                Cells(r, C).Value = (10 * Pur ^ 0.75) * (1.05 ^ -40)

' Year 2050
            ElseIf r <= 19 And r > 10 Then
                Set LookUpRange = Range("B6 : BW10")
                State = Cells(r, 2).Value + Cells(1, C).Value
                Cells(r, C).Value = (10 * Pur ^ 0.75) * (1.05 ^ -35) + Application.WorksheetFunction.VLookup(Value, LookUpRange, 74, False)

' Year 2045
            ElseIf r <= 38 And r > 19 Then
                Set LookUpRange = Range("B11 : BW19")
                State = Cells(r, 2).Value + Cells(1, C).Value
                Cells(r, C).Value = (10 * Pur ^ 0.75) * (1.05 ^ -30) + Application.WorksheetFunction.VLookup(Value, LookUpRange, 74, False)

' Year 2040
            ElseIf r <= 63 And r > 38 Then
                Set LookUpRange = Range("B20 : BW38")
                State = Cells(r, 2).Value + Cells(1, C).Value
                Cells(r, C).Value = (10 * Pur ^ 0.75) * (1.05 ^ -25) + Application.WorksheetFunction.VLookup(Value, LookUpRange, 74, False)

' Year 2035
            ElseIf r <= 98 And r > 63 Then
                Set LookUpRange = Range("B39 : BW63")
                State = Cells(r, 2).Value + Cells(1, C).Value
                Cells(r, C).Value = (10 * Pur ^ 0.75) * (1.05 ^ -20) + Application.WorksheetFunction.VLookup(Value, LookUpRange, 74, False)

' Year 2030
            ElseIf r <= 148 And r > 98 Then
                Set LookUpRange = Range("B64 : BW98")
                State = Cells(r, 2).Value + Cells(1, C).Value
                Cells(r, C).Value = (10 * Pur ^ 0.75) * (1.05 ^ -15) + Application.WorksheetFunction.VLookup(Value, LookUpRange, 74, False)

' Year 2025
            ElseIf r <= 208 And r > 148 Then
                Set LookUpRange = Range("B99 : BW148")
                State = Cells(r, 2).Value + Cells(1, C).Value
               Cells(r, C).Value = (10 * Pur ^ 0.75) * (1.05 ^ -10) + Application.WorksheetFunction.VLookup(Value, LookUpRange, 74, False)

' Year 2020
            Else
                Set LookUpRange = Range("B149 : BW208")
                State = Cells(r, 2).Value + Cells(1, C).Value
                Cells(r, C).Value = (10 * Pur ^ 0.75) * (1.05 ^ -5) + Application.WorksheetFunction.VLookup(Value, LookUpRange, 74, False)
               End If
        Else
        Cells(r, C).Value = "|"
        End If
     Next r
    Next C

End Sub

I have also tried commenting out the portion that adds the value based on a vlookup, and that had no impact.

Wondering why my SQL statement is ignoring my SET symbol

This is my SQL trigger and it is suppose to change the reorder value to Y or N depending if ON_HAND is less than or greater than the MINIMUM. The problem is it's ignoring the set statement completely. Do I have to arrange these differently?

CREATE OR REPLACE TRIGGER TRG_REORDER 
AFTER UPDATE OF ON_HAND, MINIMUM ON PART

BEGIN

IF ON_HAND <= MINIMUM THEN
   SET REORDER = 'Y';
ELSE ON_HAND > MINIMUM
   SET REORDER = 'N';

END IF;
END;

find tags inside an xml with python

I have an XML like this:

    <w:p>
        <w:r>
            <w:rPr />
            <w:t> Description 1</w:t>
        </w:r>
    </w:p>
    <w:p>
        <w:r>
            <w:rPr />
            <w:t>Checkbox 1</w:t>
        </w:r>
        <w:r>
            <w:fldChar w:fldCharType="begin">
                <w:ffData>
                    <w:name w:val="" />
                    <w:enabled />
                    <w:calcOnExit w:val="0" />
                    <w:checkBox>
                        <w:sizeAuto />
                        <w:checked />
                    </w:checkBox>
                </w:ffData>
            </w:fldChar>
        </w:r>
        <w:r>
            <w:rPr />
            <w:t> Checkbox 2</w:t>
        </w:r>
        <w:r>
            <w:fldChar w:fldCharType="begin">
                <w:ffData>
                    <w:name w:val="" />
                    <w:enabled />
                    <w:calcOnExit w:val="0" />
                    <w:checkBox>
                        <w:sizeAuto />
                    </w:checkBox>
                </w:ffData>
            </w:fldChar>
        </w:r>
    </w:p>
   <w:p>
        <w:r>
            <w:rPr />
            <w:t> Description 2</w:t>
        </w:r>
    </w:p>
    <w:p>
        <w:r>
            <w:rPr />
            <w:t> Description 3</w:t>
        </w:r>
    </w:p>
.....

On this XML I have couples of <w:p> </w:p> There are some <w:p> Description tags that contains checkbox tag after them and some that are empty. For each I need to create a JSON object and store it in a list.

I need to find tags to take text inside <w:t> and then to continue to another <w:p> tag to see if it contains checkbox, if yes then to take <w:t> value the JSON will look like this:

json['description'] = description
json['checkbox_text'] = checkbox

else if the tag after Description tag contain no checkbox then the JSON will contain only one element:

 json['description'] = description

My code looks like this:

results = []
    default_positions = [m.start() for m in re.finditer('w:p', xml_content)]
        jsonobj = {}
        for position in default_positions:
        if .. :
            //code
        else:
            //code

Any help?

Better alternative to long list of if statements

I have an int called dayCounter that runs 1 to 7. And i have a String called day. dayCounter increments every 10 seconds using TimerTask.

I use the following if statement inside the private void run() method used for TimerTask:

if (dayCounter == 1){
day = "Monday";}

I have an if statement like this for every day of the week. Is there a more efficient way which gets the same result. I was thinking maybe creating an array with holds String month and then increment it some way. But i wouldn't know how to go about it. Any ideas?

Jquery, check if multilevel array already has this in it or not

I am trying to push "arrayOne" into a multilevel array(arrayTwo). First I want to make sure it doesn't exist already so there is no duplicates. here is my code:

var arrayOne = ["3", "total_2"];
var arrayTwo = [["1", "total_2"], ["2", "total_4"], ["2", "total_6"], ["2", "total_11"]];

if (arrayTwo has arrayOne) {
    //do nothing
} else {
    arrayTwo.push(arrayOne);   
}

Im thinking im just confused on the syntax of this part:

if (arrayTwo has arrayOne) {

fiddle : http://ift.tt/1l3xrkt

Tictactoe game preventing first move from being used twice MySQL

I am making the basic tic-tac-toe game in MySQL and I can not figure out why my if statement is not stopping me from using the first move command twice. Here is what I have:

delimiter //

create procedure tictactoe(input varchar(4))
begin

declare i varchar(1);
declare j int;
declare computer_turn int;
declare user_turn int;

set computer_turn = 0;
set user_turn = 0;


if input = 'bm' then

if computer_turn = 0 then

case FLOOR(RAND()*(5-1)+1)
    when 1 then
    UPDATE grid
    SET B = 'M'
    WHERE ttt = '2';
when 2 then
    update grid
    set A = 'M'
    where ttt = '1';
when 3 then
    update grid
    set C = 'M'
    where ttt = '1';
when 4 then
    update grid
    set C = 'M'
    where ttt = '3';
when 5 then
    update grid
    set A = 'M'
    where ttt = '3';

end case;

set computer_turn = 1;

select * from grid;

else
  select 'First move has already been made. Use another command.';

  end if;

end if;

end //

Here is the table I am using:

CREATE TABLE `tictactoe_4213`.`grid` 
(`TTT` INT NOT NULL,
 `A` VARCHAR(45) NULL,
 `B` VARCHAR(45) NULL,
 `C` VARCHAR(45) NULL,
  PRIMARY KEY (`TTT`));

Insert into grid
values (1, null, null, null),
(2, null, null, null),
(3, null, null, null);

Return true if comparison (if statement) compares a undefined value

I'm working with a form that filters data. If the user does not put in any data the id will return undefined. If not it can be used in the if statement like: if (myValue < userInputValue) which will return true/false. However if nothing is filled in it returns false (of course). Is it possible to change this to true? My alternative solution would be to check for the variables and if it is undefined assign a value myself (however choosing a max number is not very error proof): if (!userInputValue) { userInputValue = 1 }.

What would be the best way to tackle this problem?

How to ignore voltage decreases?

I am programming an Arduino and I would like to have my if statement only respond when the voltage increases, not when it decreases.

This is what I have now:

void setup() {
  Serial.begin(9800);
  pinMode(13, OUTPUT);
}

void loop() {


  int sensorValue5 = analogRead(A5);
  float voltage5 = sensorValue5 * (5.0 / 1023.0);
  Serial.println(voltage5);

  if (voltage5 > 0.56 && voltage5 < 0.66) {

    digitalWrite(13, HIGH);
    Serial.println("TURNING BULB ON!");
    delay(200);
    digitalWrite(13, LOW);
    Serial.println("TURNING BULB OFF!");

  }

}

The problem with this code is that the if statement executes when the voltage increases from below 0.56 volts, but it also executes when the voltage decreases from higher than 0.66 volts. I would like the if statement to execute only when the voltage is going up, not coming back down.

Please help me this is very important. Thank you.

Java: while loop not working

I want to check the users input when a new game is created, and see if it is y, n, or neither.

For some reason it skips the while loop all together and just outputs "Welcome to Questions."

edit: I changed the = to == but now it just says invalid input no matter what the input is

import java.util.Scanner;

public class Questions {

public static final Scanner INPUT = new Scanner(System.in);

private boolean ans;


public Questions() {

  while (ans = false) {
      System.out.print("Do you want to start a new game (y/n)?: ");
      String input = INPUT.nextLine();

      if (input == "y"){
          ans = true;
          //some code
      }

      else if (input == "n"){
          ans = true;
          //some code
      }

      else {
          System.out.println("Invalid input, Try again");
          ans = false;
      }

  }//end while

}

public static void main(String[] args) {
  Questions game = new Questions();
  System.out.println("Welcome to Questions.");

}

Is `if` faster than ifelse?

When I was re-reading Hadley's Advanced R recently, I noticed that he said in Chapter 6 that `if` can be used as a function like `if`(i == 1, print("yes"), print("no")) (If you have the physical book in hand, it's on Page 80)

We know that ifelse is slow (Does ifelse really calculate both of its vectors every time? Is it slow?) as it evaluates all arguments. Will `if` be a good alternative to that as if seems to only evaluate TRUE arguments (this is just my assumption)?

I'm sorry if there was a duplicated question on SO. I did a quick search but I didn't see any.

Python: if, elif won't complete elif

I'm writing some code to create a list of predecessor files based on a file name or directory name, but can only get only get the list to work on file name OR directory name, not both. Each if statement works on its own, but the script does not complete when I ask it to look for either using elif.

Our file names are built like this:

[prefix]_[activeID]_[parentID]

where activeID identifies the file itself, and parentID identifies its immediate predecessor.

I have every file that could be a parent written to a dictionary (pdict), with its full path as the key, and its parts (e.g. activeID, parentID) written to different positions.

The for loop should do the following:

For each item on the list it finds the file directly before it. Uses the dictionary created earlier. Each item in the lineageList is also a key in the dictionary, so we pull out the associated parentID (fparentID) and match it to the activeID in the larger list (kactiveID) OR the beginning of the file directory (kfileDirName) and add those file names to the lineageList. The process then repeats with the newly added file(s), hopefully.

for f in lineageList:
    fparentID=pdict[f][4]
    for key, value in pdict.iteritems():
        kactiveID=pdict[key][3]
        kfileDirName=pdict[key][5]
        # Add a file to the list if its activeID matches the current parentID.
        if kactiveID==fparentID:
            lineageList.append(key)
        # If the current parentID isn't in the file name, add a file to the list if the directory starts with the parentID.
        elif kfileDirName.startswith(fparentID):
            lineageList.append(key)

As mentioned, I can get a list with any keys whose file names match the criteria (by commenting out the elif) or of any keys whose directories match the criteria (by making the elif the primary if statement and commenting out the other), but I cannot get it to work with both, regardless of order. The script just continues running, and has to be forced to quit. I am using PyScripter, and the bottom left corner will saying "Running" at the beginning, but that will eventually disappear but it continues to run until I stop it. Both execute within seconds when done separately.

Full code below:

import os

def getInput():
    # Tkinter for GUI file selection
    from Tkinter import Tk
    from tkFileDialog import *
    root = Tk()
    root.withdraw()

    # input file, though changed to be called infile just in case
    infile = askopenfilename(parent=root,title="Choose a file.")
    return infile

def getLineageList(infile):
    # Tkinter didn't like to return file paths with the same slashes, so it broke everything.
    inFullPath = str(infile.lower()).replace("/","\\")


    # Parse by backslash, (basically directory) and list in reverse order, with the file itself being first in the list, then its directory, and so on up the tree.
    inFullPartsRL=list(reversed(inFullPath.rsplit("\\",5)))

    # The path to the directory that the file resides in (not used?)
    inFileDir = inFullPath.rsplit("\\",1)[0]

    # The name of the input file, minus the extension.
    inFileName= inFullPartsRL[0].rsplit(".",1)[0]

    # A list of all parts of the file name (sans extension), split by an underscore.
    inFileParts=inFileName.split("_",5)

    # The filename parts
    prefix= inFileParts[0]


    # This might get us to our HUC folder
    # HUCdir = "N:\\Wetlands\\HSSD\\HUC10\\"+prefix
    HUCdir = "C:\\svn\\FileFinder\\"+prefix

    import os.path

    # A function to split every file into its parts.
    def parsefile(pfile):
        # All parts of path, separated by "\\", up to 5 parts.
        pinFullPartsRL=list(reversed(pinFullPath.rsplit("\\",5)))
        # The first position in the above list of path pieces - the file name - with extension removed.
        pinFileName= pinFullPartsRL[0].rsplit(".",1)[0]
        # The file name itself, split into as many as 5 parts.
        pinFileParts=pinFileName.split("_",5)
        # The prefix, or 1st position on the left-hand side of the file name.
        pprefix= pinFileParts[0]
        # The directory in which the file resides:
        pinFileDirName = pinFullPartsRL[1]
        # A way to deal with parts that may or may not exist - the active and parent IDs.
        try:
            pactiveID= pinFileParts[1]
        except IndexError:
            pactiveID="none"

        try:
            pparentID= pinFileParts[2]
        except IndexError:
            pparentID="none"
        # Stores all of the parts in a list (written later to a dictionary)
        plist=[pfile, pinFileName, pprefix, pactiveID, pparentID, pinFileDirName]
        return plist

    # An empty list in which to store all the files in the given directory.
    HUCfilelist=[]

    # The piece that creates the file list (path and name) of all files in the HUC directory.

    for dirpath, dirnames, filenames in os.walk(HUCdir):
        for f in filenames:
            HUCfilelist.append(os.path.join(dirpath.lower(),f.lower()))

    pdict={}

    # The part that pulls apart every file in the list. Tried assigning a number as a key but the filepath seemed like a better idea because the value in one pair can be the key in another.

    for f in HUCfilelist:
        pinFullPath = f # Create variable for parsefile function to use (pinFullPath is in function, so set input (f) as that variable.)
        plist= parsefile(f)
        pdict[f]=(plist)

#    print pdict

    # Starts the list with the input file.
    lineageList=[inFullPath]

    # For each item on the list it finds the file directly before it. Uses the dictionary created earlier. Each item in the lineageList is also a key in the dictionary, so we pull out the associated parentID (fparentID) and match it to the activeID in the larger list (kactiveID) OR the beginning of the file directory (kfileDirName) and add those file names to the lineageList. The process then repeats with the newly added file(s), hopefully.
    for f in lineageList:
        fparentID=pdict[f][4]
        for key, value in pdict.iteritems():
            kactiveID=pdict[key][3]
            kfileDirName=pdict[key][5]
            # Add a file to the list if its activeID matches the current parentID.
            if kactiveID==fparentID:
                lineageList.append(key)
            # If the current parentID isn't in the file name, add a file to the list if the directory starts with the parentID.
            elif kfileDirName.startswith(fparentID):
                lineageList.append(key)


    return lineageList


final = getLineageList(getInput())

print final

Using lists in if and else statements: Hangman as an example

Currently, I've been working on creating a hangman game and I've managed to get the majority of the scripts working and running perfectly however, I'm having problems with using lists in statements as I'd like to make a list of "used letters" which stops you from using the same letter again. The problem I've been finding is that I'll either set it up so it always includes the guess variable and not the input or it just doesn't work and I get a syntax error. Any suggestions on how I should do it?

Below, you'll find the code:

from random import randint
ans = input(">>>>>Let's play the word guessing game!<<<<<")
ans_upper = ans.upper()
if ans_upper == "YES":
    print("Good because that's what we're going to play!")
else:
    print("Tough, because we're going to play hangman anyways!")
#---#---#---#---#---#---#---#---#---#---# RANDOM WORD #---#---#---#---#---#---#---#
x = randint(1,15)
if x == 1:
    word = "bubblegum"
elif x == 2:
    word = "pasta"
elif x == 3:
    word = "cow"
elif x == 4:
    word = "chicken"
elif x == 5:
    word = "milk"
elif x == 6:
    word = "chair"
elif x == 7:
word = "computer"
elif x == 8:
    word = "psychology"
elif x == 9:
    word = "clock"
elif x == 10:
    word = "melon"
elif x == 11:
    word == "word"
elif x == 12:
    word = "brackets"
elif x == 13:
    word = "hangman"
elif x == 14:
    word = "paper"
elif x == 15:
    word = "internet"
else:
    print("ERROR: NUMBER HAS EXCEEDED THE VALUE OF 15")
#---#---#---#---#---#---#---#---#---# MYSTERY LETTERS #---#---#---#---#---#---#--
blanks = list("-"*len(word))
print("Can you guess the word, there are " , len(word), " letters!")
print(''.join(blanks))
word_list = list(word)
#---#---#---#---#---#---#---#---#---# LOOPING #---#---#---#---#---#---#---#---#---
loop = True
finished = len(word) * 1
done = 1
used = [] #This is for the used letters
while loop == True:
    guess = str(input("Enter a letter!"))
    checker = len(guess)
    if checker == 1:
        for letter_index in range(len(word_list)):
           if guess in word_list[letter_index]:
                guess_index = word_list.index(guess)
                letter_index = guess_index
                blanks[guess_index] = guess
                done = done + 1
                print("".join(blanks))

        if done == finished:
            print("You win!")
           loop = False
            break

    elif checker > 1:
        print("Hey, guess one letter at a time!")

So, the area that I'd like to have assigned to the task of storing the used letters us labeled as "used". I know that it involves the .append() command but I'm not sure where it'd go and how exactly I'd write out the command. Thanks in advance, Richard

Include html inside of

pretty new to PHP as well, I am trying to have a php load a file dynamically depending an ID that added to the page. The idea is to have one file for multiple pages... I have multiple pages loading different sidebars:

<?php

if ($PageType == 'about'){
    echo "
         <img src='http://ift.tt/1lULRDG' alt='' title='' class='img' />
         include('../include-images.html'); 
         <a href='#'><img src='http://ift.tt/1TogOLx' alt='' title='' class='img' /></a>
         <br class='brclear'/>
         ";
}

Any help how to run that INCLUDE('../include-images.html'); inside <?php if echo "" ?

Python detect the value from for loop when if statement evaluates to true python

I have a dictionary with each keys having multiple values in a list. The tasks are:

  1. To detect whether a given word is in the dictionary values
  2. If it is true, then return the respective key from the dictionary

Task 1 is achieved by using an if condition:

if (word in dictionary[topics] for topics in dictionary.keys())

I want to get the topics when the if condition evaluates to be True. Something like

if (word in dictionary[topics] for topics in dictionary.keys()):
   print topics

Prevent multiple logins using command line args, if statement checks, C#

I am currently writing a login method that keeps track of a logged in user by reading the contents of credentials saved in a text file called "accounts.txt".

The method works fine up to this point however I dont understand how I could make a simple check to prevent multiple logins. I am using command line arguments to input a string that logs in a user.

Example of this when input by command line is "login tom C#password" with "login" being passed as the command parameter, "tom" as param1, and "C#password" as the param2.

Ideally the method should check as an if statement that prevents a double login until the user inputs a "logout" command after "login" has already been used by command line args.

I'm fairly new to c#, any kind of advice is appreciated

 protected void login(string command, string param1, string param2) // string command "login" string username, string password
        {
            // login command
            // Needs to check check accounts.txt file for username and password.
            // if username and password exists, provide login message/else failed login
            // NO two logins at the same time until logout command is provided after the first login
            // checks accounts.txt file if username already exists and if there is a match, if not a prompt says login has failed

            var logins = File.ReadAllLines(@"C:\\Files\\accounts.txt");
            if (command == "login")
            {
                if (logins.Any(l => l == string.Format("{0} {1}", param1, param2)))
                    Console.WriteLine("Login {0} ", param1);
                string path1 = "C:\\Files\\audit.txt";
                using (StreamWriter sw1 = File.AppendText(path1))
                {
                    sw1.WriteLine("User " + param1 + " logged in");
                }
            }
            else
                Console.WriteLine("Login Failed: Invaild username or password");
                }

            //checks if more than one user logged in

            if (check for double login command)
            {
                Console.WriteLine("Login Failed: simultaneous login not permitted");
                string path2 = "C:\\Files\\audit.txt";
                using (StreamWriter sw2 = File.AppendText(path2))
                {
                sw2.WriteLine("Login Failed: simultaneous login not permitted");
                }
            }
            Console.Read();
        }

logout is a simple method that records if a user has logged out

 protected void logout(string command, string param1)
        {
            // remove current username and password from memory
        var logout = File.ReadAllLines(@"C:\\Files\\accounts.txt");
        if (command == "logout")
        {
            if (logout.Any(l => l == string.Format("{0} {1}", param1, param2)))
                Console.WriteLine("Logout {0} ", param1);
            string path1 = "C:\\Files\\audit.txt";
            using (StreamWriter sw1 = File.AppendText(path1))
            {
                sw1.WriteLine("User " + param1 + " logged out");
            }
        }
        else
            Console.WriteLine("Logout Failed");

        Console.Read();
    }

Boolean algorithm producing true output when output should be false

Basically i am trying to create an algorithm that will test whether a given string is a cover string for a list of strings. A string is a cover string if it contains the characters for every string in the list in a way that maintains the left to right order of the listed strings. For example, for the two strings "cat" and "dog", "cadhpotg" would be a cover string, but "ctadhpog" would not be one.

I have created an algorithm however it is producing the output true when the output should be false, as the given string is a cover String for Strings list1 and list2, but not for list3.

Any help into why this algorithm is producing the wrong output would be highly appreciated.

public class StringProcessing2 {

//ArrayList created and 3 fields added.
public static ArrayList<String> stringList = new ArrayList<>();
public static String list1 = "phillip";
public static String list2 = "micky";  
public static String list3 = "fad"; 

//Algorithm to check whether given String is a cover string.
public static boolean isCover(String coverString){
    int matchedWords = 0;
    stringList.add(list1);
    stringList.add(list2);
    stringList.add(list3);

    //for-loops to iterate through each character of every word in stringList to test whether they appear in
    //coverString in left to right order.
    for(int i = 0; i < stringList.size(); i++){
    int countLetters = 1;
        for(int n = 0; n < (stringList.get(i).length())-1; n++){
            if(coverString.indexOf(stringList.get(i).charAt(n)) <= (coverString.indexOf((stringList.get(i).charAt(n+1)), 
                    coverString.indexOf((stringList.get(i).charAt(n)))))){
                countLetters++;
                if(countLetters == stringList.get(i).length()){
                matchedWords++;                     
                }                                  
            }               
        }
    }
if(matchedWords == stringList.size()){
    return true;
}
else
    return false;   
}

public static void main(String[] args) {
System.out.println(isCover("phillmickyp"));

}


}

Using variables for if statement conditional in ruby

I am trying to use variables in if statement conditionals in Ruby and I am not getting the behavior I would expect.

I think the issue is with the "and" portion of the statement.

a = 1
b = 4
c = 3

@test = (a<b) and (b<c)

x = if @test
    puts "yes"
else
    puts "no"
end

That is returning "yes" when it should be returning "no", like it only evaluates the (a

Why won't my method work correctly?

I'm creating a game which has a player object Hek some enemy objects and the game world is a swamp. Basically the swamp can be thought of as a 4x4 grid, but the swamp size can be varied (i.e. 5x5, 6x6, 7x7, 8x8) by user input.

Within the specification, I'm working from, gives details on how Hek can move. Hek can only move to neighbouring squares, so the most squares he could pick from at one time based on a minimum of 4x4 grid is 8. The square in which he moves into is calculated at random, using Random().

Below is the code I have written to simulate this, but it doesn't seem to be working really. I don't know if my while loops are being used incorrectly?

    public void moveHek(Hek hek) {




    boolean moveMade = false;

    while (moveMade != true) {
        Random rand = new Random();
        int newMove = rand.nextInt(8) + 1;
        hek.setMove(newMove);
        int x = hek.getMove();
        int prevXPos = hek.getXPosition();
        int prevYPos = hek.getYPosition();

        if (x == 1) {
            while(prevXPos > 0 && prevYPos > 0) { //this if while checks that Hek's position isn't located within the top row  
                hek.setPosition(prevXPos - 1, prevYPos - 1); //and he isn't positioned within the first column of the map
                int newX = hek.getXPosition(); //and then moves Hek into the position that is diagonally left upwards to him.
                int newY = hek.getYPosition();
                this.addHek(hek, newX, newY);
                moveMade = true;
            } 
        } else if(x == 2) {
            while (prevXPos > 0) { //this if while checks that Hek's position isn't located within the top row and then
                hek.setPosition(prevXPos - 1, prevYPos); //moves Hek into the position that is directly above him.
                int newX = hek.getXPosition();
                int newY = hek.getYPosition();
                this.addHek(hek, newX, newY);
                moveMade = true;
            }
        } else if(x == 3) {
            while (prevXPos > 0 && prevYPos < gameMap.length) { //this if while checks that Hek's position isn't located within the top row
                hek.setPosition(prevXPos - 1, prevYPos + 1); //and he isn't positioned in the last column of the map, then moves him into the
                int newX = hek.getXPosition(); //position that is diagonally right upwards to him.
                int newY = hek.getYPosition();
                this.addHek(hek, newX, newY);
                moveMade = true;
            } 
        } else if(x == 4) {
            while (prevYPos > 0) { //this if while checks that Hek's position isn't located within the first column of the map and then
                hek.setPosition(prevXPos, prevYPos + 1); //moves him into the position that is directly left.
                int newX = hek.getXPosition();
                int newY = hek.getYPosition();
                this.addHek(hek, newX, newY);
                moveMade = true;
            } 
        } else if(x == 5) {
            while (prevYPos < gameMap.length) { //this if while checks that Hek's position isn't located within the last column of the map and then
                hek.setPosition(prevXPos, prevYPos - 1); //moves him into the position that is directly right.
                int newX = hek.getXPosition();
                int newY = hek.getYPosition();
                this.addHek(hek, newX, newY);
                moveMade = true;
            }
        } else if(x == 6) {
            while (prevXPos < gameMap.length && prevYPos > 0) { //this if while checks that Hek's position isn't located within the last row of the map and
                hek.setPosition(prevXPos + 1, prevYPos - 1); //that his position isn't located in the first column, then moves him into the position
                int newX = hek.getXPosition(); //that is diagonally left downwards to him.
                int newY = hek.getYPosition();
                this.addHek(hek, newX, newY);
                moveMade = true;
            }
        } else if(x == 7) {
            while (prevXPos < gameMap.length) { //this if while checks that Hek's position isn't located within the last row of the map and then moves
                hek.setPosition(prevXPos + 1, prevYPos); //him into the position directly below him.
                int newX = hek.getXPosition();
                int newY = hek.getYPosition();
                this.addHek(hek, newX, newY);
                moveMade = true;
            } 
        } else if(x == 8) {
            while (prevXPos < gameMap.length && prevYPos < gameMap.length) { //this if while checks that Hek's position isn't located within the last row
                hek.setPosition(prevXPos + 1, prevYPos + 1); //and the last column of the map, then it moves him into the position that is diagonally
                int newX = hek.getXPosition(); //right downwards to him.
                int newY = hek.getYPosition();
                this.addHek(hek, newX, newY);
                moveMade = true;
            } 
        } 
    }        
}

Any help would be greatly appreciated, the error that is occurring is java.lang.ArrayIndexOutOfBoundsException: -1 and sometimes the code within the inner while loops don't even execute? Thanks!

separate list into smaller list and go through each smaller list python

I have a list like this

results = [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0]

I want to separate this list, to group items into 4elements together:

size = 4
group_list_4 = [results[i:i+size] for i  in range(0, len(results), size)]
print "List:" , group_list_4

the result of this command is this:

List: [[1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [1, 0, 0, 0], [1, 0, 0, 0]]

Into each 4-group I have to check where is 1 element so if the first element on a 4group is 1 it return "first" if second return "second" till four. I have a list called lista where I save JSON obj, the condition for record in records: will be executed based on some data that is equal with numbers of lists with 4elements inside list called results , now I want inside this for loop to include the value that is 1 inside one list of 4elements, and next time that for loop will be executed to include the other list inside results list how can i do that, any help?

lista = []
for record in records:
            json_obj = {}
            json_obj['filename'] = filename
            json_obj['value_1_in_list'] =  put element 1 on list
            lista.append(json_obj)

Find sell script - logs (SUSE Linux, bash, if, find)

Sorry for my English. I have a problem with find sell script. My scrpit finds archives ten unpack some logs tar the results move it level up and remove file that were created in progres. And there is a problem it will do all operation even when script didn't find archive or logs in rsults creating empty tar. i was to fix it using if-statment or && and || operators but i can't handle it could you please direct me how to do it ?

this is my script:

#!/bin/bash

printf " -----\nSerch date: $1 \n"
printf "Serch patern: $2 \n"
printf "serch patern: $3 \n -----\n\n"

printf "Serch archives:\n"
mkdir /cc/xx/logs/aaa/envelop/tmp

find archives/ -name "$1_*_messages.tar.gz" -exec cp {} tmp \;
    ls -l tmp/
    cd tmp
    tar -xf $1_*_messages.tar.gz --wildcards --no-anchored "*$2_$3*"
    printf "Find envelop:\n"
    ls -l alsb-message/

    mv alsb-message $1_$2_$3
    tar -cvf $1_$2_$3.tar $1_$2_$3
    mv $1_$2_$3.tar ..
    rm *.gz
    rm -R $1_$2_$3
    cd ..
    rm -r tmp

Setting variable in if-case in Qt

I have a problem setting a variable in an if-case. Here's my code:

void ExcelResultFileWriter::setCombineP835(bool option){
    if(option == true){
        cout << "dario" << endl;
        this->combineSheets = true;
    }
    else{
        cout << "kein dario" << endl;
    }
}

I'm getting an address error when he tries to set the variable combineSheets. Does anyone have an idea why? When I'm only printing out the "dario" it works fine, but when it comes to setting the variable I'm getting the error. The variable is of course defined as

bool combineSheets

Thank you!

SQL, insert data into free column acording to date difference

I have got a problem. I'm a real beginer in SQL. I work on BI project and I need to create data warehouse.

My current problem is this:

I have got a table into which I push data from external Microsoft Access. In those data are two dates (billing info) and I need to generate an info into this table if there is delay in payment (there is free column in the table named delay into which I need to generate YES/NO according to if the date of payment is later then date of "need" of payment)

So I have in mind something like this:

INSERT INTO TABLE billing,
VALUES (YES)
IF DATE1 > DATE2,
ELSE VALUE (NO)

... I know this is no SQL but its just to get the idea.

If someone know something which could help me I would be grateful. Thanks

Mysql update if

this is the query i am trying to use.

  SET @id = 289;
    SET @feedId = 5;
    SET @statusid = 2;
    SET @processId = 1;

    SET @feedIdExists = (
     SELECT EXISTS (
       SELECT *
       FROM feed_statuses
       WHERE FeedId = @feedId));

    IF feedIdExists = 1 THEN
     UPDATE `snap`.`feed_statuses` 
      SET
      `ProcessId` = @processId , 
      `StatusId` = @statusId , 
      `ProcessEndDate` = NOW()
      WHERE
      `FeedId` = @feedId;
    ELSE
     INSERT INTO `snap`.`feed_statuses` 
      (`FeedId`, 
      `ProcessId`, 
      `StatusId`, 
      `ProcessStartDate`
      )
      VALUES 
      (@feedId,
      @processId,
      @statusId,
      NOW());
    END IF;

hi guys, there are 3 errors about the if syntax. i didnt understand. why doesnt it work properly?

If statement not processing - Java

I'm writing a tic tac toe problem. The tic tac toe class works fine, but the first if statement in my Main class isn't processing. The TicTacToe class isn't what's wrong, because when Player 1 wins the oNew.checkWinner(1) returns true. (I checked by placing System.out.println(oNew.checkWinner(1)); right before the if statement). But then it doesn't pass into the if statement to break the while loop and just continues on. It does the same with the first else if too.

The odd part is it works just fine for the 2nd if statement and 2nd else if statement.

public static void main(String[] args) {

        TicTacToe oNew = new TicTacToe();
        String champ = "";
        boolean hasWon = false;

        oNew.getMove();
        while(hasWon == false){
            oNew.setMove(1);
            oNew.getMove();
            if (oNew.checkWinner(1) == true){
                champ = "Player 1 wins.";
                hasWon = true;
            }
            else if(oNew.checkCatsGame() == true){
                champ = "Draw";
                hasWon = true;
            }
            oNew.setMove(2);
            oNew.getMove();
            if (oNew.checkWinner(2) == true){
                champ = "Player 2 wins.";
                hasWon = true;
            }
            else if(oNew.checkCatsGame() == true){
                champ = "Draw";
                hasWon = true;
            }
        }
        System.out.println(champ);

    }

How can I improve this if in ruby?

How can I improve this if in ruby?

Original if:

     status    = 'None available',
      css_class = 'grey'
      if pending_final > 0
        status    = 'Pending'
        css_class = 'red'
      elsif requested_final == 0 && request.granted
        status = 'Granted'
        css_class = 'green'
      elsif requested_final == 0 && request.granted == false
        status = 'Not requested'
        css_class = 'red'
      end

I was trying to refactor like this:

status, css_class = if pending_final > 0
 'Pending', 'red'
elsif requested_final == 0 && request.granted
 'Granted', 'green'
 # and so on...
else
 'None available', 'grey'
end

But then I have a syntax error in the "," commas.

dimanche 29 novembre 2015

if statement always returns true (Python 3.5) [duplicate]

This question already has an answer here:

I'm very new to Python (have not even finished the codecademy course) but I'm trying to write my first simple program. My if statement always returns true, no matter what the answer is. The indents look right, and I don't have a condition for the else, just a call to print.

answer = input("What is your favorite eldest child's name?   ")

if answer == "A" or "Al":
    print("Of course, we all knew that")
elif answer == "C" or "Chris":
    print("""Oh she must be standing right there.
But that\'s not it, try again.""")
elif answer == "E" or "Ed":
    print("Not even the right gender. Try again.")
else:
    print("I'm sorry. Only children. Were you thinking of the dogs?")

Batch file "If" statement errors

I seem to be having tons of trouble making this program. I finally only have one more error. Below is the link to the pastebin, with code on it.

Pastebin Link

Anyways if you could explain to me whats wrong, I'll fix the code, I don't expect you to.

MySQL AVG() return 0 if NULL

I have 3 tables, shown below:

mysql> select * from Raccoon;
+----+------------------+----------------------------------------------------------------------------------------------------+
| id | name             | image_url                                                                                          |
+----+------------------+----------------------------------------------------------------------------------------------------+
|  3 | Jesse Coon James | http://ift.tt/1l16r4V                                     |
|  4 | Bobby Coon       | http://ift.tt/1ItwKWi                                     |
|  5 | Doc Raccoon      | http://ift.tt/1l16ttM |
|  6 | Eddie the Rac    | http://ift.tt/1ItwM0q                                                 |
+----+------------------+----------------------------------------------------------------------------------------------------+
4 rows in set (0.00 sec)

mysql> select * from Review;
+----+------------+-------------+---------------------------------------------+--------+
| id | raccoon_id | reviewer_id | review                                      | rating |
+----+------------+-------------+---------------------------------------------+--------+
|  1 |          3 |           1 | This raccoon was a fine raccoon indeed.     |      5 |
|  2 |          5 |           2 | This raccoon did not do much for me at all. |      2 |
|  3 |          3 |           1 | asdfsadfsadf                                |      5 |
|  4 |          5 |           2 | asdfsadf                                    |      1 |
+----+------------+-------------+---------------------------------------------+--------+
4 rows in set (0.00 sec)

mysql> select * from Reviewer;
+----+---------------+
| id | reviewer_name |
+----+---------------+
|  1 | Kane Charles  |
|  2 | Cameron Foale |
+----+---------------+
2 rows in set (0.00 sec)

I'm trying to build a select query that will return all of the columns in Raccoon as well as an extra column which grabs an average of Review.rating (grouped by id). The problem I face is that there is no guarantee that there will be rows present in the Review table for every single Raccoon (as determined by the FK, raccoon_id which references Raccoon.id. In situations where there are zero rows present in the Review table (for a given Raccoon.id, ie Review.raccoon_id) I'd like the query to return 0 as the average for that Raccoon.

Below is the current query I'm using:

mysql> SELECT *, (SELECT IFNULL(AVG(rating),0) FROM Review WHERE raccoon_id=Raccoon.id GROUP BY raccoon_id) AS "AVG" FROM Raccoon ORDER BY "AVG" ASC;
+----+------------------+----------------------------------------------------------------------------------------------------+--------+
| id | name             | image_url                                                                                          | AVG    |
+----+------------------+----------------------------------------------------------------------------------------------------+--------+
|  3 | Jesse Coon James | http://ift.tt/1l16r4V                                     | 5.0000 |
|  4 | Bobby Coon       | http://ift.tt/1ItwKWi                                     |   NULL |
|  5 | Doc Raccoon      | http://ift.tt/1l16ttM | 1.5000 |
|  6 | Eddie the Rac    | http://ift.tt/1ItwM0q                                                 |   NULL |
+----+------------------+----------------------------------------------------------------------------------------------------+--------+
4 rows in set (0.00 sec)

As you can see above, the query isn't returning 0 for Raccoons with id of 4 and 6, it is simply returning NULL. I need it to return something like the following (note the ordering, sorted by lowest average review first):

+----+------------------+----------------------------------------------------------------------------------------------------+--------+
| id | name             | image_url                                                                                          | AVG    |
+----+------------------+----------------------------------------------------------------------------------------------------+--------+
|  4 | Bobby Coon       | http://ift.tt/1ItwKWi                                     | 0.0000 |
|  6 | Eddie the Rac    | http://ift.tt/1ItwM0q                                                 | 0.0000 |
|  5 | Doc Raccoon      | http://ift.tt/1l16ttM | 1.5000 |
|  3 | Jesse Coon James | http://ift.tt/1l16r4V                                     | 5.0000 |
+----+------------------+----------------------------------------------------------------------------------------------------+--------+

Using If and Else statements in Ruby

Very new to the world of programming and just starting to learn, working through Flatiron School prework and have been doing ok but unable to understand "if" and "else" statements for some reason. The problem is similiar to Chris Pine 'deaf grandma' problem but without saying "BYE!" three times.

~The method should take in a string argument containing a phrase and check to see if the phrase is written in all uppercase: if it isn't, then grandma can't hear you. She should then respond with (return) HUH?! SPEAK UP, SONNY!.

~However, if you shout at her (i.e. call the method with a string argument containing a phrase that is all uppercase, then she can hear you (or at least she thinks that she can) and should respond with (return) NO, NOT SINCE 1938!

I have so far:

def speak_to_grandma
  puts "Hi Nana, how are you?".upcase 
  if false  
puts "HUH?! SPEAK UP, SONNY!"
  else 
    puts "NO, NOT SINCE 1938!"
  end
end

but am getting wrong number of arguments...how am I supposed to add argument while using the if/else statements? This is probably a very easy and basic question but can't seem to get my head around this (overthinking probably).
Any help and clarity would be greatly appreciated.

Can someone tell me why this method is going into an infinite loop?

So it seems this method is going into an infinite loop if the if(printLibraryNumber.equals(borrowersArray[index].getLibraryNumber() statement is true, and I have no idea why.

public boolean printBorrower(String printLibraryNumber)
{
   int index = 0;
   boolean isPrinted = false;
   while(index < currentIndex)
   {
       if(printLibraryNumber.equals(borrowersArray[index].getLibraryNumber()))
       {
           borrowersArray[index].printBorrowerDetails();
           isPrinted = true;
       }
       else
       {
           index++;
           isPrinted = false;
       }
   }

   if(isPrinted == false)
   {
       System.out.println("Borrower with library number " + printLibraryNumber + " not found.");
    }

   return isPrinted;
}

How to write if-statement in java that checks repeated input?

Is there any way in java to write a condition that checks if user's input has already been entered before?

if statement not executed

I hope this question is not too stupid ... I have problem with an if statement not being executed ... the corners below are fixed, const. Now I want a static variable alphadrone move from one corner to the other.

The first 'if' works, the second not. I really go crazy with this ...

const int32_t corner_1_X = 47.590000 * 1e3 * LATLON_TO_CM;
const int32_t corner_1_Y = 7.646000  * 1e3 * LATLON_TO_CM; //bigger
const int32_t corner_2_X = 47.590000 * 1e3 * LATLON_TO_CM;
const int32_t corner_2_Y = 7.644000  * 1e3 * LATLON_TO_CM; //smaller

static int32_t alphadroneXposition = corner_1_X;
static int32_t alphadroneYposition = corner_1_Y;

// if (corner_1_Y > corner_2_Y)
    // moveAlphadroneYneg(&alphadroneYposition);
if (alphadroneYposition > corner_2_Y)
    moveAlphadroneYneg(&alphadroneYposition);

PHP how to put an if statement inside an echo block

I have the following if statement:

<?php if ( isset ( $prfx_stored_meta['wedding-user'] ) ) selected( $prfx_stored_meta['wedding-user'][0], 'select-one' ); ?>

which I need to insert into this echo statement:

$users = get_users();
$i = 0;
// Array of WP_User objects.
foreach ( $users as $user ) {
    echo "<option value='select-$i' >" . esc_html( $user->display_name ) . "</option>";
    $i++;
}

Just before closing the tag I'm not sure how to add an if statement inside of an echo

using if/else statement in html

I am new to building websites, so can anyone please help me? I want to use an if/else statement in html to display text and some movies on my website. Below I have added my html code, but it sees the if/else statement as a text and not as a code. How can I get this if/else statement to work, using the temperature output from my js code with openweather API?

       <!DOCTYPE html>
            <html>
            <head>
            <link rel="stylesheet" href="http://ift.tt/1lTlDxP">
                <link rel="stylesheet" href="main.css">
                <script src="http://ift.tt/1yCEpkO"></script>
                <script type='text/javascript' src='app.js'></script>

            </head>

            <body>
                <input type="text" value="In which city are you?" id="city">
                    <button id="search">Submit</button>
                    <p id="demo"></p>

                    <p>The weather outside is: </p>

                    <div class= "weather">
                        Fill in your location first
                    </div>

                    <p>What will you be making for dinner tonight?</p> 
                    <div class="inspiration">
                        Give me some inspiration!

                        <div class="recipe">        
    if (Math.round(data.main.temp) == null) {
        <p>Fill in your location first</p>
    } else {
        if (Math.round(data.main.temp) < -5) {
            <p> Oh man.. It is way too cold! Stay inside the whole day and have a nice and hot turkey soup. Make sure you don’t freeze </p>
            <iframe width="392" height="220" src="https://www.youtube.com/embed/SdJfxGo5PQM?rel=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>

        } else if (Math.round(data.main.temp) === -5 - 5){
            <p>wow look at that weather, it is quite cold.. With those temperatures a chicken and fries curry would be nice don’t you think? </p>
            <iframe width="392" height="220" src="https://www.youtube.com/embed/PfoOxeTXdXA?rel=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>

        } else if (Math.round(data.main.temp) === 5 - 15) {
            <p> Today is a good day, don’t you think? Some cheeseburger cups would taste great!</p>
            <iframe width="392" height="220" src="https://www.youtube.com/embed/k-2KdH6k0nA?rel=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>

        } else if (Math.round(data.main.temp) === 15 - 25) {
            <p> With those temperatures it is not a bad idea to have a BBQ! Here is a recipe for hummus to have as a side dish!</p>
            <iframe width="4392" height="220" src="https://www.youtube.com/embed/XN4aSh-Dj4Y?rel=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>

        } else if (Math.round(data.main.temp) === 25-35) {
            <p> Damn it's hot! I can hardly think of anything to have for dinner to cool down. </p>
            <p> Just go get some ice cream please. </p>

        } else {
            <p>Those temperatures are insane! Are you in a sauna?</p>
        }
    }
                        </div>
                    </div>
                </div>
            </body>
            </html>

this is my js code

        $(document).ready(function(){
        $('#search').click(function(){
            var city = $('#city').val();
            console.log(city);
            $.getJSON( "http://ift.tt/1jfvxJq" + city + "&units=metric&appid=9334f947893792dcb9b2e2c05ae23eb0", function( data ) {
                $('.weather').html(Math.round(data.main.temp)+ ' degrees Celcius');
            });
        });
        });

Trying to print only string data

I'm trying to get the for-loop and if statement to just print out string data only.

var languages = { english: "Hello!", french: "Bonjour!", notALanguage: 4, spanish: "Hola!" };

// print hello in the 3 different languages
for (var x in languages) {
    if (typeof x === "string") {
        console.log(languages[x])
    }
};

Allow a button press by true or false variable AS3

I have been making an advent calendar in which when you press the button the door opens. I have created a variable to control which date you can open them on called 'AllowOpen' if it is the right date. I have also created a function to go to a frame when clicked.

var AllowOpen: Boolean = false;
if (Day == 1) {
    AllowOpen = true;
} else {
    AllowOpen = false;
}

button1.addEventListener(MouseEvent.MOUSE_DOWN, click);

function click(event:MouseEvent):void
{
    gotoAndStop(2)
}

I can't work out how I would tell the the program to only open the door if allow open is true. I have tried the 'if' statement but it doesn't seem to work. Thanks

FileReader/Writer not writing after flush and close because of if statement [duplicate]

This question already has an answer here:

I'm having quite a bit of trouble with my code. The objective is to read an existing file and copy (via FileReader and FileWriter) that text into a new file. The issue I face is that the file is created, but empty. However, it will write the text without the first if statement that checks whether the user has entered an "r". I have not found other questions that tackle this problem with if.

The purpose of the if is to read the third command line argument and determine whether it will write a new file (r = replace) or append (a) to an existing one.

Simply put, with the if, the file is created and contains text. Without the if, file exists but no text.

import java.io.*;

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

  if(args.length == 3)  {
     try    {
        FileReader in = new FileReader(args[0]);
        FileWriter out = new FileWriter(args[1]);
        int chr = in.read();    // read the first character

        if(args[2] == "r"){ //This is the if statement that causes trouble
           while(chr != -1) {   // continue reading and writing until end 
              out.write(chr);
              chr = in.read();
           }
           out.flush();
           in.close();
           out.close();
        }   
     } //try
     catch(IOException e)  {
        System.out.println("Exception: " +  e.getMessage());
     }

  }
  else   {
     System.out.println("Please enter correct number of arguments");
  }

 } //main

} //class  

This code is not complete, I know there is more I need to add, however this phenomenon has me quite puzzled. Any ideas where my problem lies?

Also, as this is part of an assignment, it has been requested that I not use any BufferedReader or BufferedWriter.

Locking user input and counting amount of time loop happens

Im new to this so sorry if I am a bit confusing

So this is my code, its a game based around 2 players adding 1 or 2 to the variable "counter" the one who puts the final 1 or 2 adding all the numbers up to 21 wins.

So what I would like to have help with is that I want to lock the user input to only be able to select 1 or 2, not anything else because that would break the rules of the game. Also I would like to have a way to determine who won, player 1 or player 2. Like counting the amount of times the loop happens, so I can distinguish if player 1 or 2 one.

Any help would be appreciated! Thanks!

package hemtenta; import java.util.Scanner;

public class Hemtenta {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int counter = 0;
    int addcounter = 0;
    int sum;
    System.out.println("Welcome to 21");
    System.out.println("The game revolves about you or your opponent getting to 21 ");
    System.out.println("You both start on the same number 0, ");
    System.out.println("adding 1 or 2 to see which one of you will put the final number adding it all up to 21 and winning.");
    System.out.println("Think smart!");

    while(counter <= 20) { System.out.println("Please choose to add 1 or 2");
    addcounter = input.nextInt();
    counter += addcounter;

    System.out.println("We are now on a total of " + (counter));
    }
    if (counter==21) { System.out.println("Congratulations x! you won");
    } 
    else { System.out.println("Something went wrong! Try again");
    }

    }

}

if statement function for 1 value but for more than 1 validation

i have some problem when i created a calculated field in tableau.

lets say i have this "City" variable with these kind of data: 1 2 3 4 5 6 7 8

i want to make validate this number into if 1-4 become Region A, 5-8 become Region B and 1-8 is National.

this is my calculated filed code

if [City]=1 or [City]=2 or [City]=3 or [City]=4 THEN "Region A"
elseif [City]=5 or [City]=6 or [City]=7 or [City]=8 THEN "Region B"
elseif [City]=1 or [City]=2 or [City]=3 or [City]=4 or [City]=5 or [City]=6 or 
[City]=7 or [City]=8 THEN "National"
END

but after i created this calculated field, only "Region A" and "Region B" and "Null" showed. My thought is maybe that code is overlapping on Region with National (or is not?).

How can i solve this? and where this null come from when my data only have the range from 1-8?

Thank you

Error dont know what to do. project DTR

i think somethings wrong with my codes or query, i just want to make an error messagebox if the user time in twice a day. My error is it always go to the else statement part where the user will time in even though he/she already time in, my database is now full of duplicated records . could someone help me? sorry for my bad english hope you understand.

   Public Sub isTimein_Exist()
    Try
        Dim dbConnection As New MySqlConnection(dbConstring)
        dbQuery = "Select empid, date from tbldtr where empid = '" & txtInputID.Text & "' and date = '" & Date.Today & "'"
        dbCmd = New MySqlCommand(dbQuery, dbConnection)
        dbConnection.Open()
        dbReader = dbCmd.ExecuteReader()
        If dbReader.Read = True Then

            MsgBox("You Have TIME-IN Already", MsgBoxStyle.Information, "Time-IN")
            Exit Sub
        Else
            Timein()
        End If

    Catch ex As Exception

    End Try
End Sub

if statement executed, object value unchanged [duplicate]

This question already has an answer here:

I declared a String and I have an if-statement when the broadcast receiver been called, in the if-statement, I change the reference of the String, but after the if statement executed, the reference to String changed back to the original value.

I tried to search from internet but perhaps the keyword I used is incorrect I cannot find any suitable info. I appreciate if anyone can explain it to me or show me the link for the info

Code are shown as followed

public class IncomingCall extends BroadcastReceiver {
String **previousState** = "idle";
String **ringing** = "ringing";
String **offhook** = "offhook";

@Override
public void onReceive(Context context, Intent intent) {

    String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

//the first case
    if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
        Toast.makeText(context, "ringing", Toast.LENGTH_SHORT).show();
        previousState = ringing;
        Toast.makeText(context, previousState, Toast.LENGTH_SHORT).show();
    }
//the second case
 if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
        Toast.makeText(context, "off hook ", Toast.LENGTH_SHORT).show();
        if (previousState == ringing){
            Toast.makeText(context, "previous is ringing ", Toast.LENGTH_SHORT).show();
                previousState = offhook;}
        if (previousState == idle){
            Toast.makeText(context, "previous is idle ", Toast.LENGTH_SHORT).show();
                previousState = offhook;}
        }

As you can see,when someone called in, the phone state change from idle to ringing then changed to offhook if user picked up the call, so after first part is executed, the second part should be executed.

After first part is executed the previousState should be refer to ringing, but it still shown as "idle", can anyone explain why it happened?

Thank you!

How do I give the user two options for which code to run?

So I am trying to get a calculation depending on what the user inputs. Like if (game1.equalsIgnoreCase ("Bama")); player = player + 10; player2 = player2 + 10; if (game1.equalsIgnoreCase ("OSU")); player = player + 20; player2 = player 2 + 20; This is adding both up at the same time, no matter when I put in (OSU or Bama). How do I only get it to run only one of them?

(I am new to Java, as well as this website, so forgive me if this isn't a clean question.

samedi 28 novembre 2015

if else statement for great than statement

Having a difficult time setting up my if else statement. I have no clue what I'm doing wrong here. Any tips or help would go a long ways! Thanks so much!

First page

form action="total.php" method='POST'>
  Quantity:
  <input type="number" name="number">
  <input type="submit">
</form>

My PHP statement page:

<?php
$number = $_POST['number'];

?>
<!DOCTYPE html>
<html>
<head>
<title>HA</title>
</head>
<body>

<?php 
if($number < 3){
    echo ' Thank you for ordering ';
}
else{
    echo 'sorry we do not offer that many';
}
?>
</body>
</html>

How to use set and if statements in batch files

So i'm trying to make a small batch program with some sets and ifs, seems easy enough right? Apparently, you can't use "set" and "if" like this.

@echo off
setlocal enabledelayedexpansion
cls
set variableTrue EQU 1

Then continue the code and later in the program do this.

If %variableTrue% EQU 1 goto next

Please note I've tried it with exclamation marks as well. With the exclamation marks, it's like it completely ignores the statement, even if it's true it will continue as usual. With the percentage signs, it says very quickly before crashing "1" was not expected at this time. Or something like that, like I said it barely stayed for half a second. I always thought you could do it like this as long as there are no conflicting variables.

Detecting a blank line in C++ from reading a file

I have a plain text file (.txt) with the following data;

data 5

data 7
data 8

I read this file in the following manner:

 ifstream myReadFile;
 myReadFile.open(fileName.c_str());

 if (myReadFile.is_open() != true){
    return -1;
 }

string stri;
int i;

while (std::getline(myReadFile,stri)){
  i++;
  if(stri.find("data") != std::string::npos){ //extract data}

  else if(stri.empty()){ cout << "Conditional statement true"; }

  else { cout << "invalid keyword on line: " << i; }
}

I always receive the invalid keyword message and never does the conditional statement go through. I have tried if (stri == "") and (stri.compare("");

NOTE: It is safe to assume that the empty line contains NO WHITESPACE.

Java Boolean assignment. Boolean variable not setting to true

public void keepDice(int keep){
    for(int i = 0; i<dice.length; i++){
        if(keep == dice[i]){
            keepDie[i] = true;
        }   
        else{
            keepDie[i] = false;
        }
    }
}

dice is an int array, keepDie is a boolean array and I'm passing the method a value of 6. I cannot figure out why it will never assign to true even when a 6 matches a 6 unless 6 appears in the first iteration and then it assigns EVERY element to true instead of just the 6's.

this is output if a 6 appears first:

Testing keepDice(): 
6 3 5 1 6 
T T T T T 

and this is output otherwise:

Testing keepDice(): 
5 3 6 5 5 
F F F F F 

this is my toString() method:

public String toString(){

    String msg = new String("");
    String str = new String("");

    msg += "\n";

    for(int i = 0; i<dice.length;i++)
        msg += dice[i] + " ";

    msg += "\n";

    for(int i = 0; i<dice.length;i++){

        str += String.valueOf(keepDie[i]).toUpperCase();
        msg += str.substring(0, 1) + " ";
    }

    msg += "\n";

    return msg;
}

Parallel optimization with extra parameters (fmincon) using for loop and if then statements

I am trying to do parallel processing optimization (fmincon) using for loops for each a,b=0:.01:1 includes if then statement because I have a normalized condition which is a^2+b^2+c^2=1 then c=sqrt(1-a^2-b^2). I am getting confused on the coding. I tried this code (see below), but it could not work. I wrote a file objfun.m.

function f= objfun (x,a,b,c)
    load test.mat a b
    p1=-sin(((x(2)-x(1))/2)+((x(4)-x(3))/2)+((x(6)-x(5))/2))+sin(((x(4)-x(3))/2)+((x(6)-x(5))/2)-((x(2)-x(1))/2))+sin(((x(2)-x(1))/2)+((x(6)-x(5))/2)-((x(4)-x(3))/2))+sin(((x(2)-x(1))/2)+((x(4)-x(3))/2)-((x(6)-x(5))/2));
    p2=sin(((x(2)-x(1))/2)+((x(4)-x(3))/2)+((x(6)-x(5))/2))+sin(((x(4)-x(3))/2)+((x(6)-x(5))/2)-((x(2)-x(1))/2))-sin(((x(2)-x(1))/2)+((x(6)-x(5))/2)-((x(4)-x(3))/2))+sin(((x(2)-x(1))/2)+((x(4)-x(3))/2)-((x(6)-x(5))/2));
    p3=sin(((x(2)-x(1))/2)+((x(4)-x(3))/2)+((x(6)-x(5))/2))-sin(((x(4)-x(3))/2)+((x(6)-x(5))/2)-((x(2)-x(1))/2))+sin(((x(2)-x(1))/2)+((x(6)-x(5))/2)-((x(4)-x(3))/2))+sin(((x(2)-x(1))/2)+((x(4)-x(3))/2)-((x(6)-x(5))/2));
    p4=sin(((x(2)-x(1))/2)+((x(4)-x(3))/2)+((x(6)-x(5))/2))+sin(((x(4)-x(3))/2)+((x(6)-x(5))/2)-((x(2)-x(1))/2))+sin(((x(2)-x(1))/2)+((x(6)-x(5))/2)-((x(4)-x(3))/2))-sin(((x(2)-x(1))/2)+((x(4)-x(3))/2)-((x(6)-x(5))/2));

    f=p1+2*a*c*p2+2*a*b*p3+2*b*c*p4;

I wrote the main file

%x=[x(1),x(2),x(3),x(4),x(5),x(6)]; % angles;
clc;
p=0:0.1:1;q=0:0.1:1;
for m=1:length(p)
for n=1:length(q)
    a=p(m);b=q(n);
    if a^2+b^2+c^2=1 Then c=sqrt(1-a*a-b*b) 
    save test.mat a b
    lb=[0,0,0,0,0,0];
    ub=[pi,pi,pi,pi,pi,pi];
    x0=[pi/8;pi/3;0.7*pi;pi/2;.5;pi/4];
    [x,fval]=fmincon(@objfun,x0,[],[],[],[],lb,ub);
    clear a b
    opt_val(m,n)=fval;
    end 
end
end

What I have to do to make this code work? I need some help on structuring the main file please .

Whats wrong with my codes? login forms in VB

whats wrong with my login codes? every time i login the correct username and password it always go to the "incorrect username and password".

can someone help me? just new in vb. thankyou in advance.

               Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
    Dim dbQuery As String = "Select * from tblLogin  where username = '" & txtuse.Text & "'or password = '" & txtPass.Text & "'"
    Dim dbConnection As New MySqlConnection(dbConString)
    Dim dbCmd As New MySqlCommand(dbQuery, dbConnection)
    Dim dbReader As MySqlDataReader
    dbConnection.Open()
    dbReader = dbCmd.ExecuteReader()

    While dbReader.Read()
        If txtuse.Text = dbReader("username") And dbReader("account_type") = "Admin" And txtPass.Text = dbReader("password") Then
            frmAdmin.Show()
            Me.Close()
        ElseIf txtuse.Text <> dbReader("username") And dbReader("account_type") = "Admin" And txtPass.Text = dbReader("password") Then
            MessageBox.Show("Incorrect Username")
        ElseIf txtuse.Text = dbReader("username") And dbReader("account_type") = "Admin" And txtPass.Text <> dbReader("password") Then
            MessageBox.Show("Incorrect Password")
        ElseIf txtuse.Text = dbReader("username") And dbReader("account_type") = "Regular" And txtPass.Text = dbReader("password") Then
            frmRegular.Show()
            Me.Close()
        ElseIf txtuse.Text <> dbReader("username") And dbReader("account_type") = "Regular" And txtPass.Text = dbReader("password") Then
            MessageBox.Show("Incorrect Username")
        ElseIf txtuse.Text = dbReader("username") And dbReader("account_type") = "Regular" And txtPass.Text <> dbReader("password") Then
            MessageBox.Show("Incorrect Password")
        Else
            MessageBox.Show("Incorrect Password and Username")
        End If
    End While
End Sub

Javascript : Speed between "if" and "object"? [on hold]

I was wondering what was faster between an "if" and a "json" access

Just consedering this :

var val1 = "IAM1",
    val2 = "IAM2",
    val3 = "IAM3",
    val4 = "IAM4",
    myVal = null,
    obj = {};

obj[val1][val2][val3] = val4;

I want to set quickly myVal :

// First Case
myVal = obj[val1][val2][val3];

// Second case
var set = function(value) {
   if (value == val1) myVal = val1;
   if (value == val2) myVal = val2;
   if (value == val3) myVal = val3;
   if (value == val4) myVal = val4;
}
set(val4);

Knowing that "obj" can have even more elements or/and that the "set" method can be called by other objects multiple time

What is the faster way to set "IAM4" on myVal ?

Thanks !

Determining if certain letters are in HashMap value of Strings

So I have written pretty much all of the homework code and reached the ending part. I have gone through the debugger and as far as I can see it should work and have traced the issue to the exact spot of problem and would like some help in determining why this is happening and a possible way around it.

public class ReadFile {

public static void main(String[] args) throws IOException {

    /** Hardwire table from homework to use for code */
    String file_name =
                "C:/Users/Shane/Documents/College/Classes/PurchaseTable.txt";

    extract(file_name, 50);

}

private String path;

public ReadFile(String file_path) {
    path= file_path;
}

public String[] OpenFile() throws IOException {
    FileReader fr = new FileReader(path);
    BufferedReader textReader = new BufferedReader(fr);

    int numberOfLines = readLines();
    String[] textData = new String[numberOfLines];

    int i;

    for(i=0; i < numberOfLines; i++) {
        textData[i] = textReader.readLine();
    }

    textReader.close();
    return textData;
}

int readLines() throws IOException {

    FileReader file_to_read = new FileReader(path);
    BufferedReader bf = new BufferedReader(file_to_read);

    String aLine;
    int numberOfLines = 0;

    while(( aLine = bf.readLine()) != null) {
        numberOfLines++;
    }
    bf.close();

    return numberOfLines;
}

public static void extract(String filename, int threshold) {

    String file_name = filename;
    ArrayList<String> temp = new ArrayList<String>();
    ArrayList<String> products = new ArrayList<String>();
    HashMap<Integer, String> productsPerDate = new HashMap<Integer, String>();
    ArrayList<String> combos = new ArrayList<String>();
    HashMap<String, Integer> allCombinations = new HashMap<String, Integer>();

    try {
        ReadFile file = new ReadFile(file_name);
        String[] aryLines = file.OpenFile();
        int i;
        //excludes header section of any table as shown in assignment
        for (i=1; i < aryLines.length; i++) { 
            temp.add(aryLines[i]);              
        }
    }
    catch (IOException e) {
        System.out.println( e.getMessage() );
    }

    System.out.println(temp);
    System.out.println(temp.get(0));
    System.out.println(temp.size());

    int i; int j; int l;
    for (i=0; i<temp.size(); i++) {
        String str = temp.get(i);
        StringBuilder sb = new StringBuilder(str);
        int k =0;
        for (j=0; j<=sb.length(); j++) {
            if(sb.charAt(j) == '\"' && k==0) {
                sb.delete(0, j+1);
                k++;
            }
            if(sb.charAt(j) == '\"' && k!=0) {
                sb.delete(j, sb.length());
                String line = null;
                System.out.println(sb);
                for( l=0; l<sb.length(); l++) {
                     String string = Character.toString(sb.charAt(l));
                     if(string.equals(",")) {

                     }
                     else if (l ==0) {
                         products.add(string);
                         line = string;
                     }
                     else {
                         products.add(string);
                         line = line + string;
                     }
                }
                productsPerDate.put(i, line);
                //System.out.println(products);
                break;
            }
        }
    }

    System.out.println(products);
    //Hashmap set to string of 1 letter characters for products per date
    System.out.println(productsPerDate.entrySet()); 

    Set<String> removeDup = new HashSet<>();
    removeDup.addAll(products);
    products.clear();
    products.addAll(removeDup);

    System.out.println(products);


    int maxLength = productsPerDate.get(0).length();
    //determine max length of string in hashmap
    for(int m = 0; m < productsPerDate.size(); m++) { 
        if(maxLength < productsPerDate.get(m).length()) {
            maxLength = productsPerDate.get(m).length();
        }
    }

    //String allLetters //= products.get(0);
    String allLetters = null;
    for(int m=0; m < products.size(); m++) {
        if(m==0) {
            allLetters = products.get(m);
        }
        else {
            allLetters = allLetters + products.get(m);
        }
    }

    //accounts for combination method where each time it will return combinations of 
    for(int n=1; n<=maxLength; n++) { 
        combos = combinations(allLetters, n); //products of length n
        System.out.println(combos);
        int comboSize = combos.size();
        for(int p=0; p<comboSize; p++) {
            StringBuilder sbCombos = new StringBuilder(combos.get(p));


            for(int q=0; q<productsPerDate.size(); q++) {
                StringBuilder sbCompareto = new StringBuilder(productsPerDate.get(q));  //compareto productsPerDate

                threshold(sbCombos, sbCompareto, allCombinations);
            }               
        }

    }   
}

public static ArrayList<String> combinations(String nChars, int k) {
    ArrayList<String> combos = new ArrayList<String>();
    int n = nChars.length();
    if (k == 0) {
        combos.add("");
        return combos;
    }
    if (n < k || n == 0)
        return combos;
    String last = nChars.substring(n-1);
    combos.addAll(combinations(nChars.substring(0, n-1), k));
    for (String subCombo : combinations(nChars.substring(0, n-1), k-1)) 
        combos.add(subCombo + last);

    return combos;
}

public static void threshold(StringBuilder stringBuilder1, StringBuilder stringBuilder2, HashMap<String, Integer> finalHashMap) {
    boolean exist = false;
    for(int q=0; q<stringBuilder1.length(); q++) {
        if(stringBuilder2.indexOf(Character.toString(stringBuilder1.charAt(q))) > -1) {     
            exist = true;
        }
        else {
            exist = false;
            break;
        }
    }
    if(exist = true) {
        String combo = null;
        for(int r=0; r<stringBuilder1.length(); r++) {
            if(r==0) {
                combo = Character.toString(stringBuilder1.charAt(r));
            }
            else {
                combo = combo + Character.toString(stringBuilder1.charAt(r));
            }
        }
        boolean contains = finalHashMap.containsKey(combo);
        if( contains = false) {
            finalHashMap.put(combo, 25);
        }
        else {
            finalHashMap.put(combo, finalHashMap.get(combo)+25);
        }
    }
}

}

Sorry that the code is quite lengthy the assignment wasn't done in the most efficient fashion but please bear with it. The problem is traced to the code segments below:

public static void threshold(StringBuilder stringBuilder1, StringBuilder stringBuilder2, HashMap<String, Integer> finalHashMap) {
    boolean exist = false;
    for(int q=0; q<stringBuilder1.length(); q++) {
        if(stringBuilder2.indexOf(Character.toString(stringBuilder1.charAt(q))) > -1) {     
            exist = true;
        }
        else {
            exist = false;
            break;
        }
    }
    if(exist = true) {
        String combo = null;
        for(int r=0; r<stringBuilder1.length(); r++) {
            if(r==0) {
                combo = Character.toString(stringBuilder1.charAt(r));
            }
            else {
                combo = combo + Character.toString(stringBuilder1.charAt(r));
            }
        }
        boolean contains = finalHashMap.containsKey(combo);
        if( contains = false) {
            finalHashMap.put(combo, 25);
        }
        else {
            finalHashMap.put(combo, finalHashMap.get(combo) + 25);
        }
    }
}

Most specifically at the

boolean contains = finalHashMap.containsKey(combo);
if( contains = false) {
        finalHashMap.put(combo, 25);
}

where the contains inside the if statement is not using the contains declared above so it never first initializing a value of 25 in the finalHashMap and thus every value is null at the end of the code. Can anyone please help? It would be greatly appreciated for the assignment and my personal learning! Thank you!

If (dateTimePicker's date is before this month) then... else

I'm busy making an application in C#. No code yet but what I need to check is if the month in dateTimePicker1 is before this month. If the month in dateTimePicker1 is before the current month it needs to close the app.

Basically what I need is this:

if (dateTimePicker1's month is before current month)
{
    System.Environment.Exit(1);
}
else
{
    //do nothing
}

Read txt file line by line, check if input string matches content of txt file, C#

I am trying to create a login method that checks a text file called accounts.txt that has a string such as "Bob password" already logged in it. The parameters, "login" being command, "Bob" being param1 and "password" being param2

When I run command line arguments, an example would be "login Bob password" the check should read contents of the file line by line until it finds a match and returns "login Bob successful" otherwise say "invaild username/password"

Not sure how to go about this, any tips are appreciated

protected void login(string command, string param1, string param2) // string command "login" string username, string password
{
    // login command
    // Needs to check accounts.txt file for username and password.
    // if username and password exists, provide logon message
    // if username and/ or password does not exist, provide failed logon message.
    // IN MEMORY store current login username and password

    //checks accounts.txt file if username already exists and if there is a match

    if (not sure what arg would go here)
    {

        string path = "C:\\Files\\accounts.txt";
        Console.WriteLine("username and password match", path);
    }
    else
    {
        Console.WriteLine("Login Failed: invaild username or password");
        string path2 = "C:\\Files\\audit.txt";
        using (StreamWriter sw2 = File.AppendText(path2))
        {
        sw2.WriteLine("Login Failed: Invaild username or password");
        }
        throw new FileNotFoundException();
    }
}

IF statement using delayed expansion?

I have a piece of code that looks something like this(Delayed Expansion is enabled):

    for /l %%y in (1,1,%variable%) do (
     set /a rand=!random! * 100 / 32768 + 1
     echo !rand!
     if !rand! GEQ %chance% (
      set /a var=%var%+%varx%
     )
    )

the echo !rand! part displays the number, but if !rand! GEQ %chance% just sees !rand! as a string, not as its value. So even if !rand! is bigger than %chance% it still skips the command.

The weird part is no matter how many times !rand! is greater than %chance% at the end of the loop var increases by %varx% only once. What should be done here so that the IF statement sees !rand!'s value?

How will I know how much Ink I used based on the total papers used

So I wanted to make an IF statement where it will return the total Ink consumption based on the papers used.

One (1) box of Ink = 9,600 papers

What will be the right logic for this?

Here is my Code:

           if($total_papers <= 9600){
                //the number of box will increment
                //so if the total is    19,200 it should return 2 boxes.

            }else{ //not more than 1 box }

Passing parameters in a method, in an if-else statement C#

I am writing a method that can take in a certain number of parameters and contains an if-else statement. When I am using Command Line arguments I am passing in a minimum of 3 parameters and a maximum of 4.

When I run my command line with only 3 parameters it should only run the first part of the if. Only when I have to pass the fourth param it will run else, however everytime I run four parameters the code never makes it to the else and only run the beginning of the if statement. Any ideas are appreciated

protected void net_group(string command, string param1, string param2, string param3)
        {


Console.WriteLine("Got information net group command");

        //creates group.txt file when "net group" command is used
        string path = "C:\\Files\\groups.txt";
        using (StreamWriter sw = File.AppendText(path))
        {
            sw.WriteLine(param2 + ": " + param3); //param2 is name of the group //param3 is name of user
        }
            if (not sure what argument would go here) {

                //writes to the audit log and to the console when group is made w/out users
                Console.WriteLine("Group " + param2 + " created");
                string path2 = "C:\\Files\\audit.txt";
                using (StreamWriter sw2 = File.AppendText(path2))
                {
                    sw2.WriteLine("Group " + param2 + " created");
                }
            }
            else
            {
                //writes to the audit log and to the console when user is added to a new group


//currently the method wont reach here even when I pass four parameters

                Console.WriteLine("User " + param3 + " added to group " + param2 + "");
                string path3 = "C:\\Files\\audit.txt"; //doesnt write this to audit.txt
                using (StreamWriter sw3 = File.AppendText(path3))
                {
                    sw3.WriteLine("User " + param3 + " added to group " + param2 + "");
                }
            }
            Console.Read();

Getting database values in if statement

I have a database which contains multiple phone numbers. I need to check if the database contains a specific number. How do I get the database values in an if statement? Should i use Array List?

This is what i have been doing so far..

@Override
public void onReceive(Context context, Intent intent) {
Bundle bund=intent.getExtras();
String space="";

if(bund!=null) {  
Object[] smsExtra = (Object[]) bund.get(SMS_EXTRA_NAME);

for (int i = 0; i < smsExtra.length; i++) {
SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);
body = sms.getMessageBody().toString();
address = sms.getOriginatingAddress();

db = openOrCreateDatabase("Admindb", MODE_PRIVATE, null);
Cursor crs = db.rawQuery("select * from adminstbl", null);
String[] str= new String[crs.getCount()];
crs.moveToFirst();
for(int k=0;k<str.length;k++)
{
str[k] = crs.getString(crs.getColumnIndex("Number"));
crs.moveToNext();
}

if (address.equals(str)){
 //do my task here
}

(Batch file)Value not expected in IF statement? [duplicate]

This question already has an answer here:

Finally decided to ask a question myself after not being able to find it.

So here's the deal: I'm trying to make a simple settlement management game for my homework assignment in DOS. In it you select an action (looking for food, new settlers) and there's an IF statement inside a FOR loop. The problem is that when the loop starts the first IF statement says that the chance value was unexpected.

Here's the bit of code:

echo how many people to send? set /p ppl= for /l %%y in (1,1,%ppl%) do ( set /a rand=%random% * 100 / 32768 + 1 if %rand% GEQ %foodch% ( set /a food=%food%+%foodc% ) ) set /a fooduse=%ppl%*275 goto turn

where: rand: a random number between 1 and 100; food: total amount of food in the settlement; foodch: the chance for a person to find food(depends on selected difficulty); foodc: the amount of food a person finds if the check passes(depends on selected difficulty)

The problem occurs at if %rand% GEQ %foodch%, where the program says "(value of %foodch%) was unexpected at this time.

Print Line if output is greater than a certain number

I want to print a line of text into a label if the output is past a certain number (in this case 6). I was thinking of using a if, else function but I cant quite figure it out.

Any tips?

Switch Statement and If Statement

Why switch case does not take multiple lines where if do work perfectly

if(indexPath.row == 1){
            UIViewController *viewController = [UIViewController new];
            viewController.view.backgroundColor = [UIColor whiteColor];
            viewController.title = _titlesArray[indexPath.row];
            [self.navigationController pushViewController:viewControlleranimated:YES];
}

same code unable to use in switch case statement

            switch (indexPath.row) {
                case 0:
                    UIViewController *viewController = [UIViewController new];
                    viewController.view.backgroundColor = [UIColor whiteColor];
                    viewController.title = _titlesArray[indexPath.row];
                     [self.navigationController pushViewController:viewControlleranimated:YES];
    break;
                    case 1:
                    break;

                    default
                     break:
}

In switch statement its gives an errors.... I forcibly using if else statement instated of switch case. Can any one advice me how use switch case statment.

foreach and if statement to display custom taxonomies

I am trying to display custom taxonomies but if there are none to display a message.

Here is as far as I have gotten:

<?php
    $terms = get_the_terms( $post->ID , 'machine-features' );
    foreach ( $terms as $term ) {
        if ($term) {
            echo '<li>' . $term->name . '</li>';
        } else {
            echo "Contact us for details";
        }
    }
?>  

It works perfectly when there are features added but when empty I get the following error: Warning: Invalid argument supplied for foreach()

I'm new to php so apologies if this is a crazy basic question - I searched for an answer and tried various permutations but nothing worked!

Thanks a million for any help! O

What is called if 2 bools are true in if/else statements

In a normal if/else statement if one bool, for example, is true it calls that statement e.g:

bool1 = true;
bool2 = false;
bool3 = false;

if(bool1){
    DoSomething();
}else if(bool2){
    DoSomethingElse();
}else{
    DoSomethingHelpful();
}

Of course, in this example DoSomething() will be called.

But what if 2 or 3 of the bools were equal to true, e.g:

bool1 = true;
bool2 = true;
bool3 = false;

if(bool1){
    DoSomething();
}else if(bool2){
    DoSomethingElse();
}else{
    DoSomethingHelpful();
}

What statement will be called? Would it be DoSomething() because its the first statement read by the compiler?Or would it just return with an error

vendredi 27 novembre 2015

Problems with deal or no deal java game

The program is supposed to display a message on whether you have made a good deal or not. It doesn't display anything and I know the problem is something with my "message2" but I can't figure out what it is. I don't know how to get the message to display depending on the deal that the player has made. I have included the relative part of my code.

 public void deal()
{
    dealButton.setEnabled(false);
    noDealButton.setEnabled(false);

    String message = "You have chosen to accept the banker's offer of " + currency.format(bankerOffer) + " \nBut was it a good deal?\nIf we open your case we reveal";
    String message2 = "";


    for(int i = 0; i < unshuffledAmounts.size(); i++)
    {
        if(unshuffledAmounts.get(i).equals(yourCaseAmount))
        {
            yourCaseNumber = i;
        }
    }

    if(bankerOffer > yourCaseAmount)
    {
         message2 = "You made a good deal";
    }
    else
    {
        message2 = "Too bad, you made a bad deal";
    }

How to setup if-statement with multiple conditions, which uses the valid condition's variable in the if-statement?

Okay, that title will sound a bit crazy. I have an object, which I build from a bunch of inputs (from the user). I set them according to their value received, but sometimes they are not set at all, which makes them null. What I really want to do, it make an item generator for WoW. The items can have multiple attributes, which all look the same to the user. Here is my example:

+3 Agility
+5 Stamina
+10 Dodge

In theory, that should just grab my object's property name and key value, then output it in the same fashion. However, how do I setup that if-statement?

Here is what my current if-statement MADNESS looks like:

if(property == "agility") {
    text = "+" + text + " Agility";
}
if(property == "stamina") {
    text = "+" + text + " Stamina";
}
if(property == "dodge") {
    text = "+" + text + " Dodge";
}

You get that point right? In WoW there are A TON of attributes, so it would suck that I would have to create an if-statement for each, because there are simply too many. It's basically repeating itself, but still using the property name all the way. Here is what my JSFiddle looks like: http://ift.tt/1TclvHz so you can play with it yourself. Thanks!

EDIT: Oh by the way, what I want to do is something like this:

if(property == "agility" || property == "stamina" || ....) {
    text = "+" + text + " " + THE_ABOVE_VARIABLE_WHICH_IS_TRUE;
}

Which is hacky as well. I definitely don't want that.