jeudi 30 avril 2015

If-Condition Raising Exception

Is there a way to ask if a statement raises an exception? I'm trying to remove iterables from a list the moment they run out of elements to generate in.

x, iterables = 0, [iter(arg) for arg in args]
while True:
    try:
        if x >= len(iterables):
            break
        for iterable in iterables:
            yield next(iterable)
    except StopIteration:
        x += 1

If statement syntax error (BASH)

I'm trying to get the disk usage of some sites on a server using the script below, but I'm getting this error whenever I try to run it:

args.sh: line 50: syntax error near unexpected token `fi'
args.sh: line 50: `fi'

I can't see any syntax errors, but I'm obviously doing something wrong. Can anyone tell me what's going on?

Here's my code:

#!/bin/bash

prefix="/var/www/html/"
suffix=".example.com"
path="$prefix$1$suffix"
args_length="$#"
paths_array=[]
args_array=("$@")

# If there is one argument, calculate disk usage of given site.
if [ args_length -eq 1];
    then echo "Calculating disk usage..."
    output=$(du -sh $path)
    echo "This site is currently using $output"
    exit 1

# If there are no arguments, calculate disk usage of all sites.
elif [ args_length -lt 1];
    then echo "Calculating disk usage for all sites..."
    # I haven't done this part yet!
    exit 1

# If there is more than one site, calculate their disk usage    
elif [ args_length > 1];
    then echo "Calculating disk usage for selected sites..."    
    #Save arguments to sites_array
    for x in args_array; do
        paths_array[x] = args_array[x]
    done
    #Loop through array, creating paths.
    for i in paths_array; do
        site = paths_array[i]
        paths_array[i] = "$prefix$site$suffix"
    done
    #Print out disk usage for each path in array.
    for y in paths_array; do
        output = $(du -sh $paths_array[y]) 
        echo "This site is currently using $output"
fi

Side Note: For the section that I haven't written yet, can anyone tell me how I should go about saving the names of all the folders in the current working directory to an array? I've heard that parsing the output of 'ls' is a bad idea, so I'm looking for an alternative to that if anyone has one.

I can't get my else to work php mysql

I have a function to get the tire size from the database and display it. The else, which should function when the size isn't in the database, isn't working. Any help will be appreciated: Here is my code for the function:

 function tiresize() {
    global $db;

    if (isset($_POST['size'])) {
        $_SESSION['size'] = $_POST['size'];
        $size = $_SESSION['size'];
        // $size=mysql_real_escape_string($size);
        // trim($size);
    }


    if (isset($size)) {
        $query = $db->prepare("SELECT size FROM tires WHERE size = '$size'");
        $query->execute();

     $tires = $query->fetchAll();
        if (isset($tires)) {
            echo "<ul>";
            foreach ($tires as $name) {
                echo "<li id='tiresearch'>";
                echo "Tire Size is Available: " . $name['size'];
                echo "</li>";
            }
     } else {
            echo "Tire size was not found";
         echo "</ul>";
        }
 }
 }

Laravel Blade Foreach

I am developing for an application. I have an array of folder_data then I want that for same file_names will be displayed only once. I would appreciate your help.

This is my code:

@foreach($files['folders'] as $file)
                <tr>
                <td><input type="checkbox" name="check_list[]" value="{{$file['file_id']}}"></td>
                  <td>
                    <a href={{url("/home/".$file['file_name'])}}>
                      {{ $file['file_name'] }}
                    </a>
                  </td>
                  <td class="center">{{ $file['file_type'] }}</td>
                </tr>
              @endforeach

mysql subquery as if condition ( only if needed )

I want to perform a textsearch on a table containing posts belonging to topics within groups. Depending on the privacysettings for these groups I need to run a subquery to check if the requesting user is a member of the groups containg search matches.

Databasescheme:

Table: posts
Columns: id, group_id, title, text

Table: groups
Columns: group_id, privacy

Table: group_memberships
Columns: group_id, is_member

The privacy column in the group table contains an integervalue.

1 = public, anyone can access the data    
2 = system, anyone can access the data
3 = private, only members can access the data

What the query should do:

1. Find some matches in the post table
2. Check the group privacy in the groups table -> a value HIGHER THAN 2 requires a membership check
3. Do a membership check on the group_memberships table if required

I really don't know how do handle this.

It looks like mysql supports two ways? IF statements and case expressions?

What would be a correct way for this?

PS: The subquery for membership checking should be optional and only firing if needed.

How do i detect if a number is a decreasing or increasing number? iOS

I'm using a SpriteKit game engine within XCode while developing a game that bounces a ball and platforms come from the sky and the objective is to bounce on the platforms to get higher. I need to add a velocity to the ball when it falls down + comes in contact with a platform. I'm having trouble trying to detect the balls Y position. I had something like this in the update method but nothing happens?... I'm open to suggestions.

//The value of the _number instance variable is the Y position of the ball.

if (_number++) {
        NSLog(@"UP");
    }


    if (_number--) {
        NSLog(@"DOWN");
    }

how to use php && operator multiple times

