mercredi 28 février 2018

Why breakpoint breaks at else block in 'if else' condition

I am trying to figure out, why, if I put breakpoints on if and on else line, why my if else {} condition breaks on else if the condition was true in if block?

I am using realm but I do not thing, that is an issue.

//Check if Object already exists in database
if !RealmService.shared.ifPortfolioExists(name: portfolio.name){//Breakpoint on this line which is true

     //Create portfolio
     RealmService.shared.create(portfolio)
     //Assign portfolio to transaction
     transaction.portfolio = portfolio
     //Create transaction
     RealmService.shared.create(transaction)

}else{//Breakpoint on this line

     //Assign portfolio to transaction       
     transaction.portfolio = portfolio
     //Create transaction
     RealmService.shared.create(transaction)

}

Am I working out of my mind or am I just stupid? Can please someone explain me this.

I have a spreadsheet that consists of a series of drop down options. I am using a IF statement

I have a spreadsheet that consists of a series of drop down options. I need to know how to change the values of a certain formula if an option is selected. For example, if a user selects "Not Applicable" the weighted average should change. For instance, if I have 4 questions each value at 25% each, this will change if a user selects "Not Applicable" for one question. The weighted average will then need to be 33.333333% since there are only 3 questions that should be weighted. The same will happen if a user selects "Not Applicable" for 2 questions the weighted average should be 50% for the remaining questions. Below is the formula that I am currently using:

=IF(OR(D39="Yes",D39="Yes - Corrected"),0.25,"")

how to check if a value inside an array is larger than a certain value

alright so my question is probably stupid and i dont even know if it can be done but i have inserted some elements into an array through scanner, and i have put it through a certain calculation . The calculation results are also stored inside another array. what i want to do is to see if these calculated values are larger than 0. I want these calculated values to be printed along side the + or - sign. so what i was thinking is to have 2 sets of printing statements where if the sign value of the calculated amount is >0 it will proceed a print statement where as if it is <0 it will proceed another print statement.But i dont know how to check if a element inside array is larger or smaller than zero.Spare my explanation i tried my best to not make it hard to understand.

so lets say the user inputs 14. which would then go through the calculation process and store 2 inside the array.[(14-10)/2]. so since this is bigger than zero , i want a print statement to execute in a way that i can get +2 as the answer.

assume the user enters 8. which would go through the calculation process and store -2[(8-10)/2], and since -2 is stored here it is <0 and there for i want a separate statement to get executed.

My issue is i dont know how to check if a element inside an array is 0 or not. there are 5 elements inside the array and i want to check if all of them are above or below zero and print different statements for each. thank you so much in advance.

If statement that keeps characters only

Let's say we have a list list_a = [a,b,C,.,/,!,d,E,f,]

i want to append to a new list only the letters of the alphabet.

So the new list will be list_b = [a,b,C,d,E,f]. So far i have tried doing it like that way:

list_b = []
for elements in list_a:
    try:
        if elements == str(elements):
            list_b.append(elements)
    except ValueError: #Catches the Error when the element is not a letter
        continue

However, when i print the list_b it has all the elements of list_a , it doesn't do the job i expected. Any ideas ?

PS: comma in the specific example brings Error too.

If condition PHP wrong?

I have a basic question about what's giving me a very big headache.

In the code below:

$item['attributes']['chave'] = '1001';

// Adicionar item se não existir
if ($cart->isItemExists($item['attributes']['chave'])) {
  echo 'Exists, id: '.$item['attributes']['chave'];
} else {
  $cart->add($_POST['id'], $_POST["my-item-qty"], [
  'price'  => $_POST["my-item-price"],
  'color'  => $_POST["my-item-name"],]);
}

The "if" condition is not executed, even though I know that the item with code '1001' exists, if the if condition is not executed, it goes straight to the "else".

isItemExists() returning false? Or my condition some how is not cheking correct?

Here is the isItemExists() code:

public function isItemExists($id, $attributes = [])
{
    $attributes = (is_array($attributes)) ? array_filter($attributes) : [$attributes];

    if (isset($this->items[$id])) {
        $hash = md5(json_encode($attributes));
        foreach ($this->items[$id] as $item) {
            if ($item['hash'] == $hash) {
                return true;
            }
        }
    }

    return false;
}

I'm looking at the php manual, and my condition looks correct. What is wrong?

Excel nested if statements - need help troubleshooting

I need some fresh eyes. I have been working on this incrementally and go from having it work to broken. At this point my eyes are crossing and I could use some help. Column H in this spreadsheet contains a machine id and column I is a date. I want it to display nothing if both H and I are blank (This is the point where I broke it most recently and decided to ask for help. This logic is not include.) If either H or I but not both have a value, it will display "NO". If both H and I have values, it will call a custom function that will create the directory if it does not already exist. Additionally, I want to display "YES" if the directory is created or exists. All of the functionality was working before I tried to display nothing if both H and I were empty.

This is the formula I am working with:

