samedi 31 août 2019

How to make conditions that depends on one statement

So I got this homework to build a contactor for a class Date, check whether the data is valid, and in my checks, I should consider the possibility of a leap year. so I got the variable IsValidInJan:

 boolean IsValidInJan = month != 8 || 
 (year % 4 == 0 && year % 100 != 0 &&  year % 400 == 0);

and then I have an if statement that checks out whether the data is invalid (note that the body of the if statement should be activated if the data is invalid, and not the other way around)

if(year > current_year || (daysByMonth[month] < day && !IsValidInJan)|| day < 0 )

ignore the most of it. the thing is that inside the brackets (at the middel of the if stament) i want the following condtional logic:

if !IsValidInJan is true, then the whole stament is true (only inside the brackets)

if !IsValidInJan is false, then check if daysByMonth[month] < day is true or not and take that as the result (only inside the brackets)

I don't want to separate it to smaller if statement.

How can I achieve such logic?

Function return value not correct

I have written this piece of code for separating names which I need to remove or retain.

  • input.txt --> Input file containing the names
  • retain.txt --> Predefiled list of names which should not go in output.txt
  • output.txt --> txt file the code is creating after checking names of input.txt against retain.txt

It should set value of variable Text to R if name in input.txt do not match with the name in retain.txt and it should be set to A if they match. But when I execute it, I am always getting return value of function as R and thus all the groups go to output.txt which is wrong

@echo off
cls

::Picking group names from file
for /f "Delims=," %%a in (input.txt) do (

::Calling Inner loop to validate against retaining groups
CALL :InnerLoop Text

ECHO ReturnVal from Function: %Text%

if %Text%==R (
echo %%a >> output.txt
)
ECHO END
)
exit /B 0

:InnerLoop
for /f "Delims=," %%g in (retain.txt) do (
echo This combo is %%a and %%g

if not %%a==%%g (
set TEXT1=R
Echo Remove
) else (
set TEXT1=A
Echo Retain
echo TEXT1 is is %TEXT1%
set %~1=%TEXT1%
exit /B 0
)

)
echo TEXT1 is %TEXT1%
set %~1=%TEXT1%

Ironman is present in input.txt as well as retain.txt, so ideally it should not get written in output.txt

Why isn't this "if" comparing until "n" reaches a greater value than estimated?

This if is not working as intended, it should "reset" the variable "n" to 0, when it reaches 3, but instead, it does that until 5.

I tried to print "n" without the if and it is giving the values I want.

0 1 2 3 4 5 6 8 9

But when comparing them, it is like I stated that 5 should be the "cap" to compare the actual value of "n".

    for (int i = 0; i < size //4 for the sake of the example; i++){

        if (n //value 0 == aux2 //4-1 = 3) {
            n = 0;
        }

        x = 0;
        y = i;


        for (int j = 0; j <= i; j++) {
            System.out.println(aux+" "+n);
            x++;
            y--;
            n++;
            aux++;

        }

        if (aux //also 0 at the beginning == aux2) {
            m++ //also 0 at the beginning;
            aux=0;
        }
    }

Excpected output: 0 1 2 3 0 1 2 3 0 1 Given output: 0 1 2 3 4 5 0 1 2 3

error for - if : The results are not as expected

I don't get the values that I should get - You can see here: https://stackblitz.com/edit/angular-nhvnwz