if((in_array($sfname, $string)
&&(in_array($slname, $string)
&&in_array($sage, $string)
&&(in_array($sZipcode, $string))
{
    echo  " is in thefile.txt";
} else {
    echo  " is not in thefile.txt";
}

I need some help

Cannot Find Symbol Error with event handler

I am having trouble trying to initialize a variable correctly. Earlier I was getting a Number Format Exception because I was parsing an integer inside of an empty text field. Now I have created an if statement that checks first to see if the field is empty, then parses an integer inside of it. The problem i'm having now is that my event handler can't recognize the variable, because it is inside the if statement. I tried declaring it outside of the if statement but that didn't work either. Any tips to point me in the right direction? Here is my code:

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicReference;

public class Main extends Application {

   @Override
   public void start(Stage primaryStage) {

      ArrayList<Integer> deck;
      deck = new ArrayList<>();
      int i = 1;
      while(i < 52){
         deck.add(i);
         i++;
      }
      final AtomicReference<String> result = new AtomicReference<>("go.");

      Collections.shuffle(deck);

      BorderPane pane = new BorderPane();

      HBox top = new HBox(10);
      Label display = new Label(result.toString());
      Button btShuffle = new Button("Shuffle");
      btShuffle.setOnAction(
            e -> {
               Collections.shuffle(deck);
            });
      top.getChildren().add(display);
      top.getChildren().add(btShuffle);

      HBox center = new HBox(10);
      Card card1 = new Card(deck.get(0));
      center.getChildren().add(card1);

      Card card2 = new Card(deck.get(1));
      center.getChildren().add(card2);

      Card card3 = new Card(deck.get(2));
      center.getChildren().add(card3);

      Card card4 = new Card(deck.get(3));
      center.getChildren().add(card4);

      HBox bottom = new HBox(10);
      Label expression = new Label("Please Enter the expression: ");

      TextField tfExpress = new TextField();
      LinkedList<Object> expInput = new LinkedList<>();
      ArrayList<Character> signs = new ArrayList<>();
      signs.add('/');
      signs.add('+');
      signs.add('(');
      signs.add(')');
      signs.add('-');
      signs.add('^');
      signs.add('*');
      signs.add('%');
      String str = tfExpress.getText();
      char tempStor[] = str.toCharArray();
      for(char c: tempStor){
         expInput.add(c);
      }

      if(tfExpress.getText() != null && tfExpress.getText().equals(""))
      {
         int express = Integer.parseInt(str);
      }

      expInput.removeIf(p-> p.equals(signs));

      Button btVerify = new Button("Verify");
      btVerify.setOnAction(
            (ActionEvent e) -> {
               if(card1.CardValue() == (int)expInput.get(0)
               && card2.CardValue() == (int)expInput.get(1)
               && card3.CardValue() == (int)expInput.get(2)
               && card4.CardValue() == (int)expInput.get(3)){
                  if(express == 24){
                     result.set("Correct");
                  }
                  else
                     result.set("Incorrect");

               }
               else
                  result.set("The numbers in the expression don't "
                     + "match the numbers in the set.");
            });

      pane.setTop(top);
      pane.setCenter(center);
      pane.setBottom(bottom);

      Scene scene = new Scene(pane);
      primaryStage.setTitle("24 card game");
      primaryStage.setScene(scene);
      primaryStage.show();
   }

   public class Card extends Pane {
      public int cardVal;
      Card(int card){
         Image cardImage;
         cardImage = new Image("card/"+ card +".png");
         cardVal = card;
      }

      public int CardValue(){
         int card = 0;

         if(cardVal <= 13){
            card = cardVal;
         }
         else if(cardVal > 13 && cardVal <= 26){
            card = cardVal - 13;
         }
         else if(cardVal > 26 && cardVal <= 39){
            card = cardVal - 26;
         }
         else if(cardVal > 39 && cardVal <= 52){
            card = cardVal - 39;
         }         
         return card;
      }
   }
   public static void main(String[] args) {
      launch(args);
   }
}

Counting data that is valid to two conditions in columns 1 and 2

I am trying to run the following loop, the two while statements work, but the @ c awk line seems to be causing me some problems.

printf "" >! loop.txt

@ x = -125
while ($x <= -114)
    @ y = 32
    while ($y <= 42)
        @ c =`awk '{ for ($1 = $x*; $2 = $y*){count[$1]++}}' text.txt`
    printf "$x $y $c\n" >> loop.txt
    @ y++
    end
@ x++
end

With the awk line, I am trying to reference a file with lots of differing values in columns 1 and 2 of the text.txt file. I want to be able to firstly reference all of the values in column 1 that start with $x (as they all have several decimal places), then reference from that sub-list all of the values in column 2 that begin with $y. After this second sub-list has been formed, I would like to count all of the entries valid to those conditions. However, I keep getting syntax errors with the line, and I'm not sure that I'm using the correct function!

JavaScript and Jquery If Statment Append

Ok so I have a list and some of the text inside the list is to long so I want to use JavaScript and Jquery to trim the text and add ... to the end of the test if its longer than 30 characters.

<ul>
    <li><a href="#">Long List item Long List item Long List item </a></li>
    <li><a href="#">Smaller List item</a></li>
    <li><a href="#">item</a></li>
</ul>

My Jquery at the moment:

$(function(){
    $("ul li a").html(function(){
        return $(this).html().substring(0,30);
    });
    $('.box ul li a').append(' ...');
});

This works but I want to add maybe an IF statment to only add the ... if the length of the text inside of the tag is more than 30 characters. How would I go about doing that?

Thanks

why my if statement does not work

Even if the requirement of if statement is true, the Console.WriteLine does not print anything. How should I change here? I need that the program prints next string after div class="trans" lang="ru" and stops before it encounters /div>

string line =string.Empty;

        using(StreamReader sr = new StreamReader("d:/test.txt"))
            try
            {
                while (true)
                {
                    line = sr.ReadLine();


                    if (line == null)
                    {
                        break;
                    }

                    if (line.StartsWith("<div class=\"trans\" lang=\"ru\">"))
                    {
                        Console.WriteLine(line);
                        if (line.StartsWith("</div>"))
                        {
                            break;
                        }
                    }

                }

            }

if statement, SSH and executing remote commands

I'm writing some code that currently SSH to several servers in turn and remotely tests to see if a process is running. The end goal is for me to receive an email alert if the process is not running. I have that much working.

However, I also want a warning if the SSH connection fails. Trouble is, no matter what I try, I cannot get it to work with my current code of if, the, else.

#!/bin/sh
filename="/root/scripts/sysmon_server_lists.txt"
identity="/root/.ssh/sysmon"
OLDIFS=$IFS
IFS=,

while read -r server searchtxt;
do
        if [ ! -z $server ]
        then
                if [ `ssh -n -q -t -i $identity root@$server "ps -ef | grep $searchtxt | grep -v grep | wc -l"` -gt 0 ]
                        then
                                echo "Process is running on $server."
                        else
                                echo "Process is not running on $server."
                        fi

                echo "Server is $server"
                echo "Searchtext is $searchtxt"
                echo " "
                echo "-----"
                echo " "
        fi
        done < $filename

IFS=$OLDIFS
echo "Finished"

exit 0

Why is this Array.length if else check not working?

enter image description here

Obviously tagObjects is an array and has a length of 0. However it's still getting past that check and causes an error.

TypeError: Cannot read property 'length' of undefined

if (tagObjects != "empty" || tagObjects.length === 0) {
    for (var i = 0; i < tagObjects.tags.length; i++) {
        temp_tags.push(tagObjects[i].tags);
    }

    temp_tags.forEach(function(obj) {
        if (obj.selected) {
            if (vs.tags[map[obj.term]] != undefined) {
                vs.tags[map[obj.term]].selected = true;
            }
        }
    });
}

It's even getting past the string check!

enter image description here

display a value of an object that exists in the session into jsp page

Hi every one i have an object in my session and i wanna select an input type radio according to the attribut of my object i tried the if tag of struts 2 taglib and it doesn't work. here is a part of my code

  <div class="form-group">
            <label class="col-sm-2 control-label">Admin </label> <label
                class="radio-inline">
                <div class="choice">
                    <s:if test="%{#session.curentprofil.isAdmin == N}">
                        <span><input type="radio" name="isAdmin" id="isAdmin"
                            class="styled" value="O" /></span>
                    </s:if>
                </div> O
            </label> <label class="radio-inline"> <span><input
                    type="radio" name="isAdmin" id="isAdmin" checked="checked"
                    class="styled" value="N" /></span> N
            </label>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">Admin </label> <label
                class="radio-inline">
                <div class="choice">
                    <s:if test="%{#session.curentprofil.isAdmin == O}">
                        <span><input type="radio" name="isAdmin" id="isAdmin"
                            class="styled" value="O" checked="checked" /></span>
                    </s:if>
                </div> O
            </label> <label class="radio-inline"> <span><input
                    type="radio" name="isAdmin" id="isAdmin" class="styled" value="N" /></span>
                N
            </label>
        </div>

How to compare user input values with arraylist items?

I have one edittext in my app,now I have three values in arraylist [10,15,20],and I want compare this values with user input,...suppose if user enters 9 in edittext it should not go inside if statement..following is my code..with this code issue is if i enter 9 it goes to else part and if i enter 11 then also it goes to else part

    bxqtyy.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

                for(int k=0;k<allqtys.size();k++)
                {

                    allqtys.get(k);
                    System.out.println("sawsaw"+allqtys);

                if(Integer.parseInt(bxqtyy.getText().toString()) >= allqtys.get(k))
                {

                    //uprice.setText("1470");
                    System.out.println("lets check"+Integer.parseInt(bxqtyy.getText().toString()));
                }
                else
                {
                    //uprice.setText("1500");
                    System.out.println("lets uncheck");
                }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

Form inputs with sweet alert and jquery

I have a form with two states. In first state required inputs are fill and in the second state are empty. I use sweet alert to show result of input, but if-else don´t work properly. My form code is

<link rel="stylesheet" type="text/css" href="http://ift.tt/1EUgO2B"/>
       <form method='post'>
            <input type="text" name="nombre" id="nombre" autofocus required placeholder="Escribe tu nombre (Obligatorio)"/>
            <br>
            <input type="mail" name="mail" id ="mail" required placeholder="Escribe tu correo (Obligatorio)">
            <br>
            <input type="tel" name="telefono" placeholder="Escribe tu teléfono" />
            <br>
            <textarea rows="5" cols="35" name="mensaje" id="mensaje" required placeholder="Escribe tu mensaje (Obligatorio)"  /></textarea>
            <br>
            <input type="submit" id="enviar" value="Enviar" />
        </form>

And my jquery code

 <script src="http://ift.tt/1yCEpkO"></script>
 <script src="http://ift.tt/1EUgO2F"></script>
                    $("#enviar").click(function () {
                    if ($("#nombre").is(':empty')){
                        swal({
                            title: "Datos incorrectos.",
                            text: "No se ha enviado el correo.",
                            type: "warning", 
                            allowOutsideClick: false,
                            timer:5000,
                        });
                    }
                if ($("#nombre").not(':empty')){
                 swal({
                    title: "Correcto.",
                    text: "Se ha enviado el correo.",
                    type: "success", 
                    allowOutsideClick: false,
                    timer:5000,

                });
             }
        });

Any idea?

How can i make my JavaScript recognise multiple choices from check boxes

For an assignment I am matching user preferences to mobile phone contracts and outputting the matches.

In regards to the network of the contract i want the user to be able to select as many different networks as they like and the program will output any contracts from those network providers. I have it working so it will output a match if only one check box is checked but i am unsure how to modify it so that it will interpret multiple choices and output any contracts with those choices. This is my code so far:

   //Check Network
var userNetwork ="";
var networkForm=document.getElementById("userNetwork");
if(networkForm.NN.checked){
    userNetwork="NN";
}
if(networkForm.Othree.checked){
    userNetwork="03";
}
if(networkForm.Fodavone.checked){
    userNetwork="Fodavone";
}
if(networkForm.ZMobile.checked){
    userNetwork="Z-Mobile";
}


for (var c = 0; c < cont.length; c++) {
    if (userNetwork === cont[c].network || userNetwork === "") {

IF == not working for lists in python. No idea what I am doing wrong. A print() of the data reveals they are equal...what am I missing?

So, here is my code. It is meant to take answers from a user. Store their answers in a list (answerlist. Compare their answers to a list made from the lines of a answers.txt file.

The problem is, altough they ARE the same (looking at a print() output), the script does not see them as though:

import time
import os

answerlist = []
check = "N"
score=0
real_answerlist=[]
checkanswerlist=[]



name = input("\nWhat is your FIRST name?\n")
surname = input("\nWhat is your SECOND/surname?\n")
classname = input("\nWhat is your class (e.g. \"8A\")\n")
while check != "Y":
    print("Are these detail correct? : "+name + " "+surname+" " + classname+"\n")
    check = input("Enter (Y or N)\n")


#ASK QUESTIONS

for i in range(1, 11):
    answerlist.insert(i,input("The answer to question "+str(i)+" is: \n"))


#show answers
for i in range (1, 5):
    print("Your answers will be shown below in "+str(5-i)+"seconds... ")
    time.sleep(1)
    os.system('cls')

for i in range(0,len(answerlist)):
    print(str(i+1)+": "+answerlist[i])

#Ask if want any answers changing?

while check != "N":
    check=input("\n Do you want to change any answers? (Y or N)\n")
    if check!="N":
        question_to_correct=input("Which question do you want to change?\n")
        corrected_answer=input("What do you want to change your answer to?\n")
        answerlist[int(question_to_correct)-1]=corrected_answer
        print("Here are your answers...")
        for i in range(0,len(answerlist)):
            print(str(i+1)+": "+answerlist[i])

#Place result in to text file:
string_to_write=",".join(answerlist)

f = open("Y8Answers.csv","a") #opens file with name of "username"
f.write("\n"+name+","+surname+","+classname+","+string_to_write)
f.close()


print("Test completed.")

#show results
for i in range (1, 3):
    print("Your answers will be shown below in "+str(5-i)+"seconds... ")
    time.sleep(1)
    os.system('cls')

p=0;
with open("answers.txt") as f:          #Shove all the real answers from answers.txt in to a list "real_answerlist".
        for line in f:
            real_answerlist.append(line)

        for i in range (0,len(answerlist)):             #if their answer == answer in list, add one to score.
            if str(answerlist[i])==str(real_answerlist[i]):
                score=score+1
                print(answerlist[i]+" "+real_answerlist[i])
            else:
                print("Question "+str(i+1)+" is incorrect."+" Your answer: "+str(answerlist[i])+" real is: "+str(real_answerlist[i]))

print (score)

Contents of "answers.txt":

A
B
C
D
E
F
G
H
I
J
K

And my output when he script is run (after answering with the correct answers) is:

Question 1 is incorrect. Your answer: A real is: A

Question 2 is incorrect. Your answer: B real is: B

Question 3 is incorrect. Your answer: C real is: C

Question 4 is incorrect. Your answer: D real is: D

Question 5 is incorrect. Your answer: E real is: E

Question 6 is incorrect. Your answer: F real is: F

Question 7 is incorrect. Your answer: G real is: G

Question 8 is incorrect. Your answer: H real is: H

Question 9 is incorrect. Your answer: I real is: I

Question 10 is incorrect. Your answer: J real is: J

0

Process finished with exit code 0

Thanks for any help! I am sure it will be something simple as I am pretty noobish (as you may tell from my bad code :P)!

mercredi 29 avril 2015

If the user input is null or invalid, how can I make the code not do the next step

I have a data form and when the submit button is clicked, I'm checking if the user input in EditText is null or invalid. I want to make my code not go to confirmation window until the user input is not null and valid. How can I do this?

private void ifEmpty(EditText et, String message) {
    if (TextUtils.isEmpty(et.getText())) {
        Toast.makeText(MainActivity.this, message + "を入力してください。",     Toast.LENGTH_SHORT).show();
        return;
    }
}

private void ifEmptyAndNum(EditText et, String message) {
    if (TextUtils.isEmpty(et.getText())) {
        digitsOnly(et);
        Toast.makeText(MainActivity.this, "数字を入力してください。", Toast.LENGTH_SHORT)
                .show();
        Toast.makeText(MainActivity.this, message + "を入力してください。", Toast.LENGTH_SHORT)
                .show();
        return;
    }
}


@Override
public void onClick(View v) {
    ifEmpty(etName, "Name");
    ifEmptyAndNum(etAge, "Age");
    ifEmpty(etAddress, "Address");
    ifEmptyAndNum(etTel, "Phone Number");

    Intent intent = new Intent(this, ViewActivity.class);

    intent.putExtra("name", etName.getText().toString());
    intent.putExtra("age", etAge.getText().toString());
    intent.putExtra("address", etAddress.getText().toString());
    intent.putExtra("tel", etTel.getText().toString());
    startActivity(intent);

Run a script if not already running - getting [0: not found

I'm trying to run a script if not already running using another script.

test $ ls
arcane_script.py  calling_script.sh

This is what my script looks right now

test $ cat calling_script.sh 
#!/bin/bash

PROCESSES_RUNNING=$(ps -ef | grep "arcane_script.py" | grep -v "grep" | wc -l)
echo $PROCESSES_RUNNING
if [$PROCESSES_RUNNING = "0"]; then
    /usr/bin/python arcane_script.py
fi;

I've tried other variants within the if block, like [$PROCESSES_RUNNING -eq 0], but all of them output the same error message

test $ ./calling_script.sh 
0
./calling_script.sh: line 5: [0: command not found
test $ sh calling_script.sh 
0
calling_script.sh: 5: calling_script.sh: [0: not found

What am I doing wrong and how can I resolve it? I've googled around, but couldnt find much help.

Using another excel function in [Value if True] in IF function

Hi i have tried to insert a formula in [value if true] in excel IF function, but for some reason its not working. Hers the formula i have used

=IF((AND(ISBLANK(J3),ISBLANK(U3)))=FALSE,=NETWORKDAYS(J3,U3)," ")

Thanks in Advance

MySQL select specific value from duplicated rows

I have table like this

id name       value

1  Leo        0
2  Ethan      0
3  Claire     0
4  Leo        1
5  Claire     1
6  Ethan      0

I would like to get result like below:

id name       value

2  Ethan      0
4  Leo        1
5  Claire     1

It looks pretty easy but I have struggled with it for hours, please advise and give hints. thanks.

I need to nest an if condition inside another one

I have a macro that works fine pasting an array in a colum, now I want to paste a new array in the second colum, the problem is that to paste the value it has to fulfill some conditions, so I have to nest an if condition inside another one, it gives me no error but it doesnt work... this is what I have:

    Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A:A, L:L")) Is Nothing Then
    On Error GoTo Fìn
    Application.EnableEvents = False
    Dim i As Long, n As Long
    Dim arrmatrix As Variant
    ReDim arrmatrix(1 To 1, 1 To 1)
    For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
        If Cells(i, 12).Value = "Pi emitida" Then
            n = n + 1
            ReDim Preserve arrmatrix(1 To 1, 1 To n)
            arrmatrix(1, n) = Cells(i, 1).Value
        End If
    Next i
    With Worksheets("Inicio")
        .Range("G4:G" & Rows.Count).ClearContents
        .Range("G4").Resize(UBound(arrmatrix, 2), 1) =   Application.Transpose(arrmatrix)
    End With
    End If
    If Not Intersect(Target, Range("A:A, Q:Q,L:L")) Is Nothing Then
    On Error GoTo Fìn
    Application.EnableEvents = False
    Dim j As Long, m As Long
    Dim arrmatrix1 As Variant
    ReDim arrmatrix1(1 To 1, 1 To 1)
    For j = 2 To Cells(Rows.Count, 1).End(xlUp).Row

  'THIS IS THE PROBLEM.....!!!!!!!!!!!!!!!
    If Cells(j, 12).Value = "Pi emitida" Or Cells(j, 12).Value = "PI    firmada" Or Cells(j, 12).Value = "Carta credito L/c" Or Cells(j, 12).Value =  "Con booking" Then
        If DateDiff(d, Cells(j, 17).Value, Today) > 0 Then

            m = m + 1
            ReDim Preserve arrmatrix1(1 To 1, 1 To m)
            arrmatrix1(1, m) = Cells(j, 1).Value
        End If


    Next j
    With Worksheets("Inicio")
        .Range("H4:H" & Rows.Count).ClearContents
        .Range("H4").Resize(UBound(arrmatrix1, 2), 1) =    Application.Transpose(arrmatrix1)
    End With
End If

 Fìn:
Application.EnableEvents = True
End Sub

if, else if, else statements: Within the blocks of code

I am a beginner programmer, and am currently banging my head against the wall over this assignment. I have to create a program that 'simulates' the use of a car, so it goes: drive, park, and fill up. The first thing it does is ask for how many litres of gas your tank can hold, and how many litres is currently in the tank. Then, it asks the user if it wants to a) drive, b) fill up, or c)park. I need to grab a user input (which I already know how to do), and depending on whether the user enters a,b, or c, it goes to this certain block of code and runs it.

Here are the specific instructions on what a, b, and c have to do: a) Drive: 1. enter the amount of Km driven (user inputs this) 2. Output how many litres of gas were used, and the amount of gas remaining in the tank. (we assume the car uses an average of 0.1 L/Km)

b) Fill up 1. User must enter the number of litres they wish to add 2. Output number of litres in tank. (the user can't input more litres than the tank can hold)

c) Park 1. Output number of litres in tank, and total number of Km driven. 2. This exits the loop

Am I using the right kind of loop? How do I get the code to run an equation (look at the red underlined lines)? Please help me, I'm so lost.

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("How many litres of gas can your tank hold?");
    int litreCap = scan.nextInt();
    System.out.println("How much gas is currently in your tank?");
    int startingLitre = scan.nextInt();
    System.out.println("Ok! Do you want to \n a) Drive \n b) Fill up, or \n c) Park");
    String abc = scan.next();
    String a, b, c;
    a = String.valueOf(1); //Wasn't sure if the problem had to do with the fact
    b = String.valueOf(2); //That I hadn't identified a,b and c
    c = String.valueOf(3);
    double litresUsed, gasTotal;

    if (abc .equals(a)) { //this is the drive section
        System.out.println("Please enter the amount of Kilometers driven.");
        int KmCount = scan.nextInt();
        litresUsed = 0.1*KmCount;//underlined yellow
        startingLitre - litresUsed = gasTotal;//this is underlined red
      }
    else if (abc .equals(b)){ //this is the fill up section
        System.out.println("OK! Please enter how many litres you are going to add.");
        int litresAdded = scan.nextInt(); //this is underlined yellow
        litresUsed + litresAdded = gasTotal; //underlined red
    }
    else {
        //enter c) Park code here
    }
}

}

Python, can I iterate through a list within an if statement?

I am trying to edit a str (myString) based on user input str (userInput). There are already a known set of subStrings that myString may or may not contain and are put into a list of str (namingConventionList) that, if any are used in myString should be replaced with userInput. If none of the set of naming conventions are used, I want the userInputadded to myString in a couple of different ways depending on if and where an underscore ("_") is. Is there a way to iterate through namingConventionList in an if statement?

        if myString.count(conv for conv in namingConventionList):
            myString= myString.replace(conv, userInput))
        elif userInput.startswith('_'):
            myString= '%s%s' % (name, userInput)
        elif userInputConvention.endswith('_'):
            myString= '%s%s' % (userInput, name)
        else:
            myString= '%s_%s' % (name, userInput)

Prevent Empty EditText Field

How is it possible to prevent my app from crashing when my EditText field is empty?

    public class Credits extends Activity {
    int inaugural = 1992;
    int differenceInYears;
    int userGuess;
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    int output;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_credits);
        final EditText Guess=(EditText)findViewById(R.id.txtYearGuess);
        Button go = (Button)findViewById(R.id.btnCalculate);
        final TextView result = ((TextView)findViewById(R.id.txtResult));

        go.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                int userGuess= Integer.parseInt(Guess.getText().toString());
                differenceInYears = year - inaugural;
                output = userGuess - differenceInYears;

                if (output < -1) {
                    result.setText("Guess again! You guessed too low!");

                    }

                else if (output == 1) {
                    result.setText("You're REALLY close! You guessed too high!");


                    }

                else if (output == -1) {
                    result.setText("You're REALLY close! You guessed too low!");


                    }

                else if (output > 1) {
                    result.setText("Guess again! You guessed too high!");


                    }

                else {
                    result.setText("Good job! You're an FRC Genious!");

                    }



            }

        });
    }

}

