lundi 31 juillet 2017

Untangling large nested if else code structures in C#

I have inherited a large nested if else structure, I am trying to separate the leaves of the if else tree into separate if statements only e.g. :

if ( c1 )
  { dc1 }
else if ( c2 )
          { dc2 }
     else {dc3}

should become something like :

if (c1) {dc1;}

if ((!c1) & (c2)) {dc2;}

if ((!c1) & (!c2)) {dc3;}

This is much simpler than the unholy structure I am trying to untangle.

Side question : it easy to see that there is no condition that takes into account the case

if ((c1) & (c2)) 

is there a tool or simpler way of linearising the if else structures and seeing all the conditions that have not been included.

I hope my example is correct.

How can make result no duplication?

I have a two file. I tried merge two file. But my script make same line.

a.txt file has below data.

Zone,alias1,alias2
PA1_H1,PA1,H1
PA3_H1,PA1,H1

b.txt file has below data.

WWN,Port,Aliases
da,0,PA1
dq,1, 
d2,3,H1
d4,1,

My result is below.

PA1_H1;PA1;0;da;H1;
PA1_H1;PA1;N/A;H1; <----I want this data
PA3_H1;PA1;0;da;H1;
PA3_H1;PA1;N/A;H1; <----I want this data
PA2_H2;PA2;N/A;H2;
PA2_H1;PA2;N/A;H1;

Below is my script. my script make no need line because for. Who can solved this issue?

f = open('b.txt', 'r')
dict = {}
next(f)
i=0
for line in f:
        i += 1
        line = line.split(',')
        line = (line[2].replace('\n','') +',' + line[1] + ";" + line[0]).strip()
        if line.startswith(",") == 1:
                line = str("Blank") + str(i) + line
        else:
                line = line

        k, v = line.strip().split(',')
        dict[k.strip()] = v.strip()
f.close()


f = open('a.txt','r')
next(f)
with open('result.txt','w') as s:
        for lines in f.xreadlines():
                lines = lines.split(',')
                zone = lines[0]
                ali1 = lines[1]
                ali2 = lines[2].replace('\n','')

##I think below line make same line and no need line


                for eachkey in dict.keys():
                        if eachkey in ali1:
                                result = zone + ";" + ali1 + ";" + dict[eachkey] + ";" + ali2 + ";"

                        elif eachkey not in ali1:
                                result = zone + ";" + ali1 + ";" + "N/A"  + ";" + ali2 + ";"

                        s.write(result + '\n')

s.close()

Overwriting previous iterations of if statement in R

I am VERY new to R and am having a very difficult time getting an answer to this, so I finally caved to post - so apologies ahead of time.

I am using a genetic algorithm to optimize the shape of an object, and want to gather the intermediate steps for prototyping. The package I am using genalg, allows a monitor function to track the data which I can print just fine. But I'd like to stash it in a data frame for other uses and keep watching it overwrite the other iterations. Here's my code for the monitor function:

    monitor <- function(obj){

    #Make empty data frame in which to store data
    resultlist <- data.frame(matrix(nrow = 200, ncol = 10, byrow = TRUE))

    #If statement evaluating each iteration of algorithm
    if (obj$iter > 0){

    #Put results into list corresponding to number of iteration
    resultlist[,obj$iter] <- obj$population[which.min(obj$best),]}

    #Make data frame available at global level for prototyping, output, etc.
    resultlistOutput <<- resultlist}

I know this works in a for loop with no issues based on searches, so I must be doing something wrong or the if syntax is not capable of this?

Sincere thanks in advance for your time.

Checking for null only gets "Cannot read property '1' of null" in nodejs

I am trying to test for a null value after a # in a string. I have tried it various ways but I always get a Cannot read property '1' of null when submitting test data. I have ferreted out the errors I can think of but this one I cannot seem to get around. Please keep in mind I am a beginner at this, I haven't programmed since cobol days and the last time i worked on javascript was in the early 2000s.

