vendredi 30 juin 2017

BASH to pipe find output and check if it exists elsewhere

I am trying to identify files in a directory that are not links, and then check that the same filenames exists in another directory.

In my script below, it works for when find identifies only one file, but fails when there is more than one.

This is what i have:

FILENAME=`find /home/user/test1/ -maxdepth 1 -mindepth 1 \! -type l -printf "%f\n"`
if [ ! -f /home/user/test2/"$FILENAME" ]; then
    echo "File not found!"
fi

out put of echo $FILENAME

test.touch touch.2

Beginning C++: using if else, n--, number

I am struggling to get this program to work. Could someone please look it over to see what is wrong? (The compiler says that sum_positive is not defined in this way.) Also, I have searched this problem and found an answer on here, but I did not see the problem that way and want to avoid plagiarism when I turn in my homework. Thank you!

  1. Write a program that reads in ten whole numbers and that outputs the sum of all the numbers greater than zero, the sum of all the numbers less than zero (which will be a negative number or zero), and the sum of all the numbers, whether positive, negative, or zero. The user enters the ten numbers just once each and the user can enter them in any order. Your program should not ask the user to enter the positive numbers and the negative numbers separately.

Program:

#include <iostream>

using namespace std;

int main()
{

int number, n = 10, sum_positive = 0, sum_negative = 0, sum = 0;
    int count = 0, positive_count = 0, negative_count = 0;

    cout << "Please enter in 10 whole numbers, one at a time." << endl;

    do
    {
        cout << "Please enter another number." << endl;
        cin >> number;
        n--;
    }
    while (n > 0);

    if (number >= 0)
    {
        sum_positive += number;
        //positive_count++; count++;
    }
    else
    {
        sum_negative += number;
        //negative_count++; count++;

    }


    sum = sum_positive + sum_negative;

    cout << sum_postive << endl;
    cout << sum_negative << endl;
    cout << sum << endl;

return 0;
}

how to read values from a text file, store it in array and loop through it in PYTHON

Based on package dimension: Height , Length, Width and Weight, I'm creating 3 package categories: Letter, Parcel-Small and Parcel-Large. Here is the code in python:

def category(row):
    if row['Height'] <=0.98 and row['Length'] <= 9.84 and row['Width'] 
    <= 13.89 and row['WEIGHT'] <= 1.65:
        val = 'Letter'
    elif row['Height'] <=6.29 and row['Length'] <= 13.77 and 
    row['Width'] <= 17.71 and row['WEIGHT'] <= 4.4:
        val = 'Parcel-Small'        
    elif row['Height'] <=6.29 and row['Length'] <= 13.77 and 
    row['Width'] <= 17.71 and row['WEIGHT'] <= 4.4:
        val = 'Parcel-Large'
return val

As seen these dimension values are hardcoded. I want to take the inputs(package category name, height, length, width, weight) from a text file which in the format like :

[Package Category : Height, Length, Width, Weight]

It should read as many categories as specified by user and the code should be something like this :

for each package category:
    if row['Height'] <= Height and row['Length'] <=Length and row['Width'] 
    <= Width and row['WEIGHT'] <= Weight:
        val = 'Package Category'

Can someone give a actual code for the pseudo code given above? Thanks

JTable if current cell < cell total

how can I check following pseudo code in a JTable in real code ?

If( currentSelectedCell < cellTotal) {

//do stuff

}

where currentSelectedCell represents the current selected cell as the name says ... And cellTotal represent the number of all cells in the table. Both of type Integer.

I have no clue how to get the currentSelectedCell count ... Like if the table has 8 cells and about two rows 4 in one row and I select the third cell in row 2 would be cell count 6 cause it starts at "0" but how to count that ?

How to check mimeType against a specific set of mimeTypes?

Original code:

if($mimeType == 'image/jpeg' or $mimeType == 'image/png' or $mimeType == 'image/gif' && filename)

I tried this, but it will include unwanted *.pdf

if ($mimeType == ('image/jpeg' ||'image/png' ||'image/gif') && filename)

How do I make the code shorter?

And why the inner parentheses are not working?

My JavaScript code is not working properly

The code works as it is supposed to until I enter my real age as it says "At that age you would be dead" even if I enter 14. So it wont matter what digits I enter, it will still return the same thing

var age = [""];

/* Our function that is supposed to do all the magic */
function setAge() {
  /* Declairing the usersage-variable */
  var inputage = document.getElementById("input").value;

  /* If inputage isn't a number */
  if (isNaN(inputage)){
    alert("Your age must be a number");
    return false;
  }
  /* Testing if the age is higher than 115 */
  else if(inputage => 115) {
    alert("At that age you would be dead");
    return false;
  }
  /* Set the age equal to the value of the users input */
  age[0] = inputage;
  document.getElementById("output").value = age[0];
}

c#: " if " is working weird

i was developing my own BASIC language. When i was making IF command i got this:

object firstElement = tokens[1];
object secondElement = tokens[3];
string conditionType = tokens[2];
bool resultOfCondition = false;

if (conditionType == "==") {
    if (firstElement == secondElement) 
    {resultOfCondition = true; Console.WriteLine("DEBUG: true!");} else {resultOfCondition = false; Console.WriteLine("DEBUG: false!");}
} else if (conditionType == "!=") {

} else {
    throw new System.ArgumentException("It's not any type of contidion!", "original");
}

where

tokens[1] = 3;
tokens[3] = 3;
tokens[2] = "==";

and my console's output is really weird:

DEBUG: false!

I don't know what is going on, and why output is false! Can someone help me?

Check if table row is equal to week value then execute insert query

please i want to learn how to implement a query... i am designing a report system, i want each users to be able to submit reports to their upline boss once a week.

So, i want to check if the week of the last submitted report of a particular user is not equal to present week, then execute and submit report if it equals then echo warning message... here is my code below:

<?php
require('connect.php');
require('session.php');
$ddate = date("Y-m-d");
$date = new DateTime($ddate);
$week = $date->format("W");
$query= "SELECT * FROM memberTable, reportTable where user_id = '$session_id'";
$result = $DBcon->query($query);
$row3 = $result->fetch_assoc();

$submitted = "";
$status = "";
if(isset($_POST['btnsendreport'])){
    $created_date = date("Y-m-d");
    $created_dateFull = date("Y-m-d H:i:s");
    $reportPin = $_POST['reportPin'];
    $reportWeekNo = $_POST['reportWeekNo'];
    $sendercellname = $_POST['sendercellname'];
    $sendername = $_POST['sendername'];

    if($row3['reportWeekDate'] != $week){ 
        // insert query and execute
        $successMSG = "YAY!";
    }else{
        $errMSG = "NAH !"; // echo you can only submit once a week
        }

}
?>

So the issue i face now is that any users that want to submit report keep getting warning "$errMSG = "NAH !"; // echo you can only submit once a week". Whereas it supposed to be for the user who had already submitted.

I really hope someone can help me out.

Thanks in advance.

ifelse trying to create conditional column from Month column

I have a large data set and I am currently trying to create a column based on the month for either Winter (Sept - Mar) or Summer (Apr - Aug). Most things I have encountered to help split, want to split into 4 seasons, where for my data I need it specifically into these two seasons based on month. I have a Day column that is in

"%m/%d/%Y"

so I created a column with just the month

TAD_rawdata$Month <- format(as.Date(TAD_rawdata$Day), "%m")

which gave me a character string with the month as either "01" - "12"

so I tried using an ifelse statement to create my season column:

TAD_rawdata$Season <- ifelse (TAD_rawdata$Month == c("04", "05", "06", "07", "08"), "SUMMER", "WINTER" )

but it gives me this error

Warning message: In TAD_rawdata$Month == c("04", "05", "06", "07", "08") : longer object length is not a multiple of shorter object length

and then it just seems to randomly assign winter or summer, like the month will be for example 4 (so should be summer) but it will give it both summer and winter....

please help :) thanks

compare values in a field of a structure and replace with values from another column

I have a structure E.ev (1x4658) with 41 fields. When in E.ev.field1 there are the strings 'A_check' or 'A_bring', then I need to replace 'A_check' and 'A_bring' with the corresponding values (in the sense the values of the same row) of the field E.ev.field39.

If in the E.ev.field1 there are other strings, but not the ones I am interested in, then I need to keep those strings of E.ev.field1.

E.ev.field1 is made of all strings. E.ev.field39 is made of strings and empty values.

I tried with:

ii={E.ev}
if strcmp(ii.field1,'A_check'|'A_bring')
ii.field1 = ii.field39
else
ii.field1 = ii.field1
end

but it doesn't work. It says: 'Attempt to reference field of non-structure array.

IF Function/VLOOKUP Combo

So this seems like it should be pretty easy. I could just concatenate and make another column in the data to make a unique combo and get my answer. But that just seems so messy. So here I am reaching out to you fine folks to pick your brains.

I want to look up HQLine and Description in the MPCC tab to return the correct MPCC Code. I tried a couple IF statements with VLOOKUPS but couldn't get it right.

So I need to look up BK3 Positive Crankcase Ventilation (PCV) Connector in the MPCC tab. So it needs to match BK3 and the Long description and then give me the correct code.

Here is the missing data file enter image description here

Here is the MPCC export list that I want to search enter image description here

JavaScript if-Statement; when true it should play a sound

So im working on a twitch bot in JS, for now he connects with the chat and can recognize a command (like !twitter), but when someone writes !sound it should play a sound but I always see solutions with HTML and it should only work with JS and the Twitch Chat and run on my local PC. ( Sorry for bad english, its not my native language). Does someone has a solution or a advice for me?

var tmi = require('tmi.js');

var options = {
        options: {
                debug: true
        },
        connection: {
                cluster: "aws",
                reconnect: true
        },
        identity: {
                username: "",
                password: ""
        },
        channels: ["DiggnC"]
};
var client = new tmi.client(options);
client.connect();

// Connect Message in der Console
client.on('connected', function(adress, port){
console.log("Adresse: " + adress + " Port: " + port);
client.say("DiggnC", "Der Bot ist nun mit dem Stream verbunden!");
});

client.on('chat', function(channel, user, message, self) {
  if(message == "!twitter"){
    client.say("DiggnC", "Mein Twitter: https://twitter.com/thetruemitello")}
});

// Abfrage für Sound im Stream
client.on('chat', function(channel, user, message, self) {
  if(message =="!testsound"){
    client.say("DiggnC", "Dies ist eine Testausgabe zur Funktionalität der Audioausgabe");
    //Here it should play the sound on my local PC
  }
});

Explanation needed for the following python code

def greater_less_equal_5(answer):
 if answer>5 :   
  return 1
 elif answer<5 :          
  return -1
 else:
  return 0      
print greater_less_equal_5(5) 
print greater_less_equal_5(6)
print greater_less_equal_5(7)

Java Script: Array.length expression evaluate to boolean