Is it as simple as having another if statement watching for an "empty" variable? If so, what would the code for that look like? I'm sort of at a loss for ideas in preventing this crash from happening. If there is any sort of report from Eclipse that could help answer this question, please let me know where to find it.

Thanks!

Display images from a chosen array based on radio button selection?

  • Arrays

var surffamous = new Array;

surffamous[0] = "teahupoo.jpg"
surffamous[1] = "blacks.jpg"
surffamous[2] = "supertubes.jpg"
surffamous[3] = "pipeline.jpg"

var surfsocal = new Array;

surfsocal[0] = "lajolla.jpg"
surfsocal[1] = "oceanside.jpg"
surfsocal[2] = "delmar.jpg"
surfsocal[3] = "cardiff.jpg"

var surfcentralcal = new Array;

surfcentralcal[0] = "rincon.jpg"
surfcentralcal[1] = "leocarillo.jpg"
surfcentralcal[2] = "elcapitan.jpg"
surfcentralcal[3] = "hollister.jpg"

<form style="color: #2D5059">
<p>Where would you like to explore?</p< <br> <br>
<input type="radio" name="spot" id="socal" value="southern">Southern California
<input type="radio" name="spot" id="central" value="central">Central California
<input type="radio" name="spot" id="famous" value="famous">Famous Spots
</form>

  • Javascript

    function check() { for(i=0; i ' + ''); }
        else if(document.getElementById('central').checked) {
    document.write('<img src="'+  surfcentralcal[i] +'"/> ' + '</a>');
        }
    
        else if(document.getElementById('famous').checked) {
    document.write('<img src="'+  surffamous[i] +'"/> ' + '</a>');
        }
    
      }
    
    

Javascript if statement, function is not called

I found a very nice code here to preload images into application. Which works great.

// PRELOAD IMAGES
function loadImages(sources, callback) {

  var loadedImages = 0;
  var numImages = 0;
  // get num of sources
  for(var src in sources) {
    numImages++;
  }
  for(var src in sources) {
    images[src] = new Image();
    images[src].onload = function() {
      if(++loadedImages >= numImages) {
        callback(images);
      }
    };
    images[src].src = sources[src];
  }
}


var sources;
sources = {

  img1: "....../img1.png",
  img2: "....../img2.png",

};

But when i try to call loadImages() from if statement inside for loop, for whatever reasons the function is not called. Everything else works as intented i.e. iteration, conditions, etc. Code is below:

      if (data[j].FlImg === 'img2') {

    alert (j) // just to be sure it gets here, it does.

    loadImages(sources, function (images) {

      alert(j +'-this line is not executing')

      ctxGameBoard.drawImage(images.img2, 0, 0, 100, 100);

    });

Any suggestions greatly appreciated.

Error in logic for year comparison tool

I'm attempting to create a tool that compares the current year to the year that an event took place and then allows the user to guess how many years it has been since that event occurred. For example, the inaugural FRC Championship took place in 1992. The current year is 2015. The user guesses that it took place 23 years ago, which is correct.

So, in my mind the code would look like this...

  public class Credits extends Activity {
    int inaugural = 1992;
    int guess;
    int differenceInYears;
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    int output;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_credits);
        final EditText yearGuess=(EditText)findViewById(R.id.txtYearGuess);
        Button go = (Button)findViewById(R.id.btnCalculate);
        final TextView result = ((TextView)findViewById(R.id.txtResult));
        go.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                int userGuess= Integer.parseInt(yearGuess.getText().toString());
                differenceInYears = year - inaugural;
                output = userGuess - differenceInYears;

                if (output < 1) {
                    result.setText("Guess again! You guessed too low!");
                }

                else if (output == 1) {
                    result.setText("You're REALLY close!");

                }

                else if (output == -1) {
                    result.setText("You're REALLY close!");

                }

                else if (output > 1) {
                    result.setText("Guess again! You guessed too high!");

                }

                else {
                    result.setText("Good job! You're an FRC Genious!");

                }
            }

        });
     }
    }

