jeudi 30 juin 2016

If-else statements in JS

I have a bug in my code and I can't find it. Can you help me, please?

var pass = prompt("Please enter your password");
        var lung = pass.length;
        var gutlng = 0;
        document.getElementById("lungime").innerHTML =
        "Your password has " + lung + " characters";


        if(lung== 0 ){
                document.getElementById("check").innerHTML = "Please enter a relevant password."
                gutlng = 0;
        }       
        if(lung== 1 ){
                document.getElementById("check").innerHTML = "Please enter a relevant password."
                gutlng = 0;
        }
        if(lung<8 && lung!=1 && lung!=0){
        document.getElementById("check").innerHTML = "It is a bit to short. Please try again.";
          gutlng = 0;
        }

        if(lung>8 && lung<20){
                document.getElementById("check").innerHTML = "It is perfect! Proceed to the next step!"
                gutlng = 1;
        }

        if(lung>20){
                document.getElementById("check").innerHTML = "It is too long. PLease try again"
                gutlng = 0;
        }

        
     var fb = 0;
        var tw = 0;
        var sc = 0;
        var yh = 0;
        var gm = 0;
        var is = 0;
    

        if(gutlng == 1){
                var fb = 1;
                var tw = 1;
                var sc = 1;
                var is = 1;
                var yh = 1;
                var gm = 1;
        }
        
        if(gutlng == 0){
                var fb = 0;
                var tw = 0;
                var sc = 0;
                var is = 0;
                var yh = 0;
                var gm = 0;
        }

        if(fb == 1){
                document.getElementById("fb").innerHTML = "GOOD";
       
        if(fb == 0){
                document.getElementById("fb").innerHTML = "NOT GOOD";
        }

        if(tw == 1){
                document.getElementById("tw").innerHTML = "GOOD";
        }
        if(tw == 0){
                document.getElementById("tw").innerHTML = "NOT GOOD";
        }

        if(sc == 1){
                document.getElementById("sc").innerHTML = "GOOD";
        }
        if(sc == 0){
                document.getElementById("sc").innerHTML = "NOT GOOD";
        }

        if(is == 1){
                document.getElementById("is").innerHTML = "GOOD";
        }
        if(is == 0){
                document.getElementById("is").innerHTML = "NOT GOOD";
        }

        if(yh == 1){
                document.getElementById("yh").innerHTML = "GOOD";
        }
        if(yh == 0){
                document.getElementById("yh").innerHTML = "NOT GOOD";
        }

        if(gm == 1){
                document.getElementById("gm").innerHTML = "GOOD";
        }
        if(gm == 0){
                document.getElementById("gm").innerHTML = "NOT GOOD";
        }

I tried to fix it, but the bug doesen't appeear.Thank you for your time! Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!CheersCheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!Cheers!

Excel Macro Best Practice for Multiple options in If Statement or Case

I have multiple "Call Types" (from "Roaming" to "International") and I need a vlookup to apply the correct rate depending on the type in an excel macro.

What's the best practice to do this?

If CategoryType = "Roaming" AND Country coainted in List A Then

If List B Then

Do I use arrays? How do you check if a string is in an array in an IF statement?


Rates Table Example

JavaScript iterate through items backwards

I am iterating through some photos using this code:

if (this.lightboxIndex < this.photos.length - 1) {
            this.lightboxIndex++;
          } else {
            this.lightboxIndex = 0;
          }
          this.lightboxSrc = this.photos[this.lightboxIndex].src;
        },

How can i iterate backwards through the same photos? Is this along the lines of what I need to do?

if(this.lightboxIndex < this.photos.length - 1){
            this.lightboxIndex--;
          } else {
            this.lightboxIndex = 0;
          }
          this.lightboxSrc = this.photos[this.lightboxIndex].src;
        },

How to create an Excel drop down menu where items must be selected in a certain order?

I have looked everywhere for an answer to this. I want to create a drop down in Excel where 'Item 1a' must be chosen before Item 1b; Item 2a before Item 2b; Item 2b before Item 2c, etc. I want to be able to choose Item 1a, Item 2a, Item 3a, etc. in any order, but until the 'a' is chosen you can't choose the 'b'.

Each 'Item Set' is internally dependent, but externally independent.

For Example: You could choose Item 1a first, then Item 2a, then Item 2b, then Item 3a, then Item 2c, finally Item 1b. But you could not choose Item 1a, then Item 2b, because the prerequisite for choosing Item 2b is to choose Item 2a before choosing it.

Is this possible in Excel or am I cursed to creating endless, complicated drop downs?

Powershell nesting vs try/catch

I think I am going at this in the right way, but it doesn't seem to work. Im trying to nest if/elseif/then to loop some commands based on a response. Would this be more correct in a try/catch setup?

here is the code.. (hopefully I can do this right!)

$ecuPort = new-Object System.IO.Ports.SerialPort COM8,9600,None,8,one
$ecuPort.Open()

# Set OBD Mode/PID
$obdMode = "27"                                      # Mode
$obdPid = "02"                                       # PID  change value to 1 to get the seed 
# ----------------------
[int]$i = '1'                                        #  Counter Start

:keyLoop for ( $i -le '65535') {  

$key  = "{0:X}" -f [int]$i                           # ---- Loop setup----
$request = $obdMode + $obdPid + $key.PadLeft(4,"0")
$ecuPort.Write($request)                             # ---Send Request---
start-sleep -m 400
$input = $ecuPort.ReadExisting() # -split " "          # ---Get Response----  
$response = $input[2,3] -join ""

}
 if ($response -eq '35') {                           # ----Main Logic-----

  $key | Add-Content KeyLogger.txt                  # Log failed keys for testing
  $i++                                              # advance key counter
  Start-Sleep -m 11000                              # 10 second delay
  continue keyLoop 
 }
  elseif ($response -eq '34') {

   Write-Host("Unlock Key:") $key
   $key | Out-File Unlocked.txt
   # blink led
   $ecuPort.Close()
   break  
}  
 elseif ($response -eq '36') {

   $arduPort.Open()
   Start-Sleep -m 400
   $arduPort.Write("off")
   Start-Sleep -m 5000
   $arduPort.Write("on")
   $arduPort.Close()
   continue keyLoop
  }   
   elseif ($response -eq '37') {
   Start-Sleep -Milliseconds 11000
   continue keyLoop
  }
   then {

      # TBD return

        }

Im still learning so go easy on me, I realize this is pretty basic stuff, but I am weak on syntax still. Im trying to run the script block for each if, then continue to the start ':keyLoop label' to cycle through. Hence the continue statements. Never seems to run the code within the loop! Thanks

Create new variable if 2 of the 4 conditions are true using R

Is there any way to create a new variable var5 = 1 if any 2 of the 4 conditions are TRUE

Input:

 id var1 var2 var3 var4
1   60   18  36.7  1000
2   30   23  45.6  4000
3   10   35  75.6  5000
4   50   35   53   3000

condition1: if var1<20 or var1>25
condition2: if var2>25
condition3: if var3>20 
condition4: if var4<1000 or var4>3000 

Check Status of JavaScript via .JSP page

Background: My client has a sitemap that uses an accordion menu for the layout. (no talking them out of it). They are afraid SiteBots that do not use JS to view a page will not see the links hidden by the accordion.

Question: I know about the <noscrpit> tag but is there a way to programmatically write an if statement on a .jsp page that can check to see if Javascript is enabled?

This way I can server a different sitemap layout depending on how the page is being viewed.

how to make If statement run with false boolean?

i am still learning using code academy and they said that you can make a code run when the boolean value is false without using else by using an opposite boolean expression. Just curious, but how would you do that?

C++ if/else statement problems

I was using xcode the other day, and was working on a text-based conversation game-thingy.

#include <iostream>

int main()
{
    std::cout<<"Conversation simulator requires you to type in all caps for all  of your replies"<<std::endl;
    std::cout<<"Type your first and last name!"<<std::endl;
    std::string fname = " ";
    std::string lname = " ";
    bool samename = false;
    std::cin>> fname >> lname ;
    if  (fname == "MUSCLE" and lname == "MAN")
        std::cout<< "Wow, we have the same first and last name!"<<std::endl;
        samename = true;
    else
        std::cout<< fname << " "<< lname << "is a very nice name"<<std::endl;

return 0;
}

nothing seems quite wrong to me, but Xcode won't run because on this line:

else

it expected an expression? I can't think of what that might mean.

PHP If variable equals

I am trying to show some text depending upon what a status is set to in a db table.

See my code below:

$result=mysql_query("SELECT * FROM hr_recruitment_stages where vacancy_ref='$vacancyref' order by added_on DESC limit 0,1")or die('ERROR 315' );
$row = mysql_fetch_array($result);
$stage_name = $row ['stage_name'];

if($stage_name['stage_name'] == 'Shortlisting') { echo"Shortlisting"; } else { echo"Not Shortlisting"; } ?>

However this doesnt seem to be working properly as it is showing as Not Shortlisting even when stage_name equals Shortlisting.

Any ideas why?

Need help writing first VBA code

New to VBA and am in over my head.

I have a table. I would like to write a code that loops through and if the active cell contains a 1, then, in a cell outside of the table, the column heading is returned and put into a comma separated list.

I am looking for that loop to continue all the way across the first row cell by cell, and comma separated list to build with each TRUE return.

Once the loop hits the end of the row I need it to drop down to the next row and continue the same process (but creating its own comma separated list for those that returned true in row 2).

Any help would be greatly appreciated.

I know I need to somehow loop and if statement but just can't figure it out right now.

Thanks

If formula didn't work correctly