How to check array length, if I need the expression to evaluate to boolean value as a result? For example:

var myArray = [];
if(!myArray.length){
  return;
}

Or:

vr myArray = [];
if(myArray.length == 0){
  return;
}

Both of the examples work, however I’d like to understand what is the difference?

how can i increment an if statement inside a while loop.

I'm trying to increment the count in each of the if statements. but it is not reading the count. if i don't use break it is going forever. i need to keep count because out of this loop i need to print bankruptcy if the count is less than 10.

      while(count<=10 ){
      boolean flag = false;
      String status="";
     while (true){
      if (diff>=10 &&array[rows][0]== min ){
         count++;
         status= "rising";
         System.out.println("the company stock is "+status+ "the
         price changed by "+ df.format(diff)+ " . total value " +
         df.format(totalvalue)+ "c"+count);

         break;

      }

      if (diff>=10 &&array[rows][0]== max){
          count++;
          status= "falling";
          System.out.println("the company stock is;" +status+ "the
          price changed by "+ df.format(diff)+ " . total value " + 
           df.format(totalvalue)+"c"+count);
         break;

      }
      if (diff<10 ){
       count++;
       System.out.println("the company stock is steady; " +status+ 
       "the price changed by "+df.format(diff)+ " . total value "
        +df.format(totalvalue)+"c"+count);
       flag=true;
       status="steady";


       break;

       }

}

How to add if input is empty within this code? Javascript, not jQuery.

currently a beginner learning javascript but I'm a bit stuck on how to add in this code if the inputs are empty, to shoot an alert. Would I add another function within the first? Any hints would be appreciated!

function getCandidateNames() {
var inputs = document.getElementsByTagName("input");
var result = [ ];
  for ( var i = 0; i < inputs.length ; i += 1) {
    if ( inputs[i].getElementsByTagName("candidate") ) {
      result.push( inputs[i].value );
    }
}
    return result;
}

function putCandidateNames(names) {
 document.getElementById("candidateName1").innerHTML = names[0];
 document.getElementById("candidateName2").innerHTML = names[1];
 document.getElementById("candidateName3").innerHTML = names[2];
}

function candidateNames() {
  putCandidateNames ( getCandidateNames() ) ;
}

The HTML

<fieldset id="candidates">
        <legend>Candidates</legend>
        <div>
            <label for="cand1">Candidate 1</label>
            <input class="candidate" id="cand1" placeholder="Candidate">
        </div>
        <div>
            <label for="cand2">Candidate 2</label>
            <input class="candidate" id="candName" placeholder="Candidate">
        </div>
        <div>
            <label for="cand3">Candidate 3</label>
            <input class="candidate" id="candName" placeholder="Candidate">
        </div>
    </fieldset>

Python code for conditional operators. What will be the output of the following code?

def greater_less_equal_5(answer):
    if answer>5 :
        return 1
    elif answer<5 :          
        return -1
    else:
        return 0

print greater_less_equal_5(5)
print greater_less_equal_5(6)
print greater_less_equal_5(7)

Why "if-else-break" breaks in python?

I am trying to use if-else expression which is supposed to break the loop if the if condition fails, but getting an invalid syntax error.

Sample code:

a = 5
while true:
    print(a) if a > 5 else break
    a-=1

Of course, if I write in the traditional way (not using the one liner) it works.

Please let me know what is wrong in using the break command after the else keyword.

How to incude file based on database value

I want to include a particular file from many based on user information.this is the piece of code, what am i getting wrong . This piece of code displays the database value of $name, and the values in the conditions are correct for the logged in user. this will eventually be improved with an elseif

if   


                        ( $_GET['department'] == CSS || ['level'] == 300 )



                        {
                        include "timetable/sict/css/300.php";    

                         }

else echo $name;

If element is there do A else do B in selenium Java. So Stuck

I've been stuck on this for some time now. I've tried multiple ways to make this work an it just doesn't. The problem is that it gets to the if statement and just sits there and does nothing. The elementId does work as both pieces of code work if I remove the if test. One way I have tried:

if(!driver.findElement(By.id(elementId )).isDisplayed()){
   driver.findElement(By.id(downloadId)).click();
   TimeUnit.SECONDS.sleep(7);

 }else{
   CenterOnClick.testFail(elementId , driver);     
   FailScreenShot.test(caseId, driver, targetNumberCell);

 }

another way:

 if(driver.findElement(By.id(elementId)).isEmpty()){ //also used .size() > 0
   driver.findElement(By.id(downloadId)).click();
   TimeUnit.SECONDS.sleep(7);

 }else{
   CenterOnClick.testFail(elementId , driver);     
   FailScreenShot.test(caseId, driver, targetNumberCell);

 }

I've also tried switching things around. The button I am trying to click is only available if you've not downloaded the file more than twice in a month. After that an error message takes it place. Weird thing is if I change the code to this:

 if(driver.findElement(By.id(elementId )).isDisplayed()){
   CenterOnClick.testFail(elementId , driver);     
   FailScreenShot.test(caseId, driver, targetNumberCell);

 }else{
   driver.findElement(By.id(downloadId)).click();
   TimeUnit.SECONDS.sleep(7);


 }

it works, but only when the error message is showing. If the button is there it will still just sit there. Any help would be greatly appreciated as I've been at this for well over 16 hours. Thanks.

Check if last character is equal to - Excel

I'm currently using this formula which isn't working:

=IF(RIGHT(TRIM(L3),1)=4,1,0)

The value in L3 is 4, and so I would expect it to return a 1, not a 0, however I am getting the 0 returned from the if statement.

Could someone explain why this is happening?

nested IF, AND, OR function compare and give result excel

Need help with this function.

=IF(AND($F5="Miks M",OR($G5="Miks M")),0,IF(AND($F5="Miks M",OR($G5="Miks L")),1,IF(AND($F5="Miks M",OR($G5="Miks XL")),2,IF(AND($F5="Miks M",OR($G5="Miks S")),-1,IF(AND($F5="Miks M",OR($G5="Miks XL PLUS")),3,IF(AND($F5="Miks M",OR($G5="Miks XXL")),4,IF(AND($F5="Miks M",OR($G5="Super")),5,IF(AND($F5="Miks M",OR($G5="Prica Plus")),-2,IF(AND($F5="Miks S",OR($G5="Prica Plus")),-1,IF(AND($F5="Miks S",OR($G5="Miks S")),0,IF(AND($F5="Miks S",OR($G5="Miks M")),1,IF(AND($F5="Miks S",OR($G5="Miks L")),2,IF(AND($F5="Miks S",OR($G5="Miks XL")),3,IF(AND($F5="Miks S",OR($G5="Miks XL PLUS")),4,IF(AND($F5="Miks S",OR($G5="Miks XXL")),5,IF(AND($F5="Prica Plus",OR($G5="Prica Plus")),0,IF(AND($F5="Prica Plus",OR($G5="Miks S")),1,IF(AND($F5="Prica Plus",OR($G5="Miks M")),2,IF(AND($F5="Prica Plus",OR($G5="Miks L")),3,IF(AND($F5="Prica Plus",OR($G5="Miks XL")),4,IF(AND($F5="Prica Plus",OR($G5="Miks XL PLUS")),5,IF(AND($F5="Prica Plus",OR($G5="Miks XXL")),6,IF(AND($F5="Miks L",OR($G5="Prica plus")),-3,IF(AND($F5="Miks L",OR($G5="Miks S")),-2,IF(AND($F5="Miks L",OR($G5="Miks M")),-1,IF(AND($F5="Miks L",OR($G5="Miks L")),0,IF(AND($F5="Miks L",OR($G5="Miks XL")),1,IF(AND($F5="Miks L",OR($G5="Miks XL PLUS")),2,IF(AND($F5="Miks L",OR($G5="Miks XXL")),3,IF(AND($F5="Miks L",OR($G5="Super")),4,IF(AND($F5="Miks XL",OR($G5="Prica plus")),-4,IF(AND($F5="Miks XL",OR($G5="Miks S")),-3,IF(AND($F5="Miks XL",OR($G5="Miks M")),-2,IF(AND($F5="Miks XL",OR($G5="Miks L")),-1,IF(AND($F5="Miks XL",OR($G5="Miks XL")),0,IF(AND($F5="Miks XL",OR($G5="Miks XL PLUS")),1,IF(AND($F5="Miks XL",OR($G5="Miks XXL")),2,IF(AND($F5="Miks xL",OR($G5="Super")),3,IF(AND($F5="Miks XL Plus",OR($G5="Prica plus")),-5,IF(AND($F5="Miks XL Plus",OR($G5="Miks S")),-4,IF(AND($F5="Miks XL Plus",OR($G5="Miks M")),-3,IF(AND($F5="Miks XL Plus",OR($G5="Miks L")),-2,IF(AND($F5="Miks XL Plus",OR($G5="Miks XL")),-1,IF(AND($F5="Miks XL Plus",OR($G5="Miks XL PLUS")),0,IF(AND($F5="Miks XL Plus",OR($G5="Miks XXL")),1,IF(AND($F5="Miks xL Plus",OR($G5="Super")),2,IF(AND($F5="Miks XXL",OR($G5="Prica plus")),-6,IF(AND($F5="Miks XXL",OR($G5="Miks S")),-5,IF(AND($F5="Miks XXL",OR($G5="Miks M")),-4,IF(AND($F5="Miks XXL",OR($G5="Miks L")),-3,IF(AND($F5="Miks XXL",OR($G5="Miks XL")),-2,IF(AND($F5="Miks XXL",OR($G5="Miks XL PLUS")),-1,IF(AND($F5="Miks XXL",OR($G5="Miks XXL")),0,IF(AND($F5="Miks xXL",OR($G5="Super")),1,IF(AND($F5="Super",OR($G5="Prica plus")),-7,IF(AND($F5="Super",OR($G5="Miks S")),-6,IF(AND($F5="Super",OR($G5="Miks M")),-5,IF(AND($F5="Super",OR($G5="Miks L")),-4,IF(AND($F5="Super",OR($G5="Miks XL")),-3,IF(AND($F5="Super",OR($G5="Miks XL PLUS")),-2,IF(AND($F5="Super",OR($G5="Miks XXL")),-1,IF(AND($F5="Super",OR($G5="Super")),0))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))

Is there any chance to this function become shorter and simpler? For now its working perfect but if it can be shorter it would be much better. If cell F5 is Miks M and cell G5 is Miks M write 0 in H5 if G5 is Miks L write 1 in H5 and soo on.

Check List elements in C# and Python

I have worked on Python and I am new in C#. I am trying to get familier with syntaxes and concepts. I have a problem with list.

For example, I will take a word from user. I will add it to a list and I will check if it is entered before because user can't give the same word second time. If it is not entered before add it to the list. If is is already in the list pass it.

In python:

check_list = list()
if word not in check_list:
    check_list.append(word)
else:
    pass

How can I do that in C# ???

if vs else if method comparing

I wonder if there is any difference between those methods

public bool GetCondition(string s1, string s2)
{
    if (s1.StartsWith('a'))
    {
        return false;
    }
    if (s2.StartsWith('c'))
    {
        return false;
    }
    if (s1.StartsWith('b') && s2.StartsWith('d'))
    {
        return false;
    }
    return true;
}

and

public bool GetCondition(string s1, string s2)
{
    if (s1.StartsWith('a'))
    {
        return false;
    }
    else if (s2.StartsWith('c'))
    {
        return false;
    }
    else if (s1.StartsWith('b') && s2.StartsWith('d'))
    {
        return false;
    }
    return true;
}

Are they equal or is there a different behaviour to expect? If not, what is the better way to write?

Python 2.7: if-else condition to find any ip address from range 10.0.0.1 to 10.255.255.255

i want to write a program in python such as

x='10.0.1.2' or any ip address from range 10.0.0.1-10.255.255.255

if(x==any ip address range from 10.0.0.1-10.255.255.255): //do task A else: //do task B

If condition doesn't enter for identical ints and break point displays an X

Screenshot of the code

As you can see on the screenshot the values are the same but somehow the "return remark" part has an X and it's not executed.

The error when the x brake point is highlighted is:

Line 85 in LedgerManager.getRemarkForImageMap((com.paperless.transportation.services)  
No executable code found at line 85 in class com.paperless.transportation.services.LedgerManager
Suspend: thread

Crete an eval if in asp.net

I am trying to create an If that has the condition that, if the eval value is 0 the div wont appear.

<%@ if (DataBinder.Eval(Container.DataItem, "Desconto").ToString() != "0"){ %>
    <p><span class="oldprice"><%# Eval("Preço") %>€</span> <i class="newprice item_price"><%# ((decimal)Eval("Preço")-(decimal)Eval("Preço")*((decimal)(int)Eval("Desconto")/100)).ToString("N2") %></i>€</p>
<%@ } %>

But i am not figuring out the syntax to create the eval, it aways ends up as some error.

Thanks in advance for reply.

Making a payment system (Game) (Solution)

Let me prefix by saying, I know stackoverflow is for questions, but I saw none that fit this problem, and as a noob I figured someone else MUST have run into this issue at some point, so I decided to put it on here as a guide so-to-say, please don't downvote just because it isn't a question.

Okay, so I am making a game solely for me and my mate who love 'Idle' games, simply so that I can make it how the consumer(me) wants it to be, but I ran into a problem, to explain it I will give an example from another popular 'Idle' game, Cookie Clicker.

In Cookie Clicker, you can buy "Cursor's" which add a click-less form of gaining cookies, or in my case, money, since I just want this to be as SIMPLE as possible, I am trying to do that, I start the timers with loading of the form instead of first purchase since that would start a new timer every time, but I need to check if the money is equal to or more than the price.

Now here was the problem, Too make it start with 0 I set "cursor's" or in my case, "hammer's" to 0, with int hammer = 0; now I need to work out payment, so in the picture of a hammer, in other words the buy button, I do int pay = hammer * 15; since the way to work out the price for this item is the amount of hammer's times fifteen, all well and good now, So I go to add the if statements to check, and I test, thinking everything was fine, but I was able to buy a hammer with 0 cash, now I am wondering why, my code seems foolproof, it looks complete, its even organised neatly, but something is wrong, why can I buy stuff with 0 cash, then it hit me, later that day... its working out (hammers x 15) but, I set hammers to be 0, and 0 times anything equals 0, so within the hour I revised my code to work, I will share that with you now for any suffering the same problem.

int pay = hammers * 15 + 15;
        if (hammers == 0)
        {
            if (cash >= 15)
            {
                money.Text = cash; 
                hammers += 1;
                cash -= 15;
            }
            else if (cash <= 15)
            {
                notifyIcon1.BalloonTipText = "ERROR: You do not have enough cash to buy this!";
                notifyIcon1.ShowBalloonTip(1000);
            }
        }
        else if (Hammers >= 1)
        {
            if (cash < pay)
            {
                notifyIcon1.BalloonTipText = "Error: You do not have enough cash to buy this!"; notifyIcon1.ShowBalloonTip(1000);
            }
            else if (cash >= pay)
            {
                money.Text = cash;
                hammers += 1;
                cash -= pay;
            }
        }

There is the solution, Enjoy!

Javascript OR operator not working in if statement

I'm trying to get this Javascript to do something if the day of the week matches any of the days listed in my statement, as well as restricting it to between 17:00 and 19:00 hours, but the OR operator is not working as I expected, I'm new to JS and I'm wondering if I'm misunderstanding the use of this operator. If I were to list a value for just one day of the week, instead of 3 like in my example, the code works as I'd hoped.

var d = new Date();
var dayOfWeek = d.getDay(); // 0 = Sunday
var hour = d.getHours();

if ( dayOfWeek == 4 || 5 || 6 && hour >= 17 && hour < 19 ){
    // do stuff
  } else {
    // do other stuff 
} 

Can't make String equal method and Converting Strings to Numbers work together.

It is a Java beginner question. The program is not complicated, it just asks the user input grade and then finish it when the user input "y" , and then calculate max, min,average, and total.

My trouble is that I can't stop the loop when I type y. Thank you so much, if anyone can help me out. I have tried many approaches to figure that.

    do
       { 
        System.out.println("please go on");
        input = keyboard.next();                    
        grade = Integer.parseInt(input);
        InputTimes++;
        if (grade>Maxgrade)
        {   
            Maxgrade = grade;       
         }

        if(Mingrade>grade)
        {
            Mingrade= grade;            
        }

        if (input.equals("y"))
        {   
            GameOver = true;
            System.out.println("yyyyyyy");
            break;
        }   
        else 
        {
            GameOver = false;
            System.out.println("nnnnnn");   
        }   
        totalgradeNoF = grade+totalgradeNoF;

    }while(GameOver==false);

jeudi 29 juin 2017

String/Case programing error

I was able to get invalid major when I put a letter that is not listed major, but if I put t2, I would only get invalid major and not (invalid major, sophomore). Can someone detect the code and tell me where I went wrong.

    // Enter two characters

    System.out.print("Enter two characters: ");
    String status = in.next();

    char major = Character.toUpperCase(status.charAt(0));
    char year = status.charAt(1);

    String courseName = "";
    String yearName = "";

    // majors

    if (major == 'B' || major == 'I' || major == 'C')
    {
        switch(major)
        {
            case 'B':
                courseName = "Biology"; break;
            case 'C':
                courseName = "Computer Science"; break;
            case 'I':
                courseName = "Information Technology"; break;

            default:System.out.println("Invaild major"); break;
        }

        // year

        switch(year)
        {
            case '1':
                yearName = "Freshman"; break;
            case '2':
                yearName = "Sophmore"; break;
            case '3':
                yearName = "Junior"; break;
            case '4':
                yearName = "Senior"; break;

            default: System.out.println("Invalid year status"); break;
        }

        System.out.printf("%s %s%n", courseName, yearName);
    }
    else{
        System.out.printf("Invalid input.%n"); 
    }
}

}

Merge array by key with conditions

I have a problem. I would like to merge array by conditions. If array keys match then add its value if not then print as it is. I tried all the possible thing I can but didn't get the right result. here is my arrays.............

 Array1(   [1] => 199
           [3] => 1306
           [5] => 199
         )
  Array2(  [3] => 199
           [4] => 199
           )

I want to add the value if array keys match and print as it is if not match..like this...

  Resylt(  [1] => 199
           [3] => 1505
           [4] => 199
           [5] => 199    
           )

I used if else conditions. but its repeating the value which is already match here is my code...

  $all=array(); 
  foreach($sall as $sskey => $ssvalue){
     foreach($upgradesall as $uukey => $uuvalue){
         //$sskey==$uukey?$all[] = array("id"=>$sskey, "amount"=>$ssvalue+$uuvalue):($sskey!=$uukey? $all[] = array("id"=>$sskey, "amount"=>$ssvalue):($uukey!=$sskey?$all[] = array("id"=>$uukey, "amount"=>$uuvalue):''));
         if($sskey===$uukey){
             $all[] = array("id"=>$sskey, "amount"=>$ssvalue+$uuvalue);
         }
         elseif($sskey!=$uukey){
             $all[] = array("id"=>$sskey, "amount"=>$ssvalue);
         }
         elseif($uukey!=$sskey){
             $all[] = array("id"=>$uukey, "amount"=>$uuvalue);
         }

         }
        }   

Raspberry pi button delay time to a relay

I am new to Raspberry pi and python and am having a bit of trouble with some code I wish to push a button and have the gpio pin that corresponds to that button trigger a relay to turn on for a given amount of time then turn off. I have it working with the code below but by using the 'time.sleep(my-variable)' it holds up the raspberry pi for the duration of the time and i am unable to do anything else. What i am after is the ability to push one button and get the relay to act for say 10 seconds and within those 10 seconds be able to press another button to fire another relay and do the same thing without tying up the pi

my code below first checks if input_state_LHS is equel to false, then clears the LCD display, writes text to the LCD on one line then on the next line it write the value of my variable(LHS_feedtime) then fires the relay with the time on the next line time.sleep, this is the bit i wish to be rid of but am unable to figure out the code to do it.

if input_state_LHS == False:
        ## calls the LCD_Clear function which has to be in the same folder as this file
        mylcd.lcd_clear()
        mylcd.lcd_display_string("LHS Feedtime",1,2)
        mylcd.lcd_display_string(str(round(LHS_feedtime, 2)) + " sec" , 2,5)
        GPIO.output(27, GPIO.input(12) )
        time.sleep(LHS_feedtime)
        mylcd.lcd_clear()
        mylcd.lcd_display_string("Flatson Feeding", 1)
        mylcd.lcd_display_string("Systems", 2,4)
        GPIO.output(27, GPIO.input(12) )
        menuitem = 0

thanks for the help

giving if condition for time

Is there any way we can give a condition statement in a if else loop as

 a= "06/28/2017 08:45"
 b= "06/28/2017 08:32"
 c= difftime(a,b,units="mins)
`if(a+30 > b)
 { 
  print("you are late")
  }else
  print("on time")`

I'm getting error as

 `1.Error in if (a+30 > b) missing value where TRUE/FALSE needed
  In Ops.factor(a+30 > b) :‘>’ not meaningful for factors
  2: In if (a+30 > b) { : the condition has length > 1 and only the first element will be used`

What I'm trying to do is to add 30min to 'a' and compare it wih 'b' to determine if something is late or on time.

PHP - [Best way to] Concatenate between strings with ternary or with previous "settlements"?

General question: which one of these options is the best practice and why?

Specific or narrow situation: Let's say I read a file list.txt and store the data inside an array (assume list.txt content: "Name: John" & "Product: Banner"). E.g.:

$txt='/files/list.txt';
$archive = fopen($txt,'r');
$le = fread($archive,filesize($txt));

$data = explode("\n",$le);
$person = explode(":",$data[0]);
$name = $person[1]; # "John"

$field1 = explode(":",$data[1]);
$field01 = $field1[0]; # "Product"
$field1 = $field1[1]; # "Banner"

Now, I want to send an email, for the sake of the example, I want to send with or without the information about the product. Assume predefined body/table:

    <tr>
        <td>
            <b>'.$name.'</b>
        </td>
    </tr>
'.((isset($field1) || isset($field1[0])) ?
    '<tr>
        <td>
            <b>'.$field01.':</b>'.$field1.'
        </td>
    </tr>' : '' ).
'</table>

Is it safe? Is there a better way to do this (n performance wise)? Is there a chance that I get "Undefined variable" if the variable itself is not set for not having a matching field in the list.txt? Specifically or in general concatenation.

Related: if statement in the middle of concatenation?

php if statement if variable is empty or has at least 5 characters

I need to check if my variable is not empty and has at least 5 characters. The $results is a mix of letters and numbers.

 if($results == !empty AND has 5 characters){
   //do a task
 } else {
   //do another task
 }

If statement is false but code in it, still runs as well as all the code in the entire script in python - New to Python

This is code to find details about elements by asking the user about which element they want to learn about. The problem is when I run it it prints all of the print statements.

print ('Please type the element number or the name - no caps')
element = input('What element do you want to learn about?')


if element == ('1') or ('hydrogen'):
        print ('Hydrogen #1')
        print ('Gas')
        print ('Non-Metal')
        print ('Weight: 1.008')


if element == ('2') or ('helium'):
    print ('Helium #2')
    print ('Gas')
    print ('Non-Metal')
    print ('Weight: 4.0026')

if element == ('3') or ('lithium'):
    print ('Helium #3')
    print ('Solid')
    print ('Metal')
    print ('Weight: 6.94')

This is what happens when I run it.

Please type the element number or the name - no caps
What element do you want to learn about? 1
Hydrogen #1
Gas
Non-Metal
Weight: 1.008
Helium #2
Gas
Non-Metal
Weight: 4.0026
Helium #3
Solid
Metal
Weight: 6.94

how to multyply two diffrent rows in mysql?

I have this formula in excel"=IF(E3=1,1,F3*G2)" which multiply a cell with upper cell in another column . I wonder if I can have it as query in MYSQL?

Unable to iterate through my Hashmap after if statement

i have two inner classe which are downloading jsons from two seperate SQL Databases. First i'm iterating through my first Hashmap and if there is a String equal to an locale set String it should iterate through my seccond hashmap. Unfortunately it doesent work, but if i add a simple for loop its working. Here you can see the mentioned code. `

    for (final HashMap<String, String> contact : tslist) {
        Toast.makeText(getApplicationContext(),"Loop is working ",Toast.LENGTH_SHORT).show();

        if (contact.containsValue(result.getText().toString())) {
            Toast.makeText(getApplicationContext(), "QR Valid", Toast.LENGTH_LONG).show();

            new GetValues().execute();
            for (final HashMap<String, String> ts : contactList) {
                Toast.makeText(getApplicationContext(), "Seccond loop is runnign", Toast.LENGTH_LONG).show();
            }

        }`

Here is my first inner Class:

    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(qr.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(true);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url_locids);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONArray contacts = new JSONArray(jsonStr);

                    // Getting JSON Array node


                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String id = c.getString("id");


                        HashMap<String, String> contact = new HashMap<>();

                        // adding each child node to HashMap key => value
                        contact.put("id", id);


                        // adding contact to contact list
                        tslist.add(contact);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();


        }
    }

and Here my Seccond one:

 private class GetValues extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(qr.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(true);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(ts_urlts);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONArray contacts = new JSONArray(jsonStr);

                // Getting JSON Array node


                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    String uid = c.getString("userid");


                    HashMap<String, String> contact = new HashMap<>();

                    // adding each child node to HashMap key => value
                    contact.put("userid",uid);


                    // adding contact to contact list
                    contactList.add(contact);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();


    }
}

Change style of the element in the middle of an array

i use D3.js and i got another problem. I got this array pat, which let me click 2 nodes and stores the shortest path between those nodes in the array. Now, i created the middle element of pat called mid. My goal is, to change the style of this element, lets say into another color red. but i am struggling to find the right solution. Here you can see my code. How, someone can help me to find a solution.

var mid = null;

     node.on("click", function(d, i){
        var pat = start && start.pat(d) || []

        mid = pat[Math.floor((pat.length - 1) / 2)];

        node.style("fill", function(d) 
                        {
                          if (pat.includes(mid)){ return "red";}

                        });

Check if all text inputs are empty, show alert with for if/else statement?

beginner here. I'm trying to use a conditional to check whether if the text inputs have been filled out, otherwise if empty, prompt an alert but it doesn't appear to do anything? Is my JS poorly laid out? Here is my jsfiddle. http://ift.tt/2t5KeYs

Thank you!!

<div>
    <label for="cand1">Candidate 1</label>
    <input class="candidate" id="cand1" placeholder="Candidate">
</div>

<div>
    <label for="cand2">Candidate 2</label>
    <input class="candidate" id="cand2" placeholder="Candidate">
</div>

<div>
    <label for="cand3">Candidate 3</label>
    <input class="candidate" id="cand3" placeholder="Candidate">
</div>

The JS

function candidateNames() {
   var inputs = document.getElementsByTagName("input");
   var result = [];
 for ( var i = 0; i < inputs.length; i += 1 ) {
   result[i] = inputs[i].value;

  if (inputs === '' || null || 0) {
      alert('Need to fill inputs');
  }  
}
  document.getElementById("candidateName1").innerHTML = result[0];
  document.getElementById("candidateName2").innerHTML = result[1];
  document.getElementById("candidateName3").innerHTML = result[2];
}

Testing for input accuracy using a scanner with while and nested if/else statements

So I am trying to use a while loop to continue asking for input while the user's input of a random number does not equal the random number generator's output. However when I input the number the higher/lower outputs do not work. It either always says its higher or always says its lower, regardless of the actual numerical value. Help?

import java.util.Random;
import java.util.Scanner;

public class GuessingGame {
    public static final int MAX = 100;
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        Random rand = new Random();
        int rand1 = rand.nextInt(MAX);
        introduction();
        game(scan, rand1);
    }
    public static void introduction() {
        System.out.println("This program allows you to play a guessing game."     
            " I will think of a number between 1 and" +
            " 100 and will allow you to guess until" +
            " you get it.  For each guess, I will tell you" +
            " whether the right answer is higher or lower" +
            " than your guess");
    }
    public static void game(Scanner scan, int rand1) {
        System.out.println("I'm thinking of a number between 1 and 100...");
        System.out.println(rand1);
        System.out.println("Your guess?");
        int input = scan.nextInt();
        while(input != rand1) {
            if (input < rand1) {
                System.out.println("It's higher");
                scan.nextInt(input);
            }
            else if (input > rand1) {
                System.out.println("It's lower");
                scan.nextInt(input);
            }
         }
    }
}

can you have two conditions in an if statement

I'm a beginner in java coding, so I regularly browse to find beginner projects with my basic knowledge. I was recently working with to create a chatting programme where a user will chat with my computer. Here is a part of the code, since I don't need to show the whole code:

 System.out.println("Hello, what's our name? My name is " + answer4);
        String a = scanner1.nextLine();
        System.out.println("Ok, Hello, " + a + ", how was your day, good or bad?");
        String b = scanner2.nextLine();
        **if (b.equals("good"))** {
            System.out.println("Thank goodness");
        } else **if (b.equals("it was good"))** {
            System.out.println("Thank goodness");
        } else **if (b.equals("bad"))** {
            System.out.println("Why was it bad?");
            String c = scanner3.nextLine();
            System.out.println("Don't worry, everything will be ok, ok?");
            String d= scanner10.nextLine();
        }
        else **if (b.equals("it was bad"))**{
            System.out.println("Why was it bad?");
            String c = scanner3.nextLine();
            System.out.println("Don't worry, everything will be ok, ok?");
            String d= scanner10.nextLine();
        }

        if(age<18){System.out.println("How was school?");}
        else if (age>=18){System.out.println("How was work?");}

The conditions of the if statements are in Bold. The first and the second are similar, and so are the third and fourth. I thought it was possible to make them this, but it wasn't:

 if (b.equals("good"),b.equals("it was good")) {
            System.out.println("Thank goodness");
        }  else if (b.equals("bad"),(b.equals("it was bad"))) {
            System.out.println("Why was it bad?");
            String c = scanner3.nextLine();
            System.out.println("Don't worry, everything will be ok, ok?");
            String d= scanner10.nextLine();
        }

Can someone correct it for me pls? I'd really appreciate it!

Are these JS conditional statements functionally equivalent?

Regarding conditional if/else statements, are the following examples functionally equivalent?

function isEntering() {
    if (this.stage = 'entering') {
        return true;
    } else {
        return false;
}

function isEntering() {
    if (this.stage = 'entering') {
        return true;
    } return false;
}

function isEntering() {
    if (this.stage = 'entering') {
        return true;
    } 
}

isEntering = (this.stage === 'entering') ? true : false;

If so, I'd use the most terse of the options. But only if the three are functionally equivalent.

Count If A and B matches, then numbers in sequence before A changes

I have a puzzling question for SQL.

I'm looking to take 2 single criteria (criteria1 and criteria2), test it against a single row criteria in a database, then if they both match, to get a COUNT on rows in a sequence before criteria1 changes.

We have a shared table of consecutive 'serial' type numbers but with different 'part' type numbers and are looking to get a count of rows of consecutive numbers if the first test matches.

Like:

AA  12
AA  13
AA  14
AA  15
BB  16 
BB  17
BB  18
AA  19
AA  20

I've tried:

SELECT COUNT(CASE column1 WHEN 'criteria1' THEN 1 ELSE NULL END) 
    FROM [dbo].[tableName] 
    WHERE [column1] = 'criteria1' AND [column2] BETWEEN criteria2 AND criteria3

And:

IF EXISTS (SELECT 1 FROM [dbo].[tableName]  WHERE 
[column1] = 'criteria1' AND [column2] = criteria2)
BEGIN
    SELECT COUNT(CASE column1 WHEN 'criteria1' THEN 1 ELSE NULL END) 
    FROM [dbo].[tableName] 
    WHERE [column1] = 'criteria1' AND [column2] BETWEEN criteria2 AND criteria3
END

These don't do an initial criteria1 matches and criteria2 matches test before getting the series count, but get the count for matches overall 'between' criteria2 and criteria3, tho not without (consecutive) fault. These also don't look at consecutive matches before criteria1 would change. This can be done via stored procedure or direct statement.

How do nested if-Statements in JS work?

I got a problem with nested if-statements in JS. Let me show you the code example:

    if (code < 699) {
        if(hour > 6 && hour < 20) {
            $("#weatherIcon").html("<i class='wi wi-day-" + icon + "'></i>");
        }
        else {
            if(icon == "sunny") {
                $("#weatherIcon").html("<i class='wi wi-night-clear'></i>");
            }
                $("#weatherIcon").html("<i class='wi wi-night-alt-" + icon + "'></i>");
            }
        }

        $("#weatherIcon").html("<i class='wi wi-" + icon + "'></i>");
   }

I added a print statement so I can check the values for code, hour and icon (values are 502, 17 and rain-mix) so I should get <i class='wi wi-day-sunny'></i> returned but I always end up in the last line so that the output is e.g. <i class='wi wi-sunny'></i> Why is that? What am I not seeing? Any help very much appreciated, thanks!

Shell script if statement compraising of string comparision and boolean check

I have a function where in I'm trying to compare the first parameter to a string, and then a separate boolean variable.

My sample bools:

EMS=true; 
COLL=true;

At a given point, both or any one or none of them can be true.

My function body:

function some_function() {
...
...
     if [ [ "$1" = "ez" ] &&  $EMS ] || [ "$1" = "coll" ] &&  $COLL ]; then
     #do mysterious magic
     ...
     ...
fi
}

I'm calling the function like so:

some_function ez
some_function coll

However when I execute the script, I run into this:

./deployBuild.sh: line 145: [: too many arguments

My if loop is incorrect and I'm unable to fix it. How do I proceed with?

Pseudo code of what I want to achieve:

if ("$1" is "ez" AND $EMS evaluates to true) OR ("$1" is "coll" AND $COL evaluates to true)

If statement does not return expected result

job.ProductTypeId and product.GetProductTypeKey() are of type Integer.

If job.ProductTypeId is 3 and product.GetProductTypeKey() is 4 , this should result in false but that does not happen. Wrong implementation of IF statement?

if ((job.ProductTypeId <= product.GetProductTypeKey()) && 
    (product.GetProductTypeKey() < 4))

changing group color with if condition in json

I am a bit new to json and all. I wrote a program that can take in a txt file, read the header then rearrange the columns header,value into group that easier to look at.

I use javafx for GUI and json file to handle the grouping.

The program is working but i want to take it one step further. I want the color of that group change from , for example, black to red whenever the value exceed a certain threshold.

So how would i do that in json file? what is the syntax of if else ? Can you give me an example base on the snippet of the code ? Thanks

json file:

[
  {
    "id": 1,
    "name": "Magtitue",
    "columnNames": [
      "magx",
      "right mag",
      "magy",
      "forward mag",
      "magz",
      "down mag"
    ],
    "color": "red"
  },
  {
    "id": 2,
    "name": "Flight Time",
    "columnNames": [
      "flighttime",
      "flight time"
    ],
    "color": "green"
  },
  {
    "id": 3,
    "name": "Temperature",
    "columnNames": [
      "temperature"
    ],
    "color": "blue"
  }
]

java handler that use json file:

@ToString
@Data
public class ColumnGroupInfo implements Comparable {

    private static final Gson GSON = new Gson();
    private int id;
    private String name;
    private String color;
    private List<String> columnNames = new LinkedList<>();

    public ColumnGroupInfo(int id, String name, String color) {
        super();
        this.id = id;
        this.name = name;
        this.color = color;
    }

    public static ColumnGroupInfo newInstance(JSONObject json) {
        ColumnGroupInfo ent = GSON.fromJson(json.toString(), ColumnGroupInfo.class);
        return ent;
    }

    public int getId() {
        return id;
    }


    public void setId(int id) {
        this.id = id;
    }


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }


    public String getColor() {
        return color;
    }


    public void setColor(String color) {
        this.color = color;
    }


    public List<String> getColumnNames() {
        return columnNames;
    }


    public void setColumnNames(List<String> columnNames) {
        this.columnNames = columnNames;
    }

    @Override
    public boolean equals(Object obj) {

        if (!(obj instanceof ColumnGroupInfo)) {
            return false;
        }
        ColumnGroupInfo columnGroupInfo = (ColumnGroupInfo) obj;
        return columnGroupInfo.id == this.id &&
                columnGroupInfo.name.equals(this.name) &&
                columnGroupInfo.columnNames.equals(this.columnNames);

    }

    @Override
    public String toString() {
        return String.format("id:%s,name:%s,color:%s", id, name, color);
    }


    @Override
    public int compareTo(Object o) {
        if (o instanceof ColumnGroupInfo) {
            ColumnGroupInfo compare = (ColumnGroupInfo) o;
            return Integer.compare(getId(), compare.getId());
        }
        return 0;
    }
}

MYSQL query Alter table engine only if engine not innodb

I would like to run one query that alter table's engine (ALTER TABLE table1 ENGINE = INNODB) only if the current engine is not INNODB.

How can i do that?

Thanks

If statement on Sheet Range

I am writing and Excel VBA if statement, but I can't figure out why it is not working.

I have 1 Sheet called "Data" and I want to check if some variables in column I are the same as in my ActiveSheet row 2, column B (which is number 2). I used the following code which ends automatically because it is not working. Anybody an idea?

Example:

Sub test()

If Sheets("Data").Range("I:I") = ActiveSheet(2, 2) Then
MsgBox ("Yes")
Else
MsgBox ("No")
End If

End Sub

Excel formula to verify cell and skip to next row

it is possible the answer is "IF" statement. Here is the question.

Column A ABC ABC XYX XYX AAA

Column B 12 22 1 23 3

Column C If Cell A = ABC then display Column B, If Cell A doesn't = ABC then go to next row.

Question 1: I would like the formula to check A1, A2, etc. and return result in C1, C2, etc. with value equals to B1, B2.

Question 2: Just say A8 is the last entry. A9 is blank. Is there a formula to know to stop if A1 is blank and stop validation.

Excel - Separate formula for calculating different rates based on hours discussion

enter image description here

I am trying to calculate my hours based on the rate those hours were worked. Right now my formula looks like:

=IF(AND(TEXT(D6,"dddd")=H4,J14>=48,O12="Yes"),D14*(G3*2),IF(AND(TEXT(D6,"dddd")=G4,J14>40),D14*(G3*1.5),G3*D14))

I know that D14 is not the proper cell to use, just what I had came up with to partially get this working.

What I need is to add if over 8 hours calculate at this rate, if day 1 off calculate it all at 1.5 and if second day off calculate it at 2x rate. the equation I stated above is a working if for the days off part, i just need help with the rate part.

PHP If statement on select elemnet created with array

I'm new to PHP and encountering an issue I am unable to resolve.

say we have this:

<select name="car">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

and my php is:

if (isset($_POST['car']) && $_POST['car'] == "Audi") {
    echo 'Please select a better car.';
}

this works. However,I made a generated select off an array:

<select name="q1" value="<?php echo $q1 ?>">
        <?php foreach ($toppings as $key => $value) { ?>
            <option <?php if ($q1 == $key) { ?>selected="true" <?php }; ?>value="<?php echo $key ?>"><?php echo $value ?></option>
        <?php } ?>
    </select>

and then I wrote this php code as follows:

<?php
$toppings = array(1 => "Anchovie", 2 => "Tomato", 3 => "Corn", 4 => "Bulgarian", 5 => "Pineapple", 6 => "Pepperoni", 7 => "Green Olives", 8 => "Ground Beef", 9 => "Red Peppers", 10 => "Tuna", 11 => "Cheese");

if (isset($_POST['q1']) && $_POST['q1'] == "Cheese") {
    echo 'you selected cheese!.';
}
?>

This does not work and I am unable to figure why on my own. Please help, thank you.

PHP conditional string echo [on hold]

I need to print out a different text depending on what the $get_payment_method variable includes. The following code prints out either "cod" or "thepaycard".

<?php printf( $this->order->get_payment_method() ); ?>

I need to get that changed to "Dobírka" and "Kartou". Could you please suggest, what I'm doing wrong? Here is the code I've come up with:

<?php 
$platba = (string)$payment_method; 
if (strpos($platba, 'cod') !== false) {
    echo "Dobírka";
} else {
    echo "Kartou";
}?>

Thank you

My jsp page only executes the else statement

I have the following login codes.

if (uname == "Abigail" && password=="Abby14"){
    response.sendRedirect("http://localhost:8080/Practical_4/member.jsp");
     }

 else {
   response.sendRedirect("http://localhost:8080/Practical_4/index.html");

 }

I realized that my jsp page treats the if-statement as if it's an else statement, and only executes the else-statement.

Search for Specific Text with Special Characters in a String in PHP

I am using a script to check if a string $status contains the following text or not -

SC-102 || EOD-103 || EOD-31 || DLYDC-104 || EOD-72 || ST-108 || SC-104 || X-SC || EOD-114 || DLYMR-118 || EOD-76 || EOD-6 || EOD-95 || EOD-69 || EOD-16 || EOD-2 || EOD-97 || EOD-110 || EOD-15 || EOD-32 || EOD-107 || EOD-106 || EOD-46 || EOD-104 || EOD-42 || EOD-7 || EOD-111 || EOD-43

|| is used to represent OR

The Letters, Special Characters & Numbers are one single piece of TEXT. For. Example - ST-102 is an exact text to be search from $status

My present code looks like the following -

$codes = array("SC-102","EOD-103","EOD-31","DLYDC-104","EOD-72","ST-108","SC-104","X-SC","EOD-114","DLYMR-118","EOD-76","EOD-6","EOD-95","EOD-69","EOD-16","EOD-2","EOD-97","EOD-110","EOD-15","EOD-32","EOD-107","EOD-106","EOD-46","EOD-104","EOD-42","EOD-7","EOD-111","EOD-43");

if($status_code==$codes)
{
//My Script , if condition is true!
}

mercredi 28 juin 2017

how to check if variable is empty or not in php and if its no need to display it in the table

i have PHP code with MYSQL database where the code fetch and select the required values and display it in a table.

what i need is to make a check before the display if the variable is empty do not display in the table.

for this i used the if statement but its not working.

code:

$sql = $wpdb->prepare("select i.siteID
     , i.siteNAME
     , i.equipmentTYPE
     , c.latitude
     , c.longitude
     , c.height 
     , o.ownerNAME
     , o.ownerCONTACT
     , x.companyNAME
     , y.subcontractorCOMPANY
     , y.subcontractorNAME
     , y.subcontractorCONTACT
  from site_info i
  LEFT  
  JOIN owner_info o
    on i.ownerID = o.ownerID
  LEFT  
  JOIN company_info x
    on i.companyID = x.companyID
  LEFT 
  JOIN subcontractor_info y
    on i.subcontractorID = y.subcontractorID
    LEFT JOIN site_coordinates2 c
    on i.siteID=c.siteID 
    where 
    i.siteNAME = %s
    AND 
    o.ownerID = %d
    AND 
    x.companyID = %d
   ",$site_name,$owner_name,$company_name);

 $query_submit =$wpdb->get_results($sql, OBJECT);

    echo "<br>";
    echo "<br>";

foreach ($query_submit as $obj) {

  echo "<table class='t1' width='30%'> ";
  echo     "<tr>";
  echo           "<th>Site ID</th>";
  echo           "<th>Site Name</th>";
  echo           "<th> Lattitude</th>";
  echo           "<th>Longitude </th>";
  echo           "<th>Owner Name</th>";
  echo           "<th>Company Name</th>";
  if(isset ($obj->equipmentTYPE))
  { 
     echo "<th>Equipment Type</th>";


  } 
  else { echo ''; } 

  if(isset ($obj->ownerCONTACT))
  { 
     echo "<th>Owner Contact</th>";


  } 
  else { echo ''; } 

  echo   "</tr>";  
  echo   "<tr>";   
  echo         "<td>".$obj->siteID."</td>";
  echo         "<td>".$obj->siteNAME."</td>";
  echo         "<td>".$obj->latitude."</td>";
  echo         "<td>".$obj->longitude."</td>";
  echo         "<td>".$obj->ownerNAME."</td>";
  echo         "<td>".$obj->companyNAME."</td>";
  if(isset ($obj->equipmentTYPE))
  { 
     echo "<td>".$obj->equipmentTYPE."</td>";


  } 
  else { echo ''; } 

  if(isset ($obj->ownerCONTACT))
  { 
    echo "<td>".$obj->ownerCONTACT."</td>";


  } 
  else { echo ''; } 

  echo   "</tr>";            


}

?>

C# Currency Converter: Reduce the amount of if statements

So far I have created a Currency Converter that will convert between multiple different currencies however, to convert the currency, I have used 4 if statements per currency (so I can convert between all of the different currencies.) This has resulted in 20 if statements which doesn't seem very clean or efficient. Here is an example of my code:

if (currencyFrom == "B" && currencyTo == "U")
{
    currencyConversion = doubleInput * 1.29;
}
if (currencyFrom == "B" && currencyTo == "E")
{
    currencyConversion = doubleInput * 1.14;
}
if (currencyFrom == "B" && currencyTo == "J")
{
    currencyConversion = doubleInput * 145.10;
}
if (currencyFrom == "B" && currencyTo == "C")
{
    currencyConversion = doubleInput * 1.68;
}

Is there a better way to do the same calculations but without as many if statements?

Thanks for your help,

Josh

Python - too many 'elif: return()' statements?

I have ths function that's passed two arguments:

def function(a, b):
    if   a == 'd' : return(4*b)
    elif a == '!' : return(5)
    elif a == 'k' : return(1-2*k+k**2)
    elif a == 'Z' : return(1/k)
    (...)

a is checking it's equality to a single character, and b is always a number; the function always returns a number as well. Sometimes it's not always a simple return though.

def function(a, b):
    (...)
    elif a == '2':
        temp_b = foo(b)
        if b == 2 : temp_b += 2
        return(temp_b)

I have a very long list of elif statements, is there a better way to do this?

Angular 2: Not allow to search spaces

How do you say it in a condition that name is not equal to spaces? I have this

name != null && name !== ' '

But it still continues to search with multiple spaces. It only stops searching with one space. How about if there are a lot of space?

Why can't I get my if - else if statement to work? [duplicate]

This question already has an answer here:

I am trying to get my if/else if statement to change the "garaje" variable into the correct string based on the user's string response. Yet, every time I compile no errors are returned back to me. When I try to execute the code the "garaje" variable always returns back the else statement: "do not understand what a garage is... do you?". I am wondering if perhaps I misused the nextLine() method when linking it to the "garaje" variable. I tried using next() and the same result was acquired. Please help...thanks.

import java.util.Scanner;

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


       System.out.println("How many bedrooms in your home? ");
       int cuartos = input.nextInt();

       System.out.println("How many bathrooms? ");
       int banos = input.nextInt();

       System.out.println("How many living rooms? ");
       int salas = input.nextInt();

       System.out.println("How many kitchens? ");
       int cocina = input.nextInt();

       System.out.println("Does your house have a garage (Yes or No)? ");
       String garaje = input.nextLine();


       if ((garaje == "Yes") || (garaje == "yes") || (garaje == "YES")) {
           garaje = "do have a garage.";
       } else if ((garaje == "No") || (garaje == "no") || (garaje == "NO")) {
           garaje = "do not have a garage.";
       } else {
           garaje = " do not understand what a garage is...do you?";
       }


       System.out.println("You have " + cuartos + " bedrooms, " + banos + " bathrooms, " +salas + " living rooms, " + cocina + " 
        kitchens, " + " and you " + garaje);

    }
}

If Statements not working in public function? [Swift 3.0 - Xcode]

Im trying to sort out my data by putting on conditions, so I can present it in a table. My condition is that AllData.count must be equal to 4. And even when it is equal to 4, my data doesn't get append to my new array? Can anyone tell me whats going wrong?

var AllData = [String]()
var DataTable = [String]()



public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")

    if AllData.count == 4{
        DataTable.append(contentsOf: AllData)
    print("appended")}
        for i in stride(from: 0, to: DataTable.count - 1, by: 4){
        cell.textLabel?.text = DataTable[i]}
        return(cell)

}


override func viewDidLoad(){



    print("AllData count ------->",AllData.count)
    print("Datatable count---------->",DataTable.count)
    super.viewDidLoad()}

output: AllData count -------> 4 Datatable count----------> 0

Check to see a website has one of multiple words - if statement

I want to check to see if a website have at least 1 of multiple words. I can only find one word. When I try to add multiple words, I get error.

 import requests

 url = 'https://www.python.org/'

 r = requests.get(url)
 html_content = r.text
 list = "Calculations" # This works
 # list = ("Calculations", "simple") # this would fail

 if list in html_content:
     print("word exist")

thanks to everybody that helps.

How to check if user input is typed before?

I have created a hangman-game.

I want to ask how I can check if the user type the same letter. Everything is working fine but without checking if the number is allready typed.

if (word.contains(input)) {
        i = i - 1;
        char[] charOfGameBoard = gameBoard.toCharArray();
        for (int x = 0; x < word.length(); x++) {
            if (word.charAt(x) != input.charAt(0)) {
                continue;
            }

            int j = x * 2;
            charOfGameBoard[j] = input.charAt(0);
        }

        gameBoard = String.valueOf(charOfGameBoard);

    }

I cant post to much sry.

word = "house"

charOfGameBoard= _ _ _ _ _

userinput= "h" //Correct

charOfGameBoard =h _ _ _ _

userinput= "h" // incorrect at this point

charOfGameBoard =h _ _ _ _

Using ASP.NET and C# if statement to show message based on a Checkbox in Access

I'm working on a project where I can show information from an Access Database (Or SQL server I'm using both) on an aspx webpage. I'm working with Visual Studio 2017 and C#.

I'm trying to write an it statement that will state "Your Order has Shipped!" based on if the Shipped row has been marked "Yes". Else, says "Your Order is still in process".

My code so far:

protected void btnSearch_Click(object sender, EventArgs e)
    {
        SqlDataSource1.DataBind();
        string shipped = Convert.ToString(FindControl("Shipped"));
        if (shipped == "Yes") 
        {
            lblShippingMessage.Visible = true;
            lblShippingMessage.Text = "Your Order has shipped!";
        }
        else
        {
            lblShippingMessage.Visible = true;
            lblShippingMessage.Text = "Your Order is still in process.";
        }
    }

My databound items are in a FormView.

    <asp:FormView ID="FormView1" 
     DataSourceID="SqlDataSource1" 
     RunAt="server" Width="500px" 
     OnPageIndexChanging="FormView1_PageIndexChanging">
            <ItemTemplate>
                <h2><%# Eval("Name") %></h2>
                <h5>Order ID: <%# Eval("ID") %></h5>
                Location: <%# Eval("Location") %><br />
                Billing Code: <%# Eval("Billing Code") %><br />
                <br />
                Order Detail: <%# Eval("Order Details") %><br />
                Shipped: <%# Eval("Shipped")%>
            </itemtemplate>                          
        </asp:FormView>

The problem I am having is that every time I load the page, it shows every record as "Your order is still in progress." How do I make the if statement work where it shows the shipped orders as true and the non-shipped items as false?

I've tried setting the row in Access to Yes/No and working with the control as a bool saying if(shipped != 0), but that resulted in the same issue.

Any help would be greatly appreciated. Thanks!

Cassie

If-statement inside foreach, the statement is not applying

I'm processing a json from an url and showing some data. The problem is that I just want to display two accounts with certain id's but when I execute the following code is echoing the name of each account and not selecting the ones I choosen in the if-statement.

foreach ($data as $row) {

$id = $row->id;
$account = $row->account;
$time = date("Y-m-d H:i:s");

if ($id == 100) {echo $account;}
elseif ($id == 120) {echo $account;}
else {}

}

The Json is like

{"id":120,"Name":"Companytest"},{"id":121,"Name":"BensonTillis"},{"id":123,"Name":"JSBrothers"}

Thank you.

Hangman check if String is contained in the word and replace it?

I create a hangman game in java. I have no clue how to check and replace it. Everything works, the String word is correct and the gameboard is fine. So the game board give me the length of word as "_ _ _ _ _", for example.

public void spielStart(int topic) {
    String[] wordList = this.wordList.chooseThemaArray(thema);
    String word = this.wordList.pickRandom(wordList);
    String gameboard = spielbrettvorbereiten(word);
    Scanner userInput = new Scanner(System.in);

    for (int i = 0; i <= fehlversuche;) {

    System.out.println(gameboard);
    System.out.print("Write a letter ");

    String input = userInput.next();
    int length = input.length();
    boolean isTrue = letters.errateWortEingabe(length);

    if (isTrue == true) {
    if (word.contains(input)) {

    }


    } else {
       i = i - 1;
    }


    i++;
    }

I hope you guys can help me I am struggeling so hard.

Best Regards MichaelDev

Check validation if radio option selected Rails 4

I have two fields that appear when a certain radio box is selected. The value of that radio box is 4. I need the validation to check for presence: true when that specific box is clicked and the form is submitted with empty fields and cannot seem to get that to work.

check_request.rb:

validates :commission_collected, presence: true, if: :commission_invoice?
validates :commission_percentage, presence: true, if: :commission_invoice?

def commission_invoice?
  check_request_type == 4
end

Python: Create New Field in Dataframe Using Complex Conditional Summing Logic

Below is my table (Python dataframe). I'm trying to create the last column in purple text.

enter image description here

Below is the logic I want to implement:

  1. For each unique 'cbsa' value, if the associated 'zip' field values are all the same then set 'age_HC01_EST_VC31_2' field equal to 'age_HC01_EST_VC31' field (see rows highlighted in yellow).

  2. For each unique 'cbsa' value, if the associated 'zip' field values are different then set 'age_HC01_EST_VC31_2' field equal to the sum of 'age_HC01_EST_VC31' field values (see rows highlighted in orange).

  3. For each unique 'cbsa' value, if the associated 'zip' field values are some the same and some different, then set 'age_HC01_EST_VC31_2' field equal to the sum of UNIQUE 'age_HC01_EST_VC31' field values (see rows highlighted in blue).

I have tried using groupby and then sum on 'cbsa' field ... but it doesn't work for the specific, multi-layered logic I'm trying to implement.

Any help is greatly appreciated!

Nested Ifelse statement (How to compare 2 string columns in R)

I know that there are many questions around nested ifelse statements, but I was advised to use specifically ifelse since I want to test whether the values of two string columns are equal (columns are names and the test needs to also be case insensitive). I am really sorry that I will add another one of these questions but I am exhausted....

This is my code (columns are characters, I am trying to check for similar string data between the two columns and fill another column based on that)

hostpairs$hostspecificity <- ifelse(is.na(hostpairs$hostgenus1)|is.na(hostpairs$hostfamily1)|is.na(hostpairs$hostorder1), NA,
                                ifelse(is.na(hostpairs$hostgenus2), 1,
                                        ifelse(hostpairs$hostgenus1==hostpairs$hostgenus2), 1, 
                                                ifelse(hostpairs$hostfamily1==hostpairs$hostfamily2), 2,  
                                                        ifelse(hostpairs$hostorder1==hostpairs$hostorder2), 3, 
                                                                4)))))

ERROR

    Error: unexpected ')' in:
"                                                            ifelse(hostpairs$hostorder1==hostpairs$hostorder2), 3, 
                                                                    4)))"

EXPECTED RESULT

1   #Arithmetic column in the data frame filled with values according to if statement
2 
2
1
4
3
.
.

I cannot for the life of me understand why R has a problem with )s, and cannot fix it even after reading many similar questions here

Please help

Enable export as pdf inside Workbook_BeforePrint Cancel

it seems my "Workbook_BeforePrint(Cancel As Boolean)" is stopping me from exporting to PDF. I have found that if I remove this sub, PDF export works, but I'd like to keep my "fixes" before print.

Is there a way to rewrite my code to handle export to pdf?

A) To ignore the "Before print cancel" on export (no after effects on PDF)

or

B) Make the code work for export, retaining the after effects my code adds

Private Sub Workbook_BeforePrint(Cancel As Boolean)
    Application.Volatile True
    Cancel = True

    Application.EnableEvents = False
    Application.ScreenUpdating = False

   'My code

    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

(R) How to compare string columns w/ logical operation (If (col1 == col2) {true} else {false}) [duplicate]

This question already has an answer here:

So i tried an if else statement but failed...

(I am working with string columns, in R)

hostpairs["hostspecificity"] <- NA

If (hostpairs$hostgenus2 == NA){
  hostpairs$hostspecificity == 0
} else if(hostpairs$hostgenus1 == hostpairs$hostgenus2){
  hostpairs$hostspecificity == 1
} else {
  hostpairs$hostspecificity == 2
}

Error in if (hostpairs$hostgenus2 == NA) { :
missing value where TRUE/FALSE needed
In addition: Warning message:
In if (hostpairs$hostgenus2 == NA) { : the condition has length > 1 and only the first element will be used

I am pretty sure there is a pretty dumb mistake somewhere in there...

Please help!

ps. Also if there is a function that checks two string column row by row and comes up with TRUE if they are equal (case insensitive, John = JOHN) or FALSE if they are not equal (John != Mary) That would be very helpful!

Thanks a lot

if statement using jquery selectors and checkboxes

I have a form with two text input fields and a series of checkboxes.

There is a variable fields which stores some arrays with data pertaining to the selected fields. I have hardcoded the values into the script with no problem but I cannot seem to find out how to properly compose an if statement to check the status of the checkboxes and only use those values, rather than hardcoding the selected fields.

var start, end, fields;

$(function() {
  $("#form1").submit(function(event) {
    var endD = $("#endDate").val();
    end = endD;
    var startD = $("#startDate").val();
    start = startD;

    //fields = ['PM1','PM2.5','PM10'];


    //if $("#PM1").is("checked"))){
    //fields = ["PM1"];
    //}


    if ($("PM1").attr("checked")) {
      fields = ["PM1"];
    }


    event.preventDefault();

    build_graph();
  });
});
<script src="http://ift.tt/1oMJErh"></script>
<form id="form1">
  Start Datetime:<br>
  <input type="text" name="startDate" id="startDate" class="Date" placeholder="YYYYMMDD-HHMM"><br> End Datetime <br>
  <input type="text" name="startDate" id="endDate" class="Date" placeholder="YYYYMMDD-HHMM"><br> Parameter
  <br>
  <input type="checkbox" class="parameter" id="PM1">PM1<br>
  <input type="checkbox" class="parameter" id="PM2.5" checked>PM2.5<br>
  <input type="checkbox" class="parameter" id="PM10">PM10<br>
  <input type="checkbox" class="parameter" id="Temp">Temperature<br>
  <input type="checkbox" class="parameter" id="Humidity">Humidity<br>
  <input type="checkbox" class="parameter" id="Pressure">Pressure<br>
  <input type="checkbox" class="parameter" id="WindSpeed">Wind Speed<br>
  <input type="checkbox" class="parameter" id="Direction">Direction<br>
  <input type="checkbox" class="parameter" id="RainVolume">Rain Volume<br>
  <input type="submit">
</form>

Avoid adding duplicate sheets to Excel Work book

I have a collection words inside SheetNames and i'm trying to add new Worksheet for each word inside SheetNames, please find the code below.

Before adding the Worksheet i'm trying to validate whether the sheet is already existing in my workbook using sheetExists function, code provided below.

For Each SheetName In SheetNames

     If sheetExists(SheetName , newWB) = False Then
        newWB.Activate
        Set FilPage = Worksheets.Add
        FilPage.Activate
        SheetName = Replace(Replace(Replace(Replace(Replace(SheetName, ".", " "), "[", " "), "]", " "), "/", "_"), "\", " ")
        If Len(SheetName) <= 30 Then
            FilPage.Name = SheetName
        Else
            SheetName = Left(SheetName, 23) & "-trimed"
        End If
        ActiveSheet.Range("A1").Activate
        ActiveCell.PasteSpecial
    End If
Next

The code valediction using function sheetExists is not working consistently.

Function sheetExists(sheetToFind ,wb As Excel.Workbook) As Boolean

    WS_Count = ActiveWorkbook.Worksheets.Count

    sheetExists = False

    For I = 1 To WS_Count
        If ActiveWorkbook.Worksheets(I).Name = sheetToFind Then
            sheetExists = True
            Exit Function
        End If
    Next

End Function

i can see some of the worksheet added with names "Sheet99" even though SheetName is passed and sometimes if function sheetExists function returns True still workbook is trying to add a worksheet

Using If else to compare Mac Address in Batch File

This is my following Code. I keep getting the error "Try again" even though my Mac Address is same. I somehow want to execute Exec.bat if the condition is true.By the way MacCheck.txt has my Mac address as 08-3E-8E-2C-DF-F7

@ echo off

SetLocal EnableDelayedExpansion

set content=

for /F "delims=" %%i in (MacCheck.txt) do set content=!content! %%i

rem %content%

SET Mac="08-3E-8E-2C-DF-F7 "

if "content" == "Mac" (start Exec.bat) else (echo "Try again")

EndLocal

pause

Executing an if statement or try/catch based on whether or not the input is a string/int

I am trying to create an if statement or try/catch that will hopefully execute under the condition that the input received in the console application (that I am converting to Int32) is NOT an integer. This is the code snippet I have been using:

            Console.WriteLine("What year was your car made? [MUST BE IN YEAR FORMAT]");
            caryearchk = Console.ReadLine();

            if (caryearchk.GetType() != int) // Can't figure out a way to return a bool through .GetType()
            {
                Console.Write("Error. you MUST submit this in an integer form. The application will now close.");
                Console.ReadLine();
            }
            else
            {              
            }
            caryear = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("What is the drivetrain? [ FWD /// RWD /// AWD /// 4WD ]");
            cartrain = Console.ReadLine();
        }
        Car car = new Car(carmake, 

If there are any other/more efficient ways to go about this I would much rather prefer that. I am eager to know many different ways to solve basic problems like this

How are consecutive, non-nested if statements evaluated?

This is a nonsense example, but I couldn't find an answer to this type of question anywhere. As you can see, the if-statements are not nested. Does line 11 evaluate as true or not after the first if-statement changes the value of k from 1 to 0? This question is similar to one given to me as a practice study question, so I'm not looking for code improvements at this time. Thanks.

1   int main {
2
3     int i = 3, j = 0, k = 1; // variables are initialized
4
5     if ( i < 5 ) {  // evaluates as true
6       i++;
7       k--;
8     } // i now equals 4 and k equals 0   
9     else { ... }
10
11    if ( k > 0 ) // TRUE OR NOT?
12    { ... }
13  } // end main

IF ... (AND) statement run time error "13"

I need help with my if statements. In the code show below: The first if ... then section works just as intended, however the second section creates a run time error "13". Can someone please explain me how to fix this issue? / what i'm doing wrong?

Sub ASN_BaaN3()
Dim i As Integer
i = 0

ThisWorkbook.Sheets("BaaN").Activate

Do While ThisWorkbook.Sheets("BaaN").Cells(2 + i, 1) <> ""

    'CHECK NON SERIALIZED
    If Range("J" & 2 + i).Value = "N" Then
        Range("P" & 2 + i).Value = "Ok, Non Serialized"
        Range("P" & 2 + i).EntireRow.Interior.Color = RGB(198, 239, 206)
    End If

    If Range("J" & 2 + i).Value = "Y" And _
    Range("M" & 2 + i).Value = "ACK" And _
    Range("o" & 2 + i).Value = "TRUE" Then
        Range("P" & 2 + i).Value = "Ok, Non Serialized"
        Range("P" & 2 + i).EntireRow.Interior.Color = RGB(198, 239, 206)
    End If

    i = i + 1
Loop

End Sub

when typing the code like this i get the same error:

    If Range("J" & 2 + i).Value = "Y" Then
    If Range("M" & 2 + i).Value = "ACK" Then
    If Range("O" & 2 + i).Value = "TRUE" Then
        Range("P" & 2 + i).Value = "Ok, Non Serialized"
        Range("P" & 2 + i).EntireRow.Interior.Color = RGB(198, 239, 206)
    End If
    End If
    End If

Also when typing the code like this

    If Range("J" & 2 + i).Value = "Y" Then
    If Range("M" & 2 + i).Value = "Y" Then

Please help!

How to use if in a for loop in R

I am trying to compute the occurrence of a line in a dataframe, but I don’t the result expected. ps: generaldf is a dataframe, and userid if a column of integer

y<-0

        for(i in seq_len(nrow(generaldf))) 
        {
          if (generaldf$userid==1) 
            y <-y+1
        }

 return(y)

input rows of a column in to a for loop

I've have a data frame (df) in which there is a column g which has the below data

g
 1         check
 2    2267631926
 3          <NA>
 4         check
 5         check
 6         check
 7         check
 8         check
 9         check
10         check
11         check
12         check
13         check
14         check
15         check
16         check
17         check
18         check
19    2090125960
20          <NA>
21         check
22         check

I'm trying to input only the numeric values (2090125960) in into a web link and jump the others (check, NA) using the css selectors one by one and follow next commands but, it is pasting the complete list.

` for(i in g)
  {

 mybrowser$navigate("https://www.google.com")

fg<- mybrowser$findElement(using = 'css selector',"#lst-ib")
fg$clickElement()
Sys.sleep(1)
fg$sendKeysToElement(i)

Go<- mybrowser$findElement(using = 'css selector',"#tsf > div.tsf-p > div.jsb > center > input[type="submit"]:nth-child(1)")
Go$clickElement()

}`

Now I'm trying to enter the numeric value (one at a time) in the google search bar and hit on search then take the second value and click on search. I think this should clear my doubt.

I tried to convert the columns into factor or numeric. Any ideas would help. Thank you.

how to check if variable is empty in php [duplicate]

This question already has an answer here:

i have a PHP code with MYSQL where the code fetch the database select and display the result in a table.

what i need is to be able to check if the selected variable is empty or not.

if its empty i don't want to display the field in the table.

code:

$sql = $wpdb->prepare("select i.siteID
     , i.siteNAME
     , i.equipmentTYPE
     , c.latitude
     , c.longitude
     , c.height 
     , o.ownerNAME
     , o.ownerCONTACT
     , x.companyNAME
     , y.subcontractorCOMPANY
     , y.subcontractorNAME
     , y.subcontractorCONTACT
  from site_info i
  LEFT  
  JOIN owner_info o
    on i.ownerID = o.ownerID
  LEFT  
  JOIN company_info x
    on i.companyID = x.companyID
  LEFT 
  JOIN subcontractor_info y
    on i.subcontractorID = y.subcontractorID
    LEFT JOIN site_coordinates2 c
    on i.siteID=c.siteID 
    where 
    i.siteNAME = %s
    AND 
    o.ownerID = %d
    AND 
    x.companyID = %d
   ",$site_name,$owner_name,$company_name);

 $query_submit =$wpdb->get_results($sql, OBJECT);

    echo "<br>";
    echo "<br>";




// table that will dsiplay the results based on the user's selection //
echo "<table class='t1' width='30%'> ";
echo     "<tr>";
echo           "<th>Site Name</th>";
echo           "<th>Owner Name</th>";
echo           "<th>Company Name</th>";
//echo           "<th>Subcontractor Name</th>";
echo           "<th>Site ID</th>";
echo           "<th>Equipment Type</th>";
echo           "<th> Lattitude</th>";
echo           "<th>Longitude </th>";
echo           "<th> Height</th>";
echo           "<th> Owner Contact</th>";
echo           "<th> Sub Contact</th>";
echo           "<th> Sub company Name</th>";
echo   "</tr>";  


foreach ($query_submit as $obj) {

echo   "<tr>";       
echo         "<td>".$obj->siteNAME."</td>";
echo         "<td>".$obj->ownerNAME."</td>";
echo         "<td>".$obj->companyNAME."</td>";
   if(!$obj->subcontractorNAME){
      echo           "<th>Subcontractor Name</th>";
      echo           "<td>".$obj->subcontractorNAME."</td>";

   }
   else{

   }
echo         "<td>".$obj->siteID."</td>";
echo         "<td>".$obj->equipmentTYPE."</td>";
echo         "<td>".$obj->latitude."</td>";
echo         "<td>".$obj->longitude."</td>";
echo         "<td>".$obj->height."</td>";
echo         "<td>".$obj->ownerCONTACT."</td>";
echo         "<td>".$obj->subcontractorCONTACT."</td>";
echo         "<td>".$obj->subcontractorCOMPANY."</td>";
echo  "</tr>";            

} 

imacros/Javascript if else exists Text

hi everyone :) English isn't my first language so please Excuse any mistakes :)

i'm using iMacros v9.0.3 on Firefox 53.0.3 (64 bit) in Windows 8 x64

I'm attempting imacros to check the text exists if exists then run rest of the script else go to the particular URL

Here is the block of my code:

var n1 = prompt("Enter Number Of Clicks You Want: ");
    iimPlay('CODE:'+'SET !TIMEOUT_PAGE 100'+'\nURL GOTO=http://ift.tt/2tkdahC');
    iimPlay('CODE:'+'wait seconds=1');
    iimPlay('CODE:'+'SET !TIMEOUT_PAGE 100'+'\nURL GOTO=http://ift.tt/2uhQ2xw');

    for(var P = 1; P <= n1; P++)
{
    iimDisplay("Current RT account is: "+P)
    iimPlay('CODE:'+'SET !TIMEOUT_STEP 0'+'\nTAG POS=1 TYPE=h2 ATTR=class:center_title&&TXT:Instagram<sp>Likes CONTENT=EVENT:MOUSEOVER');
    iimPlay('CODE:'+'wait seconds=2');
    iimPlay('CODE:'+'SET !TIMEOUT_STEP 0'+'\nTAG POS=1 TYPE=div ATTR=class:btn3&&TXT:Like');
    iimPlay('CODE:'+'SET !TIMEOUT_STEP 20'+'\nTAG POS=1 TYPE=a ATTR=class:_1b8in<sp>_soakw<sp>coreSpriteDesktopNavLogoAndWordmark&&href:/&&TXT:Instagram CONTENT=EVENT:MOUSEOVER');
    iimPlay('CODE:'+'wait seconds=6');
    iimPlay('CODE:'+'SET !TIMEOUT_STEP 0'+'\nTAG POS=1 TYPE=span ATTR=class:_soakw<sp>coreSpriteHeartOpen&&TXT:Like');
    iimPlay('CODE:'+'wait seconds=9');
    iimPlay('CODE:'+'\nEVENT TYPE=KEYPRESS SELECTOR=* CHAR="1" MODIFIERS="ctrl"');
    iimPlay('CODE:'+'TAB CLOSEALLOTHERS');
    iimPlay('CODE:'+'wait seconds=5');
    if (P % 5 == 0 && P!=0) {
iimPlay('CODE:'+'REFRESH');
}
}

My code is working fine but unfortunately, sometimes Tab 2 closed instead of Tab 1, so the script ends up with fails

i don't have a great knowledge in javascript/programming so i refer Google and tried some of them but none seems to work :(

Here is the code that I'm trying:

 var n1 = prompt("Enter Number Of Clicks You Want: ");
    var answer=iimGetLastExtract();
        iimPlay('CODE:'+'SET !TIMEOUT_PAGE 100'+'\nURL GOTO=http://ift.tt/2tkdahC');
        iimPlay('CODE:'+'wait seconds=1');
        iimPlay('CODE:'+'SET !TIMEOUT_PAGE 100'+'\nURL GOTO=http://ift.tt/2uhQ2xw');

        for(var P = 1; P <= n1; P++)
    {
        iimDisplay("Current RT account is: "+P)
        iimPlay('CODE:'+'SET !TIMEOUT_STEP 0'+'\nTAG POS=1 TYPE=h2 ATTR=class:center_title&&TXT:Instagram<sp>Likes EXTRACT=TXT');

if(answer=="Instagram Likes"){
        iimPlay('CODE:'+'wait seconds=2');
        iimPlay('CODE:'+'SET !TIMEOUT_STEP 0'+'\nTAG POS=1 TYPE=div ATTR=class:btn3&&TXT:Like');
        iimPlay('CODE:'+'SET !TIMEOUT_STEP 20'+'\nTAG POS=1 TYPE=a ATTR=class:_1b8in<sp>_soakw<sp>coreSpriteDesktopNavLogoAndWordmark&&href:/&&TXT:Instagram CONTENT=EVENT:MOUSEOVER');
        iimPlay('CODE:'+'wait seconds=6');
        iimPlay('CODE:'+'SET !TIMEOUT_STEP 0'+'\nTAG POS=1 TYPE=span ATTR=class:_soakw<sp>coreSpriteHeartOpen&&TXT:Like');
        iimPlay('CODE:'+'wait seconds=9');
        iimPlay('CODE:'+'\nEVENT TYPE=KEYPRESS SELECTOR=* CHAR="1" MODIFIERS="ctrl"');
        iimPlay('CODE:'+'TAB CLOSEALLOTHERS');
        iimPlay('CODE:'+'wait seconds=5');
        if (P % 5 == 0 && P!=0) {
    iimPlay('CODE:'+'REFRESH');
    }
} else {iimPlay('CODE:'+'SET !TIMEOUT_PAGE 100'+'\nURL GOTO=http://ift.tt/2uhQ2xw');}
    }

So, whats wrong in this code, and how can I fix it? Please help.. all suggestions are welcomed and greatly appreciated and thanks in advanced

javascript: avoding if else with javascript object when pattern matching is involved

I am basically trying to avoid branching. I will explain my doubt with the code:

My code is like:

name = "any_random_name_generated_dynamically"

//If else conditions
// foo and bar are the part of the name not the complete name

if (name.match('foo_pattern')) {
"do_thing_1"
}
else if (name.match('bar_pattern')) {
"do_thing_2"
}
else {
"do_thing_3"
}

Is there anyway I can avoid this using javascript objects? Or there any other way to do where less branching is involved.

I tried googling it bu didn't find anything for this particular issue.

Ruby detects variable is string, but ends the script without breaking loop

code:

a = rand(1..100)
puts "Guess a number from 1 through 100!"
i = 0
loop do 
    i = i+1
    b = gets.chomp
        if b.is_a? String
        puts "Only numerical values"
    end
    if b == a
        puts "Good Job! You finished in #{i} attempts!"
        break
    end
    if b<a 
        puts "Too Low!"
    end
    if b>a
        puts "Too High!"
    end
    if b<0
        puts "Please input numbers above 0!"
    end

end

Error Message:

Guess a number from 1 through 100!
hi
Only numerical values
hi-lo.rb:14:in `<': comparison of String with 38 failed (ArgumentError)
from hi-lo.rb:14:in `block in <main>'
from hi-lo.rb:4:in `loop'
from hi-lo.rb:4:in `<main>'

My problem: basically, i want to make it so that ruby will detect when someone inputs a string instead of an integer. Thus resulting in outputting a message that states that you have entered an illegal character. It detects i am entering a string, but it shuts down the code instead of continuing the loop. Any advice? Thanks.