...however, the values continue to come out wrong when tested. What am I missing here? Is there something wrong with my math? or code? or both?

Little assistance with my tic-tac-toe program

I need some help with my tic-tac-toe game that I created in Python 3. Have a look at my fun program and try it out. After that, please help me creating a while statement in my program. That is while the user choice of square if filled, you should continue to ask them until they choose an empty square. When the choose an empty square, the program continues as before. I am not used to the while statements, please help me on this!

Here is my program:

from turtle import *

def setUp():
#Set up the screen and turtle
    win = Screen()
    tic = Turtle()
    tic.speed(10)
#Change the coordinates to make it easier to tranlate moves to screen coordinates:
    win.setworldcoordinates(-0.5,-0.5,3.5, 3.5)

#Draw the vertical bars of the game board:
    for i in range(1,3):
       tic.up()
       tic.goto(0,i)
       tic.down()
       tic.forward(3)

#Draw the horizontal bars of the game board:
    tic.left(90)    #Point the turtle in the right direction before drawing
    for i in range(1,3):
        tic.up()
        tic.goto(i,0)
        tic.down()
        tic.forward(3)

    tic.up()        #Don't need to draw any more lines, so, keep pen up

#Set up board:
    board = [["","",""],["","",""],["","",""]]

    return(win,tic,board)

def playGame(tic,board):
#Ask the user for the first 8 moves, alternating between the players X and O:
    for i in range(4):
        x,y = eval(input("Enter x, y coordinates for X's move: "))
        tic.goto(x+.25,y+.25)
        tic.write("X",font=('Arial', 90, 'normal'))
        board[x][y] = "X"

    x,y = eval(input("Enter x, y coordinates for O's move: "))                 
    tic.goto(x+.25,y+.25)
    tic.write("O",font=('Arial', 90, 'normal'))
    board[x][y] = "O"

# The ninth move:
    x,y = eval(input("Enter x, y coordinates for X's move: "))
    tic.goto(x+.25,y+.25)
    tic.write("X",font=('Arial', 90, 'normal'))
    board[x][y] = "X"

def checkWinner(board):
    for x in range(3):
        if board[x][0] != "" and (board[x][0] == board[x][1] == board[x][2]):
            return(board[x][0])  #we have a non-empty row that's identical
    for y in range(3):
        if board[0][y] != "" and (board[0][y] == board[1][y] == board[2][y]):
            return(board[0][y])  #we have a non-empty column that's identical
    if board[0][0] != "" and (board[0][0] == board[1][1] == board[2][2]):
        return(board[0][0])
    if board[2][0] != "" and (board[2][0] == board[1][1] == board[2][0]):
        return(board[2][0])   
    return("No winner")

def cleanUp(tic,win):
#Display an ending message: 
    tic.goto(-0.25,-0.25)
    tic.write("Thank you for playing!",font=('Arial', 20, 'normal'))

    win.exitonclick()#Closes the graphics window when mouse is clicked


def main():
    win,tic,board = setUp()   #Set up the window and game board
    playGame(tic,board)       #Ask the user for the moves and display
    print("\nThe winner is", checkWinner(board))  #Check for winner
    cleanUp(tic,win)    #Display end message and close window


main()

Comparing float values in bash

Hi I would like to compare 2 float numbers in bash but I haven't find anything that works properly. My actual code is the following:

  if [ $(echo " 0.5 > $X " | bc -l )==1 ]
  echo grande
  fi
  if [ "$(bc <<< "$X - 0.5")" > 0 ] ; then
  echo 'Yeah!'
  fi

What happens is that no matter if the X is bigger or smaller than 0.5, it always echos both sentences and I don't know why. I know the X is bigger or smaller than 0.5 because I also echo it and I can see it.

if...else...if executes final else for all conditions

I'm new to Java and trying to do an assignment using the if...else...if statement. Seems simple enough, however, the final "else" statement (the default) executes no matter if the other conditions are true or not. In other words, for all conditions, the code returns 0.

Here's my code:

public class Choice {

private int type; //stores the choice type: 0=rock, 1=paper, 2=scissors
private ColorImage choiceImage; //stores the image to be displayed on the canvas

public Choice(int type)
{
    //initialize the "type" instance varialble
    this.type = type;
}

/**
 * Get a number that represents the choice type
 * 
 * @return  a number that represents the choice type: 0=rock, 1=paper, 2=scissors
 */
public int getType()
{
    return type;
}

/**
 * Compare "this" with anotherChoice
 * 
 * @param   anotherChoice   the choice to be compared
 * @return  either 1, -1, or 0 which indicates the comparison result: 1 means "this" wins anotherChoice; -1 means "this" loses to anotherChoice; 0 means "this" and anotherChoice are the same
 */
public int compareWith(Choice anotherChoice)
{
    if ((this.type == 0) && (type == 1))
        return -1;
    else if (this.type == 0 && type == 2)
        return 1;
    else if (this.type == 1 && type == 0)
       return 1;
    else if (this.type == 1 && type == 2)
       return -1;
    else if (this.type == 2 && type == 0)
       return -1;
    else if (this.type == 2 && type == 1)
       return 1;
    else
    return 0;
}

javaScript to check if session exist

<script>
  $(document).ready(function() {
    session_start();
    if (!$_SESSION['kool']) {
      alert("session")
    } else {
      alert('work')
      location.href = 'lol.html';
    }

  });
</script>

it doesn't work why ?

if/else statement is correct, but not returning incorrect

These are my instructions:

have four arguments that are all number

return "correct" if the four numbers are a valid combination

return "incorrect" if the 4 numbers aren't a valid combination a combination is valid if:

  • the first number is a 3, 5, or 7

  • the second number is 2

  • the third number is between 5 and 100. 5 and 100 are both valid numbers

  • the fourth number is less than 9 or greater than 20. 9 and 20 both invalid numbers

This is my code:

module.exports.checkLock = function(a, b, c, d) {

    if (a === 3 || 5 || 7, b === 2, c >= 5 || c <= 100, d < 9 || d > 20) {

        return "correct";
    }
    else {
        return "incorrect";
    }
};

And this is the error I am getting:

1) checkLock should return 'incorrect' for the incorrect first number example:

  AssertionError: expected 'correct' to deeply equal 'incorrect'
  + expected - actual

  +"incorrect"
  -"correct"

  at Context.<anonymous> (spec.js:39:49)

2) checkLock should return 'incorrect' for incorect second number:

  AssertionError: expected 'correct' to deeply equal 'incorrect'
  + expected - actual

  +"incorrect"
  -"correct"

  at Context.<anonymous> (spec.js:43:49)

3) checkLock should return 'incorrect' for invalid third numbers:

  AssertionError: expected 'correct' to deeply equal 'incorrect'
  + expected - actual

  +"incorrect"
  -"correct"

Any help would be appreciated. Also, sorry about formatting.

Proper way to write this if else statement?

How do I combine or write more efficiently this if else statement?

Is there a better way to write it without writing the entire thing twice?

The only difference is the two conditions placed on the first part to check if sitemap exists and then checks if the sitemap file modify time has changed in last 24 hours. If those two conditions are true then move forward, if those two conditions are false then move to the else part of the statement which simply creates the xml document without checking to see if the modified time has changed, since there was no file to check against.

$time  = time();
$sitemap = $_SERVER['DOCUMENT_ROOT'].'/sitemap.xml';
if (file_exists($sitemap)) { // if sitemap exists
    if ($time - filemtime($sitemap) >= 1) { // 1 days

        $xml = new DomDocument('1.0', 'utf-8'); 
        $xml->formatOutput = true; 

        // creating base node
        $urlset = $xml->createElement('urlset'); 
        $urlset -> appendChild(
            new DomAttr('xmlns', 'http://ift.tt/xwbjRF')
        );

            // appending it to document
        $xml -> appendChild($urlset);

        // building the xml document with your website content
        foreach($dirlist as $file) {
        if($file['type'] != 'text/x-php') continue;
            //Creating single url node
            $url = $xml->createElement('url'); 

            //Filling node with entry info
            $url -> appendChild( $xml->createElement('loc', 'http://www.'.$domain.$file['name']) );
            $url -> appendChild( $lastmod = $xml->createElement('lastmod', date('Y-m-d', $file['lastmod'])) );
            $url -> appendChild( $changefreq = $xml->createElement('changefreq', 'monthly') );
            $file['name'] != '/' ? $p = '0.5' : $p = '1.0';
            $url -> appendChild( $priority = $xml->createElement('priority', $p) );

            // append url to urlset node
            $urlset -> appendChild($url);

        }
        $xml->save($sitemap);
    } // if time
} // if sitemap exists

else {

        $xml = new DomDocument('1.0', 'utf-8'); 
        $xml->formatOutput = true; 

        // creating base node
        $urlset = $xml->createElement('urlset'); 
        $urlset -> appendChild(
            new DomAttr('xmlns', 'http://ift.tt/xwbjRF')
        );

            // appending it to document
        $xml -> appendChild($urlset);

        // building the xml document with your website content
        foreach($dirlist as $file) {
        if($file['type'] != 'text/x-php') continue;
            //Creating single url node
            $url = $xml->createElement('url'); 

            //Filling node with entry info
            $url -> appendChild( $xml->createElement('loc', 'http://www.'.$domain.$file['name']) );
            $url -> appendChild( $lastmod = $xml->createElement('lastmod', date('Y-m-d', $file['lastmod'])) );
            $url -> appendChild( $changefreq = $xml->createElement('changefreq', 'monthly') );
            $file['name'] != '/' ? $p = '0.5' : $p = '1.0';
            $url -> appendChild( $priority = $xml->createElement('priority', $p) );

            // append url to urlset node
            $urlset -> appendChild($url);

        }
        $xml->save($sitemap);
}

HTML code as text in Excel

I have an Excel file that will be saved as an .csv file for importation into an email automation system. In a function I need to return a piece of HTML code as text.

=IF(A2<0,"CHECKMARK CODE",A2)