countStateStudents(){
  for (let student of this.students){
if (student.state == 1){
  this.signedup++;
} else
if (student.state == 2){
  this.boughtPIN++;
} else
if (student.state == 3){
  this.enrolled++;
} else
if (student.state == 4){
  this.notinterested++;
}
 }

How to change python code for creating arrays over a range combined with if/else statements to C?

I have code previously done in python that I need to redo in C but im not sure how exactly to go about it. First section is the python code I need to convert to C. Second section is what I have already re-written in C. Third contains the entire original python code if needed.

Has to use a for loop.

for i in range (12):
    x = (int(input("Enter site 3 monthly expenditure: ")))
    site_month.append (x)
    if x < int(monthly_target):
        print ("This site is Under the organization’s monthly target!")
        target.append ("Under")
    elif x == int(monthly_target):
        print ("This site is Exactly the organization’s monthly target!")
        target.append ("Exactly")
    else:
        print ("This site is Over the organization's monthly target!" )
        target.append ("Over!")

#include <stdio.h>
int main()


{
    int annual_target = 35500;
    int monthly_target = (annual_target/12);
    int expenditure_month [12];
    int loop;
    char *month[12];
    month[0] = "January";
    month[1] = "February";
    month[2] = "March";
    month[3] = "April";
    month[4] = "May";
    month[5] = "June";
    month[6] = "July";
    month[7] = "August";
    month[8] = "September";
    month[9] = "October";
    month[10] = "November";
    month[11] = "December";

    char target [12] ={};

   for(loop = 0; loop < 12; loop++)
      printf("%s %d %s  \n", month[loop]);}

#annual expediture target
annual_target = 35500
#monthly expenditure target found by dividing the annual target
monthly_target = (annual_target/12)
print ("Monthly Expenditure Target: ", monthly_target)

#creates an array to hold the monthly expenditures
site_month = []
#creates an array for the 12 months entered represented by numbers using y as a base entry of zero before the first entry is input
month = []
y=0
#creates an array based on how the entered expenditure compares to the monthly target.
target = []

#for loop that continues asking for monthly expenditures till all 12 month slots are filled and uses an if/else statement
#depending on how the entered expenditure compares to the given target expenditure
for i in range (12):
    x = (int(input("Enter site 3 monthly expenditure: ")))
    site_month.append (x)
    if x < int(monthly_target):
        print ("This site is Under the organization’s monthly target!")
        target.append ("Under")
    elif x == int(monthly_target):
        print ("This site is Exactly the organization’s monthly target!")
        target.append ("Exactly")
    else:
        print ("This site is Over the organization's monthly target!" )
        target.append ("Over!")
#uses for loop to print individual cells of 3 different arrays in a 3 column format   
for a,b,c in zip(month, site_month, target):
     print (a, b, c)

how to stop if methode in animation timer [on hold]

How can i stop the if methode in animation timer after a few seconds? the if should start when p is at ten, but not stop when p is not ten anymore. it should stop after a period of seconds

          new AnimationTimer() {


                public void handle(long currentNanoTime) {

                    brick1.move();
                    brick2.move();
                    k.move();

                    if (p == 10) {
                        k2.move();
                    }

Google sheet formula to swap names

I have this:

enter image description here

Image shows that those 2 cells contain input from another sheet.

Now, I want to input formula in those same cells that will rename inputs:

=if(D5="jerry.berry", "Berry Jerry", if(D5="perkins.aaron", "Aaron Perkins"))

Question: How do I insert the above formula next to =Source!H5

Note: I know I can modify those values on the root sheet itself, but I would rather not.

How do I nest an if statement within a function

I would like to nest a conditional if statement within a function, but I am not sure what the correct syntax is. Right now I have:

def answer_one()

  x=dataframe
  perRenew = x['% Renewable'].mean()
  x['Highrenew'] = 0

    if x['% Renewable'] >= perRenew :
       x['Highrenew'] = 1
    else:
       x['Highrenew'] = 0

  return x

But when I run the code I get ValueError: The truth value of a Series is ambiguous

What are some correct ways/ best practices to get the job done?

Excel - How to organize complex data according to time with IF condition?

I have a spreadsheet contains students information and their choices for classes for new semester. the spreadsheet contains Timestamp column, student name column and 9 columns (first choice - ninth choice) under each column student choose one unique class from (A1,A2,A3,B1,B2,B3,C1,C2,C3) as shown in picture below.

example

Each class ( A1 : C3 ) has 10 places. i need to fetch the first 10 students for each class according to time and available places. For example if the student no. 15 choose in first choice A1 and A1 is completed then excel directly look at the second choice(B1) if it is available so it add to B1 and look for the next student or if it is not available so excel look for the third choice and so on.

Is it possible to apply this idea using conditional formatting or using IF condition?

I tried conditional formatting and find duplicate but it was incorrect.

Batch error "( unexpected" if statement nested inside for loop

I wrote this small script to kill Spotify whenever the title of the window is "Advertisement". For now, it just looks for the spotify.exe process and, if the name of the window matches, kills it (next step is executing it every second). However, I get an error every time I execute it, telling me that there's an unexpected ( in IF /i "%A:~0,4" (, but such statement is not in my code: it seems like Windows modifies IF /i "%%A:~0,4%"=="PID:" ( before executing it.

Here's the script:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

tasklist /fi "imagename eq spotify.exe" /fo list /v > tmp.txt

FOR /F "usebackq tokens=*" %%A IN ("tmp.txt") DO (
  SET test=%%A
  echo %%A
  IF /i "%%A:~0,4%"=="PID:" (
    SET "pid=%%A:PID:          =%"
    echo %pid%
  )
  IF /i "%%A:~0,13%"=="Window Title:" (
    SET "wintitle=%%A:Window Title: =%"
    echo %wintitle%
  )
  IF "%wintitle%"=="Advertisement" (
    taskkill /F /PID %pid%
  )
)

PAUSE

Error message (with echo on):

C:\Users\marco\Desktop>antispotify.bat

C:\Users\marco\Desktop>tasklist /fi "imagename eq spotify.exe" /fo list /v  1>tmp.txt
( was unexpected at this time.
C:\Users\marco\Desktop>  IF /i "%A:~0,4" (

Does anyone know what's wrong with my code?

'Else' is an unexpected token in my Java code and the error I'm getting is that of an illegal type at line 18. What is wrong with my code?

I'm very new to Java and only started it yesterday, this is an exercise for my class and the code has to be similar to this one. I'm trying to create a simple log-in system in Java. This is the error I am getting: Error:(18, 11) java: illegal start of type

I've had a friend with similar code and it worked for him and he cannot specify why mine is not working.

I tried removing the curly brackets. I tried making different if statements and I tried putting round brackets around read.nextLine();

System.out.print("Type your username: ");
        String username = reader.nextLine();
        System.out.print("Type your password: ");
        String password = reader.nextLine();

        if (username = "Alex" && password = "mightyducks") {
            System.out.print("You are now logged into the system!");
        } else if (username = "Emily" && password = "cat")
            System.out.print("You are now logged into the system!");
        } else {
        System.out.print("Your username or password was invalid!");
        }

I simply want the program to show "You are now logged into the system!" when the correct password is given for Alex or Emily and for it to otherwise state: "Your username or password was invalid!".

VBA: Sort unique values under conditions (Working between different sheets)

I have a workbook with the following two Sheets. In Sheet1 there is the data.

| Order |     Date | Status | Country |
|-------|---------:|-------:|---------|
| 78    | 19-04-19 | OK     | FR      |
| 33    | 19-04-19 | OK     | GB      |
| 198   | 19-04-19 | CL     | GB      |
| 43    | 19-04-19 | CL     | CH      |
| 29    | 19-04-19 | CL     | CN      |
| 12    | 20-04-19 | CL     | GB      |
| 169   | 20-04-19 | OK     | GB      |
| 95    | 20-04-19 | OK     | GB      |
| 54    | 20-04-19 | OK     | FR      |
| 31    | 20-04-19 | OK     | GB      |

What I am trying to achieve is to sort 'Country' unique values under the condition that Status=OK. So far, with a bit of help I have managed to write the code for the case that there is no condition.

Sub SortUniqueValues1()

Dim i As Variant
Dim j As Variant

With Sheets("Sheet1")
j = Application.Transpose(.Range("H2", .Range("H" & Rows.Count).End(xlUp)))
End With

    With CreateObject("Scripting.Dictionary")
        For Each i In j
            .Item(i) = i
        Next
     Cells(3, 1).Resize(.Count) = Application.Transpose(.Keys)
    End With

Range("A3:M100000").Sort Key1:=Range("A3"), Order1:=xlAscending, Header:=xlNo

End Sub

I am trying to find out the following:

  1. How can I integrate into the code the Status Condition?
  2. Is there any way to create some sort of dropdown menu that will turn on/off conditions?
  3. How can I convert A3:M100000 to A3 until the last value in column M?

Thank you in advance!

Select option still appears on the page even after PHP IF.. statement

I'm developing an Online Store with PHP, so at the productdetails.php which shows the details of products, I coded this:

if(!empty($pro_colors))
{
echo "
    <div class=''>
        <h4 class='' style='float:right'>&nbsp;:رنگ <span>*</span></h4>
        <select class='select-css'>      
        ";
        foreach($pro_colors as $colors)
        {
            echo "
                <option value='$colors'>$colors</option>
            ";                                          
        }
        echo "
        </select>
    </div></br>
";
}

So simply what it should do is that, if any color has been added to the product at db, it has to show the select option and if no color has been added to the db, the select option must not appear!

But when there is not data on db as color, it shows this:

print screen

However, my table looks like this:

print screen 2

So please tell me, how should I solve this problem ?!

Excel - How can IF function return multiple values in different cells?

This is what I want: If A1 = "Red", return "yes" in the current cell and "good" in A3. And I don't want any code in A3.

Is it possible to return any one conditional that are true out of multiple ones (in a simple way)?

This has likely already been answered multiple times, but I am unable to find any good answers. I'm probably not searching for the right things..

I have a number of checkboxes that return "on" or "off".

req.query returns these checkboxes.

If they are "on" I would like to push that particular key/val pair to an array for later to be used in a query in mongoDB. I know I can use Object.entries(req.query)to loop through them, but I just want to know if there might be another way like the example below.

let checkboxCol = [];
if (checkboxa, checkboxb, checkboxc, checkboxd) {
    checkboxCol.push(/* any checkbox that is "on" */);
}

vendredi 30 août 2019

Else if statement not functioning properly

I was solving the balanced parentheses problem using stack implementation when I came across this situation wherein I was using the 'else-if' statements to check for the closing braces but this gave a different output than the expected one. On changing all the 'else-if' statements to plain 'if' statements the code worked just fine. I want to know why this happened because I always thought that using 'else-if' statements was a better practice.

int main(){
    stack<char> bracks;
    string s;   // input string: {a+(b+c-[e-f])*d}
    cin >> s;
    for(int i = 0; i < s.size(); i++){
        if(s[i] == '{' || s[i] == '(' || s[i] == '[')    bracks.push(s[i]);
        else if(s[i] == '}')
            if(bracks.top() == '{')    bracks.pop();
        else if(s[i] == ')')
            if(bracks.top() == '(')    bracks.pop();
        else if(s[i] == ']')
            if(bracks.top() == '[')    bracks.pop();
    }
    if(bracks.empty())  cout << "Balanced\n";
    else    cout << "Unbalanced\n";
}

Expected output for the input string : "{a+(b+c-[e-f])*d}" is "Balanced" but I'm getting "Unbalanced" as the output.

Check other duplicate entry(ies) upon edit but disregard a duplicate in current form

I'm kind of new to PDO, and I'm struggling about checking duplicate(s) in the database while I'm on editing form.

The current scenario is:

  • The input field is a phone number
  • Upon insert it is being checked if it already exist in the db
  • Upon edit it is being checked again if the edit got a match in the db
  • I can't just forbid the editing in the phone number once it is
    added because what if in the future it needs to be change
  • After the user hit the edit button all data is being fetch and being echoed to its respective fields therefore the user will know that field has that kind of information already or that field is still empty

The problem occurs when the user is just editing other fields like "an update for a change in PIN", the phone number field got checked again and obviously it will return an error saying "it already exist".

How can i ignore that field entry if it's not changed?

here is the part of code for edit.php

if(isset($_POST['Edith_SIM'])) {
$id = $_POST['id'];
$s_num = $_POST['sim_num'];
$s_esn = $_POST['sim_esn'];
$s_net = $_POST['sim_net'];
$s_pn1 = $_POST['simpn1'];
$s_pn2 = $_POST['simpn2'];
$s_pk1 = $_POST['simpk1'];
$s_pk2 = $_POST['simpk2'];
$s_fea = $_POST['sim_feat'];
$s_typ = $_POST['sim_type'];
$s_acq = $_POST['d_acq'];
$s_afo = $_POST['acq_for'];
$s_ufr = $_POST['d_uf'];
$s_uto = $_POST['d_ut'];
$s_dev = $_POST['use_dev'];
$s_sta = $_POST['sim_stat'];
$s_not = $_POST['sim_notes'];

$chekDuplicate = $dbConn->prepare('SELECT * FROM tst_sims WHERE SIM_num= :sim_num');
    $chekDuplicate->execute(array(':sim_num' => $s_num));

// checking empty fields
if(empty($s_num)) {                
    echo "<font color='red'>Must have SIM number my dudes</font><br/>";
    echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";
} elseif($chekDuplicate->rowCount() > 0) {
    echo "<font color='red'>Its existing my dudes</font><br/>";
    echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";
} else { 
    $sim_passed_e = "UPDATE tst_sims SET 
    SIM_num = :sim_num,
    SIM_network =:sim_net,
    SIM_PIN1 =:simpn1,
    SIM_PIN2 =:simpn2,
    SIM_PUK1 =:simpk1,
    SIM_PUK2 =:simpk2,
    SIM_features =:sim_feat,
    SIM_type =:sim_type,
    Acquired =:d_acq,
    Acquired_for =:acq_for,
    Used_from =:d_uf,
    Used_to =:d_ut,
    Used_devices =:use_dev,
    Status =:sim_stat,
    Notes =:sim_notes
    WHERE Ent_id =:id";

$que_edit = $dbConn->prepare($sim_passed_e); 

            $que_edit->bindparam(':id', $id);
            $que_edit->bindparam(':sim_num', $s_num);
            $que_edit->bindparam(':sim_esn', $s_esn);
            $que_edit->bindparam(':sim_net', $s_net);
            $que_edit->bindparam(':simpn1', $s_pn1);
            $que_edit->bindparam(':simpn2', $s_pn2);
            $que_edit->bindparam(':simpk1', $s_pk1);
            $que_edit->bindparam(':simpk2', $s_pk2);
            $que_edit->bindparam(':sim_feat', $s_fea);
            $que_edit->bindparam(':sim_type', $s_typ);
            $que_edit->bindparam(':d_acq', $s_acq);
            $que_edit->bindparam(':acq_for', $s_afo);
            $que_edit->bindparam(':d_uf', $s_ufr);
            $que_edit->bindparam(':d_ut', $s_uto);
            $que_edit->bindparam(':use_dev', $s_dev);
            $que_edit->bindparam(':sim_stat', $s_sta);
            $que_edit->bindparam(':sim_notes', $s_not);
            $que_edit->execute();

    header("location: index.php");
    echo "<font color='green'>Data added successfully my dudes.";
    echo "<br/><a href='index.php'>View Result</a>";
}
}

I hope this is not that confusing to all of you, I don't know what kind of approach I should make to this.

Thank you in advance

MediaPlayer - play sound ONLY ONCE by if statement

I'm trying to play a sound ONLY ONCE when the device is leaned in the X axis (horizontally).

Currently the sound loops when leaned in X axis.

I've tried setLooping(false), but I think the problem is that the if-statement which initiates the sound keeps updating after mediaPlayer has already started. So even if it's not looping, it's running mediaPlayer.start over and over.

   mediaPlayer = MediaPlayer.create(this, R.raw.sound);
   mediaPlayer.setLooping(false);

// phone is leaned towards the X value

            if (event.values[0] > event.values[1] && event.values[0] > event.values[2]) {
                mediaPlayer.start();
            }

How do I make the sound play only once and then wait until "if (event.value..." is triggered again before playing the sound again?

Note: I'm new to coding so I apologise for any dumb mistakes. Thanks in advance for any help.

Should I use loops or stick with nested if statements?

I am new at programming. I am using python. I am making a program that will compare different interest rates for saving accounts in my country (Paraguay). Since some of the calculations are similar in the banks, but some differ, I'd like to know how to better structure the code so that it won't repeat. Should I just keep using if statements? Is there a way to do it with loops? How should I think about it? The code I add below is just for one bank. If I wanted to add another one, how should I proceed? My natural inclination would just keep doing if statements :)

PD: If There is also any feedback on my code will be appreciated. Or some resources that you think would help me at this stage. Please be kind, I am still very insecure about all this haha.

def ahorro_cda_nominal_anual (ahorro_inicial, tiempo_en_dias, moneda):

if moneda == 'dolares':
    if ahorro_inicial>= 5000: 

        if 0 < tiempo_en_dias < 90:
            dMin = 0.05
            dMax = 0.05

        if 90 <= tiempo_en_dias < 180: 
            dMin = 0.15
            dMAx = 0.75

        if 180 <= tiempo_en_dias < 365:
            dMin = 0.25
            dMax = 1.25

        if 365 <= tiempo_en_dias:
            dMin = 1.25
            dMax = 2.00
        monto_final_min = ahorro_inicial * tiempo_en_dias*dMin/365 + ahorro_inicial
        monto_final_max = ahorro_inicial * tiempo_en_dias *dMax/365 + ahorro_inicial
        print ("Obtendrias minimamente " + str(round(monto_final_min/1000,3)) + " mil dolares.")
        print ("Hasta un valor maximo de " + str(round(monto_final_max/1000,3)) + " mil dolares.")
        return (monto_final_min, monto_final_max)

    else:
        print ("El valor minimo es de 5000 dolares. Necesitas " + str(5000 - ahorro_inicial) + " dolares mas.")

elif moneda == 'guaranies':
    if ahorro_inicial >= 5000000:

        if 0 < tiempo_en_dias < 90:
            gMin = 0.25
            gMax = 2.5

        if 90 <= tiempo_en_dias < 180: 
            gMin = 0.75
            gMax = 2.5

        if 180 <= tiempo_en_dias < 365:
            gMin = 1.0
            gMax = 4.5

        if 365 <= tiempo_en_dias:
            gMin = 1.5
            gMax = 5.5

        monto_final_min = ahorro_inicial * tiempo_en_dias*gMin/365 + ahorro_inicial
        monto_final_max = ahorro_inicial * tiempo_en_dias *gMax/365 + ahorro_inicial
        print ("Obtendras minimamente " + str(round(monto_final_min/1000000,1)) + " milllones de guaranies.")
        print ("Y a lo sumo " + str(round(monto_final_max/1000000,1)) + " millones de guaranies.")
        return (monto_final_min, monto_final_max)

    else:
        print ("El monto minimo es 5 millones de guaranies. Necesitas " + str(5000000 - ahorro_inicial) + " guaranies mas.")
else:
    print ("Solo aceptamos guaranies o dolares.")

ahorro_cda_nominal_anual (50000000, 180,'guaranies')

UnboundLocalError: local variable 'y' referenced before assignment in Pandas

I am trying to apply one funtion to a column but i am getting the error

Name    weight
Person1 30
Person2 70

My code is below

def classify(x):
    if 0 <= x < 20:
        y = "0 to 20%"
    if 20 < x < 40:
        y = "20 to 40%"
    if 40 < x < 60:
        y = "40 to 60%"
    if 60 < x < 80:
        y = "60 to 80%"
    if 80 < x <= 100:
        y = "80 to 100%"
    return ( y)

df['Target'] = df['weight'].apply(lambda x: classify(x)) throwing the Local bound error

If I use print instead of return I am able to see the outputs

Expected out

    Name    weight  Target
    Person1     30  20 to 40
    Person2     70  60 to 80

How to avoid repetitive code intensive if statements in java

I am currently working on a text based RPG and am still learning java and programming in general. My question is this, I have come to a point in my program where the user will select their units and I dont know how to accomplish this without large if statements that are very restrictive in terms of expanding or altering the game play. How could I write something that could condense my if statements and have a more modular approve overall?

Here is what the user first see:

Welcome to RPG Game!

Please select 3 units!

Enter 1 to add a Ranger 100 4 10

Enter 2 to add a Heavy 100 4 15

enter 3 to add a Medic 100 4 10

To respond to this I have codded the following

if (resp == 1){
      if (rangerCount == 0){
      ArrayList<Item> rangerInv0 = new ArrayList<Item>();    
      Ranger rangerObj0 = new Ranger("Ranger", 100, 4, 10, rangerInv0);

      rangerObj0.pickUp(mh1000);
      rangerObj0.pickUp(s1000);
      rangerObj0.pickUp(t1000);

      rangerObj0.equip(mh1000);
      rangerObj0.equip(s1000);
      rangerObj0.equip(t1000);

      playerUnits.add(rangerObj0);
      playerUnitsCount++;
      rangerCount++;
      }
      else if (rangerCount == 1){
      ArrayList<Item> rangerInv1 = new ArrayList<Item>();    
      Ranger rangerObj1 = new Ranger("Ranger", 100, 4, 10, rangerInv1);

      rangerObj1.pickUp(mh1000);
      rangerObj1.pickUp(s1000);
      rangerObj1.pickUp(t1000);

      rangerObj1.equip(mh1000);
      rangerObj1.equip(s1000);
      rangerObj1.equip(t1000);

      playerUnits.add(rangerObj1);
      playerUnitsCount++;
      rangerCount++;
      }
      else if (rangerCount == 2){
      ArrayList<Item> rangerInv2 = new ArrayList<Item>();    
      Ranger rangerObj2 = new Ranger("Ranger", 100, 4, 10, rangerInv2);

      rangerObj2.pickUp(mh1000);
      rangerObj2.pickUp(s1000);
      rangerObj2.pickUp(t1000);

      rangerObj2.equip(mh1000);
      rangerObj2.equip(s1000);
      rangerObj2.equip(t1000);

      playerUnits.add(rangerObj2);
      playerUnitsCount++;
      rangerCount++;
      }
    } 
    else if (resp == 2) {
      if (heavyCount == 0) {
      ArrayList<Item> heavyInv0 = new ArrayList<Item>();    
      Heavy heavyObj0 = new Heavy("Heavy", 100, 4, 15, heavyInv0);

      heavyObj0.pickUp(mh4000);
      heavyObj0.pickUp(s1000);
      heavyObj0.pickUp(t1000);

      heavyObj0.equip(mh4000);
      heavyObj0.equip(s1000);
      heavyObj0.equip(t1000);

      playerUnits.add(heavyObj0);
      playerUnitsCount++;
      heavyCount++;
      }
      else if (heavyCount == 1){
      ArrayList<Item> heavyInv1 = new ArrayList<Item>();    
      Heavy heavyObj1 = new Heavy("Heavy", 100, 4, 15, heavyInv1);

      heavyObj1.pickUp(mh4000);
      heavyObj1.pickUp(s1000);
      heavyObj1.pickUp(t1000);

      heavyObj1.equip(mh4000);
      heavyObj1.equip(s1000);
      heavyObj1.equip(t1000);

      playerUnits.add(heavyObj1);
      playerUnitsCount++;
      heavyCount++;
      }
      else if (heavyCount == 2){
      ArrayList<Item> heavyInv2 = new ArrayList<Item>();    
      Heavy heavyObj2 = new Heavy("Heavy", 100, 4, 15, heavyInv2);

      heavyObj2.pickUp(mh4000);
      heavyObj2.pickUp(s1000);
      heavyObj2.pickUp(t1000);

      heavyObj2.equip(mh4000);
      heavyObj2.equip(s1000);
      heavyObj2.equip(t1000);

      playerUnits.add(heavyObj2);
      playerUnitsCount++;
      heavyCount++;
      }
    } 
    else if (resp == 3) {
      if (medicCount == 0) {
      ArrayList<Item> medicInv0 = new ArrayList<Item>();    
      Medic medicObj0 = new Medic("Medic", 100, 4, 10, medicInv0);

      medicObj0.pickUp(mh3000);
      medicObj0.pickUp(s1000);
      medicObj0.pickUp(t1000);

      medicObj0.equip(mh3000);
      medicObj0.equip(s1000);
      medicObj0.equip(t1000);

      playerUnits.add(medicObj0);
      playerUnitsCount++;
      medicCount++;
      }
      else if (medicCount == 1) {
      ArrayList<Item> medicInv1 = new ArrayList<Item>();    
      Medic medicObj1 = new Medic("Medic", 100, 4, 10, medicInv1);

      medicObj1.pickUp(mh3000);
      medicObj1.pickUp(s1000);
      medicObj1.pickUp(t1000);

      medicObj1.equip(mh3000);
      medicObj1.equip(s1000);
      medicObj1.equip(t1000);

      playerUnits.add(medicObj1);
      playerUnitsCount++;
      medicCount++;
      }
      else if (medicCount == 2) {
      ArrayList<Item> medicInv2 = new ArrayList<Item>();    
      Medic medicObj2 = new Medic("Medic", 100, 4, 10, medicInv2);

      medicObj2.pickUp(mh3000);
      medicObj2.pickUp(s1000);
      medicObj2.pickUp(t1000);

      medicObj2.equip(mh3000);
      medicObj2.equip(s1000);
      medicObj2.equip(t1000);

      playerUnits.add(medicObj2);
      playerUnitsCount++;
      medicCount++;
      }
    } 
    else {
      System.out.println("Please enter a valid responce!");
    }

The objects you see referenced in the multiple instances of pickUp() and equip() look like this for reference:

static Item mh1000 = new Item ("AR1", "Damage", 2, null, 0, null, 0, false, false);

to me this all seems very cumbersome. What if I want to make it a game with 5 units or 10 units, do I really have to add 2 to 7 lines of code per entry to accomplish this? it seems like there should be a much easier way to do this. Please advise.

Is there a reason for an if statement followed by another to end the line with an 'and' operator (&&) in ruby?

I'm trying to figure out why this works and whether it's a bad practice.

The following code will throw a SyntaxError:

if true &&
  puts "ok"
end

Though the following code will not, it will execute as expected:

if true &&
  if true
    puts "ok"
  end
end

I came across this while writing a ruby script with an if statement containing a big chain of conditions, so I put each one in a separate line and then I commented out the last one and executed the script. At the moment, I realized that the if statement ended with the && operator. While I expected it to throw, I was amazed that it didn't because another if statement followed right after.

My ruby version is ruby 2.2.6p396 (2016-11-15 revision 56800) [x86_64-darwin16].

Changing column colors based on conditions in HTML table

I am trying to send email using bash script in a HTML format.

The column names are below

Portfolio
account_number
critical
distinct_file_name_count
total_file_count
Files_validation

AWK command used to populate the .HTML file

awk -F"#" '
    BEGIN {
        print "<html><head>\
            <style>\
                body {\
                    background-color: #FFF;text-align:left;\
                    }\
                        table {\
                            font-family:Tahoma;\
                            font-size:11;\
                            border-collapse:collapse;\
                            border: 4px solid #dddddd;\
                        }\
                        th { padding:10px;\
                            background-color: #94E1F7;\
                        }\
                            th { border: 1px solid black;\ 
                        }\
                        td {\
                            padding:3px;\
                            border: 2px solid black;\
                            text-align:right;\
                        }\
                            </style>\
                        </head>\
                        <body>\
                            <table>\
                                <tr>\
                                    <th>Portfolio</th> 
                                    <th>account_number</th> 
                                    <th>critical</th> 
                                    <th>distinct_file_name_count</th> 
                                    <th>total_file_count</th> 
                                    <th>Files_validation</th> 
                                </tr>" 
} 
{ 
    print "<tr>" 
    printf "<td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td>",$1,$2,$3,$4,$5 
    for (i = 6; i < 7; i++) { 
        if ($i == "Files_not_received_today") { 
            printf "<td bgcolor=#FF0000>%s</td>",$i 
        } else { 
            printf "<td bgcolor=#32CD32>%s</td>",$i 
        }
    } print "</tr>" 
} END { 
    print "</table></body></html>"
}' ${run_project_tmp_dir}/QC_VALIDATION_REPORT.txt >> ${run_project_tmp_dir}/QC_VALIDATION_REPORT.html

Condition I want to make the change is that

1) When column when `Files_validation` column is having `Files_not_received_today` then check if `critical` column is `YES`. 

If `YES` then Populate `RED` color in both `Files_validation` and `critical`. Else if  when `Files_validation` column is having `Files_not_received_today` then check if `critical` column is `NO` then Populate `AMBER` color in both `Files_validation` and `critical`.

2)  when `Files_validation` column is having other than `Files_not_received_today` Populate `GREEN` color in `Files_validation`