=IF(COUNTA(H21:I21)<>COLUMNS(H21:I21), "NO",IF(CREATEDIR(CONCATENATE(TEXT(I21,"yyyy"),"\",TEXT(I21,"m-d-yy"),"\",H21))=0,"YES", "NO"))

And this is the VBA function I am using(path details omitted)

Function CREATEDIR(dateId) If Len(Dir("Z:\pathname\" & dateId, vbDirectory)) = 0 Then MkDir "Z:\pathname\" & dateId End If End Function:

Shell script if-else case

I wrote the below script to take input interactively servername and service name. This repeats asking the inputs when y is given as input at the end of the while loop.

key='y';
service='';
serverName='';
while [[ $key == 'y' ]]; do
    echo -e "\nEnter serverName  : "
    read serverName
    echo -e "\nEnter Service Name  : "
    read service
    if [[ ! -z "$service" ] && [ ! -z "$serverName" ]]; then
        echo -e "startService $serverName $service"
        #echo -e " Atleast one input is null"
    else
        echo -e " Atleast one input is null"
    fi
    echo -e "Enter y to repeat this step. Enter n to exit :"
    read key
done

Loops, which to use, and how to stop it

my prompt is: Suppose that one credit hour for a course is $100 at a school and that rate increases 4.3% every year. In how many years will the course’s credit hour cost tripled?

The rewrote this simple code many times, but just can't seem to get it. I think i'm going about this the wrong way..

import java.util.Scanner;
public class MorenoJonathonCreditHourCostCalculator 
   {
 public static void main(String[] args)
    {

Scanner sc = new Scanner(System.in);


double cost = 100;
int years=0;
double sum=200;
double total;

    while (cost >= sum) {
        total = cost + 4.03;
        ++years;
    }


System.out.println("The tuition will double in " +years + " years ");
    }
}

Create Triggers while scanning a table

Context: This is a institution that allow you to borrow and return things.

I have a table: 1) LENDRETURN_ITEMS (column: CardNo, BorrowOrReturn, DateTime, ItemNo)

I would need to create a Trigger such that, when I include a new LENDRETURN_ITEM entry, it would scan all previous entries to check if the CardNo exceeded the Lend Limit of 5. If it exceeds 5, then stop the entry from going into LENDRETURN_ITEMS.

The LENDRETURN_ITEMS also includes returned items...

Any ideas? Thank you!

Shorthand if/else php not continue

How to get to the next argument event if the second or third is false ? in my case gender is false but marital status is true but they stop at gender and not execute marital status. how can I make it continue to next argument event second or third is false ?

public function creditScore($user, $basic_information)
    {
        $basic_information->birth_date ? dispatch(new CalculateAge($user)) : false;
        $basic_information->dependents ? dispatch(new CalculateDependents($user)) : false;
        $basic_information->education ? dispatch(new CalculateEducation($user)) : false;
        $basic_information->gender ? dispatch(new CalculateGender($user)) : false;
        $basic_information->marital_status ? dispatch(new CalculateMaritalStatus($user)) : false;
    }

Strange behaviour in the if statement

I have a piece of code that is meant to hide table elements depending on given array. I am running loops to compare innerText of one of the cells and the given array.

However, my if statement is statement is acting weird, once i set the operator to === the operation is successful and table rows that match the array are hidden. But i need my if to hide the elements that are not a part of the array, so naturally I set my operator to !== but once i do it it just executes anyway and of course hides all of the elements in the table.

Any idea why this is happening here is the code:

var td1 = document.querySelectorAll("#course");
      var rowss = document.querySelectorAll("#rows");


var diff = _.difference(soretedArray, courseNames1)
console.log(diff);

for(var i = 0 ; i < rowss.length; i++){

  for(var j= 0 ; j< diff.length; j++){


    if(td1[i].innerText === diff[j]){ // if i set the logic operator to !== it hides all of the elements
      console.log(rowss[i]);
       rowss[i].style.display= "none";
     break;
}
    }
  }

Intent in condition doesn't work

i tried searching for this topic but i didn't find anything that would help me , so here i am asking this. i am a beginner so i don't understand a lot of terms and if you answer my question please try to use simple language so i could understand.

i have a condition in that compares a position in two array lists and if they aren't equal than it jumps to another activity

if (randomColors.get(i) != userColors.get(i)) {

               Intent i = new Intent( GameActivity.this, GameOverActivity.class);
                startActivity(i);
            }

and it displays an error in debugging that i cannot solve:

 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gabie212.simonsays/com.gabie212.simonsays.GameOverActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

please help, i am a beginner and i don't know what's wrong with my code because i have done exactly as they taught us in class... thanks in advance

mardi 27 février 2018

If else statement for PHP DateTime diff

I am using meta_box value (YmdHi) and current Date&time to print time difference. And this code work for me.

Now additionally i want to print Live when 2 hours left to start Event.

What mistake I 'm doing to print if or else currently this not work for me?

$then = date( get_post_meta( get_the_ID(), '_start_eventtimestamp', true ) ) ;
$then = new DateTime($then);
$now = new DateTime();
$sinceThen = $then->diff($now);

if ($sinceThen > 2 * HOUR_IN_SECONDS){
       echo $sinceThen->d.'days'; 
       echo $sinceThen->h.'hours'; 
       echo $sinceThen->i.'minutes';
 }
else{
        echo 'LIVE';
 }

How to have multiple statement for every condition in an if function in python

I am writing a code in python 3.5.4 that requires more than one statement for every condition that I set in an if clause for example: enter code here a=10 b=20 c=30 n=int(input('please enter a number: ')) if n>0: print(d=a+b) print(e=a-b) print(f=a*b) else: print(0)

but if the first condition is met, only first statement is implemented. please tell me how to implement all 3 lines

Handlebars: display different HTML tags using IF statements

The partial:

<ul><div>
    <h2></h2>
    
       <li>
           
       </li>
    
</ul></div>

The error:

Error: Unable to find closingIf after {"name":"openingIf","value":"@root.config.isMobile"}. (token: 31)
    at findClosingTokenInner (filename:3600:8)
    at findClosingToken (filename:3635:16)

After removing the tildes from the first and last lines -- same error.

After removing all tildes from the code -- same error.

After removing everything except the first and last lines -- new error:

Error: Unable to find closingTag after {"name":"openingTag","value":"ul"}. (token: 26)
    at findClosingTokenInner (filename:3600:8)
    at findClosingToken (filename:3635:16)

This works perfectly:


    <ul>
        <h2></h2>
        
           <li>
               
           </li>
        
    </ul>

    <div>
        <h2></h2>
        
           
        
    </div>


You can see how much longer this is now, and I am repeating almost all of the information. Is there no way to make the original code work with handlebars, or am I missing something (probably really simple...)?

Also, if you can explain why this problem is a thing, I will be eternally grateful.

Thank you!!!

Boolean used with If statement

I just started learning Java at school and I encountered the following piece of code. I have trouble understanding why the output shows: 'no'. Since 'x' is updated to '100' shouldn't the boolean also update to 'false' and therefore output: 'yes' ?

Thank you in advance

Sorry for any format mistake, this is my first post.

   public static void main (String[] args)
   {
       Scanner keyboard = new Scanner(System.in);
       int x = -555;
       boolean isNegative = (x < 0);
       if (isNegative)
       {
           x = 100;
           if (isNegative)
             System.out.println("no");
          else
             System.out.println("yes");
       } 
       else
          System.out.println("maybe");

  }

Applying If Then logic to a dataframe R

I think I may have bit off more than I can chew. I am trying to apply a logical equation to a set of data based on a few factors to develop a final estimate for each year. I got all my data in the same place but now am struggling to manipulate it appropriately.

Long short of it I have a data frame that looks like this:

YEAR    ID    V1   V2   V3   Delta1   Delta2
1990    A     3    NA   NA   NA       NA
1991    A     5    2    NA   2        NA
1992    A     7    4    6    2        2
1990    B     3    1    NA   NA       NA
1991    B     5    2    NA   2        1
1992    B     7    1    NA   2        -1
etc

I want to apply the following logic to calculate a new column for each row:

For each ID in 1990

if there is a V3 value that will be selected    
else if    
if there is a V2 value that will be selected for the new column    
else
they are assigned the value of V1 (V1 is always populated).

For each proceeding year an ID is assigned a value based on

if there is a V3 value it equals V3 * Delta1
else if
the ID has never had a V3 value the calculated value will equal V2
else if
it has had a V3 but just not this year it equals the years previous calculated value for that ID * Delta2
else
the calculated value simply equals the previous years calculated value * Delta1

I know how to apply if else logic but I am lost in how to do so iteratively through years for each ID against the data frame. Any help would be appreciated, thank you.

Excel 2016 - How to fill one cell with data from multiply checkboxes?

For starters, im not very great or smart when it comes to Excel. So forgive me my question, since it might be really easy, but i just cant get it to work.

I have look though google and cant seem to find a solution for this, or anything that can help me in the right direction.

I have a list of checkboxes in excel, from D4 to D27.
I have every value of the checkboxes on E4 to E27 (TRUE or FALSE).

Then i have a cell that should get the data from the checkboxes, when they are TRUE. This is B27.

B27 have a =IF(E4=TRUE; "YaY"; "Nope") script at the moment. And this is working. BUT, i cant get anymore IF statements in there, or nest them when it comes to text. I might be doing it wrong though, i dont know. -Yes i did try and look it but, but cant get it to work.

Every checkbox has diffrent data linked to it, so if D4 is checked, then the value need to be sent to B27, with text YAY!. And then if D5 is checked, it sends the data to B27 with some other data, lets say WOO!. So B27 should be looking like this : YAY!; WOO!;

|------------------------------------------------------|
|-------D4---------|----------E4--------------------|
|-------X-----------|---------TRUE----------------|
|-------X-----------|---------TRUE----------------|
|-------B27--------|---------YAY!; WOO!;-------|
|------------------------------------------------------|

How can i get this done?

I have tried to look at Macro scripting as well, but that was a great failure.

Can someone show me in the right direction, or help me out how this can be done?

Python: Multi-threading or Loops?

I was wondering if it would be feasible to use the idea of multi-threading to perform information sharing between a light intensity sensor and a motion sensor. I'm working on a project to automate lighting quality in a room environment. (I'm a beginner at programming and would appreciate any feedback!)

The way I'm starting is just to test out code with simple numerical conditions and print statements for now. Below is the simulated code for the project.

x=1 #set simply to say some is enters room

def MotionSenseLeave(x):

    x=0
    if x==0:
        print("3. Someone left")           #Wait for someone to leave by checking condition
        LightSense()
    else:
        x==0
    return x 

def LightSense():

    #Turn on lights
    if x==1:               #and light quality is above/below a value#
        print("2. Adjust Light")    #Measure Light Quality
        MotionSenseLeave(x)
    elif x==0: 
        print("Stop operation, the person left")
        MotionSenseEnter(x)
    elif x==1:          #and light is close to value
        print("Light quality sufficent, no changes needed")
        MotionSenseLeave(x)

def MotionSenseEnter(x):

    while x!=1:
        if x==1:
            print("1. Someone here")           #Wait for someone to come in
            LightSense()
        else:
            x==0
    return x   

MotionSenseEnter(x)                           #begin operation

Basically, the operation begins with MotionSenseEnter() and waits for the condition of entry or x=1 (in this case I just set it to 1 in the beginning). If someone enters, then go to LightSense(), turn on lights, then the cases begin and after each case I run the MotionSenseEnter() or MotionSenseLeave() function to see if that person enters/leaves to shut on/off the system and restart it from the beginning until entry is detected.

I was wondering if it would be more efficient to multi-thread these processes instead. If it is, I think I would have to first check to see if someone entered the room, then multi-thread the leave condition and light monitoring condition to continue the operation or close it and await for entry again. If anyone has any opinion on this, all feedback would be welcomed. Again, I'm a beginner at programming, I appreciate all ideas, but simple ones would work best for me!

MySQL INSERT IF condition is true

I'm making a stored routine in MySQL, and I would like to know whether it is possible to make an INSERT-IF some condition is TRUE, ELSE INSERT something else.

This is My Query but I keep getting the #1064 Error (SQL Syntax Error)

DECLARE a INT;
DECLARE b INT;
DECLARE changeTypeID INT DEFAULT(0);

SET a = (SELECT roomPrice FROM RPH WHERE tier=1 AND 
startDate = '2018-02-20' AND rTypeID=1);
SET b = (SELECT roomPrice FROM RPH WHERE tier=1 AND 
startDate = '2018-02-20' AND rTypeID=2);

SET typeID = CASE WHEN (a>b) THEN 1 WHEN (a<b) THEN 2 WHEN a=b THEN 3 END;
IF (typeID = 1 OR typeID =2) THEN
(
INSERT INTO TABLE_A (X,Y,Z) VALUES (ID, changeTypeID, createdBy)
)
ELSEIF (typeID = 3) THEN
(
INSERT INTO TABLE_B (P,Q,R) VALUES (ID, rID, createdBy);
)
END IF;

Note: The insert parameter is already declared on the routine beforehand.

Any help will be appreciated :)

Why Swift ternary operator works so strange

Suppose that we have a class:

class Test: ExpressibleByNilLiteral {
    required init(nilLiteral: ()) {
    }

    init(_ text:String) {

    }
}

and we want to create instance only if some condition is false:

let condition = false

and use this code (1):

var test: Test? = condition ? Test("Z") : nil

as my understanding, in other languages and by this reference, code above is equal to:

var test: Test?
if condition {
    test = Test("Z")
}
else {
    test = nil
}

but in fact in the first case we get not nil, but an non-optional instance of the class Test. In other words, code (1) actually works like this:

let test: Test? = condition ? Test("Z") : Test(nilLiteral: ())

moreover, expression (condition ? Test("Z") : nil) returns regular, non-optional value, so we can write something like:

let test: Test = condition ? Test("Z") : nil

without compilation errors.

If we try class without ExpressibleByNilLiteral, we get nil or compilation error, depending on variable type, as expected:

class Test2 {
    init(_ text:String) {

    }
}

let test2: Test2? = condition ? Test2("Z") : nil // test2 == nil
let test2: Test2 = condition ? Test2("Z") : nil // compilation error

More interesting things:

let test: Test = nil // non-optional instance initialized with nil
let test: Test? = nil // optional, nil

So, the question is: why we get this?

let test: Test? = nil // optional, nil
let test: Test? = false ? Test("Z") : nil // non-optional instance

Using JS to do a redirect in a Content Management System if criteria is met

I am working in a CMS and I am using an html widget to do some redirect code, it is working fine, but of course there is a wrinkle. Basically, I want to create an if statement, because there is a possible message on the initial page. So what I want it to do is if it doesn't see the div - redirect, but if it does see the div, do nothing.

var msgDiv = document.getElementById('thisDiv');

if (msgDiv === null) {
   window.location = "otherpage.html";
} else {
  //do nothing
}

What is happening with this code, is it goes right into redirect regardless. If I do this version:

window.onload = function () {
    var msgDiv= document.getElementById('testDiv');

    if (msgDiv === null) {
       window.location = "otherpage.html";
    } else {
      //do nothing
    }

};

I briefly see the first page and the message, but then it redirects just after a pause. I feel like I am missing one small detail and would greatly appreciate the help.

Excel function to sum all actual costs plus estimates on blank rows with no calculation column

In Excel 2013, I need to sum all numbers in a column of actual costs plus estimates in a second column in rows where the actual costs are blank.

                   Estimate (A)    Actual (B)
     Row 1             106                  
     Row 2             212            230
     Row 3             318            295
     Row 4             424                
     totals            1060           525

I need to return 106 + 230 + 295 + 424. (or 525 + 106 + 424)

What I have tried:

--I have solved the problem if I put a placeholder (like "missing") in the blanks and then using a SUMIF nested in a simple SUM. But that badly clutters the chart. =SUM(A5, SUMIF(B1:B4,"missing",A1:A4))

--I have also solved the problem by creating a calculation column that has an ISBLANK function and then using the SUMIF over that result. However, I can't figure out how to consolidate. I realize I could create another sheet to hold the calculation column, but the workbook will already have a number of sheets and I want to avoid an extra. C1=ISBLANK(B1) dragged down to C4 and then =SUM(A5, SUMIF(C1:C4, "TRUE", A1:A4))

--I have found a number of online descriptions of managing similar tasks with pivot tables and months, but I can't seem to figure it out for a simple table.

I think my ISBLANK attempt is failing on consolidation because of something to do with absolute references vs. ranges in the column, but I can't figure it out.

Any advice would be greatly appreciated--thanks

list index out of range only when len(list) is larger than 3

So here's piece of code I wrote. now this code works for any list whose length is less than 4 but whenever I try to call it for a list that has more than 3 elements it gives me the "list index out of range error" plus it never goes into the if condition.. any explanation would be helpful

counter = 0
def almostIncreasingSequence(sequence):
    for i in range(len(sequence) - 1):
        global counter
        sequence_removed = sequence.remove(sequence[i])
        sorted_sequence = sorted(sequence)
        if sequence_removed == sorted_sequence:
            counter += 1
    print counter
    if counter > 1:
        return False
    else:
        return True


print almostIncreasingSequence([1,2,3,4])

Django: Change page when drop down menü value is selected

I am trying to change the variables used to display a page with a selection-box when another value of the selection box is chosen. I´ve got three different folders I want to apply settings to (with radio buttons). The folder can be chosen from the dropdown menü, and then the needed values can be chosen with the radio buttons. My problem is a follows: I want to display the previously selected settings by checking the options that where chosen before. So if I change the folder I want to apply settings to, I want the checked radio button to change accordingly. Therefore I would like to do something like this:

is that possible ?

A way to evaluate a threshold without using if statements

I have data being taken from a source such that if the value is above 2^13 (8192), the values are actually negative. Is there a way to do the following transition without using an if statement such as:

int data[SIZE]
for (int i=0; i<SIZE; i++)
  if (data[i] > 8191)
    data[i] = data[i]-16384;

or

int data[SIZE]
for (int i=0; i<SIZE; i++)
  if (data[i] > 8191)
    data[i] = ~(data[i] + 1 8292;

Any help eliminating the if statement without increasing the run time beyond O(n) would be greatly appreciated.

C++ Sum of numbers inserted by the user less than 10billion [duplicate]

This question already has an answer here:

So i've been trying to make a program that counts number of digits entered by it's user as long as the value is less than 10 billion, but i can't seem to get it to work properly, so far it counts the number of digits entered but it does not recognise if the value is greater or less than 10billion instead it just ignores the loop in the code and prints out"10" for every value entered that's greater than 10billion. I've tried everything i can think of(im pretty new to programming and all so excuse my errors if any) :C

#include <iostream>


using namespace std;

int main(){
long n;
cout<<"Enter a number less than 10billion:";
cin>>n;

if (( n>=10000000000 || ( n<-0 ))) {

    cout<< endl <<"Number exceeds the range"<< endl;
}
else{
int count=0;
while(n>0){

    n=n/10;
    count++;

}
cout<<"Total number of digits="<<count;

return 0;
}
}

Delete row data (do not remove row) if ¤ is present anywhere in the row

I'm trying to create a macro or VBA code that checks the spreadsheet for this symbol: ¤. If it find this value, it needs to make the data in the row into blanks, eg. it shouldn't remove the row entirely.

I'm using Excel2010 for this, and any help would be much appreciated.

Powershell IF and not condition not working properly

I'm struggling to have two conditions met, somehow it seems only one of them works. I'm trying to do :

If a user is connected AND NOT at the lock screen, do something. The commands themselves have been verified and work individually but I must be missing something. Here is what i have:

if (Get-WmiObject –ComputerName $poste –Class Win32_ComputerSystem | Select-Object -expandproperty UserName -and -not (get-process -ComputerName $poste -name logonui)) {

do something...

}

Right now it just doesn't go in this code, it skips to the lower part where something else is happening.

What is wrong with my syntax ? Thank you for your time!

jQuery If else show and hide for individual dropdown

Would like to ask how should I make it one by one to open a dropdown. Currently, when I make a click event, all of them will open. Also how can I hide it back if it was not use?

Here's my code:

<script>
$( document ).ready(function() {
if ($(".dropdown-toggle").click(function() {
        $('.dropdown-menu').show();
        else {
        $('.dropdown-menu').hide();
        }
    });
});
</script>

How can I make them open individually if I just click one of them.

Expiration date

I have 4 dates store in database named as show_first, show_second, show_third and show_fourth.

I wanth that PHP check dates stored in database and then display correct $prijavni_rok. If current date is bigger then value stored in $show_first then its need to check show_second and again if current date is bigger then show_second needs to check value in stored in show_third. If all values are smaller then current date then it is need to $prijavni_rok to be "ZAPRTO - DNI; "number of days"". Now it is only displaying like this: ZAPRTO - DNI; 17588

It is only working if I put dates directly like this: $first = strtotime('2017-12-31'); and I adjust code just for show_first.

    $current_date = date('Y-m-d');

    $show_date = $row['show_date'];
    $show_first = $row['show_first'];
    $show_second = $row['show_second'];
    $show_third = $row['show_third'];
    $show_four = $row['show_four']; 

    $date = strtotime($current_date);
    $show = strtotime($show_date); 
    $first = strtotime($show_first);
    $second = strtotime($show_second);
    $third = strtotime($show_third);
    $four = strtotime($show_four); 

    if ($date < $first) {
        $diff = $date-$first;
        $x=abs(floor($diff / (60 *60 * 24)));
        $prijavni_rok = "ODPRT - PRVI ROK";
    } else {    
        if ($date < $second) {
            $diff = $date-$second;
            $x=abs(floor($diff / (60 *60 * 24)));
            $prijavni_rok = "ODPRT - DRUGI ROK";
            $prijavni_dni = "DNI; ".$x;
        } else {
            if ($date < $third) {
                $diff = $date-$third;
                $x=abs(floor($diff / (60 *60 * 24)));
                $prijavni_rok = "ODPRT - TRETJI ROK";
                $prijavni_dni = "DNI; ".$x;
            } else {
                if ($date < $four) {
                    $diff = $date-$four;
                    $x=abs(floor($diff / (60 *60 * 24)));
                    $prijavni_rok = "ODPRT - ČETRTI ROK";
                    $prijavni_dni = "DNI; ".$x;
                } else {
                    $diff = $date-$four;
                    $x=abs(floor($diff / (60 *60 * 24)));
                    $prijavni_rok = "ZAPRTO";
                    $prijavni_dni = "DNI; ".$x;
                } 
            } 
        } 
    }

In R if(condition) gives an error "argument is of length zero

in R I have the following if statement if(x==0){...} which gives an error argument is of length zero Debugging using print(x) gives named numeric(0)

command line seems to work OK

> x<-0
> if(x==0){x<-1}
> x
[1] 1
> 

Please help in making me understand what is going wrong. Thanks

Removing rows from R data frame using the for loop with if statement

df <- data.frame(
 V1 = c(1,3,3,5,5,6),
 V2 = c(19,19,38,19,38,19),
 V3 = c(1,3,1,7,2,10)
)

How can I remove the rows where V2 is an odd number using the for loop with if statement?

JavaScript If-Statement Proved True But Outputs False

I am learning JavaScript by programming my first game (a simple laser-mirror-type game). The game operates in a grid and I want to determine if a cell holds an obstacle or not. So I call this function:

function updateGrid () {
for (let i = 0; i < cols; i++) {
        for (let j = 0; j < rows; j++) {
            for (let o = 0; o < obstacles.length; o++) {
                if (grid[i][j].x === obstacles[o].x && grid[i][j].y === obstacles[o].y) {
                    grid[i][j].obstacle = true;
                } else if (grid[i][j].x != obstacles[o].x && grid[i][j].y != obstacles[o].y) {
                    //grid[i][j].obstacle = false;
                }
            }
            for (let m = mirrors.length - 1; m >= 0; m--) {
                if (grid[i][j].x + cellOffset.x== mirrors[m].x && grid[i][j].y + cellOffset.y == mirrors[m].y) {
                    grid[i][j].mirror = true;
                } else {
                    grid[i][j].mirror = false;
                }
            }
            if (grid[i][j].x + cellOffset.x == target.x && grid[i][j].y + cellOffset.y == target.y) {
                grid[i][j].target = true;
            } else {
                grid[i][j].target = false;
            }
            if (grid[i][j].x == laserPen.x && grid[i][j].y + (rowH / 2) - (cellOffset.y / 4) == laserPen.y) {
                grid[i][j].pen = true;
            } else {
                grid[i][j].pen = false;
            }
        }
    }
}

However the if-statement that determines if the cell contains an obstacle, seems to not work.

This works (sets grid[ i ][ j ].obstacle to true):

for (let o = 0; o < obstacles.length; o++) {
    if (grid[i][j].x === obstacles[o].x && grid[i][j].y === obstacles[o].y) {
            grid[i][j].obstacle = true;
    } else if (grid[i][j].x != obstacles[o].x && grid[i][j].y != obstacles[o].y) {
        //grid[i][j].obstacle = false;
    }
}

This does not (sets grid[ i ][ j ].obstacle to false):

for (let o = 0; o < obstacles.length; o++) {
    if (grid[i][j].x === obstacles[o].x && grid[i][j].y === obstacles[o].y) {
            grid[i][j].obstacle = true;
    } else if (grid[i][j].x != obstacles[o].x && grid[i][j].y != obstacles[o].y) {
        grid[i][j].obstacle = false;
    }
}

I actually added the else-if just for safety, but it failed to work with a simple else-statement as well.

I am using the p5.js library and any insight into what is happening here would be greatly appreciated. Thanks!

How to write valid If clause inside select or write function

I have procedure like this and I get error in If clause. I think it is because COUNT. But my clause have to be like that so I don't know how to solve it. Maybe it would be good to create a function or something similar. Rest of the code is okay

CREATE PROCEDURE DohvatiSveUgovore @zavodId int
    AS
    BEGIN
    DECLARE @TempUgovori TABLE
    (
         Id int,
         UstrojstvenaJedinica nvarchar(100),
         VrstaUgovora nvarchar(100),
         KlasaUgovora nvarchar(100),
         UrudzbeniBrojUgovora nvarchar(100),
         DatumPocetkaUgovora nvarchar(10),
         DatumIstekaUgovora nvarchar(10)
    )

    INSERT INTO @TempUgovori(Id, UstrojstvenaJedinica, VrstaUgovora, KlasaUgovora, UrudzbeniBrojUgovora, DatumPocetkaUgovora, DatumIstekaUgovora)
        SELECT 
        u.Id,
        ISNULL(STRING_AGG(LTRIM(RTRIM(z.SkraceniNaziv)), ', '), '') AS 'UstrojstvenaJedinica',
        vu.Naziv AS 'VrstaUgovora',
        ISNULL(u.KlasaUgovora, '') AS 'KlasaUgovora',
        ISNULL(u.UrudzbeniBrojUgovora, '') AS 'UrudzbeniBrojUgovora',
        (SELECT ISNULL(convert(varchar(10), u.DatumPocetkaUgovora, 104), '')) AS 'DatumPocetkaUgovora',
        (SELECT ISNULL(convert(varchar(10), u.DatumIstekaUgovora, 104), '')) AS 'DatumIstekaUgovora'
        FROM Ugovor AS u    
            LEFT JOIN VezaUgovorUstrojstvenaJedinica AS vuu
                ON u.Id = vuu.UgovorId
            INNER JOIN SifVrstaUgovora AS vu
                ON u.VrstaUgovoraId = vu.Id
            LEFT JOIN [TEST_MaticniPodaci2].hcphs.SifZavod AS z
                ON vuu.UstrojstvenaJedinicaId = z.Id                        

            if( (SELECT COUNT(UstrojstvenaJedinicaId)  FROM VezaUgovorUstrojstvenaJedinica WHERE UstrojstvenaJedinicaId =  'HCPHS') = 1)  
            begin
            (SELECT *  FROM  VezaUgovorUstrojstvenaJedinica WHERE UstrojstvenaJedinicaId =  'HCPHS')            
            end
            ELSE
            (SELECT * FROM  VezaUgovorUstrojstvenaJedinica WHERE  Isdeleted = 0  and UstrojstvenaJedinicaId = @zavodId)
            end 

ERROR is here in Group by and I don't know why.

GROUP BY u.Id, vu.Naziv, u.KlasaUgovora, u.UrudzbeniBrojUgovora, u.DatumPocetkaUgovora, u.DatumIstekaUgovora

            SELECT  
            tu.Id,
            tu.UstrojstvenaJedinica AS 'UstrojstvenaJedinica',
            tu.VrstaUgovora AS 'VrstaUgovora',
            tu.KlasaUgovora AS 'KlasaUgovora',
            tu.UrudzbeniBrojUgovora AS 'UrudzbeniBrojUgovora',
            tu.DatumIstekaUgovora AS 'DatumPocetkaUgovora',
            tu.DatumIstekaUgovora AS 'DatumIstekaUgovora',
            ISNULL(STRING_AGG(LTRIM(RTRIM(p.Naziv)), ', '), '') as 'Partner'
            FROM @TempUgovori AS tu
                LEFT JOIN VezaUgovorPartner AS vup
                    on tu.Id = vup.UgovorId
                LEFT JOIN [TEST_MaticniPodaci2].dbo.Partner as p
                    ON vup.PartnerId = p.PartnerID

            GROUP BY tu.Id, tu.UstrojstvenaJedinica, tu.VrstaUgovora, tu.KlasaUgovora, tu.UrudzbeniBrojUgovora, tu.DatumPocetkaUgovora, tu.DatumIstekaUgovora

        END


                EXEC [TEST_Ugovori_Prod].[dbo].[DohvatiSve] 6;  
                GO

I am sorry for too much code but without it I can't run query.

PHP Add if statement html variable [duplicate]

This question already has an answer here:

I am trying to add if statemenet into $html variable. But it see php as a html tag. how can add this statement. Thanks

$html = '

    <?php if (x=y):?>

    <div>
          Help me )
    </div>

    <?php endif ?> 
';

lundi 26 février 2018

Javascript typeof conditional doesn't ever enter

I have a function that iterates through an array messages.

That looks like this:

const messages = args;
for (var i=0; i<=messages.length; i++) {
    if (typeof messages[i] === "object") {
        console.log('do something');
    }
}

My messages constant looks like this:

[ { response: { entities: [], intents: [Array] } },
  { response: { entities: [], intents: [Array] } },
  resumed: 0,
  childId: '*:getLuisModel' ]

For some reason my application skips right over the conditional and doesn't execute anything inside the codeblock for all indices of my array.

When going into debug it with pry, I am able to run typeof messages[i] and get an object returned

I managed to get past the conditional by using if (typeof messages[i] !== undefined) { But now when I have it log messages[i].response it says it is undefined. In my debugger when I access that variable it responds with objects

nested if else in android studio not working

I am working with chatbot in android studio the problem is when I enter start output go straight with else of choose again ? why so?

if (sendText.equals("Start")) {
 receivedMessage.setText("Are you human?\n\n1 Yes \n\n2 No");
    if (sendText.equals("1")) {
        receivedMessage.setText("proceed");
                } else if (sendText.equals("2")) {
                    receivedMessage.setText("robot");
                } else {
                    receivedMessage.setText("Choose Again");
                }
 }
else {
   receivedMessage.setText("Please Retype Start to Start!!");
     }

Conditional statements in parallel events

I have a scenario where multiple events are triggered in parallel and have different timespans, and for this I have to check some conditions and print the result of the events. How to achieve this without causing delays. The condition should not wait to finish one event to get the result and then to pass to the other, but for each event that finished to print the result. Below is a snippet of my code but as it seems does not proceed in parallel but in sequence I want to execute for a block of events. Any help/opinion highly appreciated!

         def flag=0;
         while (jobs.isBuilding()== true ){
               if (flag ==0 ){
               println(jobs.name+ ": build started and is running...")}
               flag=1;
             }

         if (jobs.isBuilding()== false){
             println(jobs.name + ": build completed and the result is " + build.getResult())
             }

Variable Returns False, but if statement doesn't acknowkedge it

I have an if statement that is supposed to execute code if a variable returns false, but even though I have checked and made sure the variable returns false, the code does not execute. Here is the code:

function letterCheck() {
            var wordToGuess = puzzle;
            var letterToGuess = guess;
            console.log(letterToGuess);
            matched = false;
            for (x = 0; x < wordToGuess.length; x++) {
                if (letterToGuess === wordToGuess[x]) {
                        console.log('Your guess was correct!');
                        console.log('You have', 6 - parts, 'incorrect guesses remaining');
                        blanks[x] = letterToGuess;
                        console.log(blanks);
                        var fillBlank = '';
                        for (y = 0; y < blanks.length; y++) {
                                fillBlank += blanks[y];
                        }
                        document.getElementById('puzzle').innerHTML = fillBlank;
                        matched = true
                        win++
                        if (win === puzzle.length) {
                            setTimeout(() => alert("You win!"), 100)
                        }
                        break;
         
                }

        }
    }


//this is the if statement that is not working
if (this.matched === false) {
        console.log("Your guess was incorrect!");
        parts++;
        graphics[parts - 1]();
        console.log('You have', 6 - parts, 'incorrect guesses remaining');
}

Conditional statements in parallel events

I have a scenario where multiple events are triggered in parallel and have different timespans, and for this I have to check some conditions and print the result of the events. How to achieve this without causing delays. The condition should not wait to finish one event to get the result and then to pass to the other, but for each event that finished to print the result. Any help/opinion highly appreciated!

How to find next row that matches current row (based on condition) then paste value from another column?

Say I have some data that looks like this

Name     Type   Rating

Dave     Good   3.0
Steve    Bad    0.0
Steve    Good   2.0
Dave     Bad    1.0
Tom      Bad    2.0
Marianne Good   0.0
Tom      Bad    1.0
Steve    Bad    5.5
Marianne Bad    3.0

I want to take rows where 'Type' matches a certain value (i.e 'Good') then find the next row where the associated name matches the current row (i.e if the name next to 'Good' is 'Dave', find the next row where the name is also 'Dave') and then paste the value in the 'Rating' column to a new column.

The output should look something like this.

Name     Type   Rating  New

Dave     Good   3.0     1.0
Steve    Bad    0.0
Steve    Good   2.0     5.5
Dave     Bad    1.0
Tom      Bad    2.0
Marianne Good   0.0     3.0
Tom      Bad    1.0
Steve    Bad    5.5
Marianne Bad    3.0

Thanks for any help!

3 JButtons not working to trigger 3 drawImages

I am trying to make a project with a border layout, 3 jbuttons, and the drawImage component of paint to create a stoplight that listens for button pushes and changes the images. I know my drawImages in the conditional statements work because if I take the if statement out the images appear fine, and I know the action listeners work because I tested each one with a joptionpane dialog box. However, in the current form, nothing happens at button push and I'm not sure why. Any help would be much appreciated, I am learning!

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TrafficLight extends JFrame implements ActionListener
{
//establishes panel, button, and boolean variables
 private JPanel pN, pS, pE, pW, pC;

 private JButton btnWait, btnGo, btnStop;

 private boolean redIlluminated = false , greenIlluminated = false , yellowIlluminated = false;

public static void main(String[] args)
{
    TrafficLight frame = new TrafficLight();
    frame.setSize(750, 850);
    frame.createGUI();
    frame.setVisible(true);

}

private void createGUI()
{
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    Container window = getContentPane();

    window.setLayout(new BorderLayout());

    //custom colors
    Color slate=new Color(49, 58, 58);
    Color eggshell=new Color(230, 226, 222);
    Color easterPink=new Color(249, 170, 170);
    Color salmon=new Color(201, 80, 65);
    Color dusk=new Color(187, 185, 184);
    Color billiards=new Color(71, 88, 68);

    //custom fonts
    Font buttonFont = new Font("SansSerif", Font.BOLD, 20);

    //sets up north jpanel 
    pN = new JPanel();
    pN.setPreferredSize(new Dimension(680,45));
    pN.setBackground(eggshell);
    window.add (pN, BorderLayout.NORTH);

    //button formatting
    //establishes go button, font, color, and click event, then adds it to pN panel
    btnGo = new JButton ("GO");
    btnGo.setFont(buttonFont);
    btnGo.setBackground(dusk);
     btnGo.addActionListener(
        new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                //trigger condition change here to cause the paint event below
              greenIlluminated = true;
            }
        }
    );
    pN.add(btnGo);

    //establishes wait button, font, color, and click event, then adds it to pN panel
    btnWait = new JButton("WAIT"); 
    btnWait.setFont(buttonFont);
    btnWait.setBackground(dusk);
    btnWait.addActionListener(
        new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
               //trigger condition change here to cause the paint event below 
              yellowIlluminated = true;
            }
        }
    );
    pN.add(btnWait);

    //establishes stop button, font, color, and click event, then adds it to pN panel
    btnStop = new JButton("STOP");
    btnStop.setFont(buttonFont);
    btnStop.setBackground(dusk);
    btnStop.addActionListener(
        new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                //trigger condition change here to cause the paint event below
              redIlluminated = true;
            }
        }
    );
    pN.add(btnStop);

    //east jpanel for stoplight
    pE = new JPanel();
    pE.setPreferredSize(new Dimension(272,318));
    pE.setBackground(billiards);
    window.add (pE, BorderLayout.EAST);

    //west jpanel
    pW = new JPanel();
    pW.setPreferredSize(new Dimension(136,318));
    pW.setBackground(billiards);
    window.add (pW, BorderLayout.WEST);

    //center jpanel for car
    pC = new JPanel();
    pC.setPreferredSize(new Dimension(272,318));
    pC.setBackground(slate);
    window.add (pC, BorderLayout.CENTER);

    //south jpanel
    pS = new JPanel();
    pS.setPreferredSize(new Dimension(680, 15));
    pS.setBackground(eggshell);
    window.add (pS, BorderLayout.SOUTH);
}