The "CHECKMARK CODE" needs to be replaced by:

< span style="font-size:16px">& #10003;.

For this post, spaces were added to prevent code from display as a checkmark.

However, all my attempts at format_text function or adding apostrophes only yields errors.

How do I return this as text exactly as needed by the email automation system?

PowerShell - If/Else Statement Doesn't Work Properly

First off I apologize for the extremely long, wordy post. It’s an interesting issue and I wanted to be as detailed as possible. I’ve tried looking through any related PowerShell posts on the site but I couldn’t find anything that helped me with troubleshooting this problem.

I've been working on a PowerShell script with a team that can send Wake-On-Lan packets to a group of computers. It works by reading a .csv file that has the hostnames and MAC’s in two columns, then it creates the WOL packets for each computer and broadcasts them out on the network. After the WOL packets are sent, it waits a minute and then pings the computers to verify they are online, and if any don’t respond it will display a window with what machines didn’t respond to a ping. Up until the final If/Else statement works fine, so I won't be going into too much detail on that part of the script (but of course if you want/need further details please feel free to ask).

The problem I’m having is with the final If/Else statement. The way the script is supposed to work is that in the ForEach loop in the middle of the script, the value of variable $PingResult is true or false depending on whether or not the computer responds to a ping. If the ping fails, $PingResult is $false, and then it adds the hostname to the $PingResult2 variable.

In theory if all of the machines respond, the If statement fires and the message box displays that it was a success and then the script stops. If any machines failed to respond, the Else statement runs and it joins all of the items together from the $PingResult2 variable and displays the list in a window. What actually happens is that even if all of the machines respond to a ping, the If statement is completely skipped and the Else statement runs instead. However, at that point the $PingResult2 variable is blank and hence it doesn’t display any computer names of machines that failed to respond. In my testing I’ve never seen a case where the script fails to wake a computer up (assuming it’s plugged in, etc.), but the Else statement still runs regardless. In situations where the Else statement runs, I’ve checked the value of the $PingResult2 variable and confirmed that it is blank, and typing $PingResult2 –eq “” returns $true.

To add another wrinkle to the problem, I want to return to the $PingResult2 variable. I had to create the variable as a generic list so that it would support the Add method to allow the variable to grow as needed. As a test, we modified the script to concatenate the results together by using the += operator instead of making $PingResult2 a list, and while that didn’t give a very readable visual result in the final display window if machines failed, it did actually work properly occasionally. If all of the computers responded successfully the If statement would run as expected and display the success message. Like I said, it would sometimes work and sometimes not, with no other changes making a difference in the results. One other thing that we tried was taking out all of the references to the Visual Basic assembly and other GUI elements (besides the Out-GridView window) and that didn’t work either.

Any idea of what could be causing this problem? Me and my team are completely tapped out of ideas at this point and we’d love to figure out what’s causing the issue. We’ve tried it on Windows 7, 8.1, and the latest preview release of Windows 10 with no success. Thanks in advance for any assistance.