With the above awk command I am able to populate the Files_validation with RED and GREEN colors based on my expectations but unable to achieve my desired result of the conditions mentioned

IF function to calculate duration (Hours:Minutes:Seconds)

I use Importxml to extract the clock from a website that tells the date and time that the market will close ... Well, using the Now () function, I calculate the imported clock minus the current time. I converted the cell with the result of the calculation to the duration format (This way I see how much time is left for the market to close).

=importxml("https://cartolafcmix.com/","//div[@class='content']/span/@data-timer")


=NOW()


=A1-A2 (Duration Formatted Cell)

I am trying to use the IF function so that if it is more than 22:00:00 and less than 23:00:00, the cell gets written (Alert 22 hours)

=IF(AND($A$3>"22:00:00",$A$3<"23:00:00"),"Alert 22 Hours","Error")

At the moment are missing 22:18:25 for the market to close, but the result of the formula is giving "error", I do not know what I may be wrong.

How do I get the count of non matching cells in a row between two sheets?

I have two sheets, Sheet A containing a truth table like such:

    A B C D E
Foo T F F T F
Bar T F F F F

Sheet B contains another table:

A B C D E
T F F T F

I need to add a column to table A counting how many cells match the corresponding cell in sheet B, as such:

Foo T F F T F 2
Bar T F F F F 1

Best I could come up with for the first count cell was

=COUNTIF(B1:F1,B1:F1=INDIRECT("sheet-b!A2:E2"))

but this gives me 0 even though it should be 2.

Clipboard.clear with timer with 2 different times does not work C#