//First lets test to see if # is in the message. If true then we will parse it and add it to the database.
var str = elt.message;
var substr = '#';
var vtest = str.indexOf(substr) > -1;
if (vtest == 1){
var Vname = elt.author;
console.log('We tested for # and the value is true');

//extracts the number and the letter after the # from incoming chat messages
var test = elt.message; // replace with message text variable. 
var pstr = test.match(/#(\d{1,3})([a-zA-Z])/);
if (pstr) {
var numbers = pstr[1];
var character = pstr[2];
var chupp = character.toUpperCase(); //Converts the lowercase to uppercase
}

//Tests to see if neither the question number or the possible answer is left out
//if (pstr[1] !== '' && pstr[2] !== ''){ //doesnt work =(
if (pstr[1] !== null && pstr[2] !== null){ //doesnt work either =(

console.log('we processed the numbers after the #sign and assigned the numbers and letter into variables.')
console.log('The question number is: ' + pstr[1]);
console.log('The letter processed is: ' + pstr[2]);

bash variable's if then statement not evaulating correctly

I have written a script that should tell me the number of lines from the nightly network backups. It should be 109 and if it is the same I get success email and if it is not the same I get a failure email. I have added 2 fake host to one of the files that is checked in the script below to see if it will fail. The if then statement simply does not work. If I make the amount of hosts in the file's 'confirm-backed-up' and 'backed-up' different it makes no difference and it just uses the very first if then statement regardless if they are different or not.

At the end you can see I ran the wc -l on the two files and they are different however the script runs and gives me the first then of the if, then: backed-up and confirm-backed-up match. It goes the other way also - if they are the same I just get the first if then statement - which at first made me think it was working until I checked it with the files not matching in number.

#!/bin/bash

# Variables
date=`date +%Y%m%d`
o1=$(cat /netops/backups/scripts/hostfiles/backed-up | wc -l)
o2=$(cat /netops/backups/scripts/hostfiles/confirm-backed-up | wc -l)
sdir=/netops/backups/storage/
hostdir=/netops/backups/scripts/hostfiles

# Functions

function confirm_backup
{
find $sdir -type f -mtime 0 -printf '%f\n' |grep $date >$hostdir/backed-up
cat $hostdir/cisco-nexus.txt >> $hostdir/confirm-backed-up
cat $hostdir/cisco-firewall.txt >> $hostdir/confirm-backed-up
cat $hostdir/esx.txt >> $hostdir/confirm-backed-up
cat $hostdir/f5.txt >> $hostdir/confirm-backed-up
cat $hostdir/fortigate.txt >> $hostdir/confirm-backed-up
cat $hostdir/rsa.txt >> $hostdir/confirm-backed-up
cat $hostdir/sw-no-pk.txt >> $hostdir/confirm-backed-up
cat $hostdir/switch-router.txt >> $hostdir/confirm-backed-up
cat $hostdir/tlite.txt >> $hostdir/confirm-backed-up
}

# Verify Backup

function backup_verify
{
if [ "echo $o1" == "echo $o2" ]; then # I tried this with if [ "$o1" == "$o2"] also & if (( $o1 != $o2 )) & [ "$o1" = "o2" ] - all same results.
echo "backed-up and confirm-backed-up match" & mail -s "All Backups   succeeded" 12345566@blah.net   < /dev/null
else
echo "a backup has failed" & mail -s "A backup failed" 123456789@vtext.com  < /dev/null
fi
}

# Start Script Run

confirm_backup
backup_verify
cat /dev/null > $hostdir/confirm-backed-up # this is here for long term - i tested it with this gone so otherwise obviously my wc -l would have been 0
cat /dev/null > $hostdir/backed-up

user@host:/netops/backups/scripts$ ./test6.sh 
backed-up and confirm-backed-up match
Null message body; hope that's ok # WRONG!
user@host:/netops/backups/scripts$ cd hostfiles/
user@host:/netops/backups/scripts/hostfiles$ wc -l backed-up 
109 backed-up # so I check manually
user@host:/netops/backups/scripts/hostfiles$ wc -l confirm-backed-up 
111 confirm-backed-up # the files are different.

Missing update statement in if statement makes infinite loop [duplicate]

This question already has an answer here:

Why does this code produce an infinite loop?

for(int i=0; i<10; ) {
  i = i++;
  System.out.println("Hello World!");
}

Using multiple Ifs in python that are not mutually exclusive

a=0
while a<30:
    a+=1
    print(a)
    if a%3==0:
        print("This is a multiple of 3.")
    if a%5==0:
        print("This is a multiple of 5.")
    else:
        print("This is not a multiple of 3 or 5.")

I'd like for this else statement to only print if NEITHER of the previous if statements are true. I don't want to use if, elif, else because the variable could be both a multiple of 3 and 5.

Making an if statement more generic

I have the following code that looks up if a logged in customer is in the 'Students' customer segment then sets a flag to true.

I would like the code to look at further customer segments in one go, such as G1, G2, G3 or G4.

Maybe a statement that looks up the segment and then sets the flag to true? Make sense?

<c:set var="ownerId" value="${CommandContext.store.owner}"/>
<% 
String isStudent = "false";
Long userIdStr = (Long)pageContext.getAttribute("userId");
Long ownerIdStr = (Long)pageContext.getAttribute("ownerId");
MemberGroupAccessBean ambrgrp = new MemberGroupAccessBean();

try {
    ambrgrp = new MemberGroupAccessBean().findByOwnerName(ownerIdStr,"Students");
    MemberGroupMemberAccessBean mgmbr = new MemberGroupMemberAccessBean();
    mgmbr = new MemberGroupMemberAccessBean().findByGroupMember(ambrgrp.getMbrGrpIdInEJBType(),userIdStr);
    isStudent = "true";
} catch(Exception ex) {
}

pageContext.setAttribute("isStudent",isStudent);
%>

Multiple ifelse statements in R - Conditionally create new variable

I'm having a little issue. Relatively new to R.

What I am trying to do is to create a new variable (data$V4) based on the value of an existing variable (data$V3).

The condition is that if the value in variable 3 is within a certain range (e.g., >=0 & <=100), then the value in data$V4 = 1. There need to be 20 statements exactly of this sort.

I have created a code which works only for two expressions, it does not go beyond this for some reason. I don't seem to be closing the statement.

data$V4 <- ifelse((data$V3>=0) & (data$V3<=100), 1, ifelse((data$V3>=101) & (data$V3<=400), 2,0)

This code works fine. But adding more expressions with the code below fails.

data$V4 <- ifelse((data$V3>=0) & (data$V3<=100), 1,
              ifelse((data$V3>=101) & (data$V3<=400), 2,
                     ifelse((data$V3>=401) & (data$V3<=800), 3,
                            ifelse((data$V3>=801) & (data$V3<=1200), 4,0))

How can I insert Oracle SQL IF ELSE in to UPDATE statement ?

I am trying to join 3 tables and I have the following sql without IF ELSE.

update transaction t
set t.lid= (
select l.id rom list l
inner join distance d
on l.uid=d.uid
inner join transaction t2
on t2.id=d.id
)

The only problem is the statement

select l.id rom list l
    inner join distance d
    on l.uid=d.uid
    inner join transaction t2
    on t2.id=d.id

returns more than one value and I wasn't able to assign it to t.gid. With our business rule, if it returns more than one value I have to set t.gid to be null. How can I incorporate if else statement in this sql ? I have seen other posts on the net but they are mostly procedures or functions.

Using 'ifelse' statements in R with quantitative criteria

New to SO. Don't kill me. I'm trying to figure out how to use 'ifelse' statements to add columns to a dataframe, based on a quantitative criteria related to a different column.

DTzips2[, politics := ifelse(pctr08zip > 0 & pctr08zip <= 0.33, "Liberal"),
                       ifelse(pctr08zip > 0.33 & pctr08zip <= 0.67, "Moderate"),
                              ifelse(pctr08zip > 0.67 & pctr08zip <=1, "Conservative")]



Error I've been getting is 'Provide either 'by' or 'keyby' but not both'. They also don't like the comma after 0.33. Help?

Javascript if statement not returning a value

I am trying to add a javascript code to display text on my website if the product price is over $35. I cannot get this if statement to return anything, can someone tell me why? This is at the bottom of an HTML file.

<script type="text/javascript">
$(function(){
    if (TRUE) {
        TRUESTATEMENT;
    }
    else{
        NOTTRUE;
    }
}
</script>

If-statement / how to include different levels of a variable in calculating sd in R?

I have a dataset of the form

     nutscode nutslevel country GDP year
     at12     nuts2     at      200 1990     
     be1      nuts1     be      300 1990
     be2      nuts1     be      350 1990
     de3      nuts1     de      200 1990
     es23     nuts2     es      180 1990

where each country gets assigned a NUTS level, with most being NUTS 2, with some exceptions. The nutscode variable varies according to the nutslevel variable.

Now, I am trying to calculate standard deviation of GDP for 1990, and want to include all NUTS2 countries AND the exceptions (Germany and Belgium, for instance). My standard deviation formula for everything NUTS2 is pretty straightforward:

    sd(alldata$gdpcapita[alldata$year=="1990" & alldata$nutslevel=="nuts2"])

But since I want to add those country exceptions too, I'd need sth like

    sd(alldata$gdpcapita[alldata$year=="1990" & alldata$nutslevel=="nuts1" for specific countries and NUTS2 otherwise])

I'm thinking of creating a variable that would take NUTS1 values if the country variable has the values of "be"|"de"|"el"|"nl"|"uk", or if the nutscode identifier has "be"|"de"|"el"|"nl"|"uk" in the name, and then use that for standard deviation. Something like

   alldata$var <- factor (with (alldata, ifelse ((country == "be"|"de"|"el"|"nl"|"uk"), nutslevel=="nuts1", nutslevel=="nuts2")))

But then this happens

   Error in country == "be" | "de" : operations are possible only for numeric, logical or complex types

or

   alldata$var <- factor (with (alldata, ifelse (((grepl("be"|"de"|"el"|"nl"|"uk", alldata$nutscode)), nutslevel=="nuts1", nutslevel=="nuts2")))

And error again

   Error: unexpected ',' in "alldata$var <- factor (with (alldata, ifelse (((grepl("be"|"de"|"el"|"nl"|"uk", alldata$nutscode)),"

What am I doing wrong? I am stuck, not sure how to proceed now and would be grateful for any guidance. I'm totally new to R, so I have no idea if there is a more sophisticated way of writing all this, or what those error messages mean. Thank you!

NESTED IF AND STATEMENTS

I think I've made a mistake as it keeps returning #VALUE.

IF(AND(G2="green",G3="green"),"GG"),IF(AND(G2="red",G3="red"),"RR") ,IF(AND(G2="red",G3="green"),"RG") ,IF(AND(G2="green",G3="red"),"GR")

I'm trying to say if it is red and it is green, print RG and others such as RR,GR,GG.

Using if, else within recode

I am trying to replicate some code but not having much luck. data$var1 has values from 1-7 which I am trying to reduce to just 2 value in a new variable, data$var2. The code looks like this: data$var2<-recode(data$var1, "1:3=1; else=0")

However, when I execute code, I get the following error: "Error: Argument 2 must be named, not unnamed"

I'm working in the latest version of R and using the Tidyverse package.

What am I missing? What about Argument 2 isn't named?

Reference any element in array

I made a script that makes 3 array elements, each of which equal:

Number(prompt())

Then I make an if statement saying:

if (!arr[0] || !arr[1] || !arr[2]) {alert("invalid data")}

This is ok for a couple of elements, however if I want to add say 10 elements then adding a bunch of logical OR operators is sort of clunky.

So I'm wondering if there is a way to just tell the interpreter "if any element in the array is not a number then alert an error else do alert(a)". (If that makes sense?.)

I am aware of the 'in' operator/keyword but this seems to check an array element name against the array name to see if it exists in that array. This is not quite what I'm after however.

I've also seen that there is a some() property/function but am not that far into learning JS yet.

Full script fiddle: http://ift.tt/2uc4Vkz

Thanks.

if flood == "y": SyntaxError: invalid syntax

i have this code,I took it from a person to help him to resolve some issues:

import os
import sys

hostname=raw_input("URL:")
request=raw_input("ping request:")
flood=raw_input("loop mode (y/n):")

def Ping():
    commandSys=os.system("ping -c"+request(hostname)

if flood == "y":
    try:
        while True:
            Ping()
    except KeyboardInterrupt:
        pass
        print "Done"
else:
    Ping()

when i launch this script from the console he tells me there's a sintax error in the if statement PS:i edit the line 9 because ("ping -c"+(request,hostname)) tell me that i "cannot concatenate 'str' and 'tuple' objects"

i hope someone resolve

Nested/Multiple IF functions in excel, how can I?

I am trying to implement an excel spreadsheet to keep track of my working hours.

I am entitled to unpaid breaks at my work, however these vary depending on the length of shift as follows.

0 - 3.75 hours = 0 min break

4 - 5.75 hours = 15 min break

6 - 7.75 hours = 30 min break

8 - 8.75 hours = 45 min break

9 - 11.75 hours = 90 min break

I would like to calculate my working hours minus breaks in excel.

I think I need to use if statement similar to the following (taking E2 as my hours):

=if(E2<=3.75, E2, if(4<=E2<=5.75, E2-30, if(6<=E2...etc...

But it never seems to work, can someone help me get this working???

Thanks.

How to print a specific word in a text file in Java

so as you can see i have a text file that goes like this one:

unbelievable, un, believe, able
mistreatment, mis, treat, ment
understandable, understand, able

I need to get the morphemes or each word like for example if I typed in the word MISTREATMENT, the output would be MIS, TREAT, MENT and the root word is TREAT.

Here's my code so far:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class morph {

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

         System.out.println("Enter a word: ");
         Scanner sc = new Scanner (System.in);
         sc.nextLine();

         BufferedReader br = new BufferedReader(new FileReader("C:/Users/xxxx/Desktop/morphemes.txt"));
         String line = null;
         while ((line = br.readLine()) != null) {

             //i'm stuck

             System.out.println("The morpheme words are: "); // EG: mis , treat, ment
             System.out.println("The Root word is: "); // EG: treat
         }
    }
}

Please help me a newbie

Argparse: multiple choices with 'if' and 'else'

My question is about argparse and how to use multiple choices.

So I declare two choices --country and --city

import argparse

parser = argparse.ArgumentParser()                                                  
parser.add_argument('--country', dest='country', type=str, metavar='') 
parser.add_argument('--city', dest='city', type=str, metavar='')

I then declare it into the script few lines below:

if args.country:
        # Do this 
elif args.city: 
        # Do this

But it is not working and the script is executing the first and the second option. It seems so easy to me. Where am I wrong?

Write value from 12 column on another worksheet if two conditions in columns 4 and 8 are true

Sub CreateTable() 
Dim bf As Boolean
Dim aTable(), aRes()
Dim i As Long, k As Long, n As Long
  With Worksheets("DOHADNÉ POLOŽKY")   ' List s tabulkou, kde se hleda
    i = .Cells(.Rows.Count, "A").End(xlUp).row
    aTable = .Range("A1:P" & i).Value ' tabulka do pole

    ReDim aRes(1 To i + 1, 1 To 1) ' velikost pole
        End With



For i = 1 To UBound(aTable)  ' od 1 do poctu radky tabulky
    If aTable(i, 1) <> Empty Then ' kdyz neni prazdna
        If aTable(i, 4) = "Depo" And aTable(i, 8) = "CZK" Then


                    aTable(i, 12) = aRes(i, 1): i = i + 1
                                           End If
                                End If
Next i
' upload vysledku na list do sloupce J
Worksheets("List1").Range("A1").Resize(UBound(aRes), 1).Value = aRes
Range("A1").Select
ActiveCell.FormulaR1C1 = "KUK"

End Sub

Something is wrong. It has no errors, but it doesn't write value in array I think. So the result on Worksheet("List1") is just empty.

Create new column within a loop based on ifelse statement in R.

I am not getting the expected results when I attempt to create a new column based upon an ifelse statement placed within a loop. The data in the new column is only based on some of the columns that are in the loop and not all of them. Why is this and how can I make the data in the new column be based on all the information in the loop? Here is a reproducible example of my attempt, in reality my dataframe contains over 500 columns:

 x1 <- sample( LETTERS[1:4], 100, replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05) )
 x2 <- sample( LETTERS[1:4], 100, replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05) )
 x3 <- sample( LETTERS[1:4], 100, replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05) )
 x4 <- sample( LETTERS[1:4], 100, replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05) )
 x5 <- sample( LETTERS[1:4], 100, replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05) )
 x6 <- sample( LETTERS[1:4], 100, replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05) )
 x7 <- sample( LETTERS[1:4], 100, replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05) )
 x8 <- sample( LETTERS[1:4], 100, replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05) )
 df <- data.frame(x1,x2,x3,x4, x5,x6,x7,x8,stringsAsFactors=FALSE)

 for (i in 2:7){
   df$newvar <- ifelse(df[,i] == "B" ,1,0)
 }

using conditional IF statements in arm templates for properties,

I have a situation where I want to only add a property to a VM if a condition is met. For example if I want to add an availability set property to a machine then do this : Below I ONLY what to execute the availability set statement if a condition is TRUE, can you do this in an ARM template? eg if a value is true then do this line, if not skip?

 {
  "name": "[parameters('ComputerName')]",
  "type": "Microsoft.Compute/virtualMachines",
  "location": "[parameters('location')]",
  "apiVersion": "2017-03-30",
  "dependsOn": [
    "[resourceId('Microsoft.Network/networkInterfaces', variables('1stNicName'))]",
    "[resourceId('Microsoft.Network/networkInterfaces', variables('2ndicName'))]"
  ],
  "tags": {
    "displayName": "[parameters('ComputerName')]"
  },

  "properties": 

{
"availabilitySet": {
      "id": "[resourceId('Microsoft.Compute/availabilitySets',variables('availabilitySetName'))]"
    },


 "hardwareProfile": {
      "vmSize": "[parameters('serverVmSize')]"


 },
    "osProfile": {
      "computerName": "[parameters('serverName')]",
      "adminUsername": "[parameters('adminUsername')]",
      "adminPassword": "[parameters('adminPassword')]"
    },

dimanche 30 juillet 2017

if function not working VBA

If (Year(n) - Year(d) >= 1) Then
    MsgBox "Latest Fiscal Year Data is" & dd & "Days," & md & "Months," & yd & "Years Old"
    Sheets("" & Filename).Cells(5, y2).Font.Italic = True
    Sheets("" & Filename).Cells(5, y2).Font.Color = RGB(0, 0, 255)
    Sheets("" & Filename).Cells(5, y2).Font.Bold = True
    Sheets("" & Filename).Cells(5, y2).Font.FontStyle = Arial

End If

Text Color turns to blue but other commands like italic bold are not executed

There was an error in my 'else' branche [on hold]

Recently, I've write a program to request an AJAX function, and in my controller(the function in it), there was an simple error in the 'else' branch. However, the program must go wrong when it goes into the else branch. When I was self-testing the program did well, but when it was put online, the sentry system is warning. So, is there any friends could please help me? Sorry for my pool English. I can figure out the obvious error near the convertEncoding where the place of ')' was wrong. What I don't know was why the program goes into the else branch. Code: enter image description here enter image description here

Bash - alternative for: ls | grep

I use the following code as variable in a script:

match=$( ls | grep -i "$search")

this is then used in an if statement:

if [ "$match" ]; then
    echo "matches found"
else
    echo "no matches found"
fi

what would be an alternative if I did not want to use find? ShellCheck recommends:

ls /directory/target_file_pattern

but I do not get the syntax right to get the same result. also I want no output when there are no matches for the if statement to work.

if conditionals in pandoc templates depending on value of a variable

In pandoc, you can see if you have a variable or not ($if(something)$ put $something$ $endif$), but I want to act depending on its value. Something like:

$if(lang)=='en'$ Hello $else$ Aloha $endif$

Is it possible? In Pandoc Manual I don't see nothing

Getting Syntax error: "fi" unexpected (expecting "then") in shell scripts

I am working on setting up some shell scripts for backups. Everything is ok but I am getting syntax errors when I use if then statements.

Looking at http://ift.tt/2vjCbeK they use a simple if statements which works on the website as it has a try it pop section. When I copy the contents into a file save as .sh and try it on my ubuntu server (16.04.2 x64), I get Syntax error: "fi" unexpected (expecting "then")

The code from the website is below

#!/bin/sh
a=10
b=20

if [ $a == $b ]
then
   echo "a is equal to b"
else
   echo "a is not equal to b"
fi

To run on terminal I use

sh /path/to/file/script.sh

There are a few questions asked and answered but none of them seem to be the same as my case. Is there something I need to update on the server? If I use bash instead of sh it says unexpected token. Anyone had this issue?

If it may help, when I run in terminal, it does not seem to like empty spaces, full error is below

sh /var/www/check-day.sh
: not foundeck-day.sh: 4: /var/www/check-day.sh:
/var/www/check-day.sh: 10: /var/www/check-day.sh: Syntax error: "fi" 
unexpected (expecting "then")

How can i compare a simple character scanned from a user with the first letter of a string thats in an array in C

Hello guys I m trying to compare in an if statement user scanned letter with the first letter of a string array can you please help?

how can i get the first letter of a string that is in an array and how do i compare it with a users input?

If conditional in mysql trigger?

Straight forward, i have problem using conditional state in trigger mysql. There are 2 status, if the status is 'guest' then do something.. and else do another thing.

Here's what i already made :

CREATE TRIGGER `update-gain` AFTER INSERT ON `payment`
FOR EACH ROW BEGIN
declare v_profit integer;
declare v_deposit integer;
declare v_status CHAR;

select (status) into v_status from item where item.id_item=new.id_item;
select sum(profit_owner) into v_profit from payment where payment.id_item=new.id_item;
select sum(profit_guest ) into v_deposit from payment where payment.id_item=new.id_item;

if v_status like 'guest' then
INSERT INTO gain
(gain.profit, gain.modal,gain.date)
VALUES
(v_profit,v_deposit,new.date)
ON DUPLICATE KEY UPDATE
gain.profit = gain.profit+new.profit_owner,
gain.modal = gain.deposit+new.profit_guest;

else
INSERT INTO gain
(gain.profit,gain.tanggal)
VALUES
(v_profit,new.tgl_stok)
ON DUPLICATE KEY UPDATE
gain.profit = gain.profit_owner+new.profit_owner;

end if;
END

So far i'm using 'like' clause, but the condition always true, even v_status is not 'guest'.

What did i do wrong here? Thanks :)

PERL And Statement Not Evaluating Properly

I am using Perl to send out an email. Pending some criteria I want to use a particular template for that email. To decide what template to use, I am setting some boolean statements. When $isA is 1 and isBis 1, my script is using templateB instead of templateA.

    if ($isA== 1 && $isB == 1)
    {
            @TEMP = @templateA;
            print "\n templateA\n\n\n";
    }
    elsif ($A == 1 && $B == 0)
    {
        print "\nEXTRA CHECK FT:" . $A. " ENC:" . $B. " ReApp:" . $C;
            @TEMP = @templateB;
            print "\n templateB\n\n\n";
    }
    elsif ($A== 0 && $B== 1)
    {
            @TEMP = @templateC;
            print "\n templateC\n\n\n";
    }
    elsif ($C== 1)
    {
            @TEMP = @templateD;
            print "\n templateD\n\n\n";
    }
    else
    {
            @TEMP = @templateE;
            print "\n templateE\n\n\n";
    }    

Any ideas on why this is not working?

php regix patern check

i need a function for check regex

$str = "/mypage/6";
$str2 = "/mypage/{id}";
function check($str,$str2){
  if(regex($str,$str2)){ // check and return number here
    return $number;
  }else{
    return false;
  }
}

I need a function that will do this to me. could it be ?

File's string dont match

here's the problem: i have a file ,,file.txt''.It is compossed by 11 words. Good. Now i have the code :

with open('/root/file.txt', 'r') as f:
 data = f.readlines()
 print data[10]

It outputs :

Password

But when i enter :

if data[10] == 'Password':
 print 'yes'
else:
 print 'no'

It outputs:

no

Can i know why ?I alredy tried to do ,,str(data[10])" but i get the same output : no. How i can do to get the yes answere ?

Datatable if statement in row array

so i have used a datatable in codeigniter that show all row[] arrays that i have queried now my problem is that, how can i put a condition statement inside a row[] array i have tried every possible way that it could fit but an error would state that i could not define an if statement inside the row[] here is my code:

foreach ($list as $foo_app) {
       $ApplicationNo++;
       $row = array();

       $row[] = $foo_app->ApplicationNo;
       $row[] = $foo_app->UserId;
       $row[] = $foo_app->FirstName.''.$foo_app->LastName;
       $row[] = $foo_app->PlateNo;
       $row[] = $foo_app->DateApplied;
       $row[] = if (.$foo_app->Status_Application. === "In-Active") {
        <b class="w3-padding w3-gray w3-hover-white w3-round-xxlarge">
        }
        elseif (.$foo_app->Status_Application. === "Accepted") {
        <b class="w3-padding w3-green w3-hover-white w3-round-xxlarge">
       }
       elseif (.$foo_app->Status_Application. === "Denied") {
        <b class="w3-padding w3-red w3-hover-white w3-round-xxlarge">
       };
       $row[] = '<div style="text-align: center;">&#8369;'.$foo_app->AmountFinanced.'</div>';

Break if elif loop when condition holds [duplicate]

This question already has an answer here:

Set-up

I scrape a ad names containing information I want to retrieve.

Example: name_ad = 'quarto duplo brilhante em santa apolonia'

Given the information in name_ad I define a variable type per ad.

Following is my code,

while True:            
    if 'cama de casal' or 'duplo' in name_ad:
        type = 'double'
        break            
    elif 'cama de solteiro' or 'único' or 'individual' in name_ad:
        type = 'single'      
        break
    else:
        type = ''
        break

which is based upon this answer.


Problem

I'm not breaking the loop correctly: for all ads I have that type = 'double', which is not true.

How do I correctly break my if/elif/else loop?

Can someone tell me what is wrong with this code?

I am trying to get this to work but to no avail, can someone help?

number = 0

statement = "i will go there",number,"times"

for number in statement:
    if number < 5:
    print (statement)
number += 1

What i am trying to do here is to build a general statement first (I will go there number times). I want to change the 'number' inside this statement to 0,1,2,3,4,5 and eventually it prints: i will go there 0 times i will go there 1 times i will go there 2 times i will go there 3 times i will go there 4 times i will go there 5 times But i am getting an error code of:

TypeError: '<' not supported between instances of 'str' and 'int'

samedi 29 juillet 2017

"Misplaced Else" Error on C++

Noob here. I cannot seem to fix the "misplaced else" error on the code below. This code should collect and compute for term grade and give remarks depending on the score. Any help is appreciated.

#include<conio.h>
#include<stdio.h>
main()
{
char name[20];
int exam,q1,q2,q3,ass,sw,att,avgq,CS,TG;
clrscr();
printf("Name: ");
gets(name);
printf("\nExam: ");
scanf("%d",&exam);
printf("\nQuiz #1: ");
scanf("%d",&q1);
printf("\nQuiz #2: );
scanf("%d",&q2);
printf("\nQuiz #3: ");
scanf("%d",&q3);
printf("\nAssignment: ");
scanf("%d",&ass);
printf("\nSeatwotk: ");
scanf("%d",&sw);
printf("\nAttendance: ");
scanf("%d",&att);
CS=(0.4*ass)+(0.4*sw)+(0.2*att);  //class standing//
avgq=(q1+q2+q3)/3;  //average quiz//
TG=(0.4*exam)+(0.3*avgq)+(0.3*CS);  //term grade//
if(TG>=90)
   printf("Term Grade: %d",TG);
   printf("Remarks: EXCELLENT");
else if (TG>=80 && TG<=89)
   printf("Term Grade: %d",TG);
   printf("Remarks: SATISFACTORY");
else if (TG>=76 && TG<=79)
   printf("Term Grade: %d",TG);
   printf("Remarks: GOOD");
else if (TG==75)
   printf("Term Grade: %d",TG);
   printf("Remarks: PASSING");
else if (TG<74)
   printf("Term Grade: %d",TG);
   printf("Remarks: FAILED");
else
   printf("Invalid Input.  Try again");
getch();
return 0;
}

2 programs playing against eachother

I'm currently writing 2 programs in python that must play a number game against each other. One program picks a number between 1 and 100. Then the other attempts to guess what that number is. Each time the guesser gives it's guess, the chooser then replies with 'too big', 'too small', or 'you got it'. According to what the reply is the guesser adjusts its next guess accordingly.

Here's my code for the program that chooses:

    import random
from guesser import g

guessCount = 0

number = random.randint(1, 100)
print("I'm thinking of a number between 1 and 100.")

outfile = open ('response.txt', 'w')
guess = 50
print (guess)
if guess < number:
    print('Your guess is too low.') 
    switch = '1'
    outfile.write (switch + '\n')

elif guess > number:
    print('Your guess is too high.')
    switch = '2'
    outfile.write (switch + '\n')
else:
    print('Correct, You guessed the number in', guessCount, 'guesses.')
    switch = '3'
    outfile.write (switch + '\n')



while guessCount < 8:
    guess = g
    print (guess)
    guessCount += 1

    if guess < number:
        print('Your guess is too low.') 
        switch = '1'
        outfile.write (switch + '\n')

    elif guess > number:
        print('Your guess is too high.')
        switch = '2'
        outfile.write (switch + '\n')
    else:
        print('Correct, You guessed the number in', guessCount, 'guesses.')
        switch = '3'
        outfile.write (switch + '\n')
        break

outfile.close()
print('The number was',number)

And here's the code for the program that gives the guesses:

low = 1
high = 100
guess = 0


guessCounter = 0

infile = open ('response.txt', 'r')  
switch = int (infile.readline())

def g (switch):

    while switch != 3 and guessCounter < 8:
        guess = (low+high)//2
        guessCounter += 1

        if switch == 1:
            high = guess

        elif switch == 2:
            low = guess + 1

        return guess    

My main question is how to get the 2 programs to interact with eachother. I'm currently trying to use a method of having them communicate through a text file called response, but surely there's an easier way?

The main problem I'm having it seems is that when chooser tries to get the variable g from guesser it can't because there's no response currently in response.txt meaning switch = int ('')

Traceback (most recent call last): File "C:\Users\Jash\Downloads\guesser.py", line 8, in switch = int (infile.readline()) ValueError: invalid literal for int() with base 10: ''

And yes, they must be 2 separate programs. And it must be done in python.

Python multiple if-else in the same line

I know this is possible:

a, b = 5, 10
print 'a' if a > b else 'b'  # outputs b

However, what if I had another variable 'c'? How do I make them print in the same line using the same type of logic as those two variables? Something like?

a, b, c = 5, 10, 20
print 'a' if a > b elif 'b' if b > c  else 'c'  # is it possible?

How to remove html widgets on the sidebar and make full-width blog posts after clicking the 'Read More' button on Blogger?

My blog looks like this: Sidebar on the Left, Blog Post on the Right.

My Sidebar on the Left is made up of a series of HTML widgets, like an About Me Widget, Twitter Widget, etc.

My Blog Posts on the right all end with the first sentence—then there's a 'Read More' button!

This is what I want to do: I want to be able to click the 'Read More' button and be taken to a page where my blog post is full screen. This thus means removing all the html widgets in the sidebar.

I understand that to remove the HTML widgets on the Left Sidebar so they only appear at the Home page requires some <b:if cond> coding. I already know how to remove the HTML widgets on the Left Sidebar with it, so that they only appear on the Home page. However, my blog posts are not full-width after clicking 'Read More'—instead of reverting to full screen size, they remain the same size, with a gaping vertical blankness where the Left Sidebar used to be.

Does anyone know what codes can be used to remedy this?

Please help! Thank you!

Code with triggered if statement is ignored

This is the code where an Image UI's sprite image is switched depending on key(s) pressed down:

using UnityEngine;
using UnityEngine.UI;

public class ImageController : MonoBehaviour {
    public Sprite left;
    public Sprite topleft;
    public Sprite backleft;
    public Sprite right;
    public Sprite topright;
    public Sprite backright;
    public Sprite top;
    public Sprite back;
    public Sprite nothing;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.UpArrow))
        {
            if (Input.GetKey(KeyCode.LeftArrow))
            {
                Debug.Log("HI");                          // Not ignored??
                GetComponent<Image>().sprite = topleft;   // Ignored
            }
            if (Input.GetKey(KeyCode.RightArrow))
            {
                GetComponent<Image>().sprite = topright;
            }
            else
            {
                GetComponent<Image>().sprite = top;
            }
        }
        if (Input.GetKey(KeyCode.DownArrow))
        {
            if (Input.GetKey(KeyCode.LeftArrow))
            {
                GetComponent<Image>().sprite = backleft;
            }
            if (Input.GetKey(KeyCode.RightArrow))
            {
                GetComponent<Image>().sprite = backright;
            }
            else
            {
                GetComponent<Image>().sprite = back;
            }
        }
    }
}

The code within the first nested if statement (in this case, if (Input.GetKey(KeyCode.LeftArrow)) {}) will not work (the image will not change). I have added Debug.Log("HI") in both if statements to see if it works and it does. Changing the conditions also does not work. All other nested if statements work properly though.

So why is the line GetComponent<Image>().sprite = topleft; being completely ignored though the if statements' conditions are all met?

@if is not working in my blade view laravel

code inside the if statement is not changing anything like i want to check if user is logged in then show his name on header but its not doing so..plus if statemet is not changing colour when i view it in sublime text.

@if (Auth::check())
    <ul class="nav pull-right">
        <li class="dropdown">
            <a data-toggle="dropdown" class="dropdown-toggle" href="#">
                <i class="fa fa-user"></i> 
                
                <b class="caret"></b>
            </a>
  <ul class="dropdown-menu">
                <li><a href="">Logout</a></li>
            </ul>                       
        </li>
    </ul>
    @endif

if statement on arrays in R

in a simple way of stating my problem, consider I have the following function:

ff<-function(a){ if (a>0){ return ("positive") } else{ return("negative") } } now: ff(-1) [1] "negative" ff(1) [1] "positive" while when i give it an array: print(ff(c(-1,1))) [1] "negative" "negative" Warning message: In if (a > 0) { : the condition has length > 1 and only the first element will be used

I was expecting print(ff(c(-1,1)))=("negative" "positive")

How should I solve this?

vendredi 28 juillet 2017

Why is if not working in my Magic Square program

This is a program in C to check if a matrix is a Magic Square or not. Sums of all rows and columns, as well as both the diagonals, are equal to 65. This shows up in printf statements. Yet the if-else returns 0 instead of 1. Why?

#include<stdio.h>

int c[5], r[5];
int d1, d2;
int ms[5][5] = {
{25, 13, 1, 19, 7},
{16, 9, 22, 15, 3},
{12, 5, 18, 6, 24},
{8, 21, 14, 2, 20},
{4, 17, 10, 23, 11}};

//to calculate sums of every row, column and both diagonals
void sumUp() {
for (int x = 0; x < 5; x++)
    for (int y = 0; y < 5; y++) {
        r[x] += ms[x][y];
        c[x] += ms[y][x];
        if (x == y) {
            d1 += ms[x][y];
            d2 += ms[y][x];
        }
    }
}


//prints sums calculated
//returns 1 if all sums equal
int isMagic() {

printf("\n%d", r[0]);
printf("\n%d", r[1]);
printf("\n%d", r[2]);
printf("\n%d", r[3]);
printf("\n%d", r[4]);
printf("\n%d", c[0]);
printf("\n%d", c[1]);
printf("\n%d", c[2]);
printf("\n%d", c[3]);
printf("\n%d", c[4]);
printf("\n%d", d1);
printf("\n%d", d2);

//every sum prints equal to 65
if (c[0] == c[1] == c[2] == c[3] == c[4] == r[0] == r[1] == r[2] == 
r[3] == r[4] == d1 == d2) //yet this does not work
    return 1; 
else 
    return 0;
}

void show() {
if (isMagic())
    printf("\nYes, Magic");
else
    printf("\nNot Magic");

}

int main() {

sumUp();

show();
return 0;
}

Exactly why is if-else returning 0? Why is control going to else part when clearly all sums are equal?

"IF" formula in excel using multiple conditions

I need help with an "IF" formula in excel using multiple conditions. This is what i am needing: "IF (cell) is <201, then *$2, if (cell) is 201-400, then *$1.15, if (cell) is >400, then *$1).
I apologize for the "noobness" of question, but i am trying to create a "settlement" spreadsheet.

TIA

Why does this "if string" conditional always give me true?

I have the next problem (oversimplified) on this python code:

a = raw_input("Write l or r:\n")
if a == 'l':
    print "you press l"
elif a == 'r':
    print "you press r"

So it give me always "you press l". I also tried str(input) but same and:

a = raw_input("Write l or r:\n")
if a == 'l':
    print "you press l"
else:
    print "you press r"

And same. What should i do?

Java code will not print out answer or read int properly

This is the whole project, it should work as far as I can see but i'm hoping that posting it here could let me see something I missed, I have a moderate amount of experience with java

package com.company;

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

public class Main {

public static void main(String[] args) {
// write your code here
    Scanner input = new Scanner(System.in);

    int number1;
    int number2;
    int answer;
    String operator;

This figures out what numbers and operators the user wants

 System.out.println("Please Enter your first number");
        number1 = input.nextInt();
        System.out.println("Please enter your second number");
        number2 = input.nextInt();
        System.out.println("Please enter your operator: + , - , * , / ");
            operator = input.next();

The if Statement should determine which operator the user wants and applys it to the two numbers and then calls the randomEquation Method to make it the wrong answer

           if (operator == "+") {
                answer = number1 + number2;
                System.out.println("Your answer is: " + randomEquation(answer));
            } else if (operator == "-") {
                answer = number1 - number2;
                System.out.println("Your answer is: " + randomEquation(answer));
            } else if (operator == "*") {
                answer = number1 * number2;
                System.out.println("Your answer is: " + randomEquation(answer));
            } else if (operator == "/") {
                answer = number1 / number2;
                System.out.println("Your answer is: " + randomEquation(answer));
            }



}

This method randomly applies one of these to the answer to create the wrong answer

  public static int randomEquation(int number) {
    Random rand = new Random();
    int random = rand.nextInt(100) + 1;
    int answer = number;
    if (random <= 100 && random >= 81) {
        answer = number * 25;
        return answer;
    }
    else if(random <= 80 && random >= 61){
        answer += 13;
        return answer;
    }
    else if(random <= 60 && random >= 41){
        answer /= 2;
        return answer;
    }
    else if(random <= 40 && random >= 21){
        answer -= 16;
        return answer;
    }
    else{
        answer %= 4;
        return answer;
    }
   }
  }

jquery if statement only half working

I can't for the life of me figure out why this won't work

$("#color").click(function () {

        if ($("a").css("color", "#ffffff")) {
       $("a").css("color","#ff0000");
     } else  {
         $("a").css("color", "#ffffff");
     };

      });

The first time you click, it changes the color. But it won't change it back if you click again.

everything I've looked at seems to tell me my syntax is fine but it's just not working.

Multiple Substrings in String - Python [duplicate]

Why wouldn't this code return "true" if any of the substrings are located in the larger someString?

substring1 = "foo"
substring2 = "text"
someString = "texting"

if ((substring1 or substring2) in someString):
    print "true"

I've looked into the any() function but I don't think it's what I'm looking for.

how can i make an if and else mysql query

i have a question - i want to make a if else query in a mysql query. Unfortunately I do not know how to do it right - can someone please explain?

how can i make a query like this:

if s_table.example1 = s_table.example2
set .s_table.example1 = 1
else
set .s_table.example1 = 2
end if

Else if statement with Selenium doesen't work

I have to test a website with Selenium in C# On the Site, there are buttons(10) in a random order. The program should check if the Button is available or not. Below I created an else if statemeent, but it didn't work. (The program doesn't click anything.

if (driver.FindElement(By.Name("btnK")).Displayed)
   {
      driver.FindElement(By.Name("btnK")).Click();
   }
else if (driver.FindElement(By.Name("btnG")).Displayed)
   {

      driver.FindElement(By.Name("btnG")).Click();
   }

Can anyone support me in this case?

Kind regards

Reducing if else branches and cleaning code using chain of functions, does it make sense

I am working on legacy code that has lots of if/else. I can use conditional decomposition and/or guard statements etc. to clean it. Another approach which can be used is to create functions out of branches and execute these functions as chain and exit with first response. I am wondering if using function chain is an overkill? Any views?

My chain looks something like below. This is a simplified example.

public class RequestStateHandler {
    private final List<Function<RequestStateInfo, Optional<Response>>> handlers = new ArrayList<>();

    public RequestStateHandler() {
        handlers.add(requestStateInfo -> xStateValidator(requestStateInfo));
        handlers.add(requestStateInfo -> yStateValidator(requestStateInfo));
        handlers.add(requestStateInfo -> zStateValidator(requestStateInfo));
    }

    public Response getResponse(RequestStateInfo requestStateInfo) {
        try {
            for (final Function<RequestStateInfo, Optional<Response>> handler : handlers) {
                final Optional<Response> response = handler.apply(requestStateInfo);

                if (response.isPresent()) {
                    return response.get();
                }
            }
        } catch (Exception e) {
            LOGGER.error("Some log", e);
        }

        return getDefaultResponse(requestStateInfo);
    }

    private Optional<Response> xStateValidator(RequestStateInfo requestStateInfo) {
        final A a = requestStateInfo.getA();
        if (a.isABC()) {
            return Optional.of(requestStateInfo.getX());
        }

        return Optional.empty();
    }

    private Optional<Response> yStateValidator(RequestStateInfo requestStateInfo) {
        if (requestStateInfo.isXYZ()) {
            final Response response = requestStateInfo.getX();
            final A a = response.getA();
            if (a.isSomeOtherTest()) {
                return Optional.of(response);
            }
        }

        return Optional.empty();
    }

    private Optional<Response> zStateValidator(RequestStateInfo requestStateInfo) {
        final Response response = requestStateInfo.getX();
        final A a = response.getA();
        if (a.isSomeAnotherTest()) {
            return Optional.of(response);
        }

        return Optional.of(getDefaultResponse(requestStateInfo));
    }

    private Response getDefaultResponse(RequestStateInfo requestStateInfo) {
        return new Response(A.create(requestStateInfo.getY()), null, null, null);
    }
}

I thought of creating a reusable executor so that we can have only business logic here. To me it looks much cleaner but it obviously add a dependency to execute the functions in order. Something like chain of responsibility, I would say. What are your thoughts?

A generic executor could be something like:

import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class ChainedExecutor<T, R> {
    private final static Logger LOGGER = LoggerFactory.getLogger(ChainedExecutor.class);
    public final List<Function<T,Optional<R>>> handlers;
    private R defaultResponse;

    private ChainedExecutor() {
        this.handlers = new ArrayList<>();
    }

    public R execute(T request) {
        return execute(request, Optional.empty(), Optional.empty());
    }

    public R execute(T request, Function<T, R> defaultSupplier) {
        return execute(request, Optional.of(defaultSupplier), Optional.empty());
    }

    public R execute(T request, Consumer<Exception> exceptionHandler) {
        return execute(request, Optional.empty() ,Optional.of(exceptionHandler));
    }

    public R execute(T request, Function<T, R> defaultHandler, Consumer<Exception> exceptionHandler) {
        return execute(request, Optional.of(defaultHandler), Optional.of(exceptionHandler));
    }

    public R execute(T request, Supplier<R> defaultSupplier) {
        final Function<T, R> defaultHandler = (input) -> defaultSupplier.get();
        return execute(request, Optional.of(defaultHandler), Optional.empty());
    }

    private R execute(T request, Optional<Function<T, R>> defaultHandler, Optional<Consumer<Exception>> exceptionHandler) {
        Optional<R> response;
        try {
            for (final Function<T,Optional<R>> handler: handlers) {
                response = handler.apply(request);

                if (response.isPresent()) {
                    return response.get();
                }
            }
        }
        catch (Exception exception) {
            handleOrLog(exceptionHandler, exception);
        }

        return getDefaultResponse(defaultHandler, request);
    }

    private void handleOrLog(Optional<Consumer<Exception>> exceptionHandler, Exception exception) {
        if (exceptionHandler.isPresent()) {
            exceptionHandler.get().accept(exception);
            return;
        }
        LOGGER.error("Unhandled exception occurred while executing handler chain. This most probably is a developer error.");
    }

    private R getDefaultResponse(Optional<Function<T, R>> defaultHandler, T request) {
        if (defaultHandler.isPresent()) {
            return defaultHandler.get().apply(request);
        }
        return getDefaultResponse();
    }

    public R getDefaultResponse() {
        return defaultResponse;
    }

    public static class Builder<T, R> {
        private final ChainedExecutor<T, R> chainedExecutor = new ChainedExecutor<>();

        public Builder(List<Function<T,Optional<R>>> handlers) {
            Validate.notNull(handlers);
            for (final Function<T, Optional<R>> handler: handlers) {
                Validate.notNull(handler);
                handlers.add(handler);
            }
        }

        public Builder() {}

        public ChainedExecutor.Builder<T, R> withHandler(Function<T, Optional<R>> handler) {
            Validate.notNull(handler);
            chainedExecutor.handlers.add(handler);
            return this;
        }

        public ChainedExecutor.Builder<T, R> withDefaultResponse(R defaultResponse) {
            Validate.notNull(defaultResponse);
            chainedExecutor.defaultResponse = defaultResponse;
            return this;
        }

        public ChainedExecutor<T, R> build() {
            Validate.isTrue(!chainedExecutor.handlers.isEmpty());
            return chainedExecutor;
        }
    }
}

SQL - How can I use a Select based on the parameter

I've got a sql statement in a SQL Server stored procedure using a where clause like this: Select (fields) From Table Where Testname like @SearchLetter + '%'

I need to do check the parameter @SearchLetter and if it's "#", I need to make the parameter choose records that the field 'Testname' starts with a numeric field (0-9)

I've tried several things (ifs/selects, etc.) but I can't seem to get what I need.

anyone know how I can do this?

day formula in a if statement

I am using the formula below to check to see if January first is on Saturday. The calendar I've created will flip years using a macro in place, so January first may not always lay on a Saturday. The reason I need to use DAY is because the cell it is refering to is in a DAY format.

=IF(DAY(H5)=1,"Winter","") Formula

January 1st Days of the week

2018- Monday Calendar

2019- Tuesday

2023- Saturday etc...

So H5 is the place of the first Saturday in January,

if H5 = January 1st it should show "Winter" if not it should return blank. The issue is the formula is getting caught on the DAY(H5)=1. It returns #Value instead of a blank. Is there a work around I can use to show blanks instead?

I have conditional formatting in place so the cell is grayed out (Font colour and Fill). It looks good when it's in the spreadsheet but once it it is printed it will still show #VALUE.

Thanks in advance,

Why postfix `if` in Ruby work so strange

I have a follows strange behaviour in Ruby:

2.3.3 :001 > var1.zero? if var1 = 1
NameError: undefined local variable or method `var1' for main:Object

From the other side, if I do same thing in a standard if, all works as expected:

2.3.3 :001 > if var1 = 1
2.3.3 :002?>   var1.zero?
2.3.3 :003?>   end
 => false

Anyone can describe how work postfix if in Ruby?

Razor - If condition not working

I'm having this condition :

if ((Convert.ToBoolean(draft) != true) && (date ­> DateTime.Now))

VS keep telling me && cannot be applied to type bool and DateTime.

What's the problem ?

Java 8 Optional instead of if

Hello I have problem with Optional and I don't know how to handle it.

public void check(String name){
   if(name != null)
      doSomething(name);
   else 
      doMore();
} 

How to change this if into Optional? Thanks in advance for help

Mapping between button and word for tooltip

While selecting the quantity during order placement I have two buttons, - and +, which decreases/increases the quantity number (not beyond min and max amount).

After reaching min, the - button is grayed out. After reaching max, the + button is grayed out. A tooltip appears which says Quantity cant be less than <min> or Quantity cant be more than <max>.

if ($button.hasClass("minus") && $quantity <= $("#dropdown").data("min")) {
  $button.addClass("grayout");
  $("#tooltip").html("Quantity can't be less than " + $("#centerbox").html()).show();
} else if ($button.hasClass("plus") && $quantity >= $("#dropdown").data("max")) {
  $button.addClass("grayout");
  $("#tooltip").html("Quantity can't be more than " + $("#centerbox").html()).show();
}

I have this if else statement which does the job. Since the contents of if else blocks are almost the same except "less" and "more". Whats the best way to optimize the code?

Things i have tried (but not yet satisfied):

  • Have conditions clubbed by "||" and within the block, check for class again and modify the text accordingly.
  • Have a map outside of the function which maps button element to word
  • Modify the tooltip text to say "Cant go beyoond the range and "

Issue with IF test on JSF xtml

sorry i tried a lot of others replies, but still i can't use it:

i want to check the value of a bean in order to print html code or not but all the time i have FALSE condition:

here the code:

<tbody>
<ui:repeat value="${wasJvmInvbean.listWasJvmInv()}" var="jvm">
    <tr>
        <td>${jvm.jvmStatus}</td>
        <td>${jvm.cellName}</td>
        <td>${jvm.serverBean.hostname}</td>
        <td>${jvm.jvmName}</td>
        <td>${jvm.type}</td>
        <td>${jvm.profilePath}</td>
        <td>${jvm.wasVersion}</td>

   <c:if test="${jvm.jvmName eq 'dmgr'}">
   <td>webconsole http://xxxx:8080</td>
  </c:if>
    <c:if test="${jvm.jvmName ne 'dmgr'}">
   <td>N.A.</td>
  </c:if>                       
<td>${jvm.fid}</td>
<td>${jvm.heapMin}</td>
<td>${jvm.heapMax}</td>
<td>${jvm.wcDefaultType}</td>
<td>${jvm.wcHost}</td>
<td>${jvm.wcPort}</td>
    </tr>
</ui:repeat>

display chart with if function in EXCEL

I am currently creating a reporting chart for my company and i want to make it as easy as possible to set up this reporting. Currently I am struggling with displaying charts in a nice way. My idea is that the user writes a 1 in say Cell A1, then a certain chart will show up at position A20, if he writes nothing it will not show.

My idea was something like

if(A1=1;Chart1;"") 

but unfortenatuly it does not work. Does anybody know a solution to this?

Thanks in advance

Javascript picking few elements from array

I want to check if an array includes clicked elements. So the condition should be fulfilled if the array contains three clicked elements(1,2,3 or 4,5,6 or, 7,8,9) but it doesn't work. The console displays "You won..." when i click third or sixth or ninht element. Syntax problem?

for (i=1;i<=9;i++) {
  functionOnclick(i){
    array.push("element" + i + "clicked");

    if(
    (array.includes(element1clicked&&element2clicked&&element3clicked)) ||
    (array.includes(element4clicked&&element5clicked&&element6clicked)) ||
    (array.includes(element7clicked&&element8clicked&&element9clicked)))

       {console.log("You won the game!"}

  }

}

Edited:

<script>

    var i="";
    var a="O";
    var tablica1=[""];

    for (i=1;i<=9;i++) {    

        function Klik(i) { 

                if (a=="X") {
                    a="O";
                    document.getElementById("pole"+i).innerHTML=a; 
                    document.getElementById("pole"+i).className=("active1");
                    document.getElementById("gracz").innerHTML="X, Click!";
                    document.getElementById("pole"+i).removeAttribute("onclick"); 
                }

                else if (a=="O") {
                    a="X";
                    document.getElementById("pole"+i).innerHTML=a;
                    document.getElementById("pole"+i).className=("active2");
                    document.getElementById("gracz").innerHTML="O, Click!";
                    document.getElementById("pole"+i).removeAttribute("onclick"); 
                    tablica1.push("pole"+i+"active2");
                }
                console.log(tablica1);

                if (
                (tablica1.includes("pole1active2"&&"pole2active2"&&"pole3active2"))
                ||
                (tablica1.includes("pole4active2"&&"pole5active2"&&"pole6active2"))
                ||
                (tablica1.includes("pole7active2"&&"pole8active2"&&"pole9active2"))
                )

                {console.log("won");}
        }       
    }


    </script> 

Multiple if statements checking length of string and shortening

I'm wondering if there's a better way of writing these multiple If statements? I'm sure there is, I just can't figure out what it'd be. In essence the code is just shortening the string.

                If text = "-----------------" Then
                    text = "-"
                End If
                If text = "----------------" Then
                    text = "-"
                End If
                If text = "---------------" Then
                    text = "-"
                End If
                If text = "--------------" Then
                    text = "-"
                End If
                If text = "-------------" Then
                    text = "-"
                End If
                If text = "------------" Then
                    text = "-"
                End If
                If text = "-----------" Then
                    text = "-"
                End If
                If text = "----------" Then
                    text = "-"
                End If
                If text = "---------" Then
                    text = "-"
                End If
                If text = "--------" Then
                    text = "-"
                End If
                If text = "-------" Then
                    text = "-"
                End If
                If text = "------" Then
                    text = "-"
                End If
                If text = "-----" Then
                    text = "-"
                End If
                If text = "----" Then
                    text = "-"
                End If
                If text = "---" Then
                    text = "-"
                End If
                If text = "--" Then
                    text = "-"
                End If

Any help is much appreciated.

refer element to show an object Jquery

I hope you can help me with this one. I want to refer an element to object. How can I do that.

the situation is like this. I got this

MatchItem

Properties

Name    Type
Id  string
MatchNumber int
Date    string
Time    string
DepartmentId    string
DepartmentCode  string
DepartmentName  string
HomeTeamId  string
HomeClubId  string
HomeTeam    string
AwayTeamId  string
AwayClubId  string
AwayTeam    string
PoolId  string
PoolName    string
PoolCity    string
MatchReport string
Played  boolean
ResultHome  int
ResultGuest int
Referees    MatchRefereeItem[]

through jquery, I called an action from the DOM.

if(data.Action == "D") {
                    element.html('<td>'+ standings.H +'-'+ standings.G +'</td>' + '<td>' + data.Time +'</td>'+ '<td>' + participant.Name + ' ' + translateAction(data.Action) + '</td>' + '<td>' + participant.Team + '</td>');
                } else {
                    element.html('<td></td>' + '<td>' + data.Time +'</td>'+ '<td>' + participant.Name + ' ' + translateAction(data.Action) + '</td>' + '<td>' + participant.Team + '</td>');
                }

its about the participant.Team the results shows H or G (home or away team) but it has to refer to HomeTeam or AwayTeam. How do I do that? or where...in php or jquery?

so far I got this in jquery.

if(participant.Name == "H"){
                    element.html('<?=$Match->HomeTeam?>');
                }else{
                    element.html('<?=$Match->AwayTeam?>');
                }

thanks again!

jeudi 27 juillet 2017

Shorten If Statement And Making It Less Redundant

new here. I was just wondering if it's possible to make this if statement shorter and less redundant.

if (!a && b)
{
    if (c == d && e > 0)
    {
        return;
    }
}
else if (a && !b)
{
    if (c != d)
    {
        return;
    }
}
else if (!a && !b)
{
    return;
}

Here's what I've ended up with

if ((!a && b && c == d && e > 0) || (a && !b && c != d) || (!a && !b))
{
    return;
}

All I did was join nested if statements with an && operator, and if-else if statements with || operator. Now I'm stuck, is it possible to make this even shorter? If you could share some tips or your way of approaching this kind of scenario, I'd be glad to hear it out.

Hello guys ineed a php expert please

"iknow may not work or stupid idea"

but imade a web app but with 2 forms and 2 codes one for mobile and one for pc or laptop.. so how ido if statement with the guest os to the right path imade * if viewing from mobile iwant him to go http://ift.tt/2w5q8hz if from pc or lap www.site.com/pc *

<?php
$mobileOS=idk
if ($guest = $mobileOS) {
header('location: /mobile');
} else {
header('location: /pc');
?>

note:bootstrap doesn't work because iwant to change the whole site into 2 pathes

(sorry for bad english)

Syntax Error: invalid syntax else: what is wrong

while False: if raw_input('Press W To Go Forward. Then Press Enter.') =='w': print 'Well Done' return True else: return False

Clear terminal every second but leave minutes

I have a seconds and minute counter, very similar to my timer. However, I cannot get the number of minutes to stay on screen.

int main()
{
    int spam = 0;
    int minute = 0;

    while (spam != -1)
    {
        spam++;
        std::cout << spam << " seconds" << std::endl;
        Sleep(200);
        system("CLS");
        //I still want the system to clear the seconds
        if ((spam % 60) == 0)
        {
            minute++;
            std::cout << minute << " minutes" << std::endl;
        }
        //but not the minutes
    }
}

New to java, what distinguishes an else-if statement from an if statement

New to java, and programming in general, what is the distinction between using "else-if" statements versus just a series of "if" statements?

Else statement not working

I am trying to return the longest even word in the array using a forEach loop and return "00" when there is no even word. I am able to get the part of returning the longest even word to work correctly, but when I introduce the else statement it doesn't work anymore:

function FindlongestWord(input) {
  var arrWords = input.split(' ');
  var wordlength = 0;
  var word = '';
  arrWords.forEach(function(wrd) {
    if (wordlength < wrd.length && wrd.length % 2 == 0) {
      wordlength = wrd.length;
      word = wrd;
    } else  {
      return "00";
    }
  });
  return word;
}

VBA My IF statement ends after finding one iteration

Thank you for reading and your help!

I have a simple problem that I just can't figure out.

In Column A I have the below values from 1 to 20.

1. NBC997
2. EVO463
3. EVO426
4. EVO420
5. EVO826
6. EVO820
7. EVO863
8. CRO001
9. BCA915
10. SBH121
11. KEN500
12. GAM201
13. GAM1011
14. GAM101
15. SPR577
16. SPR580
17. SPR579
18. SPR576
19. DON201
20. MOR101

My formula below should be looking at column A.. and deleting the entire row if the left 2 characters <> "EV".

For whatever reason once it finds one iteration.. it stops completely and doesn't go to the next line. Please help if you can. I know I'm probably missing something really silly. Thank you!

Sub remove()

Dim i As Long

    For i = 1 To 20
        If Left(Cells(i, "A"), 2) <> "EV" Then
        Cells(i, "A").EntireRow.Delete
        Else
    End If
    Next i

End Sub

Show different HTML on page depending on origin file's directory location using PHP

I am working on my employer's website and I am relatively new to PHP. I am decent at deciphering code others have written, but I can't seem to figure out how to write additional code to integrate into the current page's PHP. I'm trying to figure out a way to display an image instead of displaying the ordered list if the file is not in a directory that has pre-defined "links" on spelled out.

The site that I am working on is http://ift.tt/1KfChnZ and the following is code that uses an array to choose what links go in the rightNav bar depending on what directory the html file is located in:

(An example of a page with a rightNav with links is this page: http://ift.tt/2v1K87D

An example of a page with no links is this page: http://ift.tt/2uGJ46I)

<?PHP

/*
Array:
    0:URL (Path, or URL.  If a Path it must be an absolute link. ie: starts with a /).
    1:Text (Try to limit length).
    2:Icon (Glyph Sets:Font-Awesome).
*/






if(isset($n)){
switch($n)
{
    case "High School":
        $links = [
            ["/highschool/principal.html","Principal","<i class='fa fa-user' aria-hidden='true'></i>"],
            ["/highschool/Guidance","Guidance & Scholarships","<i class='fa fa-map' aria-hidden='true'></i>"],
            ["/highschool/lrc/index.htm","Library","<i class='fa fa-book' aria-hidden='true'></i>"],
            ["/district/athletics.html","Athletics","<i class='fa fa-futbol-o' aria-hidden='true'></i>"],
            ["/highschool/clubs/index.html","Clubs & Groups","<i class='fa fa-coffee' aria-hidden='true'></i>"],
            ["/highschool/boosterClub/","Booster Club","<i class='fa fa-arrow-circle-up' aria-hidden='true'></i>"],
            ["/highschool/chsband/index.html","Band","<i class='fa fa-music' aria-hidden='true'></i>"],
            ["/highschool/attachment/2017courseBook.pdf","2017 Course Book","<i class='fa fa-list-alt' aria-hidden='true'></i>"],
            ["http://ift.tt/2v1OeN7","Claymont On-line Learning","<i class='fa fa-globe' aria-hidden='true'></i>"],
            ["/highschool/bellschedule/bell_schedule.htm","Bell Schedule","<i class='fa fa-bell' aria-hidden='true'></i>"],
            ["/attachment/handbook/CHS_Handbook.pdf","Student Handbook","<i class='fa fa-list-ul' aria-hidden='true'></i>"],
            ["http://ift.tt/2uGODlL","Video Editing","<i class='fa fa-video-camera' aria-hidden='true'></i>"],
            ["/highschool/about-mustang/","Mustang","<i class='fa fa-paw' aria-hidden='true'></i>"]         
        ];
        break;

    case "Middle School":
        $links = [
            ["cjhslrc/index_new.html","Library","<i class='fa fa-book' aria-hidden='true'></i>"],
            ["/district/athletics.html","Athletics","<i class='fa fa-futbol-o' aria-hidden='true'></i>"],
            ["http://ift.tt/2v1OeN7","Claymont On-line Learning","<i class='fa fa-globe' aria-hidden='true'></i>"],
            ["/juniorhigh/bellschedule/bell_schedule.htm","Bell Schedule","<i class='fa fa-bell' aria-hidden='true'></i>"],
            ["/attachment/handbook/CMS_Handbook.pdf","Student Handbook","<i class='fa fa-list-ul' aria-hidden='true'></i>"],
            ["/juniorhigh/attachment/dcInfo.PDF","DC Trip","<i class='fa fa-university' aria-hidden='true'></i>"],
            ["/juniorhigh/attachment/7tripPit.PDF","Pittsburgh Trip","<i class='fa fa-map' aria-hidden='true'></i>"],
            ["http://ift.tt/2v1D6jt","Guidance","<i class='fa fa-map' aria-hidden='true'></i>"],
            ["/juniorhigh/honorroll/02-16.html","Honor Roll","<i class='fa fa-bars' aria-hidden='true'></i>"],
            ["/juniorhigh/PrincipalNewsletter.html","Principal's Newsletters","<i class='fa fa-newspaper-o' aria-hidden='true'></i>"],
            ["/attachment/supply/middleSuppyList.pdf","Supply List","<i class='fa fa-newspaper-o' aria-hidden='true'></i>"]             
        ];
        break;

    case "Intermediate":
        $links = [
            ["attachment/newsMar17.pdf","March <br>Newsletter","<i class='fa fa-newspaper-o' aria-hidden='true'></i>"],
            ["attachment/events.pdf","Events","<i class='fa fa-calendar' aria-hidden='true'></i>"],
            ["LRC/index_new.html","Library","<i class='fa fa-book' aria-hidden='true'></i>"],
            ["http://ift.tt/2uGwZyb","Guidance","<i class='fa fa-map' aria-hidden='true'></i>"],
            ["dare/darekg/index.html","D.A.R.E.","<i class='fa fa-child' aria-hidden='true'></i>"],
            ["http://ift.tt/2v1OP1n","Harcourt School","<i class='fa fa-book' aria-hidden='true'></i>"],
            ["http://ift.tt/1bHYQwp","Study Island","<i class='fa fa-tree' aria-hidden='true'></i>"],
            ["video.html","Video Gallery","<i class='fa fa-video-camera' aria-hidden='true'></i>"],
            ["/attachment/handbook/CIS_Handbook.pdf","Student Handbook","<i class='fa fa-list-ul' aria-hidden='true'></i>"],
            ["photoGallery.html","Photo Gallery","<i class='fa fa-photo' aria-hidden='true'></i>"],
            ["http://ift.tt/2v0WRI0","Renaissance <br>Parent Connection","<i class='fa fa-user' aria-hidden='true'></i>"],
            ["/attachment/supply/intermediateSuppyList.pdf","Supply List","<i class='fa fa-pencil' aria-hidden='true'></i>"]            
        ];
        break;

    case "Elementary":
        $links = [
            ["attachments/newsletter/may17.pdf","May <br>Newsletter","<i class='fa fa-newspaper-o' aria-hidden='true'></i>"],
            ["LRC/index_new.html","Library","<i class='fa fa-book' aria-hidden='true'></i>"],
            ["/attachment/handbook/Elementary_Handbook.pdf","Student Handbook","<i class='fa fa-list-ul' aria-hidden='true'></i>"],
            ["http://ift.tt/2v0WRI0","Renaissance <br>Parent Connection","<i class='fa fa-user' aria-hidden='true'></i>"],
            ["/attachment/supply/elementarySuppyList.pdf","Supply List","<i class='fa fa-pencil' aria-hidden='true'></i>"]          
        ];
        break;

    case "Primary":
        $links = [
            ["attachments/apr17.pdf","April <br>Newsletter","<i class='fa fa-newspaper-o' aria-hidden='true'></i>"],
            ["gallery/gallery.html","Photo Gallery","<i class='fa fa-photo' aria-hidden='true'></i>"],
            ["lrc/index_new.html","Library","<i class='fa fa-book' aria-hidden='true'></i>"],
            ["trentoninfo.htm","General Information","<i class='fa fa-info-circle' aria-hidden='true'></i>"],
            ["/attachment/handbook/Primary_Handbook.pdf","Student Handbook","<i class='fa fa-list-ul' aria-hidden='true'></i>"],
            ["/attachment/supply/primarySuppyList.pdf","Supply List","<i class='fa fa-pencil' aria-hidden='true'></i>"],
            ["http://ift.tt/2v0WRI0","Renaissance <br>Parent Connection","<i class='fa fa-user' aria-hidden='true'></i>"]
        ];
        break;

    case "Preschool":
        $links = [
            ["pre/pre.html","Message from the Principal","<i class='fa fa-envelope' aria-hidden='true'></i>"],
            ["FAMILY_HANDBOOK_WEB.pdf","Family Handbook","<i class='fa fa-list-ul' aria-hidden='true'></i>"],
            ["SNACK_12-13.pdf","Snack Calendar","<i class='fa fa-calendar' aria-hidden='true'></i>"],
            ["/attachment/supply/preschoolSuppyList.PDF","Supply List","<i class='fa fa-pencil' aria-hidden='true'></i>"],
            ["History.html","History","<i class='fa fa-clock-o' aria-hidden='true'></i>"],
            ["attachment/2017application.pdf","Preschool Application","<i class='fa fa-file' aria-hidden='true'></i>"],
            ["/district/Wellness/KindImmun.htm","Immunization<br> Information","<i class='fa fa-medkit' aria-hidden='true'></i>"],
            ["LRC_DISTRICT.PDF","LRC Newsletter","<i class='fa fa-book' aria-hidden='true'></i>"],
            ["http://ift.tt/2uGAtB3?","Symbaloo","<i class='fa fa-arrows' aria-hidden='true'></i>"]
        ];
        break;

    default:
        $links = [];
        break;
}
}else{
    $links = [];

}   



?>


<nav id="navRight" class="dispBox">
<h3>Links</h3>
    <ul>
    <?PHP
    if(count($links)!= 0){
        foreach($links as $link){
            $url = $link[0];
            $text = $link[1];
            $icon = $link[2];   
            echo ("<li><a href='$url'>$text$icon</a></li>");        

        //<li><a href="cjhslrc/index_new.html">Library<i class="fa fa-book" aria-hidden="true"></i></a></li>

        }}
    ?>


    </ul>
</nav>
<?PHP ?>

How to vectorize matlab function input when NaN could be the input?

I wrote a function which I hope to have vectorized input and output.

function output = myfunction(input1,input2)


if input1 == 0
    output = equation1 ;
else
    output = equation2 ;
end

I test to have input1=0 and input1= 0.5 and my function myfunction can work right. The input input1 and input2 is actually a 3D matrix. I am trying to have more efficient computation instead of running in a loop elements by elements. If all my input1 is nonzero element, myfunction can work correctly. It seems like once I input a matrix, it cannot go through the if-statement correctly. My function will give me NaN for the element that has input1=0. How to make a change so that myfunction can take either a number and also a matrix in a if-statement. Thank you!

H2o R package: multiple ifelse conditions in h2o

I am trying to write a simple ifelse function in h2o R. Single ifelse works with no issues. But when I try to to even write a code with just two ifelse it gives me an error: my_cl$Seg<-ifelse((my_cl$predict==0), '1', ifelse(my_cl$predict==1), '2','0'))

Error: unexpected ')' in "my_cl$Seg<-ifelse((my_cl$predict==0), '1', ifelse(my_cl$predict==1), '2','0'))"

In regular R it would be correct. If I remove a ) Error in ifelse((my_cl$predict == 0), "1", ifelse(my_cl$predict == 1), : unused arguments ("2", "0")

Is it because in h2o the multiple ifelse are not supported? I tried to replace ifelse with h2o.ifelse - same errors. Thank you

Problems with else

i am a vb.net programmer and i am developing a metal furnace to my game but i cant figure out why else isn't working.

If p2 = True And tmpmoldeatual = "p2" Then
        Label10.Hide()
    Else
        Label10.Show()
    End If

The labe is flickering at the rythim of the time where this code is placed. p2 means if that pickaxe cast is crafted and tmpmoldeatual is the current cast in a craftable casts list. I want to hide the "Make this cast" label when the cast is crafted without hidding them from the rest of the casts.

Why do I get false when testing for first character in AppleScript?

I've searched around a few sites and here but I haven't found an answer to why when reviewing a string in AppleScript I am returned false. The following variable:

set foobar to "1234foobar"

When checking for the first character as integer:

if first character of foobar is integer then
    return true
else
    return false
end if

it returns false so I decided to check for number:

if (first character of foobar) contains number then
    return true
else
    return false
end if

it returns false so I decided to separate the first character and convert it to number before the conditional:

set firstFoo to (first character of foobar) as number
if firstFoo is equal to number then
    return true
else
    return false
end if

Why am I getting a constant false when checking for the contents of foobar?

MYSQL IF (SELECT) query returns more than one row

I'm trying to implement an IF (SELECT) statement in an SQL query. The query looks like this so far:

SELECT *, IFNULL(duree_corrigee,duree) as
duree_final, IF((SELECT COUNT(*) FROM pointage_interval WHERE panier=1 
AND pointage_employe_id = 'FH'
AND semaine = 23 GROUP BY date)>=1,  
1,0) as panier_final FROM pointage_interval P
JOIN
employe E ON P.pointage_employe_id
= E.employe_id JOIN chantier C
ON C.chantier_id=P.pointage_chantier_id
WHERE (pointage_employe_id = 'FH'
AND semaine = 23)

When I run it, it returns me: #1242 - Subquery returns more than 1 row

Basically I can have many rows with the same date. One column is "panier", and can be either 1 or 0. I would like to create a new column panier_final, which takes the value 1 or 0 based on if there is a least one column with value of panier = 1 for the same day. So all the rows with this same date will get the same value 1 or 0 for panier_final.

If I run the query without the IF (SELECT), as this:

SELECT *, IFNULL(duree_corrigee,duree) as
duree_final FROM pointage_interval P
JOIN
employe E ON P.pointage_employe_id
= E.employe_id JOIN chantier C
ON C.chantier_id=P.pointage_chantier_id
WHERE (pointage_employe_id = 'FH'
AND semaine = 23)

I get this output:

enter image description here

As you can see, there are two rows for the same day, 2017-06-07. So I would like my IF (SELECT) query to create a new column (panier_final) for each row, the value of this new column being the same for each same date's rows. In this case each row would get a new column panier_final, the value being 1 since that for each given date, the values panier are equal or superior to 1

Shell Script won't fail in Jenkins

I have a simple shell script which I want to set up as a periodic Jenkins job rather than a cronjob for visibility and usability for less experienced users.

Here is the script:

#!/bin/bash
outputfile=/opt/jhc/streaming/check_error_output.txt

if [ "grep -sq 'Unable' $outputfile" == "0" ]; then
    echo -e "ERROR MESSAGE FOUND\n"
    exit 1
else
    echo -e "NO ERROR MESSAGES HAVE BEEN FOUND\n"
    exit 0
fi

My script will always return "NO ERROR MESSAGES HAVE BEEN FOUND" regardless of whether or not 'Unable' is in $outputfile, what am I doing wrong?

I also need my Jenkins job to class this as a success if 'Unable' isn't found (e.g. If script returns "0" then pass, everything else is fail)

if statement condition that tests for list membership is not working correctly

I wrote a simple script, but the output is not correct. Can you give me advice how to solve it? the question is about white or black squares on a chess board: If I use the def with a string 'd' and int(4), it will return white, but it has to be black?

def in_white(letter,integer):

    list_letters_1 = ['a','c','e','g']
    list_letters_2 = ['b','d','f','h']

    list_numbers_1 = [1,3,5,7]
    list_numbers_2 = [2,4,6,8]
    print(list_numbers_1)

    if str(letter) in list_letters_1 and int(integer) in list_numbers_1:
        print("black")
    elif str(letter) in list_letters_2 and int(integer) is list_numbers_2:
        print("black")
    else:
        print("white")

in_white('d',4)

JavaScript else if statement

I've been trying to perform a simple jQuery code snippet for hours now. Embarrassingly, I haven't got it to work yet.

Here's the JS first and then the HTML:

jQuery(function ($) {
    if ($('#button1')) {
        $('#button1').on('click', function(event){
            console.log('First action');
        });

    } else if ($('button2')) {
        $('#button2').on('click', function(event){
            console.log('Second action');
        });
    }
});
<script src="http://ift.tt/1vtgOwa"></script>


<!-- Button 1 -->
<div id="button1">
    <a href="#">Action for button 1</a>
</div>

<!-- Button 2 -->
<div id="button1">
    <a href="#">Action for button 2</a>
</div>

hyperlink in excel if file exists in folder

I want to create a hyperlink if and only if a file exists with a specific name in my folder. Otherwise I want the cell to remain blank. I have a folder with very specific file names that I want excel to search through and return the hyperlink if the name is found. I was thinking of the following code but can't get it to work:

=IF(find("8197837", foldername, "8197837"), hyperlink(folder name, 8197837), "")

Python: Terminating loop with integer variable type

I have made a program that stores login details that you have entered and allows you to login it with it into the main part of the menu. Everything was working fine when all the data types were strings, for example; modea = input("Etc") to allow the user to select options by entering number inputs that correspond to the option, e.g "2", it should call its assigned function as it fulfills the if modea == 2 statement, but if I try to change string to integer data type, for example modea = int(input("Etc")), even if I were to enter an expected input, the loop would never stop and continue running as if I entered nothing, contrary to simply using modea = input("etc") where it treats everything as a string, and it would still accept number input and carry out its assigned action, but not if the data type is an integer?

Everything is working the way it is but changing the data type from string to integer just makes the program unable to terminate the while loops when there is no exception. From modea = input("etc") to modea = int(input("etc")).

I added full code here for it to make more sense, which most can be ignored as it runs as intended, but I can't seem to get my head around whats going on with the logged()function part of the code where I attempted to get modea = int(input("etc")) to work by terminating its loop when the if statements are fulfilled, but it just continues on looping as if everything is null. Help would be appreciated.

#import modules
import time
import sys
import re

#Initialise variables that could help with error handling
name = ""
mode = ""
username = ""
password = ""
addusername = ""
addpassword = ""
exit = ""
modea = ""
new_app = ""
new_pass = ""
quit = ""

#Dictionary to store more than one set of login details
vault = {}

#Lists to store website names and passwords
appvault = []
passvault = []

#FIRST MENU AND REGISTERING LOGIN DETAILS -----------------------------------------------------------------------------------------------------------------------------------------

def menu(): #The menu function is the 1st menu that asks the user to either register their login details or to login with existing login details saved into the vault dictionary
    print("--------------------------*ENTERING THE MAIN MENU*-----------------------------------\n") #triple """ used to effectively format the menu
    mode = input(str("""Hello {}, below are the modes that you can choose from:\n 
    ##########################################################################
    a) Login with username and password
    b) Register as a new user
    To select a mode, enter the corresponding letter of the mode below
    ##########################################################################\n
    > """.format(name))).strip() #greets user and removes any white space
    return mode #returns the input

def login(username, password): #The login function is where the user logins in with existing registered details in the vault dictionary
    if len(vault) > 0 : #user has to append usernames and passwords before it asks for login details
        print("Welcome {} to the login console".format(name))
        noloop = True #Starts a loop if True will begin looping
        while noloop:
            addusername = input("Please enter username: ") 
            if addusername == "":
                print("Username not entered, try again!")
                continue #returns to the beginning of the while loop if null
            addpassword = input("Please enter password: ") 
            if addpassword == "":
                print("Password not entered, try again!")
                continue #returns to the beginning of the while loop if null
            try:
                if vault[addusername] == addpassword: #If the username and password match with the login details appended into the dictionary, it will count as matching details.
                    print("Username matches!")
                    print("Password matches!")
                    print("Logging into password vault...\n")
                    noloop = logged() #jumps to logged function and tells the user they are logged on
                    return noloop 
            except KeyError: #the except keyerror recognises the existence of the username and password in the list
                print("The entered username or password is not found!")

    else:
        print("You have no usernames and passwords stored!") #When the user selects option A before adding any login details to the dictionary
        return True #returning to the start of the loop when the else statement is printed

def register(): #example where the username is appended. Same applies for the password
    global username #initialises global variables
    global password
    print("Please create a username and password into the password vault.\n")

    while True:
        validname = True 
        while validname:
            username = input("Please enter a username you would like to add to the password vault. NOTE: Your username must be at least 3 characters long: ").strip().lower()
            if not username.isalnum(): #handles usernames with no input, contain spaces between them or have symbols in them.
                print("Your username cannot be null, contain spaces or contain symbols \n")
            elif len(username) < 3: #any username with less than 3 characters is rejected and looped back
                print("Your username must be at least 3 characters long \n")
            elif len(username) > 30: #any username with more than 30 characters is rejected and looped back
                print("Your username cannot be over 30 characters long \n")
            else:
                validname = False 
        validpass = True

        while validpass:
            password = input("Please enter a password you would like to add to the password vault. NOTE: Your password must be at least 8 characters long: ").strip().lower()
            if not password.isalnum(): #handles null input passwords, passwords that contain spaces or symbols
                print("Your password cannot be null, contain spaces or contain symbols \n")
            elif len(password) < 8: #passwords that are less than 8 characters long are rejected and loops back
                print("Your password must be at least 8 characters long \n")
            elif len(password) > 20: #passwords that are more than 20 characters long are rejected and loops back
                print("Your password cannot be over 20 characters long \n")
            else:
                validpass = False 
        vault[username] = password #the appending process of username and passwords to the dictionary
        validinput = True 
        while validinput:
            exit = input("\nDo you want to register more usernames and passwords? Enter 'end' to exit or any key to continue to add more username and passwords:\n> ")
            if exit in ["end", "End", "END"]: 
            else:
                validinput = False 
                register()
        return register 

#LOGGED ONTO THE PASSWORD AND WEBSITE APP ADDING CONSOLE------------------------------------------------------------------------------------------------------------------------

def logged(): #The logged function is the 2nd menu where the user is able to access after logging in with their registered login details
    print("-----------------------------*ENTERING THE PASSWORD VAULT MENU*-----------------------------------\n")
    print("You are logged in, welcome to the password vault console.")
    keeplooping = True #whileloop that is True will keep the menu in a loop
    while keeplooping:    
        try:
            modea = int(input("""Below are the options you can choose from in the password vault console:
            ##########################################################################\n
            1) Find the password for an existing website/app
            2) Add a new website/app and a new password for it
            3) Summary of the password vault
            4) Exit
            ##########################################################################\n
            > """))
        except ValueError:
            print("Please enter a valid option!")

    if modea == 1: #if the user enters 1 as instructed, then they have decided to choose to find existing apps and passwords
        viewapp() #viewapp function is called

    elif modea == 2: #if user enters 2 as instructed, then they have decided to add new app/websites and the passwords for it
        addapp() #addapp function is called

    elif modea == 3: #if the user enters 3 as instructed, then they have decided to look at the summary of passwords entered so far
        summary() #summary function is called

    elif modea == 4: #if the user enters 4 as instructed, then they have deicided to quit the entire program. All loops stop and program ends with print statement saying "Goodbye"
        keeplooping = False 
        print("*Exiting program*\n")
        time.sleep(2)
        print("############################################################")
        print("Goodbye user and thanks for using the password vault program")
        print("############################################################")
        return keeplooping 
    else:
        print("That was not a valid option, please try again: ") 
        validintro = False 


def viewapp(): #The viewapp function is the 1st option of the password and vault menu that allows the user to view the app/websites and passwords stored so far
    if len(appvault) > 0: #The website/apps and passwords are only shown once the user has entered a set of the info, otherwise no info will be shown
        print("""Below are the details of the website/apps and passwords stored so far: 
(NOTE: Websites/apps and passwords are shown in order of being appended; 1st password is for 1st website, etc...\n""")
        for app in appvault: 
            print("Here are the website/app you have stored:")
            print("- {}\n".format(app)) #Website/app is printed out here
    if len(passvault) > 0 : #The website/apps and passwords are only shown once the user has entered a set of the info, otherwise no info will be shown
        for code in passvault: 
            print("Here are the password you have stored for the websites/apps: ")
            print("- {}\n".format(code)) #The passwords are printed out here

    else:
        print("You have no apps or passwords entered yet!") 

def addapp(): 
    while True:
        validapp = True 
        while validapp:
            new_app = input("Enter the new website/app name: ").strip().lower()
            if len(new_app) > 20: #if the user enters a website with more than 20 characters, it is rejected and loops back and asks for input again
                print("Please enter a new website/app name with no more than 20 characters: ")
            elif len(new_app) < 1: #if the user enters nothing, program loops back and asks for input again
                print("Please enter a valid new website/app name: ")
            else:
                validapp = False 
                appvault.append(new_app)

        validnewpass = True 
        while validnewpass:
            new_pass = input("Enter a new password to be stored in the passsword vault: ").strip()
            if not new_pass.isalnum(): #checks if the entered username has spaces, or symbols or is a null input, which would be rejected and the program will loop back
                print("Your password for the website/app cannot be null, contain spaces or contain symbols \n")            
            elif len(new_pass) < 8: #the password must be at least 8 characters long to be accepted as valid
                print("Your new password must be at least 8 characters long: ")
            elif len(new_pass) > 20: #the password must not exceed 20 characters, otherwise it would be rejected and will loop back
                print("Your new password cannot be over 20 characters long: ")   
            else:
                validnewpass = False 
                passvault.append(new_pass) 

        validquit = True 
        while validquit:
            quit = input("\nDo you want to enter more websites/apps and passwords? Enter 'end' to exit or any key to continue to add more website/app names and passwords for them: \n> ")
            if quit in ["end", "End", "END"]: 
                return
            else:
                validquit = False 
                addapp() 
            return addapp        

def summary(): #The summary function is a print statement of how many password have been stored, the passwords with the longest or shortest characters are also displayed
    if len(passvault) > 0: #The user must have entered at least 1 password before the summary option can be viewed
            print("----------------------------------------------------------------------")
            print("Here is a summary of the passwords stored in the password vault:\n")
            print("The number of passwords stored so far:", len(passvault)) #len counts the amount of passwords stored in the passvault list
            print("Passwords with the longest characters: ", max(new_pass for (new_pass) in passvault)) #max finds the passwords appended in the passvault list with the longest password
            print("Passwords with the shortest charactrs: ", min(new_pass for (new_pass) in passvault)) #min finds the passwords appended in the passvault list with the shortet password
            print("----------------------------------------------------------------------")
    else:
        print("You have no passwords entered yet!")     

#Main routine
print("Welcome user to the password vault program")
print("In this program you will be able to store your usernames and passwords in password vaults and view them later on.\n")
validintro = False 
while not validintro:
    name = input(str("Greetings user, what is your name?: ")).lower().strip()
    if not re.match("^[a-z]*$", name):
        print("Your name must only contain letters from a-z: ")
    elif len(name) < 1: 
        print("Please enter a name that is valid: ")
    elif len(name) > 30:
        print("Please enter a name with no more than 30 characters long: ")
    else:
        validintro = True 
        print("Welcome to the password vault program {}.\n".format(name))

#The main program to run in a while loop for the program to keep on going back to the menu part of the program for more input till the user wants the program to stop
validintro = False 
while not validintro: 
        chosen_option = menu() 
        validintro = False

        if chosen_option in ["a", "A"]: 
            validintro = not login(username, password)

        elif chosen_option in ["b", "B"]: 
            register() 

        else:
            print("""That was not a valid option, please try again:\n """) 
            validintro = False