P.S Extra brownie points if you can explain what the regular expression on line 29 is called and how it exactly works. I found out about it on a web posting that resolved the issue of adding a colon between every two characters, but the posting didn’t explain what it was called. (Original link http://ift.tt/1DCHRZb)

Original WOL Script we built the rest of the script around was by John Savill (link http://ift.tt/1bVFM5d)

Script

Add-Type -AssemblyName Microsoft.VisualBasic,System.Windows.Forms

$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.ShowDialog() | Out-Null

$FileVerify = Get-Content -Path $OpenFileDialog.FileName -TotalCount 1
$FileVerify = ($FileVerify -split ',')

If($FileVerify[0] -ne "Machine Name" -or $FileVerify[1] -ne "MAC")

{

    $MsgBox = [System.Windows.Forms.MessageBox]::Show("The CSV File's headers must be Machine Name and MAC.",'Invalid CSV File headers!',0,48)
    Break

}

$ComputerList = Import-Csv -Path $OpenFileDialog.FileName |
Out-GridView -PassThru -Title "Select Computers to Wake up"

ForEach($Computer in $ComputerList)

    {

        If($Computer.'MAC' -notmatch '([:]|[-])')

            {

                $Computer.'MAC' = $Computer.'MAC' -replace '(..(?!$))','$1:'

            }

        $MACAddr = $Computer.'MAC'.split('([:]|[-])') | %{ [byte]('0x' + $_) }
        $UDPclient = new-Object System.Net.Sockets.UdpClient
        $UDPclient.Connect(([System.Net.IPAddress]::Broadcast),4000)
        $packet = [byte[]](,0xFF * 6)
        $packet += $MACAddr * 16
        [void] $UDPclient.Send($packet, $packet.Length)
        write "Wake-On-Lan magic packet sent to $($Computer.'Machine Name'.ToUpper())"

    }

Write-Host "Pausing for sixty seconds before verifying connectivity."
Start-Sleep -Seconds 60

$PingResult2 = New-Object System.Collections.Generic.List[System.String]

ForEach($Computer in $ComputerList)

    {

        Write-Host "Pinging $($Computer.'Machine Name')"
        $PingResult = Test-Connection -ComputerName $Computer.'Machine Name' -Quiet

        If ($PingResult -eq $false)

            {

                $PingResult2.Add($Computer.'Machine Name')

            }

    }

If($PingResult2 -eq "")

    {

        [System.Windows.Forms.MessageBox]::Show("All machines selected are online.",'Success',0,48)
        Break

    }

Else

    {

        $PingResult2 = ($PingResult2 -join ', ')
        [System.Windows.Forms.MessageBox]::Show("The following machines did not respond to a ping: $PingResult2",'Unreachable Machines',0,48)

    }

Incrimenting value DOWN wont print out

Having an issue printing the results of i when I'm incrementing DOWN starting from startVal and ending at endVal with an increment of incVal.

the first if statement is printing correctly and I had THOUGHT that the second else if statement should be fairly similar however even though my original values; for EX: if startVal = 100, endVal = 10, and incVal = -1, it jumps to the else if statement correctly (tested with a basic print statement) but the for loop doesn't seem to work and not print out the results of i like it should.

                if ((startVal < endVal)  &&  (incVal >= 1))
                {  
                     for (int i = startVal; i <= endVal; i += incVal)
                     {
                          System.out.println(i);
                     }

                }
                //  else if incrimenting down
                else if((startVal > endVal)  &&  (incVal <= -1))
                {
                     for (int i = startVal; i <= endVal; i -= incVal)
                     {
                          System.out.println(i);
                     }

                }

Is there something stupid I'm messing up here? I've tried different things inside the for loops to get i to print but it doesn't work the correct way..

Choose highest number in dataframe columns

I have a list with 10 dataframes with each 6 columns and 5553 rows.

Two of the columns are numeric. I want to compare those two columns row by row and pick the highest number and put in a 7th column or as a vector. I have tried different ifelse options and also if statements, but nothing seems to work.

How to set variable to blank when no check boxes are checked in JavaScript

I am working on an assignment where i have to take a users preferences and match them with a suitable mobile phone contract. If the users doesn't select a check box i want to display all the contracts, though i am struggling to do this.

This is the code i have so far:

    //Check Network
var userNetwork;
var networkForm=document.getElementById("NN");
var networkForm=document.getElementById("Othree");
var networkForm=document.getElementById("Fodavone");
var networkForm=document.getElementById("ZMobile");
if(NN.checked){
    userNetwork="NN";
}
if(Othree.checked){
    userNetwork="03";
}
if(Fodavone.checked){
    userNetwork="Fodavone";
}
if(ZMobile.checked){
    userNetwork="Z-Mobile";
}


for (var c = 0; c < cont.length; c++) {
    if (userNetwork === cont[c].network || userNetwork === "") {

I think i need to add some code to the end of the check network if statement , though im not sure what. Thanks.

Why isn't my Python function entering the if-else statement? [on hold]

I have a function in Python that returns the initialized value of the value I want to return instead of going into the if-else to find the right number to print. Here is my code:

def getCell(x, y):
   answer = -1
   if y <= 16666666.6667:
        if x <= 16666666.6667:
            answer = 0
        elif x <= 33333333.3333:
            answer = 1
        elif x <= 50000000.0:
            answer = 2
        elif x <= 66666666.6667:
            answer = 3
        elif x <= 83333333.3333:
            answer = 4
        elif x <= 100000000.0:
            answer = 5
    elif y <= 33333333.3333:
        if x <= 16666666.6667:
            answer = 6
        elif x <= 33333333.3333:
            answer = 7
        elif x <= 50000000.0:
            answer = 8
        elif x <= 66666666.6667:
            answer = 9
        elif x <= 83333333.3333:
            answer = 10
        elif x <= 100000000.0:
            answer = 11
    elif y <= 50000000.0:
        if x <= 16666666.6667:
            answer = 12
        elif x <= 33333333.3333:
            answer = 13
        elif x <= 50000000.0:
            answer = 14
        elif x <= 66666666.6667:
            answer = 15
        elif x <= 83333333.3333:
            answer = 16
        elif x <= 100000000.0:
            answer = 17
    elif y <= 66666666.6667:
        if x <= 16666666.6667:
            answer = 18
        elif x <= 33333333.3333:
            answer = 19
        elif x <= 50000000.0:
            answer = 20
        elif x <= 66666666.6667:
            answer = 21
        elif x <= 83333333.3333:
            answer = 22
        elif x <= 100000000.0:
            answer = 23
    elif y <= 83333333.3333:
        if x <= 16666666.6667:
            answer = 24
        elif x <= 33333333.3333:
            answer = 25
        elif x <= 50000000.0:
            answer = 26
        elif x <= 66666666.6667:
            answer = 27
        elif x <= 83333333.3333:
            answer = 28
        elif x <= 100000000.0:
            answer = 29
    elif y <= 100000000.0:
        if x <= 16666666.6667:
            answer = 30
        elif x <= 33333333.3333:
            answer = 31
        elif x <= 50000000.0:
            answer = 32
        elif x <= 66666666.6667:
            answer = 33
        elif x <= 83333333.3333:
            answer = 34
        elif x <= 100000000.0:
            answer = 35
    return answer

I have tried many different combinations of x & y, but it always returns -1. Why? I used this exact code in another program and it worked there.

These are the values that the other program with the same code put these x & y values:

x = 21659939 y = 42211657 put into cell 13

x = 30336851 y = 58758061 put into cell 19

Thank you.

How to write a test in Jasmine where the object's existence is checked prior to the function call on that object?

It's easiest to describe the problem by showing a code sample.

Code under test:

function something() {
    if(this.myObject) {
        this.myObject.callMyFunction();
    }

    this.callAnotherFunction();
}

Jasmine test:

it("should call myObject.callMyFunction() because 'myObject' is defined") {
    spyOn(theScope, "callAnotherFunction");
    theScope.something();
    expect(theScope.myObject.callMyFunction).toHaveBeenCalled(); // a spy has already been created for theScope.myObject.callMyFunction
} // TEST PASSES

it("should not call myObject.callMyFunction() because 'myObject' is undefined") {
    spyOn(theScope, "callAnotherFunction");
    theScope.myObject = undefined;
    theScope.something();
    expect(theScope.myObject.callMyFunction).not.toHaveBeenCalled(); // a spy has already been created for theScope.myObject.callMyFunction
} // TEST FAILS

As you can see in the second test, I'm trying to set theScope.myObject to be undefined, but the test won't run because it's then calling callMyFunction() on the undefined object theScope.myObject.

List index out of range parsing CSV file

For my school assignment I have created a program which checks for an EMAIL and PASSWORD found in rows 0 and 1 in a csv file which match up, and will then print some information about that user from rows 2-6. However, I believe this is not necessarily any cause of my problem.

The problem is the else statement.

When a user enters both their EMAIL and PASSWORD correctly the system will print their information. However if the EMAIl and PASSWORD entered don't match up with the ones in the CSV file, I attempted to create an ELSE statement that would print 'Your email or password is incorrect'

However, instead, I would receive this error:

line 12, in <module>
    if email_1 in row[0] and pass_1 in row[1]:
IndexError: list index out of range

Since I'm new to python, I'm not sure why this is happening, but I don't reckon it is to do with the code above since when details are entered correctly, the program will print the information.

I have tried to make the ELSE statement work without the use of assigning a variable to be TRUE or FALSE, but nor did that work, exactly the same issue. It's just the ELSE statement which it doesn't seem to be recognising.

Code:

import csv

email_pass = False
email_1 = raw_input('What is your email? :')
pass_1 = raw_input('What is your password? :')
with open('DATAFILE.csv', "rb") as csvfile:
    my_content = csv.reader(csvfile, delimiter=',')
    for row in my_content:
        if email_1 in row[0] and pass_1 in row[1]:
            email_pass = True
            if email_pass == True:
                print row[2:6]
                break
            else:
                print 'Your EMAIL or PASSWORD is incorrect'

PHP if statement within if statement

i'm building a php site where i want the user to create hes company.

The script is checking for the user has any companies registered already and then it should display information regards to where or not he has.

If he doesnt have registered hes company he should see a form where he can register.

If he choose to register company the script will check for any company with the same name or insert the row.

My only problem is that when there's already a company with that name the echo doesnt display.

I have written inside the code where the problem is.

<?php
        $con=mysqli_connect("mysql","USER","PASS","DB");
        if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }

            $result_get_companies = mysqli_query($con,"SELECT * FROM companies WHERE userid='". $login_session ."' ORDER BY companyid ASC") or die(mysqli_error());

            if (mysqli_num_rows($result_get_companies) >= 1) {

                while($row_companies = mysqli_fetch_array( $result_get_companies )) {

                $result_get_company_owner = mysqli_query($con,"SELECT username FROM users WHERE userid='". $login_session ."'")                 or die(mysqli_error());

                $company_owner = mysqli_fetch_assoc($result_get_company_owner);

                    echo 'THIS WORKS';
                }

            } else {

                if (isset($_POST['create_first_company']) && !empty($_POST['company_name'])) {

                    $company_name_unsafe = mysqli_real_escape_string($con, $_POST['company_name']);
                    $company_name = preg_replace("/[^a-zA-Z0-9\s]/","",$company_name_unsafe );

                    $check_companies = "SELECT companyid FROM companies WHERE company_name='". $company_name ."'";
                    $what_to_do_companies = mysqli_query($con,$check_companies);

                    if (mysqli_num_rows($what_to_do_companies) != 0) {

                        echo 'THIS DOESNT WORK
                                It does register that is should go here
                                because it does not insert new row.
                                and when the value is = 0 it does go
                                to else ELSE below and insert row.';

                    } else {

                        $result_create_company = mysqli_query($con,"INSERT INTO companies (companyname) 
                                                                    VALUES ('". $login_session ."')") 
                                                                    or die(mysqli_error());

                        echo 'THIS WORKS';  

                    }

                } else {

                    echo 'THIS WORKS!';

                }

            }

?>

Switch and strings in C [on hold]

As far i know, in C, I can't do a switch with strings, so i have a question: Which code is more correct? This, creating a new variable called metd and saving in it? or putting the code directly on the if's?

New variable

int metd=0;

if (strcmp( method, "GET")==0){
    metd=1;
}
if (strcmp( method, "HEAD")==0){
    metd=2;
}

switch (metd)
{
    case 1:
        //actions
        break;
    case 2:
        //actions
        break;

    default:
        //actions
        break;

}

If's party

if (strcmp( method, "GET")==0){
    //actions
}
if (strcmp( method, "HEAD")==0){
    //actions
}

Two Wordpress search results pages

I would like to have two different search results depending on the page, that the user is on.

I have duplicated how the previous search contents would display, added the extra code that I want the staff search to show, and then put an if statement around it.

If user is on page 'staff' - then show this Else show this.

I cant seem to get the if-statement to work, any help would be appreciated.

<?php if (is_page('staff')) { ?>

<article class="entry post clearfix">
    <-- Title / Thumbnail / Price / Description coding -->
</article> 

 <?php } else { ?>  

<article class="entry post clearfix">
    <-- Title / Thumbnail / Description coding -->
</article> 

<?php } endif; ?>

Any help on this would be great.

Change size of Google pie charts dynamically?

I have three pie charts being generated from an array of objects. They have different colors and data values. I now want them to change size according to the value of the data being passed to them. I have an array that has three predefined sizes I want to use, with the largest value correlating to the pie chart with the highest data etc. The code:

if (data) {
  var allData = [{
        arr : [['Label', 'Value'], ['Car Sales Today', data.salesToday]],
        container : 'today-sales-chart',
        customTooltips: data.salesToday,
        color: ['green']
    }
    ,{
        arr : [['Label', 'Value'], ['Car Sales Yesterday', data.salesYesterday]],
        container : 'yesterday-sales-chart',
        customTooltips: data.salesYesterday,
        color: ['blue']
    }
    ,{
        arr : [['Label', 'Value'], ['Car Sales Last Week', data.salesLastWeek]],
        container : 'lastweek-sales-chart',
        customTooltips: data.salesLastWeek
        color: ['yellow']
    }
 ];

 var theRadius = ['10', '30', '50'];

 var builds = [];
 for (var index in allData) {
    builds.push({
        package: 'PieChart',
        data: allData[index].arr,
        customTooltips:  allData[index].customTooltips,
        container: allData[index].container,
        options: {
            width: 'auto',
            height: 300,
            chartArea: { width: theRadius[1] + '%', height: '80%' },
            yAxis: { textPosition: 'none' },
            legend: { position: "bottom" },
            tooltip: { isHtml: true },
            colors: allData[index].color,
            pieSliceText: 'none'
        }
    });
 }

 for(var index in builds) {
    charts.push(builds[index]);
    google.setOnLoadCallback.drawCharts(builds[index].container);
 }

The three charts are all the same size at the moment, determined by

var theRadius = ['10', '30', '50'];
chartArea: { width: theRadius[1]...

so they are all at 30%. I would like to have them render at the various sizes dynamically, using an if statement or for loop?

VBA sheet to sheet multiple cell comparison

I'm trying to create a code that will compare the first column (Dates) on sheet8 with the first column (Dates) on sheet7. In addition, I have to compare the 2nd columns on each sheet (Shift). Once the program hits the correct shift and date, I need to copy and paste some certain data located on sheet7 to sheet8. I've searched quite a bit on it and can't seem to find the correct answer. (Note: somewhat new to vba and self taught so forgive me for any mistakes in code).

enter code here
Option Explicit
Sub GrabKPI()
Dim i As Integer, j As Integer
Dim date1 As Date, date2 As Date
Dim shift1 As Integer, shift2 As Integer
date1 = Sheets("Sheet8").Range("A" & i)
date2 = Sheets("Sheet7").Range("A" & j)
shift1 = Sheets("Sheet8").Range("B" & i)
shift2 = Sheets("Sheet7").Range("B" & j)

For i = 2 To 1697
If date1 = date2 Then
    If shift1 = shift2 Then
        Sheets("Sheet7").Activate
        Range("C" & j, "F" & j).Select
        Selection.Copy
        Sheets("Sheet8").Activate
        Range("I" & i).PasteSpecial xlPasteAll
        j = j + 1
    Else: j = j + 1
    End If
Else: j = j + 1
End If
i = i + 1
Next i
End Sub

Right now, I get the error "Application-defined or object-defined error" referring to the date1 and date2 statements. However I tried using this general code with a different set up and it would run but nothing would happen. Any help would be greatly appreciated. Thank you.

Matlab if loop function, How to improve this function?

I am new to matlab and I am trying to figure how to write the following function in a smart/efficient way. First I create a matrix 'y' with entries HL, and every line is a permutation of a predefined length ( n ). For example, for n=3 I get the first line of the matrix y : H H H. Then I want for each line, to create a matrix of size n x n where for example the entry (1,2) corresponds to a variable which links entry y(1,1) with y(1,2) , and entry (3,2) corresponds to a variable which links entry y(1,3) with y(1,2). Is this possible?

Thank you

function A1=mystupidfunction(s , n)
%n is the number of agents and s is the number of state, this function
%returns the matrix of influence. Stupid code must be improved to work for
%n agents

x = 'HL';                 %// Set of possible types
K = n;                      %// Length of each permutation

%// Create all possible permutations (with repetition) of letters stored in x
C = cell(K, 1);             %// Preallocate a cell array
[C{:}] = ndgrid(x);         
y = cellfun(@(x){x(:)}, C); 
y = [y{:}];

A1 = sym('A1',[n n], 'positive' ); 
syms H L A_HH A_HL A_LH A_LL
for k=s
for i=1:n
for j=1:n
if ( y(k,1)==H) && ( y(k,2)==H) && (y(k,3)==H)
A1(i,j)=A_HH
elseif ( y(k,1)==L) && ( y(k,2)==L) && (y(k,3)==L)
A1(i,j)=A_LL
elseif ( y(k,1)==H) && ( y(k,2)==L) && (y(k,3)==L)
A1(1,1)=A_HH 
A1(1,2)=A_HL
A1(1,3)=A_HL
A1(2,1)=A_LH
A1(3,1)=A_LH
A1(2,2)=A_LL
A1(2,3)=A_LL
A1(3,3)=A_LL
A1(3,2)=A_LL
elseif ( y(k,1)==H) && ( y(k,2)==H) && (y(k,3)==L)
A1(1,1)=A_HH 
A1(1,2)=A_HH
A1(1,3)=A_HL
A1(2,1)=A_HH
A1(3,1)=A_LH
A1(2,2)=A_HH
A1(2,3)=A_HL
A1(3,3)=A_LL
A1(3,2)=A_LH
elseif ( y(k,1)==L) && ( y(k,2)==L) && (y(k,3)==H)
A1(1,1)=A_LL 
A1(1,2)=A_LL
A1(1,3)=A_LH
A1(2,1)=A_LL
A1(3,1)=A_LH
A1(2,2)=A_LL
A1(2,3)=A_LH
A1(3,3)=A_HH
A1(3,2)=A_HL
elseif ( y(k,1)==L) && ( y(k,2)==H) && (y(k,3)==H)
A1(1,1)=A_LL 
A1(1,2)=A_LH
A1(1,3)=A_LH
A1(2,1)=A_HL
A1(3,1)=A_HL
A1(2,2)=A_HH
A1(2,3)=A_HH
A1(3,3)=A_HH
A1(3,2)=A_HH
elseif ( y(k,1)==L) && ( y(k,2)==H) && (y(k,3)==L)
A1(1,1)=A_LL 
A1(1,2)=A_LH
A1(1,3)=A_LL
A1(2,1)=A_HL
A1(3,1)=A_LL
A1(2,2)=A_HH
A1(2,3)=A_HL
A1(3,3)=A_LL
A1(3,2)=A_LH

elseif ( y(k,1)==H) && ( y(k,2)==L) && (y(k,3)==H)
A1(1,1)=A_HH 
A1(1,2)=A_HL
A1(1,3)=A_HH
A1(2,1)=A_LH
A1(3,1)=A_HH
A1(2,2)=A_LL
A1(2,3)=A_HL
A1(3,3)=A_HH
A1(3,2)=A_HL
else A(i,j)=0
end
end
end
end

for example for n=3 and s=1 the function returns :

A =

[ A_HH, A_HH, A_HH]
[ A_HH, A_HH, A_HH]
[ A_HH, A_HH, A_HH]

Thank you

Is it possible in Python to write a sort of truth table to simplify the writing of if statements?

Let's say I'm trying to print out the orientation of a tablet device using its accelerometer that provides acceleration measurements in the horizontal and vertical directions of the display of the device. I know that such a printout could be done using a set of if statements in a form such as the following:

if abs(stableAcceleration[0]) > abs(stableAcceleration[1]) and stableAcceleration[0] > 0:
    print("right")
elif abs(stableAcceleration[0]) > abs(stableAcceleration[1]) and stableAcceleration[0] < 0:
    print("left")
elif abs(stableAcceleration[0]) < abs(stableAcceleration[1]) and stableAcceleration[1] > 0:
    print("inverted")
elif abs(stableAcceleration[0]) < abs(stableAcceleration[1]) and stableAcceleration[1] < 0:
    print("normal")

Would it be possible to codify the logic of this in some neater form? Could a sort of truth table be constructed such that the orientation is simply a lookup value of this table? What would be a good way to do something like this?

Simple loop through array to change a pie chart color?

My code, which uses the Google Charts API to generate three pie charts:

var allData = [{
        arr : [['Label', 'Value'], ['Car Sales Today', data.salesToday]],
        container : 'today-sales-chart',
        customTooltips: data.salesToday
    }
    ,{
        arr : [['Label', 'Value'], ['Car Sales Yesterday', data.salesYesterday]],
        container : 'yesterday-sales-chart',
        customTooltips: data.salesYesterday
    }
    ,{
        arr : [['Label', 'Value'], ['Car Sales Last Week', data.salesLastWeek]],
        container : 'lastweek-sales-chart',
        customTooltips: data.salesLastWeek
    }
];

var theColors = ['green', 'pink', 'blue'];

var options = {
    width: 'auto',
    height: 300,
    chartArea: { width: '50%', height: '80%' },
    yAxis: { textPosition: 'none' },
    legend: { position: "bottom" },
    tooltip: { isHtml: true },
    colors: theColors,
    pieSliceText: 'none'
}

var builds = [];
for (var index in allData) {
    builds.push({
        package: 'PieChart',
        data: allData[index].arr,
        customTooltips: [ allData[index].customTooltips ],
        container: allData[index].container,
        options: options
    });
}

for(var index in builds) {
    charts.push(builds[index]);
    google.setOnLoadCallback.drawCharts(builds[index].container);
}

}

I just want to have the color to be different for each of the charts. I understand that it is in the allData arrays' objects that this will happen. I have tried the following:

 var allData = [{
        arr : [['Label', 'Value'], ['Car Sales Today', data.salesToday]],
        container : 'today-sales-chart',
        customTooltips: data.salesToday,
        colors: ['green']
    }
    ,{

etc but no charts will display when this happens. 'objects : objects' is from the charts api.

are multiple 'if' statements and 'if else-if' statements the same?

Is there any difference between writing multiple 'If' statements and 'if' else-if' statements?? because when I tried to write a program with multiple 'if ' statements, it did not give the expected results. But with 'if else-if' it worked. ## if' ##

How to make an if statement with multiple conditions.

Basically I have two different columns; column G and H

I would like to make it so that if the Column H is greater than today's date Coloumn G equals "G" for good and if Column H is less than today's date Column G will equal "R" for not on track

=IF(H84<TODAY,"R","G")

My return is #NAME?

timing a function call as if-statement condition in cpp

I have a function and sometimes it gets called as a condition in if-statements, and I am interested to time exactly these calls.

I wonder if there is any way to do something like this for timing it in cpp:

using watch = std::chrono::high_resolution_clock;
std::chrono::nanoseconds time(0);
if ( auto start = watch::now(); SOME_FUNCTION(); auto end = watch::now();)
{...}else{...}
time += (end - start);

Batch file problems with IF statements and parantheses

I am trying to batch start some experiments. I need to redo some of them but not all. The ones where (s==1000 and r==0.5 and (c==1 or c==25 or c==75)) have been done ok so can be skipped (they take a long time to run). Ever since I introduced the IF statements, the way the parentheses are parsed is giving errors. I keep getting unexpected ( or ). I've tried rewriting the whole thing, but to no avail.

I know this is a lot like a 'please check my code for bugs' question, but I am really at my wits end here.

SET dotest=1
FOR %%s IN (1000,2000) do (
    FOR %%r IN (0.5,0.75,1) do (
        FOR %%c IN (1,25,75,100) do (
            IF (%%s==1000) (
                IF (%%r==0.5) (
                    IF (%%c==1)
                        (SET dotest==0)
                    IF (%%c==25)
                        (SET dotest==0)
                    IF (%%c==75)
                        (SET dotest==0)
                )
            )
            IF (%%dotest==1) (
                ECHO "Hello World!"
            )
        )
    )
)

Query if else if else check true?

Hello i want to check if a div has the class active. the first item works, after that it stops. Can someone tell me how to fix this? (Its a slider, so it has to work not on click.) It slides automatic.

    <script>
$(document).ready(function () {
  if ($('#211').hasClass('item active')){
            $('.vandaag').css("background-color", "blue");
            console.log("werkt1!");}
   else if ($('#218').hasClass('item active')){
            $('.vandaag').css("background-color", "#005993");
            console.log("werkt2!");}

    else if ($('#219').hasClass('active')){
            $('.vandaag').css("background-color", "#005993");
            console.log("werkt3!");}
});

</script>

the number is the id of the image slider. and the .item .active is when the slide is active. Greetz

In Excel: Return nth largest value in a group of numbers given constraints

I was wondering if anyone could help with the following Excel question:

If I have three columns, Column A containing tweet texts, Column B containing the number of impressions that tweet has generated, and Column C containing the date of the tweet - I would like to output the following things without using VBA or pivot tables if I can:

  • Produce a table with the top 10 tweets by impressions over a selected date range
  • The table should have the tweet text in one column, and the associated impressions in the second column.

Essentially I want to look up the nth largest value given date constraints, and return that value as well as the tweet text alongside it.

I have been looking up the =LARGE(IF()) function but I haven't been successful so far, does anyone have any suggestions?

How do you make a c++ program search for a string?

How do you make a c++ program search for a string?

I'm new to the programming language c++.

Is there a way so that my program will look for a string of a .txt file and do something if the program found it?

Compare multiple values in one condition

Int32 int1, int2, int3 = 123;

Given the above variables, how can I test that all of my variables have the value 123 without creating a colletion to perform some Any or something on?

What I've Tried

if(int1 == int2 == int3 == 123)
{
   // Fantastic code here
}

I'm disappointed to see that the above won't compile, it would've been a nice way of comparing all to one value.

if statement without the inner scope?

Afaik, every pair of { } in the code creates a new scope. Even if it's used just for the sake of it without any if, for, function or other statement that demands it:

void myFun(void)
{
    int a;
    {
        int local;
    }
}

I started wondering - when the if statement is written without using the braces (with 1-line body) does it still create a new scope?

voidmyFun(int a)
{
    int b;
    if (a == 1)
        int tmp;   // is this one local to if?
    else
        int tmp2;   // or this one?
    b = 2;   // could I use tmp here?
}

mardi 28 avril 2015

How && if loop Expression evaluation?

In evaluating the expression (x==y && a<b) the Boolean expression x==y is evaluated first and then a<b is evaluated. True or False????

Please explain the working for the same. I quite confused for this if expression.

How to increase a counter inside of a do-while loop with if-else condition (c++)

Hey guys I'm trying to build a program that calculates a percent composition of a compound.

There is an array of elements such as H, O, C end etc

The program must take the user_compound and compare it to the array of elements and return the value(mass) that is in the same position.

Unfortunately right now it works just for H and than it loops any ideas on how to increase the i( i.e run i++ part) ?

do{

        cin >> user_compound[i];

            if(user_compound[i][i] == elements[i][i]){

               cout << "this is user compound " << user_compound[i][i] << << " "<< values[i]<<endl;}

            **else{
                i++;}}**

    while(user_compound[i][i] == elements[i][i]);

how can i Echo "text" only if attached thumbnail is bigger than "X" resolution in wordpress?

can someone please help me out with the following.

how can i Echo "text" only if attached thumbnail resolution is over 500px x 500px in wordpress?

I want to echo a link if the attached thumbnail is bigger than the specified image resolution.

Thanks.

Java - else in the loop statement keeps executing

this has me stumped. Im using a loop to go through an array and then using ifs/else to find whether it meets the criteria. However the else statement keeps being executed even though an if is being executed aswell. Probably something really basic im missing. I need to check in the if statements twice as the user is entering a genre aswell as the item in the array meets that genre too.

cheers

  for (int i = 0; i < movies.length; i++)
  {
     //RentalMovie movie = movies[i];

     if(movies[i].getMovieGenre().equalsIgnoreCase("action") && movies[i].getMovieGenre().equalsIgnoreCase(genreID))
     {
        genreList += movies[i].getMovieID() + " - " + movies[i].getMovieTitle() + "[" + movies[i].getMediaType() + "]\n";
     }
     else if(movies[i].getMovieGenre().equalsIgnoreCase("childrens") && movies[i].getMovieGenre().equalsIgnoreCase(genreID))
     {
        genreList += movies[i].getMovieID() + " - " + movies[i].getMovieTitle() + "[" + movies[i].getMediaType() + "]\n";         
     }
     else if (movies[i].getMovieGenre().equalsIgnoreCase("drama") && movies[i].getMovieGenre().equalsIgnoreCase(genreID))
     {
        genreList += movies[i].getMovieID() + " - " + movies[i].getMovieTitle() + "[" + movies[i].getMediaType() + "]\n";            
     }
     else
     {
        genreList += "- No rental movies were found for the genre: " + genreID; 
     } 

  }

Issues with if statement

I am trying to find a keyword in a text file and return the sentence if found. If the keyword is not found I want to call a Writer method. But for some reason the Writer method always runs.

What needs to change to ensure the writer method is only called if the keyword is not found?

Here is my code

    private static HashMap<String, String[]> populateSynonymMap() {
   responses.put("professor", new String[]{"instructor", "teacher", "mentor"});
    responses.put("book", new String[]{"script", "text", "portfolio"});
    responses.put("office", new String[]{"room", "post", "place"});
    responses.put("day", new String[]{"time",  "date"});
    responses.put("asssignment", new String[]{"homework", "current assignment "});
    responses.put("major", new String[]{"discipline", "focus"," study"});


    return responses;
}

Here is my main method and the Writer Method

public static void main(String args[]) throws ParseException, IOException {
    /* Initialization */
    HashMap<String, String[]> synonymMap = new HashMap<String, String[]>();
    synonymMap= populateSynonymMap(); //populate the map

    Scanner in = new Scanner(System.in);
    Scanner scanner = new Scanner(System.in);
    String input = null;

    System.out.println("Welcome To DataBase ");
    System.out.println("What would you like to know?");

    System.out.print("> ");
    input = scanner.nextLine().toLowerCase();           
     String[] inputs = input.split(" ");

    boolean found = false;
    for(String ing : inputs){ //iterate over each word of the sentence.
        for (Map.Entry<String, String[]> entry : synonymMap.entrySet()) {
            String key = entry.getKey();
            String[] value = entry.getValue();
            if (key.equals(ing) || Arrays.asList(value).contains(ing)) {

                    found = true;
                    parseFile(entry.getKey());

                    System.out.println(" Would you like to update this information ? "); 
                String yellow = in.nextLine(); 
                if (yellow.equals("yes")) {
                    removedata(entry.getKey());
                }
                if (yellow.equals("no")) {
                    System.out.println("Have a good day"); 
                    break;
                }


                    break;
                    //System.out.println("Have a good day!");
                   // break;
            }
        }
        if(found){
             Writer();
        }   
    }
}
}


 public static void Writer() {
    boolean endofloop = false;
    Scanner Keyboard = new Scanner(System.in);
    Scanner input = new Scanner(System.in);

    File file = new File("data.txt");
    try (BufferedWriter wr = new BufferedWriter(new FileWriter(
            file.getAbsoluteFile(), true))) { // Creates a writer object
                                                // called wr
                                                // file.getabsolutefile
                                                // takes the filename and
                                                // keeps on storing the old
        System.out.println("I do not know, Perhaps you wanna help me learn?"); // data
        while ((Keyboard.hasNext())) {

            String lines = Keyboard.nextLine();
            System.out.print(" is this correct ? ");
            String go = input.nextLine();

            if (go.equals("no")) {
                System.out.println("enter what you want to teach me");
                lines = Keyboard.nextLine();
                System.out.print(" is this correct ? ");
                go = input.nextLine();
            }

            if (go.equals("yes")) {
                wr.write(lines);
                wr.write("\n");

                wr.newLine();

                wr.close();
            }

            System.out.println("Thankk you");
            break;
        }
    } catch (IOException e) {
        System.out.println(" cannot write to file " + file.toString());
    }
}

if statements won't continue

i am trying to do some computations on vb.net. I used the if else statement since i'm a bit familiar with it. my goes like this

 Try
        Dim a As Integer = msalary.Text
        If (a < 9000) Then
            Label5.Text = a - 200
        ElseIf (9000 < a < 9999.99) Then
            Label5.Text = a - 225
        ElseIf (10000 < a < 10999.99) Then
            Label5.Text = a - 250
        ElseIf (11000 <= a < 11999.99) Then
            Label5.Text = a - 275
        ElseIf (12000 <= a < 12999.99) Then
            Label5.Text = a - 300
        ElseIf (13000 <= a < 14000) Then
            Label5.Text = a - 325
        ElseIf (14000 <= a < 15000) Then
            Label5.Text = a - 350
        ElseIf (15000 <= a < 16000) Then
            Label5.Text = a - 375
        ElseIf (17000 <= a < 18000) Then
            Label5.Text = a - 400
        ElseIf (18000 <= a < 19000) Then
            Label5.Text = a - 425
        ElseIf (19000 <= a < 20000) Then
            Label5.Text = a - 450
        ElseIf (20000 <= a < 21000) Then
            Label5.Text = a - 475
        ElseIf (21000 <= a < 22000) Then
            Label5.Text = a - 500
        ElseIf (22000 <= a < 23000) Then
            Label5.Text = a - 525
        ElseIf (23000 <= a < 24000) Then
            Label5.Text = a - 550
        ElseIf (24000 <= a < 25000) Then
            Label5.Text = a - 575
        ElseIf (25000 <= a < 26000) Then
            Label5.Text = a - 600
        ElseIf (26000 <= a < 27000) Then
            Label5.Text = a - 625
        ElseIf (27000 <= a < 28000) Then
            Label5.Text = a - 650
        ElseIf (28000 <= a < 29000) Then
            Label5.Text = a - 675
        ElseIf (29000 <= a < 30000) Then
            Label5.Text = a - 700
        ElseIf (30000 <= a < 31000) Then
            Label5.Text = a - 725
        ElseIf (31000 <= a < 32000) Then
            Label5.Text = a - 750
        ElseIf (32000 <= a < 33000) Then
            Label5.Text = a - 800
        ElseIf (33000 <= a < 34000) Then
            Label5.Text = a - 825
        ElseIf (34000 <= a < 35000) Then
            Label5.Text = a - 850
        ElseIf (a >= 35000) Then
            Label5.Text = a - 875
        ElseIf a = "" Then

        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try


End Sub

the farthest the condition was able to go was to -225 even if i put 20000 in it. it will only subtract 225 from the 20000..is there something wrong on what i did or is there a better way to do it?

Distinguish efficiently between different possible combinations in a tuple

I have a two-element tuple t, each element is either a positive integer or None, and the combination may be in one of the four forms:

1: (x, y): e.g. (2, 3)

2: (x, x): e.g. (1, 1)

3: (x, None) (or equivalently, (None, x)) : e.g. (3, None) or (None, 5)

4: (None, None)

My application logic wants to treat 2) and 3) as one case, 1) as the second case, and 4) as the third case.

I want to find an operation on a given tuple to make it easier/more efficient to distinguish between the three cases. For example, t[0] or t[1] will help us distinguish between the case of 2) and 3) and that of 4), but it cannot distinguish 2) and 3) from 1).