public void actionPerformed(ActionEvent click) {


    }

public void paint(Graphics g) {
    super.paint(g);
    //draws stoplight
    g.drawImage(new ImageIcon(getClass().getResource("red1.png")).getImage(), 460, 150, this);
    g.drawImage(new ImageIcon(getClass().getResource("green1.png")).getImage(), 460, 272, this);
    g.drawImage(new ImageIcon(getClass().getResource("yellow1.png")).getImage(), 460, 373, this);

    //draws car in center
    g.drawImage(new ImageIcon(getClass().getResource("car.png")).getImage(), 150, 600, this);

    //sets conditions to show images on button click based on boolean logic changed by buttons
    if (redIlluminated)
    {
        g.drawImage(new ImageIcon(getClass().getResource("red2.png")).getImage(), 460, 150, this);
    }

    else if (greenIlluminated)
    {
        g.drawImage(new ImageIcon(getClass().getResource("green2.png")).getImage(), 460, 272, this);
    }
    else if (yellowIlluminated)
    {
        g.drawImage(new ImageIcon(getClass().getResource("yellow2.png")).getImage(), 460, 373, this);
    }
     }

}

Scrolllock controller, switch shortcut if else

Halo,

i want to program for cmd, powershell, VBS which working as switch for Scroll lock key. If schroll lock is off my ethernet interface is on and wlan interface is off, else scroll lock is on, ethernet is off and wlan is on. And after this program install as service to computer.