I'm making a clipboard application where my program must be able to paste both questions from my list and my sums. Now I want that if I copy a sum that the result can be pasted for 10 seconds. And that my question from my list can only be pasted for 1 second. At the moment it only works with the questions from my list. That timer for that is called DeleteQuestionTimer. now wants another timer with the nameSumDeleteCopyTimer that ensures that the result of the sum that can be pasted into this piece of code for 10 seconds

clipboardText = clipboardText.Replace(',', '.');
            //de regex voor de operator
            var regex = new Regex(@"^(?<lhs>\d+(?:[,.]{1}\d)*)[ ]*(?<operator>[+\-\:x\%])[ ]*(?<rhs>\d+(?:[,.]{1}\d)*)$");
            Match match = regex.Match(clipboardText);
            if (!match.Success)
                return; // not valid form (a + b)
                        //de operators
            Dictionary<string, Func<double, double, double>> binaryOperators = new Dictionary<string, Func<double, double, double>>()
            {

               { "+", (a, b) => a + b},
               { "x", (a, b) => a * b },
               { "-", (a, b) => a - b },
               { "%", (a, b) => a / b * 100 },
               { ":", (a, b) => b == 0 ? double.NaN : a / b },
        };
            var lhs = double.Parse(match.Groups["lhs"].Value, CultureInfo.InvariantCulture);
            var rhs = double.Parse(match.Groups["rhs"].Value, CultureInfo.InvariantCulture);
            var answer = binaryOperators[match.Groups["operator"].Value](lhs, rhs);
            System.Windows.Forms.Clipboard.SetText(answer.ToString());
            //Kopieert het resultaat van de som in het clipboard
            //De timer zorgt ervoor dat het resultaat van de som naar x aantal seconde niet meer te plakken is
            // Laat antwoord zien
            ShowNotification(clipboardText, answer.ToString());
        }

so what i want is that the result of the sum can be pasted for 10 seconds and the copied for my questionList can be pasted for 1 second.

This is my full code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;

namespace it
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //Invoke a clipboard monitor
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer);

        private IntPtr _ClipboardViewerNext;

        //Make some global variables so we can access them somewhere else later
        //This will store all Questions and Answers
        //In here will be the Questions and Answers
        List<question> questionList = new List<question>();
        private object result;

        // Demonstrates SetText, ContainsText, and GetText.



        private void Form1_Load(object sender, EventArgs e)
        {
            //Set our application as a clipboard viewer
            _ClipboardViewerNext = SetClipboardViewer(Handle);

            //Add question/answer to list
            question newQuestion = new question("What is the capital of the Netherlands?", "Amsterdam");
            questionList.Add(newQuestion);

        }

        private void GetAnswer(string clipboardText)
        {
            //Loop through all questions and answers//
            foreach (question q in questionList)
            {
                if (q._question.StartsWith(clipboardText) || q._question.EndsWith(clipboardText))
                {
                    ShowNotification(q._question, q._answer);
                    break;
                }
            }
            clipboardText = clipboardText.Replace(',', '.');
            //de regex voor de operator
            var regex = new Regex(@"^(?<lhs>\d+(?:[,.]{1}\d)*)[ ]*(?<operator>[+\-\:x\%])[ ]*(?<rhs>\d+(?:[,.]{1}\d)*)$");
            Match match = regex.Match(clipboardText);
            if (!match.Success)
                return; // not valid form (a + b)
                        //de operators
            Dictionary<string, Func<double, double, double>> binaryOperators = new Dictionary<string, Func<double, double, double>>()
            {

               { "+", (a, b) => a + b},
               { "x", (a, b) => a * b },
               { "-", (a, b) => a - b },
               { "%", (a, b) => a / b * 100 },
               { ":", (a, b) => b == 0 ? double.NaN : a / b },
        };
            var lhs = double.Parse(match.Groups["lhs"].Value, CultureInfo.InvariantCulture);
            var rhs = double.Parse(match.Groups["rhs"].Value, CultureInfo.InvariantCulture);
            var answer = binaryOperators[match.Groups["operator"].Value](lhs, rhs);
            System.Windows.Forms.Clipboard.SetText(answer.ToString());
            //Kopieert het resultaat van de som in het clipboard
            //De timer zorgt ervoor dat het resultaat van de som naar x aantal seconde niet meer te plakken is
            // Laat antwoord zien
            ShowNotification(clipboardText, answer.ToString());
        }

        private void ShowNotification(string question, string answer)
        {
            notifyIcon1.Icon = SystemIcons.Exclamation;
            notifyIcon1.BalloonTipTitle = question;
            notifyIcon1.BalloonTipText = answer;
            notifyIcon1.BalloonTipIcon = ToolTipIcon.Error;
            notifyIcon1.ShowBalloonTip(1000);
        }

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            {
                const int WM_DRAWCLIPBOARD = 0x308;
                if (m.Msg == WM_DRAWCLIPBOARD)
                {
                    // Kopieert en kijkt of het overeen komt met de list
                    DeleteQuestionTimer.Enabled = false;
                    var text = Clipboard.GetText(TextDataFormat.UnicodeText);
                    DeleteQuestionTimer.Interval = 5000;
                    DeleteQuestionTimer.Enabled = true;
                    // als je gekopieert hebt reset de clipboard en als je voor 5 minuten niet kopieert sluit het programma zich af
                    if (!string.IsNullOrEmpty(text))
                    {
                        InteractiveTimer.Enabled = false;
                        GetAnswer(Clipboard.GetText(TextDataFormat.UnicodeText));
                        InteractiveTimer.Interval = 300000; // reset the timer
                        InteractiveTimer.Enabled = true;   // and start it again
                    }
                }
            }
        }
        private void InteractiveTimer_Tick(object sender, EventArgs e)
        {
            this.Close();
        }
        //Deze timer zorgt ervoor dat het programa zich naar x aantal minuten zichzelf sluit

        private void DeleteQuestionTimer_Tick(object sender, EventArgs e)
        {
            DeleteQuestionTimer.Enabled = false;
            Clipboard.Clear();
        }
    }
}

Search for specific words inside one cell and write retrieved searched result in other cell

Need help for following use case:

- I have three columns, one named "Issue", second "Client" and the last one "Tags"

- Columns "Issue" and "Tags" are filled automatically after csv. file import, where each cell of Tags column may contain multiple tags, but none of Tag cells can contain multiple client tags

- Column "Clients" needs to be determined based on "Tags" column, and this is where I suck :(

enter image description here


Basically, I want to insert formula into "Clients" column that will do following:

1) Search for all possible client tags (Client A, Client B, Client C, Client D and Client E) in "Tags" column.

2) Retrieve if client tag is found and write that tag in corresponding cell inside Client column.

Wished output:

enter image description here

In my opinion, formula has to be generic to suits all Client cells, meaning formula in my opinion should contain all clients at once (A,B,C,D,E) and check if one of the client is found and write that client. What is searched and found should be written as it is.

I tried smth like this:

=iferror(if(search({"Client A","Client B", "Client C", "Client D", "Client E"},J7,1)>0,"?????","no client"))

Python: Populate new df column based on if statement condition

I'm trying something new. I want to populate a new df column based on some conditions affecting another column with values.

I have a data frame with two columns (ID,Retailer). I want to populate the Retailer column based on the ids in the ID column. I know how to do this in SQL, using a CASE statement, but how can I go about it in python?

I've had look at this example but it isn't exactly what I'm looking for.

Python : populate a new column with an if/else statement

import pandas as pd

data = {'ID':['112','5898','32','9985','23','577','17','200','156']}

df = pd.DataFrame(data)

df['Retailer']=''

if df['ID'] in (112,32):
    df['Retailer']='Webmania'
elif df['ID'] in (5898):
    df['Retailer']='DataHub'
elif df['ID'] in (9985):
    df['Retailer']='TorrentJunkie'
elif df['ID'] in (23):
    df['Retailer']='Apptronix'
else: df['Retailer']='Other'


print(df)

The output I'm expecting to see would be something along these lines:

     ID Retailer
0   112 Webmania
1  5898 DataHub
2    32 Webmania
3  9985 TorrentJunkie
4    23 Apptronix
5   577 Other
6    17 Other
7   200 Other
8   156 Other


jeudi 29 août 2019

advanced custom fields true/false only works in front-page.?? not in innerpages why?

i have a acf true or false based if condition for to show a section based on the mentioned code. it works correctly in the front page/homepage of the WordPress. but it doesn't works in the inner pages, not getting the values of the field and i use this code in footer templates.

its a WordPress site with latest version. and the code is in the footer template

<?php 
$show_company_info = get_field( "show_company_info", get_the_ID() );
if($show_company_info ): 
?>
<section class="company">
  <div class="container">

      <?php if ( is_active_sidebar( 'company-info-widget' ) ) : ?>
      <?php dynamic_sidebar( 'company-info-widget' ); ?>
      <?php endif; ?>

  </div>
</section>
<?php endif; ?>

if we checked the acf true/fields condition in any page it will show the section otherwise not. but it actually works in homepage only

If elseif .... What am I missing

I want to show a picture depending on the value of a variable i am reading from a sql database. For some reason it shows always the same pic and i dont know why. The values in the datatable are different....

<?php 
if ($Last < $Nr) {
     $position = '<img src="./images/arrowdwn.png" width="15" height="15" />';
   } elseif ($Nr == $Last) {
     $position = '<img src="./images/arrowstay.png" width="15" height="15" />';
   } elseif ($Last > $Nr) {
     $position = '<img src="./images.arrowup.png" width="15" height="15" />';
   } else {
     $position = '<img src="/images/new.png" width="15" height="15" />';
   }
?>

It only shows the first elseif.... The one where $Nr == $Last.....

Getting the wrong result with if else r function with decimal variable [duplicate]

This question already has an answer here:

I am working in r with the following data.frame with aprox 40.000.000 rows:

structure(list(group = c(1003, 1003, 1003, 1003, 1003, 1003, 
1003, 1003, 1003, 1003), t_year = c("2014", "2014", "2014", "2014", 
"2014", "2014", "2014", "2014", "2014", "2014"), tmonth = c(3, 
3, 3, 3, 3, 3, 3, 3, 3, 3), tday = c("02", "02", "02", "02", 
"02", "02", "02", "02", "02", "02"), md = c(2507.416244074, 2507.416244074, 
2507.416244074, 2507.416244074, 2507.416244074, 2507.416244074, 
2507.416244074, 2507.416244074, 2507.416244074, 2507.416244074
), st = c(640722481.20599, 640722481.20599, 640722481.20599, 
640722481.20599, 640722481.20599, 640722481.20599, 640722481.20599, 
640722481.20599, 640722481.20599, 640722481.20599), bsc = c(255530.960493802, 
255530.960493802, 255530.960493802, 255530.960493802, 255530.960493802, 
255530.960493802, 255530.960493802, 255530.960493802, 255530.960493802, 
255530.960493802), animal = c("HOUSA000062901617", "HOUSA000006684687", 
"HO982000202967406", "HOUSA000057341913", "HOUSA000139926709", 
"JEUSA000057281350", "HOUSA000056634042", "XXUSA000056639940", 
"HOUSA000064279445", "HOUSA000066846844"), ln = c(6L, 2L, 1L, 
2L, 4L, 2L, 3L, 2L, 5L, 1L), gluc = c(37892.914163, 100000, 606286.6266, 
303143.3133, 303143.3133, 35355.339059, 37892.914163, 37892.914163, 
214354.69251, 37892.914163), gluc_cat = c(1L, 1L, 6L, 5L, 5L, 
1L, 1L, 1L, 4L, 1L), ol = structure(c(1L, 1L, 2L, 1L, 1L, 1L, 
1L, 1L, 1L, 2L), .Label = c("mult", "prim"), class = "factor"), 
    group_size = c("<2000", "<2000", "<2000", "<2000", "<2000", 
    "<2000", "<2000", "<2000", "<2000", "<2000"), date = structure(c(16131, 
    16131, 16131, 16131, 16131, 16131, 16131, 16131, 16131, 16131
    ), class = "Date"), season = c("Spring", "Spring", "Spring", 
    "Spring", "Spring", "Spring", "Spring", "Spring", "Spring", 
    "Spring")), row.names = c(NA, 10L), class = "data.frame")