I have a script (game) and I wanted add simple customization but I have a little problem.

In script I have at the beginning:

var customText ='Text';

and later:

resultTxt = new createjs.Text();
resultTxt.font = "30px Arial";
resultTxt.color = "#333333";
resultTxt.text = customText;

I wanted now make different "customText" which depends on var "player.score". I tried to make something like this:

var customText ='Text';
var customText1 ='Text1';
var customText2 ='Text2';

and later:

resultTxt = new createjs.Text();
resultTxt.font = "30px Arial";
resultTxt.color = "#333333";
resultTxt.text = customText;
if (player.score < 2) {
resultTxt.text = customText1
} else if (player.score < 5) {
resultTxt.text = customText2
} else {
resultTxt.text = customText
}

And it didn't work, because always is showing "customText1" (not "customText" which is interesting for me). How can I make it good?

VLOOKUP-like function: Select case for a long list in VBA Excel

Instead of multiple If ... Then statements in Excel VBA, you can use the Select Case structure. But how does one perform this task efficiently if the case is a long list? For example, have a look the following data:

Code ID Girls Names
0001    Sophia
0002    Emma
0003    Olivia
0004    Isabella
0005    Ava
0006    Lily
0007    Zoe
0008    Chloe
0009    Mia
0010    Madison
0011    Emily
0012    Ella
0013    Madelyn
0014    Abigail
0015    Aubrey
0016    Addison
0017    Avery
0018    Layla
0019    Hailey
0020    Amelia
0021    Hannah
0022    Charlotte
0023    Kaitlyn
0024    Harper
0025    Kaylee
0026    Sophie
0027    Mackenzie
0028    Peyton
0029    Riley
0030    Grace
0031    Brooklyn
0032    Sarah
0033    Aaliyah
0034    Anna
0035    Arianna
0036    Ellie
0037    Natalie
0038    Isabelle
0039    Lillian
0040    Evelyn
0041    Elizabeth
0042    Lyla
0043    Lucy
0044    Claire
0045    Makayla
0046    Kylie
0047    Audrey
0048    Maya
0049    Leah
0050    Gabriella
0051    Annabelle
0052    Savannah
0053    Nora
0054    Reagan
0055    Scarlett
0056    Samantha
0057    Alyssa
0058    Allison
0059    Elena
0060    Stella
0061    Alexis
0062    Victoria
0063    Aria
0064    Molly
0065    Maria
0066    Bailey
0067    Sydney
0068    Bella
0069    Mila
0070    Taylor
0071    Kayla
0072    Eva
0073    Jasmine
0074    Gianna
0075    Alexandra
0076    Julia
0077    Eliana
0078    Kennedy
0079    Brianna
0080    Ruby
0081    Lauren
0082    Alice
0083    Violet
0084    Kendall
0085    Morgan
0086    Caroline
0087    Piper
0088    Brooke
0089    Elise
0090    Alexa
0091    Sienna
0092    Reese
0093    Clara
0094    Paige
0095    Kate
0096    Nevaeh
0097    Sadie
0098    Quinn
0099    Isla
0100    Eleanor

I put list of Code ID in column AA and list of Girls' Names in column AB. There's no way I will type the above list using the Select Case structure, so I use the following code to do the same task. It matches the partial text in column A and print the result in column E:

Sub Matching_ID()
.......................................
Dim ID As String, j As Integer, k As Integer, List As Integer
List = Cells(Rows.Count, "AA").End(xlUp).Row
ID = Mid(Cells(i, "A"), j, 4)
For k = List To 2 Step -1
    If ID = Cells(k, "AA").Value Then
        Cells(j, "E") = Cells(k, "AB").Value
        Exit For
    Else
        Cells(j, "E") = ""
    End If
Next k
.......................................
End Sub

Though the above code works fine, but it's really time-consuming. Is there a better way?

How to add if statement to record

How do I add if statement inside this record?

CorpData.Address viewAddress = new CorpData.Address
        {
            DocumentId = lblDocId.Text.ToUpper(),

            Address =  txtAddress.Text.ToUpper(),
            AddressCity = txtCity.Text.ToUpper(),
            AddressZip = txtZip.Text.ToUpper(),
            StateCode = statesDropdown.SelectedValue,
        };

I am trying to add an if statement to check if stateCode in the US

Php how to check if a Digital number is bigger than another

I got two digital numbers as a string:

The first one looks like this:

$num1 = "00:10:00"

and the second one like this:

$num2 = "00:02:02"

How can I check wether one of them is bigger.

How to check if data table has empty rows?

I am writing function that filters out some random data from a data table random according to an id value ,but I want it first to check if there is actual data rows in the data table first. I ended up writing an if statement and using is.null but its still for the condition but its not working and ends up accessing the else statement and then giving me an error. The code is posted below, please help me

new.filterID <- function(DataTable,id) {
  if(DataTable == is.null){
    return(print("No Data Available: ",id))
  } else { filtered <- subset(DataTable, ID == id)
    return(aggregate(Value ~ YEAR_WW, filtered, mean))
  }
}
filteredData <- new.filterID(random, 213)

The error I get when I run this is

Error in aggregate.data.frame(mf[1L], mf[-1L], FUN = FUN, ...) : 
  no rows to aggregate 

Also below the empty data table random

Value   YEAR_WW

If statement not working after minimization

I had an if statement inside a scroll function, to check if the div #homepage-flag or the div #landingspage-flag exists. It was something like this:

$(window).scroll(function(e){
    if($('#homepage-flag').length > 0 || $('#landingspage-flag').length > 0){
      // code
    }
});

I minified the code, but now the if statement only works for the div #landingspage-flag:

$("#homepage-flag").length > 0 || $("#landingspage-flag").length > 0 && $(window).scroll(function(l) {
  // code
})

If directory has no files then ... - Linux

I'm looking to see if a directory has no files in it or not. I do not want to take folders into account.

Right now I have ls -1ap | grep -v / | wc -l which will give me the number of files in the directory, but I cant seem to incorporate that into an if statement.

if ls -1ap | grep -v / | wc -l < 1; then echo "one"; else echo "two"; fi

Is there anything I can tweak a bit to get this to work? Thank you

Performance hit from if: pass statements

I am writing a script that parses user input, reads a file, does some work, and then sends an html POST request.

There is one section of the code that requires me to do a different action based on the interaction of three variables, but some of the cases are handled with 'do nothing' i.e. pass. Initially, I included all of the pass conditional paths to help with maintainability for the other employees that are not as familiar with this script/Python.

So with this information, my question is:

Will there be any kind of performance speedup if I remove these pass paths? These statements are not in a module that will be imported anywhere else, it will be run from the command line.

problems with Classes/Objects

I posted earlier my question. my code was messy. I apologise for that.

I rewrite it.

when I run it choice number 1 and 2 works fine but when i try choice number 3 and 4 for some reason it doesn't work properly like the output example.

Any help would be appreciated. thanks in advance

import java.util.Scanner;

public class Problem2 {

public static void main(String[] args) {

    while (true) {

        Scanner in = new Scanner(System.in);

        System.out.println("1.Enroll Student");
        System.out.print("");
        System.out.println("2.Offer Course");
        System.out.println("3.Registration ");
        System.out.println("4.Enter Result ");


        int choice = in.nextInt();

        if (choice == 1) {

            StudentClass[] studentList = new StudentClass[500];

            studentList[0] = new StudentClass();

            while (true) {

                System.out.print(" Enter name of the student: ");
                studentList[0].setName(in.next());

                System.out.println("");
                System.out.print("The student is given the unique ID =  " + studentList[0].getUniqueStudentID() + " and the number of students =  " + studentList[0].getNumberOfStudents());

                System.out.println("");

                System.out.print("Enter the e-mail address of the student: ");

                studentList[0].setEmail(in.next());

                System.out.print("Enter the semester number of the student:  ");

                studentList[0].setSemesterNumber(in.nextInt());

                System.out.print(" Add another student (Y/N): ");
                char add = in.next().charAt(0);
                if (add == 'Y' || add == 'y') {

                }

                if (add == 'N' || add == 'n') {
                    break;
                }

            }

        } else if (choice == 2) {

            while (true) {

                int num;

                CourseClass[] courseOfferedList;
                courseOfferedList = new CourseClass[500];
                courseOfferedList[0] = new CourseClass();

                System.out.print("Enter the course code : ");
                courseOfferedList[0].setCourseCode(in.next());

                System.out.println(" Enter the course title: ");
                courseOfferedList[0].setCourseTitl(in.next());

                System.out.println(" Enter the credit hours of the course: ");
                courseOfferedList[0].setCreditHours(in.nextInt());

                System.out.print(" Add another course (Y/N): ");
                char add2 = in.next().charAt(0);
                if (add2 == 'Y' || add2 == 'y') {
                }

                if (add2 == 'N' || add2 == 'n') {
                    break;
                }

            }

        } else if (choice == 3) {

            RegistrationClass[] registrationList;
            registrationList = new RegistrationClass[500];
            registrationList[0] = new RegistrationClass();

            CourseClass[] courseOfferedList;
            courseOfferedList = new CourseClass[500];
            courseOfferedList[0] = new CourseClass();

            StudentClass[] studentList = new StudentClass[500];
            studentList[0] = new StudentClass();

            while (true) {

                while (true) {
                    System.out.print("Enter the unique student ID: ");

                    registrationList[0].setUniqueStudentID(in.nextInt());

                    if (registrationList[0].getUniqueStudentID() == studentList[0].getUniqueStudentID()) {

                        while (true) {
                            System.out.print("Enter the course code: ");
                            registrationList[0].setCourseCode(in.next());

                            if (registrationList[0].getCourseCode().equalsIgnoreCase(courseOfferedList[0].getCourseCode())) {

                                System.out.println("The registration is given the unique ID = " + registrationList[0].getUniqueRegistrationID() + " and the number of registrations =  " + registrationList[0].getNumberOfRegistrations());

                                System.out.print(" Add another course (Y/N): ");
                                char add2 = in.next().charAt(0);
                                if (add2 == 'Y' || add2 == 'y') {

                                }

                                if (add2 == 'N' || add2 == 'n') {

                                    break;

                                }

                            } else {
                                System.out.println("The course has not been offered yet, try again");

                            }

                        }

                    } else {
                        System.out.println("The student does not exit, try again ");
                    }

                }

            }

        } else if (choice == 4) {

            while (true) {

                RegistrationClass[] registrationList;
                registrationList = new RegistrationClass[500];
                registrationList[0] = new RegistrationClass();

                StudentClass[] studentList;
                studentList = new StudentClass[500];
                studentList[0] = new StudentClass();

                CourseClass[] courseOfferedList;
                courseOfferedList = new CourseClass[500];
                courseOfferedList[0] = new CourseClass();

                System.out.println("Enter the registration ID: ");

                registrationList[0].setUniqueRegistrationID(in.nextInt());

                System.out.print(" Enter marks of " + studentList[0].getName() + " in " + courseOfferedList[0].getCourseCode() + " (" + courseOfferedList[0].getCourseTitl() + ") :");

                System.out.println("");
                System.out.print(" Add another registration (Y/N): ");
                char add2 = in.next().charAt(0);

                if (add2 == 'Y' || add2 == 'y') {

                }

                if (add2 == 'N' || add2 == 'n') {

                    break;
                }

            }

        } 

    }
}

}