Is something like that possible and functiona?

Thnx for all answer.

Is it possilble in php for expression if($y != $z && $x == $y && $x == $z) to give true value for some value of x,y and z [on hold]

I came across a question which i am not able to answer , Quetion:

You have this PHP function:

function almighty_function($x, $y, $z) {
  if ($y != $z && $x == $y && $x == $z) {
    return "Success!";
  }
  return "FAIL!";
}

Please provide set of values for $x, $y and $z for function to return "Success!". Explain your solution.

13 error (type doesn't match) when comparing two dates within a conditional instruction (vba)

I've wrote the following code to delete rows of worskheet 2 in which value of column 7 (a date) is less tan a value of a certain cell of worksheet 1:

Sub delete()

Dim listaops As Worksheet
Dim RToDelete As Range
Dim DTtoCompare As Date
Dim DTofOp As Date
Dim i As Integer

Set listaops = ThisWorkbook.Worksheets("QryOperacionesComprasyAmort0239")
Set RToDelete = Range("G2", Range("G2").End(xlDown))

DTtoCompare = ThisWorkbook.Worksheets(1).Cells(1, 1).Value

For i = RToDelete.Cells.Count + 1 To 2 Step -1

    DTofOp = listaops.Cells(i, 7).Value

    If DTofOp < DTtoCompare Then
        Cells(i, 7).EntireRow.delete
    End If

Next i

End Sub

When it arrives to the instruction in which I set DTtoCompare: DTtoCompare = ThisWorkbook.Worksheets(1).Cells(1, 1).Value I get the following:

13 Error: Types mismatch

I guess it is because variables are not right formatted or right assigned to a date format, I have tried so many things without success.

Could anyone help me?

multiple statement in function

I would like to create a function with 2 statements (if and else if).I have 26 Swiss cantons and the 27th is the Swiss government (it should be the sum of all other cantons). By running my code, I obtain exactly what I want (a vector with 27 values), except that the second statement (else if), doesn't work. I have 0 (because I set at the begining sep = 0) instead of the sum of all the previous 26 cantons.

So I should do something wrong in the second statement. Here is my code

A.function = function(p){
  sep <- 0
  for(i in 1:length(Canton))
    if(IR[i] < 100) {
    sep[i] <- (100-IR[i])^(1+p)*Pop[i]
    }
    else if(IR[i] = 100) {
    sep[i] <- sum(sep)
    }

  return(sep)
}

Anyone could help me?

if statement with not equals in Java android

I have this code the idea is to take the three strings and make sure that they are same strings and ALSO they are not null or empty (if it empty so it will be same), So I wrote this code that and it's working fine in java online compiler but not working in Android studio (the condition is false i think!) or because I put the if outside so it doesn't working!

 int i = 0; ...

    B1 = (Button) findViewById(R.id.B1);
    B2 = (Button) findViewById(R.id.B2);
    B3 = (Button) findViewById(R.id.B3);

    B1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            if (i==0){
                B1.setText("X");
                i++;}
            else if (i==1){
                B1.setText("O");
                i = 0;}
        }
    });

  // the same for B2 and B3...

    String SB1 = B1.getText().toString();
    String SB2 = B2.getText().toString();
    String SB3 = B3.getText().toString();
    if (SB1.equals(SB2) && SB2.equals(SB3) && !SB1.equals("") ){
        Win.setText("win");
    }