I need to create a factor of the variable "bsc" in the data.frame.

I used the ifelse function like bellow:

a <- seq(0:200000)
b <- seq(200000:400000)
c <- seq(400000:8000000)

a <- as.numeric(a)
b <-as.numeric(b)
c <- as.numeric(c)

df$bsc <- as.numeric(df$bsc)

df$bsc_cat <- ifelse(df$bsc %in% a, "Low",
                     ifelse(df$bsc %in% b, "Medium",
                            ifelse(df$bsc %in% c, "High",
                         "N")))

But I am getting only results "N". I imagined that it is happening because the bsc variable have decimal numbers. Because I used the same function to others variables without decimals and it worked well.

How do I fix it?

Unable to break out of While loop

I would like to break out of a loop when it gets to a blank line in a file. The issue is that my regexp's used to condition my data create a line with characters so I need something from the beginning to check if a line is empty or not so I can break out. What am I missing?


#NOTES: chmod this script with chmod 755 to run as regular local user

#This line allows for passing in a source file as an argument to the script (i.e: ./script.sh source_file.txt)
input_file="$1"

#This creates the folder structure used to mount the SMB Share and copy the assets over to the local machines
SOURCE_FILES_ROOT_DIR="${HOME}/operations/source" 
DESTINATION_FILES_ROOT_DIR="${HOME}/operations/copied_files"

#This creates the fileshare mount point and place to copy files over to on the local machine.
 echo "Creating initial folders..."
 mkdir -p "${SOURCE_FILES_ROOT_DIR}"
 mkdir -p "${DESTINATION_FILES_ROOT_DIR}"
 echo "Folders Created! Destination files will be copied to ${DESTINATION_FILES_ROOT_DIR}/SHARE_NAME"