In the end, I want to minimize the number of if checks needed.

Split list item and remove split items if both are not contained in another list in Python

I have a file, called "nwk", with two values in each row. I would like to use .split to separate the values of each row, and then compare both of those values to another list of integers, called "vals". If both of the values in a row in nwk are not contained in vals, I would like to remove that row from nwk. Here is what I have so far:

for line in nwk:
    a = [ (int(n) for n in line.split()) ]
    if a[0] not in vals:
        nwk.remove(line)
    else:
        if a[1] not in vals:
            nwk.remove(line)
        else:
            continue

However, when I print nwk, the code has merely removed 1/2 of my original lines in nwk, which I know to be incorrect. How may I fix this? Thank you in advance for your help.

Batch files: If directory exists, do something

I'm trying to do the following:

IF EXISTS ("C:\Users\user\Desktop\folder1\") {

MOVE "C:\Users\user\Desktop\folder2\" "C:\Users\user\Desktop\folder1\"
RENAME "C:\Users\user\Desktop\folder1\folder2\" "folder3"

} else {

MKDIR "C:\Users\user\Desktop\folder1\"
MOVE "C:\Users\user\Desktop\folder2\" "C:\Users\user\Desktop\folder1\"
RENAME "C:\Users\user\Desktop\folder1\folder2\" "folder3"

}