creating new column in data frame with condition on nonempty cells in R

I have a table looking like this:

  A   B
  aa  bb
  aa  
  aa  bb

And I want to Check if a data frame cell is blank and if yes find a result table like this:

  A  B  S
  aa bb bb
  aa    aa
  aa bb bb

I'm using this code but it doesn't work

for(k in dim(df))
  if (df$BB == ""){
    df$S <- df$AA
  }else {df$S <- df$BB}

How to reference another table value when updating current table in an IF statement

Basically, I would like to update a column in table1 by writing an if statement that references a column in table1 and another column in table2. My idea for the code goes something like this, but I get an error in my syntax when referencing table2 in the IF statement.

UPDATE table1 JOIN table2 ON table1.col_a = table2.col_b
SET 
    table1.POD = IF(table1.col_x LIKE '2%' AND table2.col_y = 'YES', 1, NULL)

I'm confused as when for example I update my table1/join with table2:

SET table1.random_col = table1.random_col1 * table2.random_col2

something like the above works fine with no problems.

Plotting zero values

I want create a bivariate map plotting two variables: production and possession. In order to give part of the data the correct colour I want to add a column with color codes "A", "B", "C" for one variable and for the other 1, 2, 3. Then later concatinating the two. Just so that the data is coded like the following example:

enter image description here

Here's my example df and failing code:

library(dplyr)

example_df <- structure(list(production = c(0.74, 1.34, 2.5), possession = c(5, 
23.8, 124.89)), .Names = c("production", "possession"), row.names = c(NA, 
-3L), class = c("tbl_df", "tbl", "data.frame"))

example_df %>%
  mutate(colour_class_nr = case_when(.$production %in% 0.628:0.608 ~ "1",
                                     .$production %in% 0.609:1.502 ~ "2",
                                     .$production %in% 1.503:3.061 ~ "3",
                                     TRUE ~ "none"),
         colour_class_letter = case_when(.$possession %in% 0.276:9.6 ~ "A",
                                         .$possession %in% 9.7:52 ~ "B",
                                         .$possession %in% 52.1:155.3 ~ "C",
                                         TRUE ~ "none"))

With these results...:

# A tibble: 3 x 4
  production possession colour_class_nr colour_class_letter
       <dbl>      <dbl> <chr>           <chr>              
1      0.740       5.00 4               none               
2      1.34       23.8  4               none               
3      2.50      125    4               none  

But this IS the desired output:

# A tibble: 3 x 4
  production possession colour_class_nr colour_class_letter
       <dbl>      <dbl>           <dbl> <chr>              
1      0.740       5.00 2                A               
2      1.34       23.8  2                B               
3      2.50      125    3                C 

I'm new with case_when() incombination with mutate, hope someone can help.

Optimize long if statement in Python

I have a if statement inside a loop that sets a variable to a specific country name if it matches the condition, that is, if the parameter contains the country name.

The parameters are a list of paths that contain a country name in different positions, i.e. C:\\some\\path\\text_country_text.xlsx or C:\\some\\path\\text_text_country_text.xlsx

The if statement is pretty long at the moment because it checks a rather long list of countries. The code I wrote works but it does not look really optimized. Is there a shorter way to do this?

def my_function(*args): 
    for country in args:
        if "Australia" in country:
            country_name = "Australia"
        elif "Austria" in country:
            country_name = "Austria"
        # etc. for many countries

Repeat one particular case statement on invalid output condition and loop inside the case

I have a case statement like 1) 2) 3) ... as below where there are multiple if else condition on 1) format case. I want to repeat the particular case on invalid condition. When user select 1 first it ask for the name of the juice. next it asks the availability. If yes it continues else asks for the count and does an operation. If the operation "exit 0" it just prints done. if the operation "exit 1" I wanted the loop to continue from the top ie from "name of the juice?"

1)
echo "Name of the Juice ?"
read juice
echo "Is it available? [Y/N]"
read deci
if [ "$deci" = "N" ]
then
echo "Continue.!"
else
echo "how many left in the warehouse ?"
read left
I have a command here which exits 0 or 1
if [ $? -eq 0 ]; then
echo "done"
else 
<I have to continue from the start [ie;name of the juice]>
fi
fi
;;
echo "Name of the Pizza ?"
read juice
echo "Is it available? [Y/N]"
read deci
if [ "$deci" = "N" ]
then
echo "Continue.!"
else
echo "how many left ?"
read left
I have a command here which exits 0 or 1
if [ $? -eq 0 ]; then
echo "done"
else 
<I have to continue from the start [ie;name of the juice]>
fi
fi
;;

Beginners "Hangman" break [on hold]

The game allows the user to input an unlimited number of attempts, even after the word is is fully spelled out.I cant figure out how to incorporate a break or an if statement for the code to stop after 5 attempts.

using System;

class Hang
{
    static void Main(string[] args)
    {
        Console.WriteLine("Welcome to Hangman!");

        Random r = new Random();
        string[] wordBank = { "One", "Two", "Three", "Four"};
        string wordGuess = wordBank[r.Next(0, wordBank.Length)];

        char[] guess = new char[wordGuess.Length];
        for (int i = 0; i < wordGuess.Length; i++)
        guess[i] = '_';

        while(true)
        {
            {
                Console.Write("enter your guess: ");
                char myGuess = char.Parse(Console.ReadLine());

                for (int j = 0; j < wordGuess.Length; j++)

                    if (char.ToLower(myGuess) == char.ToLower(wordGuess[j]))
                        guess[j] = wordGuess[j];
            }

            Console.WriteLine(guess);
        }
    }
}

dimanche 25 février 2018

Linux Shell Scripting: Script Check

I am new to Linux bash scripting and I can't seem to find what I'm doing wrong. Here's my code. Entering number 2 and 3, after the prompt that I ask the user my code stops it doesn't continue to the IF ELSE statements. Thank you to those who will help!

!/bin/bash

while true do clear echo "Please enter one of the following options" echo "1. Move empty files" echo "2. Check file size" echo "3. Which file is newer" echo "4. File check rwx" echo "5. Exit". echo -e "Enter Choice:" read answer case "$answer" in 1) ./move_empty exit 55 ;; 2) echo "Enter a filename" read filename if [ -f $filename ]; then ./file_size fi ;; 3) echo "Enter first file:" read filename echo "Enter second file:" read filename2 if [ ! -f "$filename" ]; then echo "Supplied file name" $filename "does not exist"; if [ $filename" -nt $filename" ]; then echo $filename "is newer" exit 1

fi fi ;;

    5) exit ;;

esac done

Want to break after if statement, kinda?

So what i am trying to do is test a form textbox for input. Once i click a button, i want it to check if there is any text, if not, i want it to break there and keep prompting a messagebox until the user inputs proper text, and then continue with the program.