class RegistrationClass {

private int uniqueRegistrationID;
private int uniqueStudentID;
private String courseCode;
private int marks;
static int numberOfRegistrations = 0;

public RegistrationClass() {
    uniqueRegistrationID = 0;

    uniqueStudentID = 0;

    courseCode = null;

    numberOfRegistrations = 0;

}

public int getUniqueRegistrationID() {
    return uniqueRegistrationID++;
}

public void setUniqueRegistrationID(int uniqueRegistrationID) {
    this.uniqueRegistrationID = uniqueRegistrationID;
}

public int getUniqueStudentID() {
    return uniqueStudentID++;
}

public void setUniqueStudentID(int uniqueStudentID) {
    this.uniqueStudentID = uniqueStudentID;
}

public String getCourseCode() {
    return courseCode;
}

public void setCourseCode(String courseCode) {
    this.courseCode = courseCode;
}

public int getMarks() {
    return marks;
}

public void setMarks(int marks) {
    this.marks = marks;
}

public static int getNumberOfRegistrations() {
    return numberOfRegistrations++;
}

public static void setNumberOfRegistrations(int numberOfRegistrations) {
    RegistrationClass.numberOfRegistrations = numberOfRegistrations;
}

}

class StudentClass {

private String name;
private int uniqueStudentID;
private String email;
private int mobileNumber;
private int semesterNumber;
static int numberOfStudents = 0;

public StudentClass() {

    name = null;
    uniqueStudentID = 1;
    email = null;
    mobileNumber = 0;
    semesterNumber = 0;
    numberOfStudents = 1;

}

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

public void setUniqueStudentID(int uniqueStudentID) {
    this.uniqueStudentID = uniqueStudentID;
}

public void setEmail(String email) {
    this.email = email;
}

public void setMobileNumber(int mobileNumber) {
    this.mobileNumber = mobileNumber;
}

public void setSemesterNumber(int semesterNumber) {
    this.semesterNumber = semesterNumber;
}

public void setNumberOfStudents(int numberOfStudents) {
    this.numberOfStudents = numberOfStudents;
}

public String getName() {

    return name;
}

public int getUniqueStudentID() {

    return uniqueStudentID++;

}

public String getEmail() {

    return email;

}

public int getMobileNumber() {

    return mobileNumber;
}

public int getSemesterNumber() {

    return semesterNumber;
}

public int getNumberOfStudents() {

    return numberOfStudents++;
}

void setName() {

}

void setuniqueStudentID() {

}

void setnumberOfStudents() {

}

void setsemesterNumber() {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

void setmobileNumber() {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

void setemail() {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

void setemail(String next) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

void setsemesterNumber(int nextInt) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

}

class CourseClass {

private String courseCode;
private String courseTitl;
private int creditHours;
static int numberOfCourses = 0;

public CourseClass() {

    courseCode = null;
    courseTitl = null;
    creditHours = 0;
    numberOfCourses = 0;

}

public String getCourseCode() {
    return courseCode;
}

public void setCourseCode(String courseCode) {
    this.courseCode = courseCode;
}

public String getCourseTitl() {
    return courseTitl;
}

public void setCourseTitl(String courseTitl) {
    this.courseTitl = courseTitl;
}

public int getCreditHours() {
    return creditHours;
}

public void setCreditHours(int creditHours) {
    this.creditHours = creditHours;
}

public static int getNumberOfCourses() {
    return numberOfCourses;
}

public static void setNumberOfCourses(int numberOfCourses) {
    CourseClass.numberOfCourses = numberOfCourses;
}

boolean setCourseCode() {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

}

this is how the output should look like

is used for input and < is used for output

{Display the menu, Choose the menu item}

1

Enter name of the student: john

< The student is given the unique ID = 1 and the number of students = 1

Enter the e-mail address of the student: john@stu.kau.edu.uk

Enter the semester number of the student: 3 Add another student (Y/N): Y Enter name of the student: Ibrahim

< The student is given the unique ID = 2 and the number of students = 2

Enter the e-mail address of the student: Ibrahim@stu.kau.edu.uk

Enter the semester number of the student: 3 Add another student (Y/N): N

{Display the menu, Choose the menu item}

2 Enter the course code: CPCS203

Enter the course title: Programming 2

Enter the credit hours of the course: 4 Add another course (Y/N): Y

Enter the course code: CPCS204

Enter the course title: Data Structures

Enter the credit hours of the course: 3 Add another course (Y/N): N

{Display the menu, Choose the menu item}

3

Enter the unique student ID: 3

< The student does not exit, try again

Enter the unique student ID: 1

Enter the course code: CPCS205

< The course has not been offered yet, try again

Enter the course code: CPCS203

< The registration is given the unique ID = 1 and the number of registrations = 1

Add another registration (Y/N): Y

Enter the unique student ID: 1

Enter the course code: CPCS204

< The registration is given the unique ID = 2 and the number of registrations = 2

Add another registration (Y/N): Y

Enter the unique student ID: 2

Enter the course code: CPCS204

< The registration is given the unique ID = 3 and the number of registrations = 3

Add another registration (Y/N): Y

Enter the unique student ID: 2

Enter the course code: CPCS204

< The registration is given the unique ID = 4 and the number of registrations = 4

Add another registration (Y/N): N

{Display the menu, Choose the menu item}

4

Enter the registration ID: 1

Enter marks of john in CPCS203 (Programming 2): 85

Add another registration (Y/N): Y

Enter the registration ID: 2

Enter marks of john in CPCS204 (Data Structures): 60

Add another registration (Y/N): Y

Enter the registration ID: 3

Enter marks of Ibrahim in CPCS203 (Programming 2): 95

Add another registration (Y/N): Y

Enter the registration ID: 4

Enter marks of Ibrahim in CPCS204 (Data Structures): 85

Add another registration (Y/N): N

{Display the menu, Choose the menu item}

IF Statement using SQL data to set variable

I'm currently writing a java application which is used to print bar codes out, which the information for is obtained from a MySQL database. The data in SQL has a property which defines which type of bar code it is, value 1 = serialized and 2 = un-serialized. I was wondering how I would use an if statement to set a variable to define what type of bar-code is being used - in java.

On the SQL database the value for bar code type is 'FK_BarcodeTypeID'

The code I have so far is:

 String SQL ="SELECT  [PK_PrintQueueID]" +
            "      ,[FK_PrinterID]" +
            "      ,[FK_BarcodeTypeID]" +
            "      ,[Barcode]" +
            "      ,[Quantity]" +
            "      ,[QueueDate]" +
            "      ,[ProcessedDate]" +
            "  FROM [Brad].[dbo].[PrintQueue]" +
            " WHERE ProcessedDate IS NULL";

    //Declare variable connection.
    Connection connection = null;
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //get current date time with Date()
    Date date = new Date();
    // System.out.println(dateFormat.format(date));



    //
    try {
        connection = DriverManager.getConnection(connectionString);
        Statement stmt = connection.createStatement();
        Statement stmt2 = null;
        ResultSet rs = stmt.executeQuery(SQL);

        while (rs.next()) {
            System.out.println(rs.getString("Barcode"));
            // System.out.println(rs.getString("PK_PrintQueueID"));
            // System.out.println(rs.getString("ProcessedDate"));
            String SQL2 = "UPDATE PrintQueue SET ProcessedDate =   '"+dateFormat.format(date)+"' WHERE PK_PrintQueueID =     '"+rs.getString("PK_PrintQueueID")+"' ";
            // System.out.println(SQL2);

            String ZPL = "^XA ^FX BARCODE ^BY4,2,050   ^FO140,40^BC^FD"+rs.getString("Barcode")+"^FS ^XZ";
            System.out.println(ZPL);



            // THIS IF STATEMENT SETS TYPE OF BARCODE TO
            // TYPE 1 OR 2

            // if ("FK_BarcodeTypeID") = 1) {

I am struggling to work out how to do the above, therefore any advice is appriciated.

Thankyou!

Show and Hide Tabs with if else

I have some tabs on my Home page. I have two groups, New Joinees and Administrators. I want to hide some tabs for the group New Joinees.

I have the following if else statement, but I am not sure where to insert this in my code.

 if ("New Joinees" in user.groups)
{
<ul class="tabs">
    <li class="tab-link current tab1" datatab="tab-1">'Business System   
Functionality'</li>
    <li class="tab-link tab2" datatab="tab-2">'Product'</li>
    <li class="tab-link tab3" datatab="tab-3">'Environment 
 Administration'</li>
    <li class="tab-link tab4" datatab="tab-4">'Training'</li>
    <li class="tab-link tab5" datatab="tab-5">'Release Notes'</li>
</ul>
}
else {
<ul class="tabs">
    <li class="tab-link current tab1" datatab="tab-1">'Business System 
Functionality'</li>
    <li class="tab-link tab2" datatab="tab-2">'Product'</li>
    <li class="tab-link tab3" datatab="tab-3">'Environment 
Administration'</li>
    <li class="tab-link tab4" datatab="tab-4">'Training'</li>
    <li class="tab-link tab5" datatab="tab-5">'Release Notes'</li>
    <li class="tab-link tab6" datatab="tab-6">'Architecture'</li>
    <li class="tab-link tab7" datatab="tab-7">'Testing'</li>
    <li class="tab-link tab8" datatab="tab-8">'System Administration'</li>
    <li class="tab-link tab9" datatab="tab-9">'Site Management'</li>
    <li class="tab-link tab10" datatab="tab-10">'Staging'</li>
    <li class="tab-link tab11" datatab="tab-11">'RCB'</li>
</ul>
}

Here is my html and css. Can somebody please help me to understand where to insert the above statement in the code to make it work?

http://ift.tt/297rgcZ

Just started Java can't get my code to work?

So I made this

if (1 > 2){
system.out.print ("Hello math is wrong here");
}
else {
system.out.print ("Hello math is right!");
}

And I can't figure out why it wont display am I not entering the right commands? Also what should I save the file as in order to get it to run?

mercredi 29 juin 2016

Javascript for if statement works outside function but not inside

Can't seem to figure out why my code works outside of a function but not inside.

Outside:

for(var j=0; j<contacts.length; j++){
    if(contacts[j].hasOwnProperty("like")===false) {
      console.log("No such property");
    } 
  }

Inside:

function lookUpProfile(fN, prop){

for(var j=0; j<contacts.length; j++){
    if(contacts[j].hasOwnProperty("like")===false) {
      console.log("No such property");
    } 
  }
} 

"less than or equal to" operator not working in if condition

my $path="/mnt/splash/logs/";
my $serv= sprintf("splash-%s-%02d%02d%02d-%s",$server,$year,$mon,$date,$hourStart);
my $eserv= sprintf("splash-%s-%02d%02d%02d-%s",$server,$eyear,$emon,$edate,$hourEnd);
print $serv;
print $eserv;
#OPEN THE SPLASH LOGS DIRECTORY AND READ THE FILES PRESENT THEN STORE IT IN ARRAY.

my $remote_dir=sprintf("ssh %s 'ls %s'",$server,$path);
chomp $remote_dir;
my @list=`$remote_dir`;

#FINDING THE ONLY SPLASH LOGS FILES FROM THE DIRECTORY AND STORED IN AN ARRAY USING PUSH METHOD.
my @srt_list= sort @list;
my @arlist=();
my @arrlog=();
my $i=0;
my $filt;
for(@srt_list) {
    if ($_ ge $serv && $_ le $eserv) {
        #my $filter= sprintf("$_\n");
        chomp $_;

        push (@arrlog, $_);
    }
}

Above is the perl code i used to retrieve the logs from the array. I used if condition with the ge and le operators but if i searched for the log file between 20160628-0400.log to 20160629-1000.log this code is giving the logs from 20160628-0400.log to 20160629-0900.log this is not retrieving the log 20160629-1000.log which the end time log i m searching. i dunno how this happening i used le operator that means it should select the logs that is less than or equal log right?

Please clarify this. i really don't wanna add any other check to retrieve the end time log.

php condition statement not working [duplicate]

This question already has an answer here:

I'm trying to add a condition statement using php, but it's fighting me. Here's my code.

$ext = pathinfo($path, PATHINFO_EXTENSION);
$fiType = substr($ext, 0, 3);
$iconElem = '';
if ($fiType = 'doc') {
    $iconElem = "fa-file-word-o";
} elseif ($fiType = 'txt') {
    $iconElem = "fa-file-text-o";
} elseif ($fiType = 'xls') {
    $iconElem = "fa-file-excel-o";
} elseif ($fiType = 'ppt') {
    $iconElem = "fa-file-powerpoint-o";
} elseif ($fiType = 'pdf') {
    $iconElem = "fa-file-pdf-o";
} else {
    $iconElem = null;
}

Somehow, I keep getting "fa-file-word-o" no matter what type of file I upload. fiType is different with every file type, but my elseif doesn't think so. Help.

how to use handlebars conditional helpers?

I have a Handlebars template with multiple iff blocks. iff is a custom helper for comparing values. The template compiles, but oo applying it i get no output and no errors.

Please what am I doing wrong?

iff helper

Handlebars.registerHelper("iff", function (v1, operator, v2, options) {
    switch (operator) {
        case '==':
            return (v1 == v2) ? options.fn(this) : options.inverse(this);
        case '===':
            return (v1 === v2) ? options.fn(this) : options.inverse(this);
        case '<':
            return (v1 < v2) ? options.fn(this) : options.inverse(this);
        case '<=':
            return (v1 <= v2) ? options.fn(this) : options.inverse(this);
        case '>':
            return (v1 > v2) ? options.fn(this) : options.inverse(this);
        case '>=':
            return (v1 >= v2) ? options.fn(this) : options.inverse(this);
        case '&&':
            return (v1 && v2) ? options.fn(this) : options.inverse(this);
        case '||':
            return (v1 || v2) ? options.fn(this) : options.inverse(this);
        case '!=':
            return (v1 != v2) ? options.fn(this) : options.inverse(this);
        case '!==':
            return (v1 !== v2) ? options.fn(this) : options.inverse(this);
        default:
            return options.inverse(this);
    }
});

template


    
    <div class='sb-date'></div>
    
    
    <div class='sb sb-text sb-'><div class="sb-time"></div></div>
    
    
    <div class='sb sb-text sb-'><div class="sb-time"></div></div>
    
    
    <div class='sb sb-text sb-'><div class="sb-time"></div></div>
    
    
    <div class='sb sb-image sb-'><img alt="" src="media/" /><div class="sb-time"></div></div>
    
    
    <div class='sb sb-file sb-'>media/<div class="sb-time"></div></div>
    


Alternative to many IF statements in python? [duplicate]

This question already has an answer here:

I know there are a lot of questions about that, but they are all about some specific cases.

I have a general question. I have code which compares user input to many possible values (keywords).

All works, but I hate the "monstrosity".

it's like this:

 if userinput == "input1":
   print('input1')
 elif userinput == "input2":
   print('input2')
 elif userinput == "input3":
   print('input3')
 elif userinput == "input3":
   print('input3')
 elif userinput == "input3":
   print('input3')
 # repeat many times until the last else
 else:
   print('all the rest')

  • the inputs can be ANYTHING. And comparison is not always just ==.
  • the action on match sometimes can be a long piece of code too, not just print.

I can't really combine those conditions and I on purpose don't want to, since each one detects it's own thing.

My question is: Any practice of making such cases more readable? Cleaner?

One thing I am thinking is to call an external functions per case from each comparison and store those functions in separate *.py file. The best I can think of at this point..

Any better ideas\ways to handle that?

Relative references in IF formula in Excel

I have conditionally formatted a cell to turn a different color based on whether the value in it is below, between, or above two numbers in columns AU and AV. What I would like to do is have a cell to the left of this hold a value also based on what is in AU and AV. For instance, if the value in the colored cell is bigger than AV, then I want the cell to the left to hold a value of 25. If it is between AV8 and Au8, then cell to the left = 15, and otherwise cell to left = 0. The problem with my formula is that I want to be able to have this work for multiple cells to the left of multiple values pulling from multiple values in AU and AV. I am thinking formulaR1C1 might work here but I don't know how to use it. Also, I am really writing this in VBA but for purposes of this question it might be easier to just understand the formula in excel first.

Range(Cells(i, j * 4 + 2), Cells(i + 1, j * 4 + 4)).FormulaR1C1 =
"=IF(J8 >=$AV8,25,IF(J8 >=$AU8,15,0))"

How to return "if" in a if loop?

Hi guys actually first I wanted to do this loop.

Process p = Process.GetProcessesByName("etcProgram.bin")[0];
                foreach (System.Diagnostics.ProcessModule moz in p.Modules)
                    if (csh.Text == "csh" || bin.Text == "bin")
                    {
                        if (moz.FileName.IndexOf("csh") != -1)
                        {
                            csh.Text = moz.BaseAddress.ToString();
                        }
                        if (moz.FileName.IndexOf("bin") != -1)
                        {
                            bin.Text = moz.BaseAddress.ToString();
                        }
                    }
                else
                    {
                      !!!!!! return to "if" until "if code" happens !!!!!!
                    }

But my poor code knowledge can't come through this problem. So I wrote nearly same thinh with timer. Then I wrote this code.

 private void tmrActive_Tick(object sender, EventArgs e)
        {
            try
            {
                Process p = Process.GetProcessesByName("Wolfteam.bin")[0];
                foreach (System.Diagnostics.ProcessModule moz in p.Modules)
                    if (csh.Text == "csh" || bin.Text == "bin")
                    {
                        if (moz.FileName.IndexOf("csh") != -1)
                        {
                            csh.Text = moz.BaseAddress.ToString();
                        }
                        if (moz.FileName.IndexOf("bin") != -1)
                        {
                            bin.Text = moz.BaseAddress.ToString();
                        }
                    }
                else
                    {
                        tmrActive.Stop();
                        MessageBox.Show("It's stopped");
                    }
            }

But I saw that MessageBox appears 5-6 times when I started this.And I dont know why. So I dont feel very safe about use this code.

1- Do you know what's the problem with that timer. Shouldn't this messagebox appear once?

2- Can you help me about the code without timer.Is there anyway to do it?

check for results of `getent passwd user` in bash if statement

A user exists called teststu

Here's my script checkuser.sh

#!/bin/bash
USERINFO=$(getent passwd $1)
echo "User info:  $USERINFO"
if [$USERINFO]; then
   echo "$1 already exists"
else
   echo "New user: $1"
fi

if I run: sh checkuser.sh teststu I get:

User info:  teststu:*:10001:10001:teststu:/home/teststu:/bin/bash
checkuser.sh: 4: checkuser.sh: [teststu:*:10001:10001:teststu:/home/teststu:/bin/bash]: not found

New user: teststu

and if I run sh checkuser.sh nonexistantuser:

User info:
checkuser.sh: 4: checkuser.sh: [-n: not found

New user: nonexistantuser

How can I get my if statement to properly differentiate between these two results?

I was trying to use this:

[ -n STRING ] or [ STRING ] True if the length of "STRING" is non-zero.

How to write if not contains for selenium?

I want to know how if y is not contain x. Can you please tell me how?

enter code hereString x = driver.get Page Source();
        String y = validation;

        if(y.contains(x){   <------ how to make this if (y not contain x)

That what i want to do.

Thanks

if statement for input value showing even when not true

I'm trying to have the script show me the first character that is typed into an input field only if that character is a specific number. I'm probably missing something simple, but the if statement is returning results to me no matter what number I type in.

HTML

<input class="cardnum">

JS

$('.cardnum').keyup(function(){
  var card = $('.cardnum').val(),
      cardnum = card.charAt(0);
  if ($(cardnum == 3)) {
    console.log(cardnum);
  }
});

Here is a jsFiddle I created in case it helps.

PHP 7 "for loop" bug with if statement. Stops working after 32.767 loops?

I`ve been playing around with PHP and tried to find this "bug" fix, but could not find anything about it...

The Task: Find out how many tries it takes to discover a random selected number.

I generated a random number outside a for loop and declared a variable that will be the maximum amout of times the for loop will run to try and guess this number. If the random number generated inside the for loop is "==" to the number generated outside the loop I save that number in a variable, save the amout of times it took to get it right and break out of the loop... Simple stuff.

THE "BUG":

Evertything works great, until we get up to 32.767 times inside the for loop.. If we work with small numbers nothing goes wrong, but if we try some big random numbers, like above 50.000, the if statement inside the for loop will execute on the 32.767th time, no matter what. It`s like the "==" sundently turns into a "=".

Beeing new to PHP I thought this could be a memory thing, but I tried out some big loops without the if statement and they all worked...

Here is the code:

<?php

$number = rand(1,50000); // Change this to something small, bellow 30.000, and it will start to work. make it the same as line 10.
$correctNumber;
$maximumLoops = 50000; // No matter how much loops you try, if the random number is big and we get to the 32.767th loop, the if statement will execute.
$numberOfLoops = 0;


for($i = 0; $i < $maximumLoops; $i++){
    $randNumber = rand(1,50000); // Change this to something small, bellow 30.000, and it will start to work. make it the same as line 3.
    if($randNumber == $number){
        $correctNumber = $number;
        $numberOfLoops = $i;
        break;

    }
}

echo "The Number was: $number<br>";
echo "Correct Number is: $correctNumber<br>";
echo "The maximum number of loops was: $maximumLoops<br>";
echo "Number of loops to get it right: $numberOfLoops";

Any help would be greatly appreciated. Thanks

Nested if statement in for loop bash

I'm writing a bash script that goes through a for loop which is a list of each hostname, then will test each one if it's responding on port 22, if it is then execute an ssh session, however the second if statement is only executed on the first host in the list, not the second. If the host isn't responding on port 22, I want the script to continue to the next host. Any ideas how to ensure the script runs the ssh on each host in the list? Should this be another for loop?

!/bin/bash

hostlist=$(cat '/local/bin/bondcheck/hostlist_test.txt')

for host in $hostlist; do

test=$(nmap $host -P0 -p 22 | egrep 'open|closed|filtered' | awk '{print $2}')

    if [[ $test = 'open' ]]; then

                    cd /local/bin/bondcheck/
                    mv active.current active.fixed
                    ssh -n $host echo -n "$host: ; cat /proc/net/bonding/bond0 | grep Active" >> active.current

                    result=$(comm -13 active.fixed active.current)

            if [ "$result" == "" ]; then
                            exit 0
            else
                    echo "$result" | cat -n
            fi

    else
            echo "$host is not responding"
    fi

done

Python: if condition and "with"

I'm just wondering if is there a simpler (shorter) way to write the following (this is a simple example, which in real code is much more complicated)?

def my_fun(value):
 foo = 20
 if value == '0':
    with temporary_set('foo',20):
         #here we run many operations on foo
else:
   #here we run many other operations on foo

find a match of a2 in sheet2 g2 then copy value of cell AI2

find a match of A2 in sheet 2 G2 then copy value of cell AI2, i am new to excel and i cant get anything to work.

Please help.

C - Most succinct way to check if a variable is *none* of many options?

Background:

Often, we developers must check if a single variable is at least one of many options. For example,

if ( (data == 125) || (data == 500) || (data == 750) )
{
    /* ... do stuff ...*/
}

The suggestion here (albeit written in C#), provides an elegant solution to use a switch statement like so,

switch ( data )
{
    case 125:
    case 500:
    case 750:
        /* ... do stuff ...*/
        break;

    default:
        break;
}

This works well for "or" conditionals, but is ugly for negated "or" conditionals like the following,

if ( !( (data == 125) || (data == 500) || (data == 750) ) )
{
    /* ... do stuff ...*/
}

which could be written as

switch ( data )
{
    case 125:
    case 500:
    case 750:
        break;

    default:
        /* ... do stuff ...*/
        break;

}

and seems a bit hackish.

Question:

Is there a more succinct way to check if a single variable is none of many options, like the negated "or" conditional above?

References:

Powershell Background if Ping script

I have an old CMD Script which I want to convert into a Powershell Script which runs in the Background, the CMD Script:

@echo off
timeout /t 300 /nobreak
ping -n 1 -i 135 -w 130 192.168.1.250
if errorlevel 1 goto Ende
goto Program
:Program
start "" "C:\Program Files (x86)\XXX\XXX.exe"
Exit

:Ende
Exit

The Script checks if the Router is pingable, if yes it starts a program. I have completly zero experience with either CMD or Powershell(see Goto <.<), I tried to do it with google and found some solutions to run it in background but they didn't really work out for me.

The Sleep option should work with start-sleep -s 300, the Ping Check with if (test-connection -computername Server01 -quiet) but im not completly sure how to do an if-statement around the ping.

Greetings

Bash if/else Loop Error

Exactly as title says. Simple for loop in Bash. I've been trying to figure out why this loop isn't working and I haven't come up with anything for two days now. Insight would be appreciated.

declare -r TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S,%3N)

CHECK="$(grep -c "$TIMESTAMP" /var/log/host/logname.log)"
if [ "$CHECK" -eq 0 ]
then
     COLOR="green"
elif [ 0 -lt "$CHECK" ] && [ "$CHECK" -le 5 ]
     COLOR="yellow"
else
     COLOR="red"
fi

The COLOR var is something that is preset by the system I'm using. The red/yellow/green are all correct, something in either my syntax or logic is the issue, though I've been struggling to determine which. Thanks!

How to calculate means from data frame in R for a variable with specific amount of NAs or not NAs at all?

So I have lots of data in the form (4 values for each day)

         date   var1      var2 
1  2003-10-28    1.2       970     
2  2003-10-28     NA       510     
3  2003-10-28     NA       640     
4  2003-10-28     NA       730     
5  2003-10-30    2.0       570     
6  2003-10-30     NA       480     
7  2003-10-30    1.2       580     
8  2003-10-30    1.2       297     
9  2002-05-07    3.0       830     
10 2002-05-07    4.8       507     
11 2002-05-07    4.8       253     
12 2002-05-07     NA       798    

and I need to calculate sums for var1 for every day, IF there is for example less than 2 NA values (or none) for that specific date and otherwise that date should be ignored. At the same time I should calculate means of var2 for the same dates, IF the sum for var1 was also calculated. Then I should save those means, sums and dates to another data frame so that those ignored dates aren't there.

I have tried all kinds of loop structures, but I get confused by the fact that mean and sum have to be calculated for the dates where there are not NAs at all. Also saving the dates, means and sums gets me into difficulties because I have no idea how to do the indexing properly.

PHP if else statement, one works other not. why? [duplicate]

This question already has an answer here:

I have a form in HTML which is submitted to a PHP page.

It is working fine but I wonder why I had to change code to do so.

what is wrong with my personal way. I set the variable $sendcopy to eigther Ja or Nee at the end I check whether it's Ja or Nee and have a if else statement.

if ($sendcopy = 'Ja') { 
//echo yes; 
} else {
//echo no; 
}

this doesn't work for me and I don't know why because through troubleshooting $sendcopy does have the correct value Ja or Nee.

here is the form and php page

HTML just the form part nothing wrong here

there is a checkbox to choose to get a copy of the submitted form its name and id is scopy.

            <section id="form" class="main">
                    <div class="container">
                    <form method="POST" action="./form-submit.php" onsubmit="versturen.disabled = true; return true;">
                        <div class="row uniform 50%">
                            <div class="6u 12u$(xsmall)">
                                <input type="text" name="naam" id="naam" value="" placeholder="Naam Verplicht" required />

                            </div>
                            <div class="6u$ 12u$(xsmall)">
                                <input type="email" name="clientemail" id="clientemail" value="" placeholder="Email Verplicht" required />

                            </div>
                            <div class="12u$">
                                <div class="select-wrapper">
                                    <select name="onderwerp" id="onderwerp">
                                        <option value="">- Onderwerp -</option>
                                        <option value="Info">Informatie</option>
                                        <option value="Offerte">Offerte</option>
                                        <option value="Admin">Administratie</option>
                                        <option value="Overig">Anders</option>
                                    </select>
                                </div>
                            </div>
                            <div class="12u$">
                                <textarea name="bericht" id="bericht" placeholder="Laat uw bericht achter" rows="4"></textarea>
                            </div>

                                </div>
                                <div class="6u 12u$(small)">
                                    <input type="checkbox" id="scopy" name="scopy">
                                    <label for="scopy">Email een copy naar u zelf</label>
                                <br />
                                    <input type="checkbox" id="ismens" name="ismens" required>
                                    <label for="ismens">check als je een mens bent</label>

                                </div>
                                <div class="12u$">
                                    <ul class="actions">
                                        <li><input type="submit" name="versturen" value="Send Message" class="special" /></li>
                                        <li><input type="reset" value="Reset" onclick="versturen.disabled = false; return true;"/></li>
                                    </ul>
                                </div>
                            </div>
                        </form>
                        </div>
                    </section>

PHP full page

<?php
//var_dump($_POST);

if(isset($_POST['ismens'])) {

    $email_to = "webmaster@yourdomain.com"; // Je eigen Email adres


    function died($error) {

        // fout code gaat hier

        echo "Het spijt ons heel erg, maar er zijn fout(en) gevonden in het formulier dat u verstuurde. ";

        echo "Deze fout(en) staat hier beschreven.<br /><br />";

        echo $error."<br /><br />";

        echo "Gaat u alstublieft terug om de fout te herstellen.<br /><br />";

        echo "<a href='#' onClick='history.go(-1)'>Go Back</a>";  

        die();

    }

 // Obsolete checks for html5 

 //    echo "Test line 1";

    // validatie van het formulier

    if(!isset($_POST['naam']) ||

        !isset($_POST['clientemail']) ||

        !isset($_POST['ismens']) ||

        !isset($_POST['bericht'])) {

        died('Het spijt ons, het formulier is onjuist ingevuld. <br /> Controleer dat de verplichte velden zijn ingevuld.');       

    }
 // End Checks

 // Set variables 

 //    echo "Test line 2";

    $first_name = $_POST['naam']; // verplicht

    $email_from = $_POST['clientemail']; // verplicht

    $comments = $_POST['bericht']; // verplicht max 300 tekens

    $subject = $_POST['onderwerp'];
#############################################
    if(!isset($_POST['scopy'])) {
        $sendcopy = 'Nee';
    } else {
        $sendcopy = 'Ja';
    }
#############################################
 // Check for errors, Obsolete for html5   

    $error_message = "";

    $string_exp = "/^[A-Za-z .'-]+$/";

  if(!preg_match($string_exp,$first_name)) {

    $error_message .= 'Onbekende tekens in uw Naam.<br />';

  }

  if(strlen($comments) < 9) {

    $error_message .= 'De inhoud van het bericht wat u probeert te versturen is te kort.<br />';

  }

  if(strlen($error_message) > 0) {

    died($error_message);

  }


    function clean_string($string) {

      $bad = array("content-type","bcc:","to:","cc:","href");

      return str_replace($bad,"",$string);

    }

    $email_subject = "Website Contact $subject";

    $comments = wordwrap($comments, 50,"<br />\n");

    $email_message = "<br /><br />Formulier gegevens: <br /><br />\n\n";

    $email_message .= "Klant Naam: ".clean_string($first_name)."<br />\n";

    $email_message .= "Klant Email: ".clean_string($email_from)."<br />\n";

    $email_message .= "Kopie gestuurd: ".clean_string($sendcopy)."<br /><br />\n";

    $email_message .= "Bericht: ".clean_string($comments)."<br />\n\n";



     #######################################

// create email headers
//if ($sendcopy = 'Ja') {
if(isset($_POST['scopy'])) {

$headers = 'From: '.$email_from."\r\n".

'Cc: '.$email_from."\r\n".

'Reply-To: '.$email_from."\r\n" .

'X-Mailer: PHP/' . phpversion();

} else {

$headers = 'From: '.$email_from."\r\n".

'Reply-To: '.$email_from."\r\n" .

'X-Mailer: PHP/' . phpversion();


}
#########################################

//mail($email_to, $email_subject, $email_message, $headers);  

?>



<!-- include your own success html here -->



Thank you for contacting us. We will be in touch with you very soon.


<?php
/*
echo "<br /><br />";

echo "Subject: $email_subject <br /><br />";
echo "$email_message <br /><br />";
echo "$headers";
 */
}

?>

this solved it but I don't understand why can someone explain this to me.

if(isset($_POST['scopy'])) {
//echo yes; 
} else {
//echo no;
}

If table have 0 rows exit procedure

I have a procedure inside a package and I want to implement a logic, wich will not insert the temp table into the main table if the temp table have 0 rows, and then go to the next procedure of the package.

IF (not exists(select 1 from temp)) THEN
   RETURN;
ELSE
   EXECUTE IMMEDIATE 'TRUNCATE TABLE main';
   INSERT --+APPEND 
          INTO main
          Select * from temp;
   EXECUTE IMMEDIATE 'TRUNCATE TABLE temp';
END IF;

With this solution, the package is compiled with error.

Can anyone give me some tips?

If function in google docs

I know how excel works, but google docs is not the same :( I have one function in excel which I want to put into google docs. Can you help?

=IF(A2="paypal";((A4*B4)+A4);A4)

A B 1 2 PAYPAL 3 60 4%

Crystal reports return string or number

What I am trying to do is return a number or a string from CR formula. Something like

IF A/B != 0
return A/B
else
return "N/A"

Here is my attempt which unforunatelly does not compile - In this place a sequence is required (own translation from my native language), and points on the first line.

stringvar result := {report_lpb_requests_kpi;1.phone_requests};
IF {ps_hd_report_lpb_requests_kpi;1.all_requests} <> 0 THEN
    result := {report_lpb_requests_kpi;1.phone_requests} / {report_lpb_requests_kpi;1.all_requests} *100
ELSE
    result :='N/A'

If #REF! then hide certain rows

I have created 2 sheets, Sheet no. 1 shows the data nicely and the other imports the data. Therefore sheet no. 1 gets data from sheet no. 2. However sometimes there are no data in sheet no 2. This gives the cells in sheet 1 "#REF!". When this happens i need to hide certain rows in sheet 1.

So i imagine something like this

Sub HideCharts()

BeginRow = 132
EndRow = 138
ChkCol = 8

For RowCnt = BeginRow To EndRow
    If Cells(RowCnt, ChkCol).Value = 0 Then
        Cells(RowCnt, ChkCol).EntireRow.Hidden = True
    End If
Next RowCnt

        For RowCnt = BeginRow To EndRow
            If Cells(RowCnt, ChkCol).Value <> 0 Then
                Cells(RowCnt, ChkCol).EntireRow.Hidden = False
            End If
        Next RowCnt
End Sub 

However this only works if the data is 0 and i got no clue on how to catch the #REF! also this only hides the rows that contains the 0 value, but i need to catch certain rows like 130 to 140

So i thought, who else to turn to than Stack Overflow?

VBA - what is faster? Case statements or If Statements

I am writing some code for a very large spreadsheet. Where certain things need to go in specific places, and I am wondering what sort of statement would be faster, and what are the pro's and con's of each statement.

Kind Regards,

lewisthegruffalo

C# if statement list check

hey guys I need some help. basically I need to check web extensions. i dont want to sit and write out each one as follows

if (RegEmail.Text.Contains("@") &&   (RegEmail.Text.Contains(".com")||RegEmail.Text.Contains(".net"))
        {
            RegEmailB = true;

            //RegEmail.Background = _orginalDrawable;
            RegEmail.SetTextColor(Color.Green);
        }

i would like to do something like this

        string emailExtensions = ".co.za" + ".com";
        if (RegEmail.Text.Contains("@") && RegEmail.Text.Contains(emailExtensions))
        {
            RegEmailB = true;

            //RegEmail.Background = _orginalDrawable;
            RegEmail.SetTextColor(Color.Green);
        }

but i dont know how to go about it..

mardi 28 juin 2016

Is there a component in talend for switch cases?

I have 100 when-then cases.I am looking for a component in Talend data tool which will help me putting this cases in a simple way. I have tried ternary operator in tmap and also if-else code in tJava. Anything else.

Unable to get bash if condiftion to work with multiple commands per outcome

I have been trying to get various versions of this to work:

[[ -e "~/usersl" ]] && { user=`cat ~/usersl`; echo Username: $user; } || { read -p "Username:" user; echo $user > ~/usersl; }

The main goal is to have a if..then..else all in one line. From what I have read on this site and others, this should work. It should check to see if the usersl file exists and if it does then it prints out the detected username and populates the $user variable. If the usersl file doesn't exist then it should ask for the username and populate the variable at the same time then record the new username into a file. Once that has been done the next tiem the command is ran the file already exists and it just displays the username and propagates the variable. Hope my explanation isn't overly complicated but the task is very simple.

Any help is much appreciated

return value of python function using while true statement

I am trying to pass a string value to a while loop, but the won't return the updated string, what am I doing wrong?

  def test(str):
        random stuff
        while True:
              if(test 1 passes):
                    break
              else:
                    more random stuff
                    if(test 2 passes):
                          break
                    else:
                          tests didn't work
                          test(str)
               break
       return str

Wordpress PHP mark a custom post type as viewed in post listing

I have created a function that allows users to mark a custom post type in wordpress as viewed. When they mark it, the post_id they have viewed is noted in wp_usermeta in the db.

Here is the code that marks the post as viewed:

function lesson_watched() {
    $nonce = $_POST['nonce'];

if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
    die ( 'Busted!');

if(isset($_POST['lesson_watched']))
    {
    $user_id = get_current_user_id();
    $post_id = $_POST['post_id'];

    if(!hasAlreadyWatched($post_id, $user_id)) 
        update_user_meta($user_id, 'has_watched_lesson', $post_id);
    else if(hasAlreadyWatched($post_id, $user_id))
        delete_user_meta($user_id, 'has_watched_lesson', $post_id);
    }
    exit;
}

function hasAlreadyWatched($post_id) {
    $user_id = get_current_user_id();
    if(get_user_meta($user_id, 'has_watched_lesson', $post_id)!='') {
        return true;
    } else {
        return false;
    }
}

I have created a function to check if a post is marked as viewed and returns true or false:

function is_lesson_watched() {
$member = MS_Plugin::$api->get_current_member();
// if user has membership AND has watched the video
if(hasAlreadyWatched($post_id) && $member->has_membership()) {
    return true;
}
    return false;
}

On the front end of my site, I have a loop that shows all posts from a custom post type. I am trying to add a span to all posts that are marked as viewed by using the following code:

<?php if(is_lesson_watched()) {
    echo '<span class="fa fa-eye watched_lesson_stamp"></span>';
} ?>

Note: this code is placed within a loop. My issue is that this code seems to add the span to all listed posts in the post type - not the ones that are viewed.

Batch- if command and "check internet connection"

I have problems with my router when downloading through steam and other programs, such as the internet losing connection with the router. I cant plug my pc to my router using cable so i made a solution: and the other one \Every X secounds disconect and connect to internet

But the problem is i want to make it more efficient so i would like a command that does this:

:a \Check connection \if connected then goto a \if noconnection disconect and connect to internet

i get problems with check connection command as its does not move on to the if

Please help and thanks for your time

Multiple AND conditions in bash that work independently based on an OR condition separator?

This question is different from the multitude of potential duplicates, I've not been able to find this particular question answered or even asked...

Maybe I'm overlooking some simple logic here, but I'm running into the following issue:

I'm trying to have an if statement where conditions must be met like $V1 AND $V2 are TRUE || OR $V3 AND $V4 are TRUE. Here's a simple test:

#!/bin/bash

V1="File Placeholder"
#echo $V1
V2="May contain some text"
#echo $V2

V3="Some command output"
#echo $V3
V4="Command output contains this text"
#echo $V4

if [[ "$V1" ]] && [[ "$V2" == *"contain some"* ]] || [[ "$V3" ]] && [[ "$V4" == *"output contains"* ]]
then
echo "Hello $V1"
echo "World full of: $V2"
fi 

Meaning, I'd like to do something if:

$V1 is true (a file exists) AND $V2 is true (some string is found)

OR

$V3 is true (ie not null) AND $V4 is true (command output contains text)

It appears to work a bit, but I realize it's not working properly: it won't return TRUE if both the second && conditions are FALSE ie: || [[ "$V6" ]] && [[ "$V4" == *"outpuy contains"* ]] (why I think I may be overlooking some logic, maybe getting cancelled out some how?).

Why isn't this working as I assume it would if a AND b are TRUE ... OR ... if x AND z are TRUE?

If statement with || and multiple &&

I have booleans A, B, C, D set to false.

I have following code if (A && B || C && D) {Debug.i("Check", "stars")}

When will I get "stars" message?

  1. When A and B OR C and D set to true.
  2. When A, B/C, D set to true

=============================

ANSWER

A && B || C && D

should be treated as

(A && B) || (C && D)

Why does Length not work on a NSString?

I am trying to check the length of string, but I get unrecognized selector when the code is executed and hits the IF statement.

THE VALUE IN THE DICTIONARY IS A STRING.

NSString * checkString = [myDictionary objectForKey:@"somekey"];
    NSLog(@"length: %lu", checkString, (unsigned long)[checkString length]);

if([checkString length]  > 0){

}

ERROR From console:

length: 0
[__NSCFNumber length]: unrecognized selector sent to instance

For simplicity:

 NSString * checkString = @"my string"; //[myDictionary objectForKey:@"somekey"];
    NSLog(@"length: %lu", checkString, (unsigned long)[checkString length]);

    if([checkString length] > 0){
}

length: 9
[__NSCFNumber length]: unrecognized selector sent to instance

Why?

C# if statements. if not a or not b

I am trying to add a number to a list but only if the number is not 255 or not 0 id like to avoid a nested if. The code I have to do this is as follows.

if (!(r == 255 || r == 0))
{
    rlist.Add(r);
    listBox2.Items.Add(Math.Floor(r).ToString());
}

However I am still getting 255 and 0 added to the listbox and I can not figure out why. Can anyone point out what i am doing wrong? Thanks in advance for any help.

Creating a program that compares two lists

I am trying to create a program that checks whether items from one list are not in another. It keeps returning lines saying that x value is not in the list. Any suggestions? Sorry about my code, it's quite sloppy.

Searching Within an Array

Putting .txt files into arrays

with open('Barcodes', 'r') as f:
    barcodes = [line.strip() for line in f]

with open('EAN Staging', 'r') as f:
    EAN_staging = [line.strip() for line in f]

Arrays

list1 = barcodes
list2 = EAN_staging

Main Code

fixed = -1

for x in list1:
    for variable in list1:                                                  # Moves along each variable in the list, in turn
        if list1[fixed] in list2:                                           # If the term is in the list, then
            fixed = fixed + 1
            location = list2.index(list1[fixed])                            # Finds the term in the list
            print ()
            print ("Found", variable ,"at location", location)              # Prints location of terms

linq - multiple where statements if variables are not null

I would like the query to return from WANOM_DETAILS & STRDT tables where PIPELINE = 'F' AND HISTORICAL_FLAG <> 'T' AND INSTALLATION = 'EA' AND ANOMALY_CLASS = 'Critical'.

The if statements work correctly, but at the moment the query is only returning from WANOM_DETAILS & STRDT tables where ANOMALY_CLASS = 'Critical' as this is the final line before the model.ToList();

Any help would be much appreciated. Here is the code;

        strdt = "EA";
        anom_class = "Critical";

        var models = db.WANOM_DETAILS;

        var model = models.Where(wanom_details => wanom_details.STRDT.PIPELINE == "F");
        model = models.Where(wanom_details => wanom_details.STRDT.HISTORICAL_FLAG != "T");
        if (strdt != "")
        {
            model = models.Where(wanom_details => wanom_details.INSTALLATION == strdt);
        }
        if (anom_class != "")
        {
            model = models.Where(wanom_details => wanom_details.ANOMALY_CLASS == anom_class);
        }
        if (subdt != "")
        {
            model = models.Where(wanom_details => wanom_details.WANOM.SUBSTRUCTURE == subdt);
        }
        if (comp != "")
        {
            model = models.Where(wanom_details => wanom_details.WANOM.TYPE + "-" + wanom_details.WANOM.IDENT == comp);
        }

        return PartialView("_SiteAnomalyGridViewPartial", model.ToList());

How to check if the first variable passed into a method is a string. Perl

I have no idea how to check for this. My method(if condition in method) should only work (execute) if the first argument passed in is a string. I know how to check other types, but I can't seem to find anything for checking for a string.

for a hash I would do something like;

if(ref eq 'HASH') {...}

If someone could provide a simple example I'm sure I would be able to apply it to what I'm doing. I will put up the code for the method and an explanation for the whole operational details of the method if needed.

Show correct or wrong answer in javascript by if or else statement

I'm working on Javascript and want to show the correct answer when someone clicks on a wrong option. Here is my code

 function processQuestion(choice){
    var bgcolor = '';
    var explanationhtml = '';
    if(quiz.questions[currentquestion]['choices'][choice] == quiz.questions[currentquestion]['correct']){
        bgcolor = '#8AFC7F';
        explanationhtml = '<div class="outcome-headline correct-text"> <i class="glyphicon glyphicon-ok"></i>'+quiz.questions[currentquestion]['correct']+'</div> ';
        score++;
    } else {

        var correct=quiz[currentquestion]['correct'];

    $('li.choice:contains('+correct+')').css('background-color', '#50D943');

         $('.choice').eq(choice).css({
             'background-color': '#D92623'
        explanationhtml = '<div class="alert alert-danger"><div class="outcome-headline incorrect-text"><i class="glyphicon glyphicon-remove"></i><strong>Sorry Wrong Answer!</strong> '+quiz.questions[currentquestion]['correct']+'</div></div> ';

Where did I go wrong?

nothing shows up after using if statement in node red?

Guys this is my example code node red, I am trying to get "hi". I managed to get value for age, but when i deploy the application, nothing shows up about the if statement.

var data= {
     "age" : "24",      

     "hometown" : {"country": "USA",
                   "City": "Missoula, MT"},                                                         
     "gender" : "male"
 };
node.send( {payload:data.hometown.country});
node.send( {payload:data.hometown.City});
node.send({payload:data});
var s =({payload:data.age});
node.send(s);
if (s == '24'){
    node.send("hi");
}

Here is the result

msg.payload : string [3]
USA
6/28/2016, 9:55:17 AM8ae7211a.e3f0b
msg.payload : string [12]
Missoula, MT
6/28/2016, 9:55:17 AM8ae7211a.e3f0b
msg.payload : Object
{ "age": "24", "hometown": { "country": "USA", "City": "Missoula, MT" }, "gender": "male" }
6/28/2016, 9:55:17 AM8ae7211a.e3f0b
msg.payload : string [2]
24

I can see the value for data.hometown.country, city, and age, but my if statement is not working.

How can I create a dynamic condition?

Here is my current code:

/* A part of index.php content */

if( time() - $_SESSION["TimeUpdateRep"] >= max(100 - $_SESSION["Reputation"] / 100, 20) ) {

    $smt = $db->prepare('SELECT reputation, notification FROM users WHERE id = ? limit 1');
    $smt->execute(array($_SESSION["Id"]));
    $num_row = $something->fetch();
    $_SESSION["Reputation"]        = $num_row['reputation'];
    $_SESSION["Notification_numb"] = $num_row['notification'];
    $_SESSION["TimeUpdateRep"]     = time();

}

/* note:
 * This line of code executes once before code above when user logs in
 * $_SESSION["TimeUpdateRep"] = time();
 */

As you see, code above updates the number of reputation and notification for each user based on a dynamic period. My current code depends on the number of user's reputation. The user who has more reputation, then that updating will be happened for him earlier.

So please focus on this line:

if( time() - $_SESSION["TimeUpdateRep"] >= max(100 - $_SESSION["Reputation"] / 100, 20) ) {

Actually my codes works as well, just it isn't tangible. I mean there isn't any obvious different in that updating between userA (1 rep) and userB (10k rep). (the different is just a few seconds)

How can I make a huge different between newcomer users, average users and super users in updating their reputations and notifications?

jQuery fadeIn() between if and else

I want to fade between different images which are loaded when different things happen. I created some if, else rules and thought I can tell jQuery with the fadeIn() to fade in every new image. But it's not working and I don't know why. I think it's a super little code thing I can't figure out. Hope you guys can help me!

Here is my code so far:

if(count == 1){
    $('.star').html('<img src="' + stern1 + '">').delay(1000).fadeIn('slow');
} else if (count == 2){
    $('.star').html('<img src="' + stern2 + '">').delay(1000).fadeIn('slow');
} else if(count == 3){
    $('.star').html('<img src="' + stern3 + '">').delay(1000).fadeIn('slow');
} else if(count == 4){
    $('.star').html('<img src="' + stern4 + '">').delay(1000).fadeIn('slow');
} else if(count == 5) {
    $('.star').html('<img src="' + stern5 + '">').delay(1000).fadeIn('slow');
} else {
    $('.star').html('<img src="' + stern1 + '">').delay(1000).fadeIn('slow');
}

PHP if statemant

I have the following if-statemant:

<br><br>
"if (isset($_POST['submit']) && !empty($_POST['submit']) && !empty($_POST['name']) && !empty($_POST['price'])) {
        include 'add.php';
        $message = "Product has been added";
        echo "<script type='text/javascript'>alert('$message');</script>";
    } else {
        $message = "Please fill all the fields";
        echo "<script type='text/javascript'>alert('$message');</script>";
    }" 
<br><br>

I want that the else part only executed if the submit button is pressed and any of the fields is empty, not before the button pressing.

Incorrect output from a formula in Excel

I am working on a excel sheet containing time and I am trying to find it's shift timing according to time. The shift allocation is as below:

If Time >= 05:30 PM & <= 01:30 AM - 1st shift

If Time >= 01:30 AM & <= 09:30 AM - 2nd shift

If Time >= 09:30 AM & <= 01:30 AM - 3rd shift

I am using IF AND conditions but still it's showing incorrect results. Below is the formula I am using.

=IF(AND(D2>=TIMEVALUE("05:30:00 PM"),(D2<=TIMEVALUE("01:30:00 AM"))),"1",
 IF(AND(D2>=TIMEVALUE("01:30:00 AM"),(D2<=TIMEVALUE("09:30:00 AM"))),"2","3"))

enter image description here

Any idea where I am doing wrong?

Nested If-Else in batch command

I am trying to check if two services are present or not. If either one is not present it should print "No" else print "Yes". What I tried is:

@echo off
set service1=present_service
set service2=not_present

sc query %service1% | find "does not exist" >nul
if %ERRORLEVEL% EQU 1 (
    sc query %service2% | find "does not exist" >nul
    if %ERRORLEVEL% EQU 1 (
      echo Yes
    ) else (
      echo No
    )    
) else (
echo No
)

If I check for the single one, it works fine. Here probably %ERRORLEVEL% is not changing its value in the second case. Even if service2 is not present, it prints Yes. Can I get any help on this.

Multiple if conditions in one loop awk

Hi have the following code:

for file in /dir/*;do if grep -q E "$file"; then awk '{print $2,$10}' OFS='\t' "$file" > /newfile fi done

where the files are tab separated and the loop checked the occurring of E in the files(this works). I need to check two columns $3 and $4 of any file, but this not work in the same if like:(grep -q E "$file"&& $3>10&&$4>100). How I can check all this conditions in the same loop?

gwt: if/else NullPointerException

when i run the Code below, and connect shapeEnde with con_sequenz.startEndPoint, everthing works fine. But when i try to connect shapeStart with con_sequenz.startEndPoint, i get a NullPointerException:

Caused by: java.lang.NullPointerException: null
        at com.exa.projekt.client.Projekt$27.onElementConnect(Projekt.java:1237)
        at pl.tecna.gwt.connectors.client.Diagram.onElementConnect(Diagram.java:421)
        at pl.tecna.gwt.connectors.client.elements.EndPoint.glueToConnectionPoint(EndPoint.java:71)
        at pl.tecna.gwt.connectors.client.drop.DiagramWidgetDropController.onDrop(DiagramWidgetDropController.java:57)
        at com.allen_sauer.gwt.dnd.client.PickupDragController.dragEnd(PickupDragController.java:130)
        at com.allen_sauer.gwt.dnd.client.MouseDragHandler.drop(MouseDragHandler.java:529)
        at com.allen_sauer.gwt.dnd.client.MouseDragHandler.onMouseUp(MouseDragHandler.java:277)
        at com.google.gwt.event.dom.client.MouseUpEvent.dispatch(MouseUpEvent.java:56)
        at com.google.gwt.event.dom.client.MouseUpEvent.dispatch(MouseUpEvent.java:1)
        at com.google.gwt.event.shared.GwtEvent.dispatch(GwtEvent.java:1)
        at com.google.web.bindery.event.shared.EventBus.dispatchEvent(EventBus.java:40)
        at com.google.web.bindery.event.shared.SimpleEventBus.doFire(SimpleEventBus.java:193)
        at com.google.web.bindery.event.shared.SimpleEventBus.fireEvent(SimpleEventBus.java:88)
        at com.google.gwt.event.shared.HandlerManager.fireEvent(HandlerManager.java:127)
        at com.google.gwt.user.client.ui.Widget.fireEvent(Widget.java:129)
        at com.google.gwt.event.dom.client.DomEvent.fireNativeEvent(DomEvent.java:116)
        at com.google.gwt.user.client.ui.Widget.onBrowserEvent(Widget.java:177)
        at com.google.gwt.user.client.DOM.dispatchEventImpl(DOM.java:1351)
        at com.google.gwt.user.client.DOM.dispatchEvent(DOM.java:1307)
        at sun.reflect.GeneratedMethodAccessor49.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
        at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
        at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
        at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:338)
        at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:219)
        at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
        at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:571)
        at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:279)
        at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
        at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
        at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:242)
        at sun.reflect.GeneratedMethodAccessor47.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
        at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
        at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
        at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:293)
        at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:547)
        at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
        at java.lang.Thread.run(Thread.java:745)

The Code (line 1237 is marked with a comment):

diagram.addDiagramListener(new DiagramListenerAdapter() {

                  @Override
                  public void onElementConnect(ElementConnectEvent event) {
                      if(con_sequenz.startEndPoint.isGluedToConnectionPoint()){  
                          Widget connectedstart = con_sequenz.startEndPoint.gluedConnectionPoint.parentWidget;
                        if(connectedstart.equals(shapeEnde.connectedWidget))
                        {
                            String fullstartEnde = new String("END"); //    line 1237
                            text.setWidth100();
                            text.setContents(fullstartEnde);
                            pop.addChild(text);
                        }   
                        else if(connectedstart.equals(shapeStart.connectedWidget))
                        {
                            final String fullstartStart = new String("START");      
                            text.setWidth100();
                            text.setContents(fullstartStart);
                            pop.addChild(text);
                        }   
                          }
                    }      
                  });