With the following code:

@ECHO OFF

FOR /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a" SET "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%" SET "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"

SET "date=%DD%%MM%%YY%"

IF EXIST "C:\Users\user\Desktop\folder1\" (GOTO MOVER)

PRINT "It doesn't exists" PAUSE

:MOVER PRINT "MOVER" PAUSE EXIT :END

But the system does not print the test words.

IF statement with multiple worksheets in Excel

This is my formula. =IF(Start!I7:End!I7>0, 0, Start!I7:End!I7) I get the error #value!

I have a worksheet called Start at the beginning and a worksheet called End at the end of the sheets.

On my sheet in the middle, I want a cell to add up all of the I7 values from Start to End and if it is greater than 0 to display 0. If not, I want it to display the sum of all of the I7 values.

This formula works if I do =IF(Start!I7-End!I7>0, 0, Start!I7-End!I7) with the subtraction.

Argument error length in for loop nested conditional?

I am currently returning the error

Error in if (sandc[which(Index == i)] == 1) if (sandc[which(Index == i)] ==  : 
  argument is of length zero

when I try and run the following code:

weather<-read.xls("finaldata4.xls")
attach(weather)
length(Low)

for(i in 2:length(low)){
 w<-rep(0,length(low))
  w[1]<-1000;
  if(sandc[which(Index==i)]==1){
    w[i]<-gross[which(Index==i)]*w[i-1]
  }
  else{
    w[i]<-(gross[which(Index==i)]*-1)*w[i-1]
  }
}

It's unclear to me what is going, wrong, but I suspect it is something to do with the indexing. The dataset just has a simple index (1 to 1254) and several variables, which I have attached (like gross, and sandc).

Any ideas where this error is coming from?

Macro for run-once conditioning

I am trying to build a macro that runs a code only once. Very useful for example if you loop a code and want something inside to happen only once. The easy to use method:

static int checksum;

for( ; ; )
{
    if(checksum == 0) { checksum == 1; // ... }
}

But it is a bit wasteful and confusing. So I have this macros that use checking bits instead of checking true/false state of a variable:

#define CHECKSUM(d) static d checksum_boolean
#define CHECKSUM_IF(x) if( ~(checksum_boolean >> x) & 1) \
                    {                                               \
                        checksum_boolean |= 1 << x;
#define CHECKSUM_END }1

The 1 at the end is to force the user to put semi-colon at the end. In my compiler this is allowed.


The problem is figuring out how to do this without having the user to specify x (n bit to be checked). So he can use this:

CHECKSUM(char); // 7 run-once codes can be used

for( ; ; )
{
    CHECKSUM_IF
        // code..
    CHECKSUM_END;
}


Ideas how can I achieve this?