if (entryName.Text == "")
        {
            MessageBox.Show("Please enter a name for the entrant");
        }
        if (pickPartner.Text == "")
        {
            MessageBox.Show("Please pick a partner to rope with");
        }
        if (comboBox1.SelectedIndex == -1)
        {
            MessageBox.Show("Please choose a role");
        }
        else
        {
            if(comboBox1.SelectedIndex == 0)
            {
                headerEntries.Add(entryName.Text);                   
                using (StreamWriter writeRopers = new StreamWriter("headers.txt"))
                {
                    writeRopers.WriteLine(entryName.Text);
                }
                using (StreamWriter writeRopers = new StreamWriter("teams.txt"))
                {
                    writeRopers.WriteLine(entryName.Text + " & " + pickPartner.Text);
                }
                    Debug.WriteLine(entryName.Text + " has been added as a header");
                headerCount = headerCount + 1;
                entryName.Clear();
                comboBox1.SelectedIndex = -1;

            }

conditions and singular output

i = int(input("Enter an integer "))

if i%3 == 0: 
    print('Fizz')

if i%5 == 0:
    print('Buzz')

if i%3 == 0 and i%5 == 0:
    print('Fizz Buzz')

When I enter the integer "15", the program returns "Fizz", "Buzz", and "Fizz Buzz". I'd like to seek some ideas as to how I get the program to return only one output base on the conditions.

No solutions!

Can an IF statement be used inside math.max in Java?

I want to know if it is possible to use an if statement inside of math.max. For example if you have an object like so:

    public class Obj {
        private int i;
        private boolean b;
        public void setInt(int newInt) {
            this.i = newInt;
        }
        public void setBool(int newBool) {
            this.b = newBool;
        }
        public String getInt() {
            return this.i;
        }
        public String getIsTrue() {
            return this.b;
        }
    }

After initializing 3 new objects and defining all values, is it possible to do something like this:

    System.out.println(Math.max(if(obj1.getIsTrue()) {obj1.getInt()}, if (obj2.getIsTrue()) {obj2.getInt()}, if (obj3.getIsTrue()) {obj3.getInt()}));

I know that it can be done with an array and a for loop, so I'm not asking is it possible at all, just is it possible to nest if statements in this way.

T-SQL If Statement issue

I have 2 datatables dbo.Videos and dbo.Checkouts. The dbo.Videos datatable contains a list of videos while the dbo.Checkouts is datatable keeping track of the videos that have been checked out. The goal in my tsql command is to insert a new row in the dbo.Checkouts table including VideoId, UserId, CheckoutDate. Once this is successful I then want to update the dbo.Videos and decrement the TotalCopies column value based on the VideoID selected only if the value is greater than 0. If less than 0 I want to throw an exception. The VideoID in both datatables are linked by foreignkey. However, the IF statement I have included in my statement below throws an error. How would I fix this. Thanks in advance.

INSERT INTO dbo.Checkouts (VideoId, UserId, CheckoutDate)
VALUES (32, 'b0281f0d-8398-4a27-ba92-828bfaa9f90e', CURRENT_TIMESTAMP)

IF (SELECT TotalCopies FROM dbo.Videos WHERE VideoId = 32) > 0
UPDATE dbo.Videos SET
TotalCopies = TotalCopies - 1
WHERE VideoID = 32

VBA needing to automatically fill a column with an if statement when column locations are not fixed

I am trying to do the following:

Find a column called Employee SGrp, then add a column to the right of Employee SGrp which has the heading of Employee Classification as the first column. I then auto fill this column with a formula.

However the data is based on a report and the column location are not fixed (i.e. Employee SGrp may be in M one month and L the next). Therefore I can't use cell references like 'A2' in my formulas. In addition there are a few different options in the previous two columns so I am going to need to use an if statement as my formula to fill the columns. For example if "driver" write contractor, if part time write "permanent" if casual write "permanent".

I have added a column using the offset and resize features and have added add a value to serve as the heading. I have managed to put a formula in but only have it fill basic calculation such as sum or fill in a number) I have not been able to nest an if statement in this form and have also been unable to build the if statement properly. I can create a formula using fixed values (e.g. A2) but I need to be able to reference the column by name not fixed location since it isn't always in the same cell reference. I would appreciate any help in accomplishing this as I haven't found anything yet which will allow me to accomplish what I need to do.

'Insert a new column to the right of rngLocation
rngEmpClass.Offset(, 1).EntireColumn.Insert
Set rngNewCol = rngEmpClass.Offset(, 1)


rngNewCol.Value = "Employee Classifications"
With rngNewCol.Offset(1).Resize(lRow)
    .NumberFormat = "General"   'Set column to General format
    .Formula = "2"

if statement - unexpected 'else' (T_ELSE)

I'm making this comment section page, but i'm getting this error: syntax error, unexpected 'else' (T_ELSE) on line 33

I'm trying to solve this error for about an hour, and i can't find the solution..

Here it is my code :

    <?php 
session_start();
$_SESSION['user'] = "Admin";

function get_total(){
    require 'connect.php';
    $result = mysqli_query($conn, "SELECT * from parents order by date desc");
    $row_cnt = mysqli_num_rows($result);
    echo '<h1>Comentários ('.$row_cnt.')</h1>';
}