while read -r line; 
  do  
    if [ -n "$line" ]; then 
        continue
    fi      
    line=${line/\\\\///}
    line=${line//\\//}
    line=${line%%\"*\"}
    SERVER_NAME=$(echo "$line" | cut -d / -f 4);
    SHARE_NAME=$(echo "$line" | cut -d / -f 5);
    ASSET_LOC=$(echo "$line" | cut -d / -f 6-);
    SMB_MOUNT_PATH="//$(whoami)@${SERVER_NAME}/${SHARE_NAME}";

     if df -h | grep -q "${SMB_MOUNT_PATH}"; then
       echo "${SHARE_NAME} is already mounted. Copying files..."
     else
       echo "Mounting it"
       mount_smbfs "${SMB_MOUNT_PATH}" "${SOURCE_FILES_ROOT_DIR}"
      fi
   cp -a ${SOURCE_FILES_ROOT_DIR}/${ASSET_LOC} ${DESTINATION_FILES_ROOT_DIR}

  done < $input_file

# cleanup
 hdiutil unmount ${SOURCE_FILES_ROOT_DIR}

exit 0```

Expected result was for the script to realize when it gets to a blank line and then stops. The script works works when i remove the         `if [ -n "$line" ]; then    
            continue
        fi` The script runs and pulls assets but just keeps on going and never breaks out. When I do it as is now I get :
Creating initial folders...
Folders Created! Destination files will be copied to /Users/baguiar/operations/copied_files
Mounting it
mount_smbfs: server connection failed: No route to host
hdiutil: unmount: "/Users/baguiar/operations/source" failed to unmount due to error 16.
hdiutil: unmount failed - Resource busy

In If else branches, what is the preferred approach?

I am writing a validation function, which checks a multitude of conditions and returns Success if none of the checks fail. I want to know, what would be the preferred way among two choices and why ?

private ResponseObj validationFunc1(ObjA objA, ObjB objB, ObjC objC){
ResponseObj responseObj = new ResponseObj();
if(condA){
   responseObj.setStatus("FAILURE");
   responseObj.setMessage("condA message");
   return responseObj;
} else if(condB){
   responseObj.setStatus("FAILURE");
   responseObj.setMessage("condB message");
   return responseObj;
} ....
...
}else if(condZ){
   responseObj.setStatus("FAILURE");
   responseObj.setMessage("condZ message");
   return responseObj;
}
responseObj.setStatus("SUCCESS");
responseObj.setMessage("Valid");
return responseObj;
}


private ResponseObj validationFunc2(ObjA objA, ObjB objB, ObjC objC){
if(condA){
   return new ResponseObj("FAILURE","condA message");
} else if(condB){
   return new ResponseObj("FAILURE","condB message");
} ....
...
}else if(condZ){
   return new ResponseObj("FAILURE","condZ message");
}
return new ResponseObj("SUCCESS","Valid");
}

Which of the above 2 functions would be preferred in production code ? If so, does one method has a performance gain over another ? Or, Am I just mistaken and the compiled code for both the functions will be same ?

Thanks in advance for your answers. If I have asked the same question again, I am very sorry. I did try my best to search for this.

problem creating a code to print maximum between 3 numbers

i wrote a program which takes 3 numbers from the user and prints out the maximum number, but when i run the program it is not taking the numbers from the user correctly

#include <stdio.h>
#include <stdlib.h>

int main()
{
int num1, num2, num3;
printf ("PROGRAM TO FIND THE BIGGEST NUMBER\n");
printf ("\n");

printf ("enter first number : ");
scanf ("%d ",&num1);

printf ("enter second number : ");
scanf ("%d ",&num2);

printf ("enter third number : ");
scanf ("%d ",&num3);

printf("%d - %d - %d \n",num1,num2,num3);


if (num1>num2 && num1>num3){
    printf ("the biggest number is %d",num1);

}
else if  (num2>num1 && num2>num3){
    printf ("the biggest number is %d",num2);
}
else if (num3>num1 && num3>num2){
    printf ("the biggest number is %d",num3);
}


return 0;
}

Use of empty() and "or" in if statement PHP

I'm trying to make an IF statement using the function empty() and a ||. I'm not sure the problem is between the operator and the function, but I don't have any leads on anything else.

Each check in the IF is working individually.

Here is what I want to do, but I have an error :

if(empty($arrayA['somevalue']) || ($x->val1 == 0 && intval($x->valInteger) > 0)){
    $arrayA['somevalue'] = $y;
}

The error :

Fatal error: Uncaught Error: Call to undefined function [path] () in [path]/ProductsImporter.php:648 Stack trace: #0

Line 648 is the IF

I also tried with is_numeric(), but it doesn't change a thing.

My quick fix, which is working fine, but it's so ugly, is this :

if(empty($arrayA['somevalue'])){
    $arrayA['somevalue'] = $y;
} else if ($x->val1 == 0 && intval($x->valInteger) > 0){
    $arrayA['somevalue'] = $y;
}

How to show a simple Message Box in APEX

I'm trying to show a confirmation Message Dialog box in my screen after an IF validation results as true.

PL/SQL Condition.

        IF LV_SOURCE = 'SoS' THEN
:P3600_SHOW_GRIDS := 0;
ELSIF LV_SOURCE ='Bin' THEN
    :P3600_SHOW_GRIDS := -1;
ELSE
    clearInfo;
    :P3600_MESSAGE := LV_ERROR;
END IF;
EXCEPTION
    WHEN OTHERS THEN
        clearInfo;
        :P3600_MESSAGE := REPLACE(SQLERRM, '''', '');
END;

JavaScript condition to show or hide a grid

$(document).ready(function(){
$("#P3600_LOTID").keypress(function(event){
    var k = event.keyCode || event.which;
    if( k == 13 && $(this).val().replace(" ", "") != "" ){
        apex.submit({request:'P3600_LOTID', showWait: true});
        return false;
    }
});

if( $("#P3600_SHOW_GRIDS").val() == "-1" ){
    $("#main_lot .t20RegionBody").append("<a id='apply_btn' href='#' onClick='js_save_changes()' class='t20button' style=''>Update Date Code</a>");
    $("#P3600_CHILD").focus();
}
$("#main_lot .t20RegionBody").append("<a href='#' onClick='apex.submit(\"CLEAR_ALL\");' class='t20button'>Reset Form</a>");

//On Enter for child lot
$("#P3600_CHILD").keypress(function(event){
    if( event.keyCode == 13 && $(this).val().replace(" ", "") != "" ){
        apex.submit({request:'P3600_CHILD', showWait: true});
    }
});

});

I would like to show the message after the PL/SQL condition is evaluated, not in the JS. Any suggestion?

Excel VBA FOR loop with IF statement to match with data in another column and append a seperate column

So I have two columns of name data with the second matching the first only sparingly. I'd like to create an iterator that loops through the first column and the second column simultaneously and, upon finding a match, appends a different column, of the same row, with a specific phrase.

Data looks similar to this

Row 1             Row 2            Row 3

Kyle Hammer                        John Doe
John Doe                           Gary Wilson
Bill Walter
Gary Wilson


I'm pretty new to VBA. Done a lot of javascript but never had to work with excel. I tried the code below but keep getting a run time error 424?

Sub Iterator()
'
' Iterator Macro
'
Set dbsheet2 = ThisWorkbook.Sheets("Sheet1")

lr1 = dbsheet2.Cells(Rows.Count, 1).End(xlUp).Row
lr2 = dbsheet2.Cells(Rows.Count, 4).End(xlUp).Row

For x = 1 To lr1
    act1 = dbsheet2.Cells(x, 1)

    For y = 1 To lr2
        act2 = dbsheet1.Cells(y, 1)

        If act2 = act1 Then
            dbsheet2.Cells(y, 6).Value = "Match"

        Else
            dbsheet2.Cells(y, 6).Value = "Nothing here for me Dawg"
        End If
    Next y
Next x
End Sub


I'm hoping to simply write "match" to column 6 when there is a match between the names in column 1 and 3.

My if-statement won't work when passing in a Scanner value? [duplicate]

This question already has an answer here:

I'm trying to use a Scanner to read an input from the user. The input should be '+', '-', '*' or '/'. For some reason, whenever I try and pass this input into my if-statement, it doesn't read, instead stopping all input, saying my program is no longer running.

I've tried figuring out exactly what the Scanner is being passed, but I can't really find anything suggesting it's not just a string.

import java.util.Scanner;

public class TestIfStatements{

public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter the operation: *, +, -, and /: ");
    if (sc.nextLine() == "+"){
        System.out.println("Hello");
    }
}

}

It should be printing "Hello" on an input of "+" but it's not. Instead, it says my program has stopped running.

Variable in a function stored in global variable

This is a dice game where you get random number when 'rolling' the dice, the point are accumulated until you get 1, then you start again with 0 points (nextPlayer function is called). The challenge was to add if else statement when you roll 6 two times in a row - you start again.

this is the solution: dice is the random number(Internal variable), lastDice is the previous rolled number of points, so that it can be compared. So the previous roll has to be saved in a separate GLOBAL variable.

Why does the lastDice has to be global and why does it retain the previous roll if there's the statement lastDice = dice?

var lastDice

function() {
   if(gamePlaying) { 
     var dice = Math.floor(Math.random() * 6) + 1; 

   IF the rolled nr was NOT = 1, update score

   if (dice === 6 && lastDice === 6){
     scores = 0;
     nextPlayer(); 

   } else if (dice !== 1) {
     roundScore += dice;

   } else {
       nextPlayer();
   }

   lastDice = dice
}

});

How to add an If statement in Google Scripts

I am trying to add an If Statement to my code. The result I want to end up with is similar to this:

If C3:C = 'Y' then clear B3:B

The code below will clear B3:B, but I can't get an If statement to make this script run on the condition of another cell.

function clearData() {
  var sheetActive = SpreadsheetApp.openById("1zzPUsGTIyCBqi1J9HAoFafaxBSOntCit0lfucf8SL78").getSheetByName("Manual Requests");
  sheetActive.getRange('B3:B').clearContent();

Adding an if statement to the for loop code to hide the covers

What I want to do is hide the covers after they are clicked using an if statement placed in the for loop code. If that’s where it would go.

Preventing this from occurring. Image

I attempted to do that here but wasn't able to figure it out.

What am I doing wrong in trying to figure this out?

https://jsfiddle.net/8mg0v6eL/2/

(function manageCover() {
    "use strict";

    function hide(el) {
        el.classList.add("hide");
    }

    /*function coverClickHandler(evt) {
        const cover = evt.currentTarget;
        hide(cover);
    }*/

    function addCoverListener(evt) {
        const cover = evt.target;

        const coversSelector = ".jacket-left, .jacket-middle, .jacket-right";
        const covers = document.querySelectorAll(coversSelector);

        for (let i = 0; i < covers.length; i += 1) {
            /*covers[i].addEventListener("click", coverClickHandler);*/
            if (covers[i] !== evt.target) covers[i].hide(cover);
        }
    }

}());

Excel VBA check multiple checkboxes

I have 2 checkboxes within my Excel sheet; option1 and option2. I am wishing to run a macro to check if option1 is selected, option2 is selected, or neither of them is selected.

Once I have checked if the checkboxes are selected I will then do the following:

  • 'option1' - Dispay message relating to option 1

  • 'option2' - Display message relating to option 2

  • neither selected - display a message that neither was selected

These will then be sent out as an email with the text corresponding to option 1 or option 2.

-

-

Here is an attempt of code I made, but not complete

If Sheet1.CheckBox1.Value = True Then

SEND OPTION1 RELATED CONTENT

    ElseIf
    Sheet1.CheckBox2.Value = True Then

SEND OPTION2 RELATED CONTENT

Else **neither option1 or option2 selected --not sure on this**
    Sub MsgBoxCriticalIcon()
    MsgBox "You must select an option", vbCritical
    End Sub
End If

Here is my working code without my attempts inserted..

Sub Email_VBA()


    Dim OlApp As Object
    Dim NewMail As Object
    Dim TempFilePath As String
    Dim FileExt As String
    Dim TempFileName As String
    Dim FileFullPath As String
    Dim MyWb As Workbook


    Set MyWb = ThisWorkbook

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Save your workbook in your temp folder of your system
    'below code gets the full path of the temporary folder
    'in your system

    TempFilePath = Environ$("temp") & "\"
    'Now get the extension of the file
    'below line will return the extension
    'of the file
    FileExt = "." & LCase(Right(MyWb.Name, Len(MyWb.Name) - InStrRev(MyWb.Name, ".", , 1)))
    'Now append a date and time stamp
    'in your new file

    TempFileName = MyWb.Name & "-" & Format(Now, "dd-mmm-yy h-mm-ss")

    'Complete path of the file where it is saved
    FileFullPath = TempFilePath & TempFileName & FileExt

    'Now save your currect workbook at the above path
    MyWb.SaveCopyAs FileFullPath

    'Now open a new mail

    Set OlApp = CreateObject("Outlook.Application")
    Set NewMail = OlApp.CreateItem(0)




    On Error Resume Next
    With NewMail
        .To = "ashley@hotmail.com"
        .CC = ""
        .BCC = ""
        .Subject = "NEW Type your Subject here"
        .Body = "NEW Type the Body of your mail"
        .Attachments.Add FileFullPath '--- full path of the temp file where it is saved
        .Display   'or use .Display to show you the email before sending it.
    End With
    On Error GoTo 0

    'Since mail has been sent with the attachment
    'Now delete the temp file from the temp folder

    Kill FileFullPath

    'set nothing to the objects created
    Set NewMail = Nothing
    Set OlApp = Nothing

    'Now set the application properties back to true
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With


End Sub

The end result being both checkboxes are checked and a message being sent in Outlook related to the option chosen. Or if neither are chosen the user is prompted to choose an option.

Feel free to ask any questions & thanks for your help

Kind regards

How to get correct if-statement with similar words?

So I have been trying to figure out what I am doing wrong here with my if statement, It is apparently that I have two similar words which is filtered and unfiltered. What I am trying to do is that if a string is filtered, it should grab the values from filtered and vice versa with unfiltered.

I started to use Redis to have a sort of SQL however:

#getRedis.decode("utf-8").lower() --> is a list of ['filteredkeywords', 'unfilteredkeywords']

getInfo = filtered

redis = Redis()

if any(x in getInfo.lower() for x in ['filtered', 'unfiltered']):
    redisURL = redis.redis.keys('*test')
else:
    redisURL = redis.redis.keys('*Orange')

for getRedis in redisURL:

    if any(x in getInfo.lower() for x in getRedis.decode("utf-8").lower()):
        try:
            print('show - {}'.format(getInfo.lower()))
            print('show - {}'.format(getRedis.decode("utf-8").lower()))
            informationValues = json.loads(redis.redis.get(getRedis))
        except:  # noqa
            informationValues = [] 

outprint:

show - filtered
show - unfilteredkeywords

The first if statement of if any(x in getSite.lower() for x in ['filtered', 'unfiltered']): seems to give the correct value of filtered/unfiltered however when we come to the second value which is:

if any(x in getSite.lower() for x in getRedis.decode("utf-8").lower()):

here is what goes wrong. It seems to always locate the value unfiltered even if the getInfo is filtered.

so my question is that how can I possible make a if statement that if getInfo = filtered that means it should grab the value filtered and not the unfiltered one?

Is there a function to check the same value in range?

I am using google sheets and I have a query that if the value in the range is the same then write something. If at least value is other from rest. Can somebody have an idea how to bite this topic?

I was trying to use

=if(A2:C2="Something";"YES";"NO")


=if(A2="Something" AND B2="Something";"YES";"NO")

Is there a way of importing/translating my VBA code into Google Sheets

Google Sheets > MS Excel in Terms of working together

I've just recently found out about Google Sheets. This application seems to handle Problems, i have with MS Excel, pretty well.

I do now have the Problem, that my VBA codes do not Import into Apps Scripts.

While im able to translate some parts of my Code, other parts just aren't as easy as others.

Is someone able to Translate this Piece of my VBA Code into Apps Scripts code?

I would appreciate it.

Worksheets("Example2").Select

Dim zelle As Range

For Each zelle In ActiveSheet.Range("A:A").Cells

If zelle = Worksheets("Example1").Range("A14") Then

zelle.Activate

Exit For

End If

Next

.....

JQuery not closing brackets properly (problem with closing if tag) [on hold]

I am having a hard time understanding why my code isn't working. The brackets are not closing properly though they should.

$(document).ready(function(){  
    if(!($("#drop-industries").is(":hover"))){
        if(!($("#hover-industries").is(":hover")){
            $("#drop-industries").hide();
        }
           }            //this should close the first if bracket but it is not
});                     //this is closing it instead 

Note that I first had an && to check for both conditions together, but it wasn't working either (now I see it probably wasn't the &&), but anyway, here is the code if you'd like to see that instead:

$(document).ready(function(){  
    if(!($("#drop-industries").is(":hover")) && !($("#hover-industries").is(":hover"))){
    $("#drop-industries").hide();
}
});

I've tried several ways of closing the brackets, etc, but it's not working. Is it that I am probably using ! improperly? Any help is appreciated.

How to add if statement to a variable from Python code's output

I am using virusTotal API for url scan info. All the results (urls scanned by VirusTotal) are printed in Command Prompt.In that output, there is a data column header called "detected". So what I want to do is put an if statement and print if "detected==true" print("Detected") else if "detected ==false" print("Not detected") I wrote the code and it does not give any errors But I don't get any results

if (response.'detected'=="false"):
  print("Malware Not Detected")
elseif(response.'detected'=="true"):
  print("Not Detected")

Here is my full code

 import csv
 import itertools
 import requests
 import json

 domainfile=open('domainsi.csv',newline='',encoding='utf_8')
 reader=csv.reader(domainfile)
 w=[]
 for row in reader:
    w.extend(row)

 domain = list(itertools.permutations(w,1))
 print(domain)

 def url_report(domain):
    url = 'https://www.virustotal.com/vtapi/v2/url/report'
    params = {'apikey': '', 'resource':domain}

    response = requests.get(url, params=params)
    return response

def pp_json(json_thing, sort=True, indents=4):
    if type(json_thing) is str:
            print(json.dumps(json.loads(json_thing), sort_keys=sort, 
            indent=indents))
    else:
            print(json.dumps(json_thing, sort_keys=sort, indent=indents))
    return None

 for d in domain:
    response = url_report(d)
    json_response = response.json()

    pretty_json = pp_json(json_response)

print(pretty_json)
input()

mercredi 28 août 2019

If field = a echo... else

On a report, I'm trying to show a signature depending on the value of a field. So, I'm adding php inside html.

<?php

if ($lawyer == "DS") {
    echo '<div class="signature">
<p class="boldcentrado">
E.D.</br>
Lawyer</div>
<div class="assinaturacaixa">
<p class="boldcentrado">DS</p>
</div>';
} else {
    echo '<div class="signature">
<p class="boldcentrado">
E.D.</br>
Lawyer</div>
<div class="assinaturacaixa">
<p class="boldcentrado">PM</p>
</div>';
}
?>

If field "lawyer" equals "DS", it should "show":

<div class="signature">
<p class="boldcentrado">
E.D.</br>
Lawyer</div>
<div class="assinaturacaixa">
<p class="boldcentrado">DS</p>
</div>

if it's any other value, show:

<div class="signature">
<p class="boldcentrado">
E.D.</br>
Lawyer</div>
<div class="assinaturacaixa">
<p class="boldcentrado">PM</p>
</div>

Problem is it's always showing the first option, no matter the field value.

Problem with if condition on a "random walk" script

I'm trying to make the coordinate "x" randomly move in the interval [-1,1]. However, my code works sometimes, and sometimes it doesn't. I tried ShellCheck but it says "no issues detected!". I'm new to conditionals, am I using them wrong?

I'm running this on the windows subsystem for linux. I'm editing it on nano. Since I have a script that will plot 200 of these "random walks", the code should work consistenly, but I really don't understant why it doesn't.

Here's my code:

x=0
for num in {1..15}
do
  r=$RANDOM
  if [[ $r -lt 16383 ]]
  then
    p=1
  else
    p=-1
  fi
  if [[ $x -eq $p ]]
  then
    x=$(echo "$x-$p" | bc )
  else
    x=$(echo "$x+$p" | bc )
  fi
  echo "$num $x"
done

I expect something like this:

1 -1
2 0
3 1
4 0
5 1
6 0
7 1
8 0
9 1
10 0
11 -1
12 0
13 1
14 0
15 1

But the usual output is something like this:

1 1
2 0
3 -1
4 0
5 -1
6 0
7 -1
(standard_in) 1: syntax error
8
(standard_in) 1: syntax error
9
(standard_in) 1: syntax error
10
(standard_in) 1: syntax error
11
(standard_in) 1: syntax error
12
(standard_in) 1: syntax error
13
(standard_in) 1: syntax error
14
(standard_in) 1: syntax error
15

Always stopping after a -1.

If statements with multiple variables

I'm trying to use if statement with multiple comparison operations but the day variable isn't working in my if statements.

Here's my code:

int day;
string rain;

cout << "What day of the week is it?" << endl;
cin >> day;

while (0 < day < 8)
{
    cout << "Is it raining? Please type 'yes' or 'no' " << endl;
    cin >> rain;

    if ((0 < day < 3) && (rain == "yes"))
    cout << "Read in bed" << endl;

    else if ((0 < day < 3) && (rain == "no"))
        cout << "Go out and play!" << endl;

    else if ((2 < day < 8) && (rain == "yes"))
        cout << "Take an umbrella!" << endl;
    else
        cout << "No umberella needed" << endl;

    cout << "What day of the week is it?" << endl;
    cin >> day;
}

cout << "Invalid day sorry" << endl;

Getting Read in bed or go out and play, but never Take an umbrella.

My code also works if I put day = 9.

"if" not working as expected trying to print out right condition [on hold]

I am trying to use the if-condition. For example if the argument equals the condition in the if-statement, it will print what's defined in the if-clause, otherwise it will print out what's defined in the else-clause.

It doesn't seemed to work properly it works one way or it doesn't work at all

for (String arg: args){
    if (arg.equals("-d")){
        System.out.println(String.join("", Collections.nCopies(numberCharacters, (args[1]))));     
    } else {
        System.out.println(String.join("", Collections.nCopies(numberCharacters, str)));
    }
}

If condition loop

I am trying to run a command to stop an application and then use the psutil to check if all the associated processes are killed. If not, wait for 60 seconds. The code is:

import os, psutil, time

os.system("App -STOP")

for p in psutil.process_iter():
    x = p.as_dict(attrs=['pid', 'name', 'username'])
    if 'as_' in x.get('name') or 'AP_' in x.get('name'):
           time.sleep(60)

If the "as_" process exists, the the loop sleeps for 60 seconds. But once the 60 seconds is complete, the "for" loop would go on to check the other processes. I would like to know a way I can check for the "as_" again and again, and sleep for 60 seconds every time if it is still running (sounds like a bummer, but the process dies for sure in a few minutes). Once the process dies, only then loop goes on to check for other processes. Thanks in advance.

Can I assign a variable to the result of an if statement in javascript?

I am just wondering, is there a way to assign a variable to the result of an if statement. Would something like this be allowed in javascript?

var result = if (someVariable === 2) { 
  return something; 
} else if (someOtherVariable) {
  return somethingElse;
} else { return null; }

Where result would end up being equal to whatever the if statement returns. Also, if this is not allowed in JS, is it allowed in other languages (just out of curiosity)?

How to write if statements without so many && symbols

I'm working on a project where a function takes an array of numbers and converts them into blocks on the screen. It's working fine, but in that function there are four if statements all checking if 5 values are true:

if (adj[1] && adj[2] && n > 13 && n % 14 && blocks[n - 15] !== 1) {
  cor.push([0, 0]);
}
if (adj[0] && adj[2] && n > 13 && (n + 1) % 14 && blocks[n - 13] !== 1) {
  cor.push([1, unit * 14 / 16]);
}
if (adj[0] && adj[3] && n < 98 && (n + 1) % 14 && blocks[n + 15] !== 1) {
  cor.push([3, unit * 14 / 16]);
}
if (adj[1] && adj[3] && n < 98 && (n % 14) && blocks[n + 13] !== 1) {
  cor.push([2, 0]);
}

That's the actual code, and as you can see many of those values are repeated. The point is, I want my code to look cleaner and smoother, and I feel like there is a way to simplify or shorten this section.

Let me know if you'd like to see the rest of the code, but that shouldn't matter, just consider this:

if (a && c && e && g && !i) variable = m + o;
if (a && d && e && h && !j) variable = m + p;
if (b && d && f && g && !k) variable = n + q;
if (b && c && f && h && !l) variable = n + r;

I'm just wondering if there is a way to simplify the above code; maybe using chained ternary expressions, switch statements, or an array of values to choose from, but hopefully be more readable and easier to modify.

Thanks for helping out!

Note: I'm not super concerned with performance, just simplicity and readability.

Why strings are not comparing [on hold]

I'm trying to compare two values using equals() that should be identical.

I've used normalizing methods such as toString() and trim() but nothing seems to allow these seemingly identical values to compare successfully. I know that there are a lot of ways to do compares, but why isn't this code working.

   public Boolean findUser(String username)  {
      Boolean found = false;
      String user= "";
      try {
          context.setRequestControls(null);
          NamingEnumeration<?> namingEnum = context.search("ou=users," + domainRoot, "objectClass=user", getSimpleSearchControls());
      while (namingEnum.hasMore() && found == false) {
         SearchResult result = (SearchResult) namingEnum.net();
         Attributes attrs = result.getAttributes();
         user = attrs.get("cn").toString().trim();
         if (user.equals(username.trim()))) found = true;
       }
     } catch (exception e) {
      e.printStackTrace();
     }
     return found
    }

If I print out both values they look identical. But if statement is never successful and therefore doesn't set found=true. I'm not looking for all permutations of how this code could be written differently I just want to know why it won't work as-is and how to fix given this approach. I realize that code could be shortened or tightened up.

If statement trouble in Python

I am interfacing a RFID sensor (MFRC522) with a Raspberry Pi. I am currently testing the whole system out. Basically, once the RFID tag is swiped it outputs a number associated with it. I want the python code to read in the RFID number and compare it with the variable 'a.' When I attempt to do this, though, I am getting an invalid syntax error for the 'if' statement and I am not sure why. I am new to Python.

import RPi.GPIO as GPIO

from mfrc522 import SimpleMFRC522

GPIO.setwarings(False)

a = 699562167785

reader = SimpleMFRC522()

try:
    id = reader.read()
    print (id)

if id == a
    print ("Awesome")

finally:
    GPIO.cleanup()

I need to save the output of Print command into a list

I am using pandas to compare time durations to mark attendance. I have used DateTime and timedelta to compare the durations. I want to save the output in the adjacent column so that we know who was present and who was not.

I can compare the values and print if the person was present or absent, but i want to do it in the excel file in front of the name of the person

df1 =df[['Date', 'Agent Name', 'Login Time']]

for x in df1['Login Time']:
s1 = str(x)
s2 = '12:00:00'
s3 = '3:10:00'
s4 = '01:00:00'
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
if x == s4:
    print('Aussi')
elif (str(tdelta)) < s3:
    print('Present')
else: 
    print('Check')

what i am thinking is, i will store the value of the output in a list and then add the list to a new column in the df.

refactoring nested if statements

I'm trying to refactor some code that looks similar to the code below. I feel that there should be a simpler way to do what it does. My main concern is the call to getDataB() in both if and else blocks of the (!data.isEmpty()) condition.

    DataA dataA = getDataA();

    if (!dataA.isEmpty()) {

        if (dataA == Status.FINAL) {
            // process finalized dataA
        }

        if (dataA == Status.RECEIVED) {
            DataB dataB = getDataB();
            if (!dataB.isEmpty()) {
                dataA.setStatus(dataB.getStatus());
                // process dataA with updated status from dataB
            }
        }

        if (dataA == STATUS.IN_PROGRESS) {
            // process in progress dataA
        }

    // empty dataA
    } else {
        Datab dataB = getDataB();
        if (!dataB.isEmpty()) {
            // process dataB
        }
    }

Find Sub string in SSRS and evaluate or replace

In SSRS I have data field called Event_dt it returns as Digital followed by Month, then Year. It looks like this Digital January 2021 or Digital May 2019

Question 1: In one field - I need to truncate the word Digital so the string would only read January 2021 or May 2019

Question 2: In the second string i need to evaluate, if Event_dt string contains the word Digital then it should output something else. I know the iff(part ... but i'm not sure how to get the sub string part in SSRS.

BASH script error exits when variable is empty, but works when variable is set

I have the following bash code that is exiting when I enable "set -o errexit" and the variable in the code is empty, BUT works fine when the variable is set; the code is designed to test if a screen session matching ".monitor_*" exists, and if so do something.

I have the following turned on:

set -o errexit
set -x xtrace; PS4='$LINENO: '

If there is a sessions matching the above pattern it works; however, if nothing matches it just exits with no information other than the following output from xtrace

storage-rsync@nasro-prod01:~/scripts/tests> ./if_test.sh
+ ./if_test.sh
+ PS4='$LINENO: '
4: set -o errexit
5: set -o pipefail
6: set -o nounset
88: /usr/bin/ls -lR /var/run/uscreens/S-storage-rsync
88: grep '.monitor_*'
88: awk '{ print $9 }'
88: /usr/bin/grep -Ev 'total|uscreens'
8: ms=

I tested the command I am using to set the "ms" var and it agrees with the xtrace output, it's not set.

storage-rsync@nasro-prod01:~/scripts/tests> test -n "${mn}"
+ test -n ''

I have tried using a select statement and get the same results... I can't figure it out, anyone able to help? Thanks.

I read through all the possible solution recommendations, nothing seems to address my issue.

The code:

#!/usr/bin/env bash

set -o xtrace; PS4='$LINENO: '
set -o errexit
set -o pipefail
set -o nounset

ms="$(/usr/bin/ls -lR /var/run/uscreens/S-"${USER}" | /usr/bin/grep -Ev "total|uscreens" | grep ".monitor_*" | awk '{ print $9 }')"
        if [[ -z "${ms}" ]]; then
            clear; printf '\e[104m%-76s\e[0m\n\n' " START NEW MONITOR SESSION"
            read -r -p "ENTER NEW SCREEN SESSION NAME: " sname
            monitors="monitor_${sname}"
            /usr/bin/screen -S "${monitors}" -dm
            printf "\nSCREEN NAME : %s \n\n" "${monitors}"
            read -n 1 -s -r -p "Press any key to continue... "
            /usr/bin/screen -X -S "${monitors}" exec /usr/bin/env bash /mnt/storage_team/scripts/rsyncstatus/data/data.sh
            /usr/bin/screen -r "${monitors}"
        elif [[ -n "${ms}" ]]; then
            clear; printf '\e[104m%-76s\e[0m\n\n' " ATTACH TO ACTIVE MONITOR SESSION?"
            /usr/bin/ls -lR /var/run/uscreens/S-"${USER}" | /usr/bin/grep -Ev "total|uscreens" | grep ".monitor_*" | awk '{ print $9 }'; echo
            read -r -p "ENTER MONITOR'S SESSION NAME: " sname
            echo; read -n 1 -s -r -p "Press any key to attach... "
            /usr/bin/screen -r "${sname}"
        fi
exit

Trying to write an If statement that will show date of last item selected and change as updated

I have a series of data. That goes down the left side column of dates... 8/2, 8/3, and such. Then 2 columns over I have a column left for if the date is checks so 8/2:X, 8/3:X, 8/4: ,8/5: and such. I'm wanting to reference the date in the last field that has a X in it

A B C D 8/1 X 8/2 X 8/3 x 8/4 8/5

Trying to reference the date for the last A cell if there is an X in the D cell. So it would be for 8/3 would be the date. I'm not sure how to run with this.

I've looked through but now sure how to state an if statement

Is there a way to use an if statement in an array?

So I'm setting up random generation of worlds in batch. For this, I need to put an if statement into an array. However, it does not seem to recognize that I'm trying to put a variable inside a variable.

So far, I've tried using !, %%, and % for the variables. I also tried removing the if statements, and although the error stopped, the numbers still got below 0 and above 15.

This is the code I currently have. i believe that the problem is in the 2 if statements on lines 8 and 9, as without them

echo Generating biomes...
rem 0x 0y
set /A biomenum0x0y = %RANDOM% * 16 / 32768 + 1
rem The rest!
for %%x in (neg1 0 1) do (
   for %%y in (neg1 0 1) do (
      set /A nextbiomenum = !RANDOM! * 4 / 32768 - 1, biomenum[%%x][%%y] = biomenum[0][0] + nextbiomenum %% 2
      if %%biomenum[%x%][%y%]%% LSS 0 set %%biomenum[%x%][%y%]%% EQU "0"
      if %%biomenum[%x%][%y%]%% GTR 15 set %%biomenum[%x%][%y%]%% EQU "15" 
   )
)
echo %biomenum[neg1][neg1]% is the biome for -1,-1
echo %biomenum[neg1][0]% is the biome for -1, 0
echo %biomenum[neg1][1]% is the biome for -1, 1
echo %biomenum[0][neg1]% is the biome for 0, -1
echo %biomenum[0][0]% is the biome for 0, 0 -the starting chunk-
echo %biomenum[0][1]% is the biome for 0, 1
echo %biomenum[1][neg1]% is the biome for 1, -1
echo %biomenum[1][0]% is the biome for 1, 0
echo %biomenum[1][1]% is the biome for 1, 1

What it should be doing is keeping the number between 0 and 15, however sometimes it goes to -1 and 16. It also prints out Environment variable %biomenum[][]% EQU "15" not defined 9 times.

how to fix the syntax error in prime number program?

Iam getting syntax error near else part and how to set right indendation?

I tried running on Py3

num=int(input("enter the no"))
if(num>1):
    for i in range(2,num):
        if(num%i==0):
            print("not prime",num)
            break;
        else:
            print("prime",num)
        else:
            print("not prime",num)

If group.group_type then do this in PrestaShop, problem

PrestaShop 1.7.5.x

How can I call the attribute group of the $group.group_type color? I need to have the colors that are in group[{$id_attribute_group}] for e.g. group_1, in the right column of product page.

I want to do something like:

{if $group.group_type == 'color' && id_attribute_group == '1'} then do this...

but it doesn't work, it calls only the first color of the group (but the id is correct!).

I have to do the same for radio

{if $group.group_type == 'radio' && id_attribute_group == '2'} then do this...

The basic code is:

 {elseif $group.group_type == 'color'}
    <ul id="group_{$id_attribute_group}">
      {foreach from=$group.attributes key=id_attribute item=group_attribute}

        <li class="float-xs-left input-container">
          <label>
            <input class="input-color" type="radio" data-product-attribute="{$id_attribute_group}" name="group[{$id_attribute_group}]" value="{$id_attribute}"{if $group_attribute.selected} checked="checked"{/if}>
            <span
              {if $group_attribute.html_color_code}class="color" style="background-color: {$group_attribute.html_color_code}" {/if}
              {if $group_attribute.texture}class="color texture" style="background-image: url({$group_attribute.texture})" {/if}

            ><span class="sr-only">{$group_attribute.name}</span></span>
          </label>
           <div class="colors-names">{$colors.$id_attribute.name}</div>
        </li>
      {/foreach}

Thanks if you can help me!

Using If statement to verify if string value is in an array of strings

I have a string and an array of strings. I was wondering if it is possible to use an If statement in order to return a boolean value if the string contains a value from the array.

The code below doesn't work properly. Contains can only take in one value as far as I can see. Is there a better way to do this without having to use a loop?

Dim FilePath As String = "C:\Users\Downloads\Test.jpg"
Dim GetExtension As String = FilePath.Substring(FilePath.Length - 3)
Dim FileExtensionArray() As String = {".png", ".jpg", ".tif"}

If GetExtension.Contains(FileExtension) = True Then
   ' Code
Else
   ' Code
End If

If Else Statement inside entity query

im trying to produce an if else statement inside entity query, i have the following code:

                var asset = dbContext.Set<Asset>()
                .Include(x => x.Item)
                .Include(x => x.Item.ItemDetailSubCategory)
                .Include(x => x.AssetCurrentStatus)
                .Include(x => x.AssetCurrentStatus.AssetCondition)
                .Include(x => x.Currency)
                .Include(x => x.AssetCurrentStatus.AssetAccessories)
                .Where(x => x.AssetCurrentStatus.Room.Floor.IsActive == true)
                .Where(x => x.AssetCurrentStatus.Room.Floor.Building.IsActive == true)
                .Where(x => x.AssetCurrentStatus.Room.IsActive == true)
                .ToList();

now i expect something like :

                var asset = dbContext.Set<Asset>()
                .Include(x => x.Item)
                .Include(x => x.Item.ItemDetailSubCategory)
                .Include(x => x.AssetCurrentStatus)
                .Include(x => x.AssetCurrentStatus.AssetCondition)
                .Include(x => x.Currency)
                .Include(x => x.AssetCurrentStatus.AssetAccessories)
if(x.AssetCurrentStatus.AssetLocation != null)
{
                .Where(x => x.AssetCurrentStatus.Room.Floor.IsActive == true)
                .Where(x => x.AssetCurrentStatus.Room.Floor.Building.IsActive == true)
                .Where(x => x.AssetCurrentStatus.Room.IsActive == true)
}
else
{
.tolist()
}

is there any way to achieve this? thanks in advance

Form a column out of a Datetime field python [duplicate]

This question already has an answer here:

Here is the DataFrame column and its datatype

df['Hours'].head()
OutPut: 

0   00:00:00
1   00:00:00
2   11:38:00
3   08:40:00
Name: Hours, dtype: timedelta64[ns]

I want to conditionally form anaother column from it, such that it will look like.

Hours        Test
00:00:00     N/A
00:00:00     N/A
11:38:00     02:38:00
08:40:00     Under Worked

Where ,

if df['Hours'] == '00:00:00':
  df[Test] = 'N/A'
elif (df['Hours'].dt.total_seconds()//3600) < 9:
  df['Test'] = 'Under Worked' 
else:
  df['Test'] = (df['Hours'].dt.total_seconds()//3600)-9

But it gives me error

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

How can it be solved?

Alternative to nested if statements spaghetti code

I'm looking for a better design solution to nested if statements. The problems to solve are poor readability, poor extensibility, and repetitive code.

Some requirements:

  • There can be an arbitrary/growing amount of cases to check for
  • There can be an arbitrary/growing amount of criteria used for checks
  • Criteria will be all strings. That means checks can be for (partial) equality of strings only

Here is an example:

//some trigger function to call upon matching any of the nested if statements
function triggerEvent(name){
    //trigger something
  }

  //Criteria to be used with checks
  //all string values.
  var eventAction = something.get('eventAction'), //value that might change depending on URL and user behaviour
      eventLabel = something.get('eventLabel'), //value that might change depending on URL and user behaviour
      url = window.location.href //e.g. www.example.com/some/url/path1/path2
      //Potentially more criteria

  //Below can be an arbitrary amount of if checks depending on aboves criteria 

  //example 1 - same eventAction, but different URL
  // OR operator and checking equality
  if (eventAction === "foo" || eventAction === "bar"){
    //Check partial equality
    if (url.indexOf('/path1/')>-1) triggerEvent('Event1.1');
    else if (url.indexOf('/path2/')>-1) triggerEvent('Event1.2');
  }

  //example 2- same URL, but different eventAction
  //Already getting repetitive compared to example 1
  if(url.indexOf("/path1/")>-1){
    //AND operator
    if (eventAction === "baz" && eventLabel === "a") triggerEvent('Event2.1');
    if (eventAction === "baz" && eventLabel === "b") triggerEvent('Event2.2');
  }

  //example 3 - More and less specific case mix
  if (eventAction === "baz" && eventLabel !== "a" && eventLabel !== "b") triggerEvent('Event3.1'); //less specific. should not fire when 'Event3.2' or 'Event3.3' is true. This will be bloated quickly
  if (eventAction === "baz" && eventLabel === "a") triggerEvent('Event3.2');
  if (eventAction === "baz" && eventLabel === "b") triggerEvent('Event3.3');

  //More combinations ...

What would be a better approach to implement such logic?

Note: Consolidation and switch statements are not an option as there might be new checks that need to be added requiring constant refactoring.

mardi 27 août 2019

mysql use variable to decide if to execute insert

I have a table that must have only one row. if this row exist don't do nothing if there is no row insert data that does NOT contain the indexs field

i tried to use the below code but i get arror

select count(id) into @myvar from customer; IF(@myvar>0) BEGIN INSERT INTO customer (dateformat, alarmDays, backup, pastPass, loginFails, passLength, timetochangepass) values('d,m,y',30, 30, 3, 5, 8, 90) END

How do I make a field mandatory if the previous field is set to yes?

I need some help with JavaScript code, please. I have a form that asks a question, if you answer yes, then more fields appear. I want to set it to if yes, those fields become mandatory.

This part works fine:

  <label for="export">Do you export?</label>
  <ui:inputSelect value="{!v.account.Export__c }" aura:id="export">
    <ui:inputSelectOption text="No" />
    <ui:inputSelectOption text="Yes" />
  </ui:inputSelect>

  <aura:if isTrue="{!v.account.Export__c == 'Yes'}">

I would like to make the below mandatory only if yes is selected:

    <label for="export-where">Where do you export?</label>
      <ui:inputSelect multiple="true" aura:id="export-where" value=" !v.account.Export_to_where__c}" change="{!c.handleExports}">
        <ui:inputSelectOption text="Option 1" />
        <ui:inputSelectOption text="Option 2" />
        <ui:inputSelectOption text="Option 3" />
       </ui:inputSelect>

      <label for="export-what">What do you export?</label>
        <ui:inputTextArea aura:id="export-what" value="{!v.account.Export_what__c}" maxlength="32768" />                          
    </aura:if>

The below JavaScript works as all being mandatory.

else if(getCurrentStep == 3){
    this.removeBorder(component, 'export');
    if((account.Export__c == 'No')) {
        return true;
    }
else{
    component.set("v.errorMessage","* Please fill all the required details");
   if(account.Export__c =='Yes' || account.Export_to_where__c == 'undefined' || account.Export_to_where__c == null || account.Export_to_where__c.trim() == '') {    
        this.addBorder(component, 'export-where');
    }
}

How do I change it so that when the Export_to_where__c question is filled it validates? Any help would be appreciated.