function get_comments(){
    require 'connect.php';
    $result = mysqli_query($conn, "SELECT * from parents order by date desc");
    $row_cnt = mysqli_num_rows($result);

    foreach ($result as $item) {
        $date = new dateTime($item['date']);
        $date = date_format($date, 'M j, Y | H:i:s');
        $user = $item['user'];
        $get_comment = $item['text'];
        $par_code = $item['code'];

        echo '<div class="comment" id="'.$par_code.'">'
            .'<p class = "user">'.$user.'</p>&nbsp;'
            .'<p class = "comment-text">'.$comment.'</p>'
            .'<a class = "link-reply" id="reply" name="'.$par_code.'">Reply</a>';

            $chi_result = myqsli_query($conn, "SELECT * FROM `children` WHERE `par_code` = '$par_code' ORDER BY `date` DESC");
            $chi_cnt= mysqli_num_rows($chi_result);

            if ($chi_cnt == 0) 
                { else{
                    echo '<a class ="link-reply" id="children" name="'-$par_code.'"><span id="tog_text">Respostas</span> ('.$chi_cnt.')</a>'
                    .'<div class="child-comments" id="C-'.$par_code.'">';
                foreach ($chi_cnt as $com) {
                    $chi_date = new dateTime($com['date']);
                    $chi_date = date_format($chi_date, 'M j, Y | H:i:s');
                    $chi_user = $com['user'];
                    $chi_com = $com['text'];
                    $chi_par = $com['par_code'];

                    echo '<div class="child" id="'.$par_code' -C">'
                            .'<p class="user">'.$chi_user.'</p>&nbsp;'
                            .'<p class="time">'.$chi_date.'</p>'
                            .'<p class="comment-text">'.$chi_com.'</p>'
                            .'</div>';
                }
                echo '</div>';
            }
            echo '</div>';
    }
}
      ?>

i think it is a stupid error, and sorry for bad english!!

Printing User Input/Multidimensional Array

I apologize if this is a repeat question. I'm not sure what to look for.

This is for an assignment so I would really like a push in the right direction versus just getting the answer. The code is to repeatedly ask a user to enter a state name which returns the state bird and state flower. Once the user has entered "None," a summary prints out that contains the state, bird, and flower of each state the user entered. Currently, the summary only prints the information of the LAST state entered by the user.

I am sorry for the sloppy work. I'm only beginning to learn!

public class StateInformation {

    private String[][] stateInfo =  {
        {"Alabama", "Yellowhammer", "Camellia"},
        {"Alaska", "Willow Ptarmigan", "Alpine Forget-Me-Not"},
        {"Arizona" , "Cactus Wren", "Saguaro Cactus Blossom"},
        {"Arkansas", "Northern Mockingbird", "Apple Blossom"},
        {"California", "California Quail", "California Poppy"},
        {"Colorado", "Lark Bunting", "Rocky Mountain Columbine"},
        {"Connecticut", "American Robin", "Mountain Laurel"},
        {"Delaware", "Blue Hen Chicken", "Peach Blossom"},
        {"Florida", "Northern Mockingbird", "Orange Blossom"},
        {"Georgia", "Brown Thrasher", "Cherokee Rose"},
        {"Hawaii", "Nene", "{Pua Aloalo"},
        {"Idaho", "Mountain Bluebird", "Syringa"},
        {"Illinois", "Greater Prairie-Chicken", "Violet"},
        {"Indiana", "Northern Cardinal", "Peony"},
        {"Iowa", "Eastern Goldfinch", "Wild Rose"},
        {"Kansas", "Weatern Meadowlark", "Wild Native Sunflower"},
        {"Kentucky", "Northern Cardinal", "Goldenrod"},
        {"Louisana", "Brown Pelican", "Louisana Iris"},
        {"Maine", "Black-Capped Chickadee", "White Pine Cone and Tassel"},
        {"Maryland", "Baltimore Oriole", "Black-Eyed Susan"},
        {"Massachusetts", "Black-Capped Chickadee", "Mayflower"},
        {"Michigan", "American Robin", "Apple Blossom"},
        {"Minnesota", "Common Loon", "Pink and White Lady Slipper"},
        {"Mississippi", "Northern Mockingbird", "Magnolia"},
        {"Missouri", "Eastern Bluebird", "White Hawthorn Blossom"},
        {"Montana", "Western Meadowlark", "Bitterroot"},
        {"Nebraska", "Western Meadowlark", "Goldenrod"},
        {"Neveda", "Mountain Bluebird", "Sagebrush"},
        {"New Hampshire", "Purple Finch", "Pink Lady's Slipper"},
        {"New Jersey", "Eastern Goldfinch", "Violet"},
        {"New Mexico", "Greater Roadrunner", "Yucca"},
        {"New York", "Eastern Bluebird", "Rose"},
        {"North Carolina", "Northern Cardinal", "Dogwood"},
        {"North Dakota", "Western Meadowlark", "Wild Prairie Rose"},
        {"Ohio", "Northern Cardinal", "White Trillium"},
        {"Oklahoma", "Scissor-Tailed Flycatcher", "Mistletoe"},
        {"Oregon", "Western Meadowlark", "Oregon Grape"},
        {"Pennslyvania", "Ruffed Grouse", "Mountain Laurel"},
        {"Rhode Island", "Rhode Island Red Chicken", "Violet"},
        {"South Carolina", "Carolina Wren", "Yellow Jessamine"},
        {"South Dakota", "Ring-necked Pheasant", "American Pasque"},
        {"Tennessee", "Northern Mockingbird", "Passion Flower"},
        {"Texas", "Northern Mockingbird", "Ennis"},
        {"Utah", "California Gull", "Sego Lily"},
        {"Vermont", "Hermit Thrush", "Red Clover"},
        {"Virginia", "Northern Cardinal", "American Dogwood"},
        {"Washington", "Willow Goldfinch", "Coast Rhododendron"},
        {"West Virginia", "Northern Cardinal", "Rhododendron"},
        {"Wisconsin", "American Robin", "Wood Violet"},
        {"Wyoming", "Western Meadowlark", "Indian Paintbrush"},
    };//End array initialization
public StateInformation() {
}
public String[][] getStateInfo(){
   return stateInfo;
}
public void setState(String[][] state) {
    this.stateInfo = stateInfo;
}
}//End of Class

Here is the second class:

//Second Class
import java.util.Scanner;

public class TestStateInformation {
public static void main(String [] args) {

StateInformation states = new StateInformation();   
String [][] state = states.getStateInfo();  
//Inserting scanner & variable. 
Scanner scanner = new Scanner(System.in);

while(true) {
    //Prompt the user to input a state name.  
    System.out.println("Please enter a state or None to exit: ");
    //Read the state entered by user, including leading/trailing white spaces.
    String stateInfo = scanner.nextLine();

    //If loop to end if None is entered.
    if (stateInfo.equalsIgnoreCase("None")) {
        break;
    } else {
        int position = getStatePosition(state, stateInfo);
        if (position != -1) {
            System.out.println("Bird: " + getBird(position, state) +'\n' + "Flower: " + getFlower(position, state) + '\n');
        }
        if ((scanner.nextLine().equals("None"))) {
                System.out.println("***** Thank you! *****" + '\n' + "A summary report for each State, Bird, and Flower is: "
                         + '\n' + getState(position, state)+ ", "+ getBird(position, state) + ", "+ getFlower(position, state)
                         + '\n' + "Please visit our site again!");
            }//end if loop for printing bird and flower of state entered by user.
        }//End else loop
    }//end if loop
}//end while loop
private static int getStatePosition(String state[][], String stateInfo) {
    for (int i = 0; i < state.length; i++) {
        if (stateInfo.equalsIgnoreCase(state[i][0])) {
            return i;
        }
    }
return -1;
}
//Creates the position of the state name into [0]
private static String getState(int position, String [][] state) {
    return state[position][0];  
}
    //Creates the position of the state bird into [1].
    private static String getBird(int position, String [][] state) {
        return state[position][1];
}
    //Creates the position of the state bird into [2]
    private static String getFlower(int position, String [][] state) {
        return state[position][2];
}
}

Checking individual digits and copying valid ones by looping

I am creating a "CodeBreaker" game. In this game, the computer randomly generates a secret numeric code that is three digits in length, composed of digits ranging from one through six. The player's task is to guess all of the digits of the code, in the correct order. After twelve guesses, the game is over.

The computer checks the digits guessed by the player, comparing each to ones in the secret code, and determines whether each digit in the player's guess is of the correct identity and in the correct place, or whether each digit is of the correct identity but is not in the correct place. With each guess, it counts the number of “correct” and “misplaced” digits, and prints these totals to the screen, alongside the player's guess. This is the section I am having trouble with. I need to loop through the player's input, checking each digit, then copy the valid digits using an if-else statement.

#include <iostream>
#include <cstdlib>
#include "Project1.h"

using namespace std;

string get_player_code() {


    string player_code = string(CODE_LENGTH, '0');

    string player_input;                            

    char digit;

    bool valid_code = false;                            
    bool invalid_digit_entered;                     

while ( !valid_code ) {

    invalid_digit_entered = false;

    cout << "Enter Code: ";
    cin >> player_input;

    /* Is code too short or too long? */

    if ( player_input.size() != CODE_LENGTH ) {

        cout << "ERROR: Code must be exactly " << CODE_LENGTH << " digits long!\n\n";

    }

    /* If not, loop through player_input and check each digit, copying validated digits into player_code */

    else {

        // *** INSERT CODE HERE ***

        valid_code =  true;

         }

} // End while()

return player_code;
}

How to pick 1 of my 3 formulas in my program?

I just wrote up a program to ask the user to calculate the area, circumference, and the diameter of a circle based on a radius input. However, I'm stumped on how to ask which calculation they want to make between the 3 choices. which is step 1. I have completed 2-4 steps. Any help on this one? (I.e. Only allow them to make one calculation per run of the program) The bolded area is obviously what I tried and failed miserably at....

**Radius = float(input("What type of calculation would you like to 
make? "))
if 1 = "area"
elif: 2 = "circumference"
else: 3 = "diameter"
return("num")**

PI = 3.14
radius = float(input(' Please Enter the radius of a circle: '))
area = PI * radius * radius
circumference = 2 * PI * radius

print(" Area Of a Circle = %.2f" %area)
print(" Circumference Of a Circle = %.2f" %circumference)

import math

circumference = float(input(' Please Enter the Circumference of a 
circle: '))
area = (circumference * circumference)/(4 * math.pi)

print(" Area Of a Circle = %.2f" %area)

import math

diameter = float(input(' Please Enter the Diameter of a circle: '))
area1 = (math.pi/4) * (diameter * diameter)
# diameter = 2 * radius
# radius = diameter/2
radius = diameter / 2
area2 = math.pi * radius * radius

print(" Area of Circle using direct formula = %.2f" %area1);
print(" Area of Circle Using Method 2 = %.2f" %area2)

if..else statement in Google Distance Matrix results

I'm using Google Distance Matrix API to calculate the driving distance + time from one point to another.

I would like to add if..elseif..else statements to the result of the distance search to vary the answers according to how big the distances (e.g. < or > 10 km) are but I'm a newbie to JS and can't seem to figure out where to stick the statements into my code. Any tips?

Here's my code:

$(function(){
   function calculateDistance(origin, destination) {
      var service = new google.maps.DistanceMatrixService();
      service.getDistanceMatrix(
      {
        origins: [origin],
        destinations: [destination],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
      }, callback);
    }

    function callback(response, status) {
      if (status != google.maps.DistanceMatrixStatus.OK) {
        $('#result').html(err);
      } else {
        var origin = response.originAddresses[0];
        var destination = response.destinationAddresses[0];
        if (response.rows[0].elements[0].status === "ZERO_RESULTS") {
          $('#result').html("We can't seem to find "
                            + origin + ". Are you sure you entered a valid postcode and place?");
        } else {
          var distance = response.rows[0].elements[0].distance;
          var duration = response.rows[0].elements[0].duration;
          var distance_value = distance.value;
          var distance_text = distance.text;
          var duration_value = duration.value;
          var duration_text = duration.text;
          var kilometer = distance_text.substring(0, distance_text.length - 3);
          $('#result').html("It is " + kilometer + " kilometer from " + origin + " to " + destination + " and it takes " + duration_text + " to drive.");
        }
      }
    }

    $('#distance_form').submit(function(e){
        event.preventDefault();
        var origin = $('#origin').val();
        var destination = $('#destination').val();
        var distance_text = calculateDistance(origin, destination);
    });

  });

What is the logic behind "if" statements? Drawing with for-loops

So I'm supposed to draw a mountain using a for-loop, using if statements to decide what character to use. This what I did initially.

for (int y = intMaxHeight; y >= 0; y--){
           for (int x = 0; x < arr.length; x++){
             double height = arr[x];

              if (y == 0){
                   System.out.print("-");
               } 

              if (((y - height) < 1) && ((y - height) > -1)){
                   System.out.print("^");
               } 

               if (y > height){
                   System.out.print(" ");
               }

               if ( y < height){
                   System.out.print(symbol);
               }       
           }
           System.out.println();
     }

This prints out a very ugly mountain This prints out a very ugly mountain Now, by adding "else" to the last three statements, the mountain looks like what it's supposed to, and I wonder why is that. enter image description here

But the new problem is that the mountaintop symbol "^" will be printed twice sometimes, which is not supposed to happen. I tried switching the order of the if statement, but just like with the ugly mountain, it didn't change anything. Any ideas on what the problem could be?

Remove class from nav when sibling is clicked

I've created a navigation that highlights whatever menu item is selected by adding an 'active' class. If you click the body it removes the active class from the menu item and starts over. It works as expected except when you click a sibling on the menu. The active class is added to the newly clicked menu item, but it also remains on the old one. I wrote code that is suppose to loop through all menu items to see if any of them have the 'active' class, remove the class and then add the 'active' class to the new selection. It's not working.

What am I doing wrong? Also is there any easier way to do this? I need to solve this with vanilla Javascript. I can't use jQuery.

// html

<ul class="nav-items">
   <li class="nav-item"></li>
   <li class="nav-item"></li>
   <li class="nav-item"></li>
   <li class="nav-item"></li>
   <li class="nav-item"></li>
   <li class="nav-item"></li>
   <li class="nav-item"></li>
</ul>

// js

if (navItems) {
    navItems.addEventListener("click", function(e) {
        var background = document.querySelector('.background');
        var callout = document.querySelectorAll('.background, .nav-close')
        console.log(e.target.closest('.nav-item'));

        if (background.style.display !== "block") {
            background.style.display = "block";
            for( let i = 0; i < e.target.closest('.nav-items').children.length; i++ ) {
                console.log(e.target.closest('.nav-items'));
                e.target.closest('.nav-item').classList.remove('active');
            }

            e.target.closest('.nav-item').classList.add('active');

            if (background.style.display === "block") {
                callout.forEach(function(elem) {
                    elem.addEventListener("click", function(event) {
                        background.style.display = "none";
                        console.log('target', e.target);
                        e.target.closest('.nav-item').classList.remove('active');
                    }); 
                });
            }

        } else {
            background.style.display = "none";
            e.target.closest('.nav-item').classList.remove('active');

        }
    })
}

How to stop other "else if conditions" from executing if 1st "if condition" is true

Its been bugging me for a day now and I don't know how to do this because I'm still new to java and android. I have this code that has a if and else if statement in a for loop. Now the problem is that if the 1st condition is true it will also execute the other condition below the 1st which is not what I want. I want to stop the loop when the above condition is true and exit it.

So can anyone please tell me what is wrong.

for(findpet_getItems items:arrayList)
        {
            for(int i=0; i <arrayList.size();i++)
            {
                if(i !=0){
                    if (items.getHair().toLowerCase().contains(hair) && items.getColor().toLowerCase().contains(color)
                            && items.getSize().toLowerCase().contains(size) && items.getWeight().toLowerCase().contains(weight)
                            ) {
                        new_list.add(items);
                        break;
                    }
                    else if (items.getSize().toLowerCase().contains(size) && items.getWeight().toLowerCase().contains(weight)) {
                        new_list.add(items);
                        break;
                    }

                    else if (items.getHair().toLowerCase().contains(hair) && items.getColor().toLowerCase().contains(color)) {
                        new_list.add(items);
                        break;
                    }
                    else {
                        results.setText("Search not found");
                    }
                }
            }
        }

accept two different input for the same if statement

how can I accept two different answers for the same if statement

something like

if (action = a || b ) { then do this

// this does not work, also is there a way to make sure it accepts the entry regardless if it's cap or noncap

thanks

Component does not render list with if statement

I am using mobx + react setup for this subpage to make a searchable list of users. My list of items is not rendering with if statement. In the solution I am trying to render one of two lists in my subpage. Depending on boolean 'isSearching'. First element should be shown when input field is empty, and second one is when input field has value written. They are same arrays, Only difference between lists arrays are that one of them is filtered.

<ul className='items__block'>
    {
    this.props.PeopleStore.people.isSearching = false //checks mobx prop
    ?
    (this.props.PeopleStore.people.map(this.person))
    : 
    (this.props.PeopleStore.searchingList.map(this.person))
    }
</ul>

Althought if I remove conditional if statement it works separated:

<ul className='items__block'>
    {
    this.props.PeopleStore.people.map(this.person)
    }
</ul>

-

<ul className='items__block'>
    {
    this.props.PeopleStore.people.map(this.person)
    }
</ul>

Store file:

import { runInAction, observable, action, toJS } from 'mobx';
// ES7 compiler
import regeneratorRuntime from 'regenerator-runtime';

class PeopleStore {
    @observable people = [];
    @observable loading = false;
    @observable isSearching = false;
    @observable searchingList = [];

// API call
loadPeople = async() => {
    this.loading = true;
    const response = await fetch('https://randomuser.me/api/?results=71');
    const json = await response.json();
    runInAction(() => {
        this.people = json.results;
    });
    this.loading = false;
    console.log(toJS(this.people));
}

// this function is called by onChange event
@action.bound filterList = textTyped => {
   // changing boolean to identify if input is empty or not
    if (textTyped.target.value.length < 1) {
        this.isSearching = false;
    } else {
        this.isSearching = true;
    }

    console.log(this.isSearching);

    let peoplesNames = [];
    for (let i = 0; i < this.people.length; i++) {
        peoplesNames.push(toJS(this.people[i]));
    }
    peoplesNames = peoplesNames.filter(function(item) {
        return item.name.first.toLowerCase().search(textTyped.target.value.toLowerCase()) !== -1
    });

    this.searchingList = peoplesNames;
// tracking both arrays, they both work
    console.log(toJS(this.searchingList));
    console.log(toJS(this.people));
    }
}

export default new PeopleStore();

Component file:

@inject('showHandler', 'PeopleStore') @observer
class PickList extends React.Component {

componentWillMount() {
    this.props.PeopleStore.loadPeople();
}


person = ({name, picture}, index) =>
    <li className="items__block--user" key={index} onClick={this.props.PeopleStore.selectPerson}>
        <img className="user--image" src={picture.medium} alt="face" />
        <span className="user--name">{`${name.first} ${name.last}`}</span>
    </li>;

render() {
    // loading screen
    if (this.props.PeopleStore.loading) {
        return (
            <div className="loader"></div>
        );
    }

    return (
        <React.Fragment>
            <input className="users__block--input" onChange={this.props.PeopleStore.filterList}></input>
            <ul className='items__block'>
                {
                this.props.PeopleStore.people.isSearching = false //checks mobx prop
                ?
                (this.props.PeopleStore.people.map(this.person))
                : 
                (this.props.PeopleStore.searchingList.map(this.person))
                }
            </ul>

Why is it not working? On page render isSearching prop is set to false and that should effect the if statement as it is.

JS Dice - Assigning Math.random value to an html image using if condition

Hello i'm using Javascript to create a random dice output (from 1-6) including an image of the dice side.
The mathRandomDice function is working fine but my 'if' condition which assigning it to the image is not...
My goal is to assign the Math.random value to an image.

function mathRandomDice() {
    document.getElementById("dice").innerHTML = Math.floor(Math.random() * 6) + 1; 

}

var x = mathRandomDice;

  if (x = 1) {
            d.innerHTML = '<img src=https://image.ibb.co/cQKOhc/dice1.png>';
    }

function mathRandomDice() {
    document.getElementById("dice").innerHTML = Math.floor(Math.random() * 6) + 1; 

}
  body {
    text-align:center;}


/* button */

button {
  display: inline-block;
  padding: 15px 25px;
  font-size: 24px;
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  outline: none;
  color: #fff;
  background-color: #4CAF50;
  border: none;
  border-radius: 15px;
  box-shadow: 0 9px #999;
}

button:hover {background-color: #3e8e41}

button:active {
  background-color: #3e8e41;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}
 <h5> Press the button for a random dice number<h5>
    <span id="yournum"></span>
   <p id="dice"></p>
<button onclick="mathRandomDice()">Roll The Dice</button>
<br><br>
   <img src="https://image.ibb.co/cQKOhc/dice1.png" alt="1" class="center">
   <img src="https://image.ibb.co/cmyG2c/dice2.png" alt="2" class="center">
   <img src="https://image.ibb.co/bPNyFx/dice3.png" alt="3" class="center">
   <img src="https://image.ibb.co/fmkJFx/dice4.png" alt="4" class="center">
   <img src="https://image.ibb.co/d6D5vx/dice5.png" alt="5" class="center">
   <img src="https://image.ibb.co/nFqkvx/dice6.png" alt="6" class="center">

If date greater than or equal then function

Public DateRng As String

Private Sub DateLookup()

'Dim ColCnt As Integer

'Prompt Date to look for
  DateRng = InputBox("Insert date in format dd/mm/yy", "User date", Format(Now(), "dd/mm/yy"))
  If IsDate(DateRng) Then
    DateRng = Format(CDate(DateRng), "dd/mm/yy")
    ColumnDateCheck
'    MsgBox DateRng
  Else
    MsgBox "Wrong date format"
    Exit Sub
  End If



End Sub

Private Sub ColumnDateCheck()

    For C = 3 To 29
        If Cells(C, 2) >= DateRng Then
            'Function
            Cells(C, 5) = Cells(C, 3) + Cells(C, 4)

        End If
    Next

End Sub

Data in which code is performing on

Test Sheet

Not having error executing code but function is not working as intended. It executes function in a mess without any pattern behind it. Can't understand output.

  1. InputBox in DateLookup sub prompts for date
  2. If entry is valid, call out ColumnDateCheck Sub
  3. Look for date entered in column B from Row 3 to 29. If date is greater or equal to, adds column C & D in Column E.

PHP print message if the mark posted from previous page is not same with the input value that player input

I am struggling with php now. What I am trying to do is to put the mark wherever in the block of input when selecting the second turn and moving to the next page. But it is not showing anything for now when moving to next page. Here is my code. I really appreciate everybody's help! What I am trying to do is adding something like this. if(isset($_POST["start"])){if($senkou=="second" && $mark=="×"){$block='×';} if($senkou=="second" && $mark=="○"){$block='○';}

<?php
session_start();
if(isset($_POST["start"])){
$namae=$_POST['namae'];
$senkou=$_POST['senkou'];
$mark=$_POST['mark'];
$_SESSION['namae']=$namae ;
$_SESSION['senkou']=$senkou ;
$_SESSION['mark']=$mark ;
}else{
$namae=$_SESSION['namae'];
$senkou=$_SESSION['senkou'];
$mark=$_SESSION['mark'];
}
$block=array('','','','','','','','','');
if(isset($_POST["send"])){
$block[0]=$_POST["block0"];
$block[1]=$_POST["block1"];
$block[2]=$_POST["block2"];
$block[3]=$_POST["block3"];
$block[4]=$_POST["block4"];
$block[5]=$_POST["block5"];
$block[6]=$_POST["block6"];
$block[7]=$_POST["block7"];
$block[8]=$_POST["block8"];

$blank=0; 
for ($i=0; $i<=8; $i++){
if($block[$i]==''){
$blank=1;
}
if($blank== 1 && $winner=='n'){
$i=rand() % 8 ;
while($block[$i] !=''){
$i=rand() % 8 ;
}
if ($mark=="○"){
$block[$i]='×';
}
if ($mark=="×"){
$block[$i]='○';
}
}
}
?>
<html>
<head>
<title>TicTacToe</title>       
</head>
<body class="body">
<input type="hidden" id="postedmark" value="<?php echo $mark ?>">
name:<?php echo $namae ;?>
who goes first:<?php echo $senkou ;?>
mark:<?php echo $mark ?>
<form name="myform" method="post" action="tttgames2.php">
<?php
for ($i=0; $i<=8; $i++){
printf('<input type="text" name="block%s" value="%s" id="block" 
onchange="check()">',$i,$block[$i]);
if($i==2 || $i==5 || $i==8){
print('<br>');
}
}
print('<input type="submit" class="send" name="send" id="send" value="send">');
} 

?>
</form>
</body>
</html>

Find maximum of three inputs

Here are the steps we need to take:


a. Use the Scanner class to create an object to read input from the keyboard.

b. Declare three int variables called x, y, z, and max.

c. Prompt the user to enter a value for variables x, y, and z.

d. Find the maximum of x, y, and z, then assign the maximum to max.

e. Display the maximum.

My code seems to run endlessly whats wrong here's my code:

import java.util.Scanner;

public class Maximum {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        int x;
        int y;
        int z;
        int max;

        System.out.print("Enter Value For x: ");
        x = keyboard.nextInt();

        System.out.print("Enter Value For y: ");
        y = keyboard.nextInt();

        System.out.print("Enter Value For z");
        z = keyboard.nextInt();

        max = Math.max(Math.max(x, y), z);

        if (x > y && x > z) {
            x = max;
        }
        if (y > x && y > z) {
            y = max;
        }
        if (z > x && z > y) {
            z = max; // Getting "assigned value is never used"
        }
        System.out.println("The Maximum is" + max);
    }
}

Can you shorten this code?

This is an equation to check whether 1 of the 3 elements has value. If yes, all elements must have value.

if(   (a!='' || b!='' || c!='')   &&   (a=='' || b=='' || c=='')   )
alert('Please fill all elements');

samedi 24 février 2018

function needs to be void with if, else if, else? hash map, java

OK, very odd. Not come across this before from what I can remember.

OK, so the compiler is telling me that the following method should be void for some reason:

 public static HashMap<String, ArrayList<FlightData>> mapper(ArrayList<String> lineBuffer) {

    HashMap<String, ArrayList<FlightData>> mapdata = new HashMap<>(); //array list for Mapdata object

    for (String flightData : lineBuffer) {
        String[] str = flightData.split(",");
        FlightData flight = new FlightData(str[0], str[1], str[2].toCharArray(), str[3].toCharArray(), new Date(Long.valueOf(str[4])), Long.valueOf(str[5]).longValue()); //creating the object
        mapdata.get(flight.getFlightID()); //getting the flight data
        if (mapdata.containsKey(flight.getFlightID())) { //checking if the data for the oject contains hash key Flightdata
            mapdata.get(flight.getFlightID()).add(flight);
        } 
        else if (mapdata.containsKey(flight.getFromID())) {
            mapdata.get(flight.getFromID()).add(flight);
            ArrayList<FlightData> noID2 = new ArrayList<>(); //creating an array for noID
            noID2.add(flight);
            mapdata.put(flight.getFlightID(), noID2);
        }
        else {
            ArrayList<FlightData> noID = new ArrayList<>(); //creating an array for noID
            noID.add(flight);
            mapdata.put(flight.getFlightID(), noID);

            //  System.out.println(mapdata);

        }

        return mapdata;

    }

Which is odd, because when I remove the additional if (if else to just else) its fine:

 public static HashMap<String, ArrayList<FlightData>> mapper(ArrayList<String> lineBuffer) {

    HashMap<String, ArrayList<FlightData>> mapdata = new HashMap<>(); //array list for Mapdata object

    for (String flightData : lineBuffer) {
        String[] str = flightData.split(",");
        FlightData flight = new FlightData(str[0], str[1], str[2].toCharArray(), str[3].toCharArray(), new Date(Long.valueOf(str[4])), Long.valueOf(str[5]).longValue()); //creating the object
        mapdata.get(flight.getFlightID()); //getting the flight data
        if (mapdata.containsKey(flight.getFlightID())) { //checking if the data for the oject contains hash key Flightdata
            mapdata.get(flight.getFlightID()).add(flight);
        } else {
            ArrayList<FlightData> noID = new ArrayList<>(); //creating an array for noID
            noID.add(flight);
            mapdata.put(flight.getFlightID(), noID);
        }
      //  System.out.println(mapdata);

    }

    return mapdata;

}

I get the following:

screenshot of compiler correction suggestion

the error is telling my missing return statement/type. Hence void suggestion. any ideas why??

Any help would be great.

Cheers, Glenn