mardi 30 juin 2020

i don't know how to use ' NaN ' in javascript's if command

Hi guys i know this code is too easy but i'm new in javascript and i'm still learning it . this code gets a value from user then shows an answer but it dosen't matter if value is number or not it just says = its a number .

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <!--Javascript starts-->
    <script>
        var age = prompt("How old are you ?","18");
           if(age == NaN)
           {
               alert("its not a number");
           }else
           {
               alert("its a number");
           }  
    </script>
        <!--End of Javascript-->

    </body>
</html>

hi i have a problem with my code. The output is displayed too slow

$v = 0; // detect item_id from $itemId
$c = 0;// sum id column

for($h1 = 0;$h1 < $a;$h1++){
 
 if($col[$h1] == 0)
 {   echo "<td></td>";$sumCol[$c]=0;$c++;}
 
 for($h2 = 0;$h2 < $col[$h1];$h2++){ 
   
    $id = $itemId[$v];
    $sqlData = "SELECT * FROM MASTER WHERE  Category = $h1+1 AND Item = $id AND $invStock[$r1] IS NOT NULL  AND Date = '$year-$month-$i'";
   
    $result = $conn->query($sqlData);
    while($row = $result->fetch_assoc())
    {   
         if($row['Status'] == 'OPENING')
          {     $opening[$c] = $row['Stock_In'];$sumCol[$c]+=$row['Stock_In']; }
         else if($row['Status'] == 'CLOSING')
          {     $closing[$c] = $row['Stock_In']; }
         else

          switch($invStock[$r1]){
             
            case "Stock_In" : $curr += $row['Stock_In'];$sumCol[$c]+=$row['Stock_In'];$class="text-success";$remarks.=$row['Remarks']."\n"; break;
            case "Adjustment" : $curr += $row['Adjustment'];$sumCol[$c]+=$row['Adjustment'];$class="text-info";$remarks.=$row['Remarks']."\n";break;
            case "Stock_Out" : $curr += $row['Stock_Out'];$sumCol[$c]-=$row['Stock_Out'];$class="text-danger";$remarks.=$row['Remarks']."\n";break;
          }       
     }

if --- else javascript

What I want is to call function b with parameter arr1, if arr1 has at least one value in it, else if arr1 is empty call function b with parameter arr2. However the else block is not calling function b when arr1 is empty.

function a(){
    let arr1 = [];
    let arr2 = [];
    if(arr1){
        b(arr1);
    }
    else {
        b(arr2);
    }   
}

function b(arr){
    doSomething with arr;
}

google finance function not correct in google sheets

The function below should be pulling back the amazon share price on 04/04/2020. The result states $11.43 which is incorrect. This has been working for the past 6 months but not today for some reason. Is this an issue with google finance ?

=GOOGLEFINANCE("amzn","price",date(2020,4,4))

Result is:

Date                    Close
06/04/2020 16:00:00     11.43

If month column A, then return Qty column G

I’m trying to get a formula to show items in or out in a month. In column A I have dates (eg 01/01/20, 15/01/20), and then in column G I have QTY in (eg 15, 7 etc), and out in column H. I’d like to find month And return total value of G (eg in the above total of 22). Thanks, Will

C problem: Trying to convert numbers to binary and hexadecimal, but not getting the right output

I thought my logic was sound, but when I input a number I just get a row of zeroes for the binary conversion and a lot of AAAAs for the hexadecimal conversion. I was originally gonna make hexLetter a character array, but couldn't get it working right. When I tried debugging, I noticed that loop in the binary part completely skips to the printing phase and the if statement goes through the A part multiple times, even if the remainder isn't 10. This happens even if I change the number and character.

Here's my code:

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

/*
 * 
 */
int main(int argc, char** argv) {
    
    int base10;
    int conversion;
    int i=8;
    int bits[32]={};
    char hex[9];
    int quotient=base10;
    int remainder;
    char hexLetter ='A';
    
    
    printf("Enter a number in base 10: \n");
    scanf("%d", &base10);
    printf("Base 10 is: %d\n", base10);
    
    
    
    for(i<9; i=0; --i) { 
        conversion = pow(2,i); //converts each possible 1 to its decimal equivalent for analysis
        if (base10 < conversion) { 
            bits[i]=0;  }
            else{ (bits[i]=1);
            base10 = base10 - conversion; } } //subtracts converted amount from original number} } 
               
           printf("%d %d %d %d %d %d %d %d %d is the decimal number in binary\n", bits[8], bits[7], 
           bits[6], bits[5], bits[4], bits[3], bits[2], bits[1], bits[0]); //backwards so binary number evaluates from right to left
           
           
           
           
           
           //divide by 16 with remainders
           //keep track of remainders
           //divide quotient by 16 until quotient is 0
           //print remainders as one string
           
     printf("Hexadecimal is: ");   
    while(quotient!=0) {
        remainder = quotient % 16; //divide for remainder
            if ( remainder = 10 ) {
            hexLetter ='A';
             printf("%c", hexLetter); } //print hexadecimal equivalent of remainder
        
            else if( remainder =11 ) {
               hexLetter ='B';
                printf("%c", hexLetter); }
        
            else if( remainder =12 ) {
               hexLetter ='C';
               printf("%c", hexLetter); }
        
            else if( remainder =13 ) {
               hexLetter ='D';
               printf("%c", hexLetter); } 
        
            else if( remainder =14 ) {
               hexLetter ='E';
               printf("%c", hexLetter); }
        
            else if( remainder = 15 ) {
               hexLetter ='F';
               printf("%c", hexLetter); }         
                    
            else printf("%d ", remainder); //print integer otherwise
        quotient = quotient /16; } //divide for new quotient   
           
    return (EXIT_SUCCESS);
}

Check in if is switch case choosen

How can i check if case (for example 3 ) was choosen to make continuation of story? I wrote this in java and I would go full detail with story but i dont know how could i .I thought I could nest cases inside each other but if I can choose options(scanner.nextInt();) also add in them.I thought if statement would work better but i dont know how can i check it .I must add that didnt found any answers to this problem before posting.Thanks for reviewing and have a good day

             int choice_1 = scanner.nextInt();
        switch(choice_1)
        {
            case 1:
                System.out.println("Guard: Its a honor to meet u sir.Its a pleasure to let You through \nBut do u have coin pass?");
                if(pass==1){
                    ending();
                }
                else{"You should get coin pass first. I am sure that wont be a problem for Prince *laughs*"}
                break;
            case 2:
                System.out.println("*Guard immediately avoided attack and attack u harder that u excepted");
                playerHp = playerHp -30;
                playerArmorHp = playerArmorHp - 50;
                break;

            case 3:
                System.out.println("Guard : Goodbye Sir");
                plan();
                break;
            default:
                System.out.println("Guard is impatient of your not telling anything.Choose option before making him mad.\n"+line);
                break;
        }
        if(switch ( case:3)){
            System.out.println("Do u have coin pass?");
            int pass = scanner.nextInt();
        }

Karate: assert with conditional nesting on json

My API returns a response like below:

response = ''' { "value": [ "testvalue: "myvalue", "id": "12345", "child":[ { "testvalue": "child1value", "id": "568" "child": [] }, { "testvalue": "child2value", "id": "999" "child": [ { "testvalue": "child2.1value", "id": "100" "child": [] ] } ] ] } '''

My response could be nested at any child level. I basically enter an id as a param while hitting my API When params {"id":"100"} Where I get the above response which is nested at a child level. My use case is to validate and move ahead into the nested response based on a condition My API will always return one list but it could have nested child elements I want to validate something like: response = value[0]

if response.id == 100 then assert as match found If not then go inside the first child And perform the same if condition

I need to dig until I found the id matching as part of the entire response.

Is that something we could achieve with karate?

How to check if there is a particular user in RDS Database using a shell script

I need to create a script to find whether a particular use in RDS database and, if the user is not there create the user.(Automating the creating users) Can someone help me on that?

How does if-statements work within a method in Java [closed]

!Very edited to provide more details!

When calling a method I want it to return either true or false. Because this is for a school assignment and it will go through an anti-plagarism program I cannot provide too much details on it, so I just show a simplified version of it.

I have a constructor and I have created two objects to it (not sure if it is correct described but hopefully you get what I mean). Say the constructor name is Flowers, and my objects are lily and rose.

In the main method it would sort of look like this.

Flowers lily = new Flowers(12);
Flowers rose = new Flowers(5);

rose.example(lily);

The example method:

public boolean example(Flowers name) {
    if (value == name.value) {
        return true;
    } else {
        return false;
    }   
}

If true I then want something to happen.

Bash if statement: Comparison not working with assignment

In the following test_if2() works as expected but test_if not. The difference is that in test_if() I do a variable assignment. Where is the error?

test_if() {
  declare file_path
  if [[ -n ${file_path=$(echo "")} || -n ${file_path=$(echo "Hi")} ]]; then
    echo Non null: ${file_path}
  else
    echo null
  fi      
}

test_if2() {
  declare file_path
  declare greet="Hello"
  if [[ -n $(echo "") || -n $(echo "Hi") ]]; then
    echo Non null
  else
    echo null
  fi      
}

test_if #prints null
test_if2 #prints Non null

if x = y, change x to = z. please help me

x = "y"

if x == "y": x = "z"

ITS IN PYTHON 3 IM FAIRLY NEW TO PROGRAMMING OG EASY ON ME I DONT GET WHY THIS NOT WORKING PLS HELP

An if condition does not work properly in TraCI module in Python

I got into a problem while utilizing if conditions in a for loop in TraCI, a Python module. This module is used to control a traffic simulation software called SUMO. As it is shown here in the first code, the if conditions are checked for every vehicle at every simulation step. However, since in the second code, the term 'vehtp == "1"' is added to the if condition, while running, every vehicle is checked once in the if conditions. I was wondering to know how I should change it that the if conditions are checked for every vehicle at every simulation step until the end of simulation. I appreciate for any help in advance.

Thanks, Reza.

enter image description here

enter image description here

Is there a way to slice a string in a new variable using JavaScript? [closed]

I am using JavaScript for a pop up that when the user visits the web page there is a chart saying What is your name? So the user need to write his name. In just one field. If the user writes two words the program would dive the name into separate first and last name strings.

I'm using this code but is not working the slice method for the last name, it just give in the first name everything. What I am doing wrong?

var fullname;
fullname = prompt("What is your name?");
fullname.indexOf(" ");

var indexOfSpace = fullname.indexOf(" ");
var firstname = "";
var lastname = "";

if (fullname.indexOf = -1) {
  firstname = fullname;
  lastname = "";
} else {
  firstname = fullname;
  lastname = fullname.slice(fullname.indexOf + 1);
}


console.log("Your visitor wrote : " + fullname + "\n\n" +
  "So his first name is: " + firstname + "\n" +
  " and" + "\n" +
  "his lastname is: " + lastname
);
alert("You wrote : " + fullname + "\n\n" +
  "So your first name is: " + firstname + "\n" +
  " and" + "\n" +
  "your lastname is: " + lastname + "!"
);

How to assign TRUE / FALSE to dates (holidays) as boolean variable in r?

I have a df of 10 years of hourly measurements and I want to add a new variable containing german holidays.

In the end I want a new column containing TRUE/FALSE for the holidays.

So far I've tried the 'holiday' function from the timeDate package, different ifelse functions and loops. The data in a MRE format (I hope):

#mydata
df <– structure(list(value = c(359.9, 60.3, 13.7, 25.1, 12.4, 27.1, 
80.2, 24.3, 30.1, 28.8, 45.1, 58.2, 65.6, 55.6, 69.9, 13.5, 20.1, 
41.3, 9.9, 12.1), urban = c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 
TRUE, TRUE, TRUE), traffic = c(FALSE, FALSE, FALSE, FALSE, FALSE, 
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, 
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), date = structure(c(14245, 
14246, 14247, 14248, 14249, 14250, 14251, 14252, 14253, 14254, 
14255, 14256, 14257, 14258, 14259, 14260, 14261, 14262, 14263, 
14264), class = "Date"), season = structure(c(1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L
), .Label = c("winter", "spring", "summer", "fall"), class = "factor")), row.names = c(NA, 
20L), class = "data.frame", .Names = c("value", "urban", "traffic", 
"date", "season"))

#holidays (some vary over years)
holidays <- data.frame(
  K.Fr = c("2009-04-10", "2010-04-02", "2011-04-22", "2012-04-06", "2013-03-29", "2014-04-18", "2015-04-03", "2016-03-25", "2017-04-14", "2018-03-30"),
  OsterMo = c("2009-04-13", "2010-04-05", "2011-04-25", "2012-04-09", "2013-04-01", "2014-04-21", "2015-04-06", "2016-03-28", "2017-04-17", "2018-04-02"),
  PfingstMo = c("2009-06-01", "2010-05-24", "2011-06-13", "2012-05-28", "2013-05-20", "2014-06-09", "2015-05-25", "2016-05-16", "2017-06-05", "2018-05-21"),
  W1 = c("2009-12-25", "2010-12-25", "2011-12-25", "2012-12-25", "2013-12-25", "2014-12-25", "2015-12-25", "2016-12-25", "2017-12-25", "2018-12-25"),
  W2 = c("2009-12-26", "2010-12-26", "2011-12-26", "2012-12-26", "2013-12-26", "2014-12-26", "2015-12-26", "2016-12-26", "2017-12-26", "2018-12-26"),
  ErsterMai = c("2009-05-01", "2010-05-01", "2011-05-01", "2012-05-01", "2013-05-01", "2014-05-01", "2015-05-01", "2016-05-01", "2017-05-01", "2018-05-01"),
  Neujahr = c("2009-01-01", "2010-01-01", "2011-01-01", "2012-01-01", "2013-01-01", "2014-01-01", "2015-01-01", "2016-01-01", "2017-01-01", "2018-01-01"),
  F1 = c("2009-05-21", "2009-10-03", "2010-05-13",  "2010-10-03", "2011-06-02",  "2011-10-03", "2012-05-17",  "2012-10-03", "2013-05-09", "2013-10-03"),
  F2 = c("2014-05-29",  "2014-10-03", "2015-05-14", "2015-10-03", "2016-05-05",  "2016-10-03", "2017-05-25",  "2017-10-03", "2018-05-10","2018-10-03")
)

holidays <- gather(holidays, key = "holiday", value = "date")
holidays <- holidays[,2]
holidays <- as.POSIXct(
  holidays,
  format = "%Y-%m-%d"
)
holidays <- as.Date(holidays)

And here is what I tried yet:

df <- dplyr::mutate(
  df,
  ifelse(df$date == holidays[1],
         T,
         F)
)

df <- for (i in seq(nrow(df$date))){
  ifelse(df$date[i] == holidays,
         T,
         F)
}

x <- 1
repeat {
  df <- for (i in seq(nrow(df$date))){
  ifelse(df$date == holidays[x],
         T,
         F)
  } 
  x = x+1
  if (x == nrow(df)){
    break
  }
}

Answering certain input answers with print commands in python

I am coding in python code to give you a link to website/video and I want my code to answer each input with a print command saying you picked __ here is where you can watch ___ link:

Here is my code it has an error I can't work it out

import time

print ("Please put in anime yo``u would like to watch we have")
time.sleep(0.5)
Anime = input("Naruto,DragonBall:")
if input == "Naruto"
print("Test")

Check if number is within the range in JavaScript [duplicate]

I am trying to find whether the value of the wind direction is within the range for each output. For example, to output "27" I want the metar.wind.degrees to be between 180 and 360 and for an output of "09" I want the metar.wind.degrees to be between 0 and 180.

I would really appreciate any help I could get with this as I've spent a long time truing to figure it out. Here is the code I have so far:

        document.getElementById('wind_direction').innerText = metar.wind.degrees;
        if (180 < metar.wind.degrees < 360) { 
            runway = "27";
        }
        else if (0 < metar.wind.degrees < 180) {
            runway = "09";
        }
        else {
            runway = "Winds allow for either runway.";
        } } 
        document.getElementById("runway").innerHTML = runway;
      }

How to do code loop until last sheet in another workbook using VBA code Excel?

good people, I hope you have a nice day. I am new to Excel Macro VBA here. I need to build Excel Macro Enabled Workbook for specific data processing.

Background: I am trying to copy data as values from every sheet from "source" workbook to a table in my master workbook, then when every data on every sheet has been copied, I need to remove duplicates from that table in my master workbook.

Problem: The number of sheets in "source" workbook is uncertain.

Goal: To copy from every sheet in "source" workbook, stacked in my master workbook then remove duplicates in my master workbook.

I provided my set of code for single sheet "source" workbook, please help me achieve my goal. I tried using do while loop, do until loop but they failed to execute my code

Sub Copy_SourceToMaster()

    Dim FileToOpen As Variant
    Dim OpenBook As Workbook
    Application.ScreenUpdating = False
    FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range")
    If FileToOpen <> False Then
        Set OpenBook = Application.Workbooks.Open(FileToOpen)
        OpenBook.Sheets(1).Activate
        Range("C6").Select
        Range(Selection, Selection.End(xlDown)).Select
        Range(Selection, Selection.End(xlToRight)).Select
        Selection.Copy
        ThisWorkbook.Activate
        ActiveSheet.Range("B4").Select
        Selection.End(xlDown).Select
        ActiveCell.Offset(1, 0).Range("A1").Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
        OpenBook.Close False
    
    End If
    Application.ScreenUpdating = True
Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range

Set sht = ActiveSheet
Set StartCell = Range("B5")

'Find Last Row and Column
  LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
  LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column

'Select Range
  sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select
  Selection.RemoveDuplicates Columns:=2, Header:= _
        xlYes
    Range("B5").Select
    Selection.End(xlDown).Select
End Sub

Python if not but also not that or that [duplicate]

Im trying to check if a list is empty and a variable is not filled with neither of two strings. Thats my code:

var = "random"
my_list = []

if not my_list and (var != 'String1' or var != 'String2'):
    return False
else:
    return True

The part which checks if the list is empty works, but how can i add the second condition with the variable? I tried a few version but none of them works. This one i found makes the most sense to me but it doesnt work. Should not be that hard but i cant seem to figure it out.

My expectiation is: If my_list is empty and var is not 'String1' or 'String2' the Condidion should be true and return False (Like in that code sample) How can i accomplish that?

Hi, i've some problem with this, please tell me where I've gone wrong

I want to count cells with blue colour into cell on the other sheet. Sheet with coloured cells is "MAPA" and sheet where is the result is "Skupinka 1" Thank a lot for help!

That's the code

Private Sub Skupinka1_obnov1_Click()
Dim counter As Integer
For counter = 4 To 26

  If Worksheets("MAPA").Cells(counter, 1).Interior.ColorIndex = 5 Then
    Worksheets("Skupinka 1").Cells(32, 20) = Cells(32, 20) + 1
  ElseIf Worksheets("MAPA").Cells(counter, 1).Interior.ColorIndex = 2 Then
    Worksheets("Skupinka 1").Cells(32, 20) = 0

' That's for one column, that was working, but when I try it for 2 columns, it was wrong

  ElseIf Worksheets("MAPA").Cells(counter, 2).Interior.ColorIndex = 5 Then
    Worksheets("Skupinka 1").Cells(32, 20) = Cells(32, 20) + 1
  ElseIf Worksheets("MAPA").Cells(counter, 2).Interior.ColorIndex = 2 Then
    Worksheets("Skupinka 1").Cells(32, 20) = 0

  End If
Next counter
End Sub

'It shows me Subscript out of range. Thanks for answers.

FORM Skip logic

Hi i wanted to have a logic in a form where i can update status from 'under review' (default) to either 'approved' or 'on-hold' or 'rejected'. I tried this code to allocate a 3 yr period on date of approval [today]):

<% if(collection.status = "approved"){ %>        
                    <input class="form-control" type="hidden" name="collection[validto]" value="<%=new Date(Date.now() +(1000*60*60*24*30*36)) %>">
        
    <% } else { %>
    <% } %>

But it is not doing the logic. So i must have an error in my coding. Any tip how to solve this?

lundi 29 juin 2020

Else statement not triggered with fetch

Trying to work on a weather app with JavaScript and at some point in my very not organized code, the 'else' statement doesn't get triggered. I have tried with a really condition, and also with console.log but nothing happens in both ways.

Here is the code:

// Select UI Elements
const weatherIcon = document.querySelector(".weather-icon");
const temperatureValue = document.querySelector(".temperature-value p");
const temperatureDescription = document.querySelector(
  ".temperature-description p"
);
const cityLocation = document.querySelector(".location .city");
const countryLocation = document.querySelector(".location .country");
const notification = document.querySelector(".notification p");

// Temperature Variable
const KELVIN = 273;

// API var and key
const key = "16955d729b3c76913ae62114164ca0d7";

// Error

// Load Geolocation detection
window.addEventListener("load", () => {
  let latitude;
  let longitude;

  // Check browser support for geolocation
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition((position) => {
      latitude = position.coords.latitude;
      longitude = position.coords.longitude;

      const api = `http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${key}`;

      fetch(api)
        .then((response) => {
          return response.json();
        })
        .then((data) => {
          const tempData = Math.floor(data.main.temp - KELVIN);
          const descriptionData = data.weather[0].main;
          const cityLocationData = data.name;
          const countryLocationData = data.sys.country;
          temperatureValue.innerHTML = `<p>${tempData} °C`;
          temperatureDescription.textContent = descriptionData;
          cityLocation.innerHTML = `<span class="city">${cityLocationData},</span>`;
          countryLocation.innerHTML = `<span class="country">${countryLocationData}</span>`;
        });
    });
  } else {
    notification.style.display = "block";
    notification.textContent = `Something went wrong`;
    // console.log("something went wrong!");
  }
});

I'm using the OpenWeatheMap API to fetch the data.

Checking internet connection state as long as the app is running

I'm working on Desktop-based application.

Can I check the internet connection state as long as the application is running?

for example

If the internet is offline, the application should notifies the user that there is no internet connection

/*
But the application should not stop, 
to check the case of reconnection. 
*/

and in case of reconnection, the application will return to working properly.

My question is

How can I make the application check the state of the Internet as long as it's running?

Thanks in advanced 👍🏻.

Javascript in adobe form field - converting a "Trade In Value" To Be Multiplied if falls within specified range

Im attempting to create a Javascript range calculator for a "trade in value of a car" this is a small part of a huge project im working on, i have the finished version in an excel file but decided to remake in adobe acrobat pro using Javascript, the purpose is to adjust the value of a number if it falls between the ranges below, if someone can point me in the right direction to get this code to work, id really appreciate it!

In plain text below,

Trade Value X 2.00 If Less Than 5999.00;
Trade Value X 1.75 If Greater Than 5999.00 But Less Then 9000.00;
Trade Value X 1.50 if Greater Than 9000.00 But less Than 11,000.00;
Trade Value X 1.40 if Greater Than 11,000.00 But less Than 12,000.00;
Trade Value X 1.35 if Greater Than 12,000.00 But less Than 13,000.00;
Trade Value X 1.30 if Greater Than 13,000.00 But less Than 14,000.00;
Trade Value X 1.25 if Greater Than 14,000.00 But less Than 17,000.00;
Trade Value X 1.20 if Greater Than 17,000.00 But less Than 20,000.00;
Trade Value X 1.15 if Greater Than 20,000.00 But less Than 24,000.00;
Trade Value X 1.10 if Greater Than 24,000.00;

Should = “Amount Financed” Field In Adobe

The code im attempting to implement:

var VTV = Number(this.getField("VehicleTradeValue").valueAsString);
var AMF = Number(this.getField("AmountFinanced").valueAsString);
((VehicleTradeValue)*2.00) If (VehicleTradeValue) < 5999.00;
elif:
((VehicleTradeValue)*1.75) If (VehicleTradeValue) < 5999.00 < 9000.00;
elif:
((VehicleTradeValue)*1.50) if (VehicleTradeValue) > 9000.00 < 11,000.00;
elif:
((VehicleTradeValue)*1.40) if (VehicleTradeValue) > 11,000.00 < 12,000.00;
elif:
((VehicleTradeValue)*1.35) if (VehicleTradeValue) > 12,000.00 < 13,000.00;
elif:
((VehicleTradeValue)*1.30) if (VehicleTradeValue) > 13,000.00 < 14,000.00;
elif:
((VehicleTradeValue)*1.25) if (VehicleTradeValue) > 14,000.00 < 17,000.00;
elif:
((VehicleTradeValue)*1.20) if (VehicleTradeValue) > 17,000.00 < 20,000.00;
elif:
((VehicleTradeValue)*1.15) if (VehicleTradeValue) > 20,000.00 < 24,000.00;
else:
((VehicleTradeValue)*1.10) if (VehicleTradeValue) > 24,000.00;
    event.value = self;

Compound if condition inside list comprehension doesn't seem to work

I have this code:

 jira_regex = re.compile("^[A-Z][A-Z0-9]+-[0-9]+")
 with open(ticket_file, 'r') as f:
     tickets = [word for line in f for word in line.split() if jira_regex.match(word) and word not in tickets]

ticket_file contains this:

PRJ1-2333
PRJ1-2333
PRJ1-2333
PRJ2-2333
PRJ2-2333
MISC-5002

After the code runs, the tickets list contains these:

['PRJ1-2333', 'PRJ1-2333', 'PRJ1-2333', 'PRJ2-2333', 'PRJ2-2333', 'MISC-5002']

I expected this:

['PRJ1-2333', 'PRJ2-2333', 'MISC-5002']

Why is word not in tickets condition not eliminating duplicates? The regex filter is working fine, however.

How do I assign points/score based on word detection in a dataframe?

im new to python and trying to learn word detection. I have a dataframe with words

sharina['transcript']
Out[25]: 
0      thank you for calling my name is Tiffany and we want to let you know this call is recorded...
1                                                Maggie 
2                                  through the time 
3      that you can find I have a question about a claim and our contact is..
4                       three to like even your box box and thank you for your help...

I have created an app that detects words from this:

def search_multiple_strings_in_file(file_name, list_of_strings):
    """Get line from the file along with line numbers, which contains any string from the list"""
    line_number = 0
    list_of_results = []
    # Open the file in read only mode
    with open("sharina.csv", 'r') as read_obj:
        # Read all lines in the file one by one
        for line in read_obj:
            line_number += 1
            # For each line, check if line contains any string from the list of strings
            for string_to_search in list_of_strings:
                if string_to_search in line:
                    # If any string is found in line, then append that line along with line number in list
                    list_of_results.append((string_to_search, line_number, line.rstrip()))
 
    # Return list of tuples containing matched string, line numbers and lines where string is found
    return list_of_results

# search for given strings in the file 'sample.txt'

matched_lines = search_multiple_strings_in_file('sharina.csv', ['recorded','thank'])
 
print('Total Matched lines : ', len(matched_lines))
for elem in matched_lines:
    print('Word = ', elem[0], ' :: Line Number = ', elem[1], ' :: Line = ', elem[2])

I want to assign a score if certain words are detected in the dataframe, for example

if the word 'recorded' has been mentioned = 7 points if the word 'thank' has been mentioned = 5 points

and then the output gives the summation of the total points/score = 12 in this case. How can i do this?

If statement with OR condition not working

First, bless all you overflow angels out there. I have no JS or other language background. I have learned everything in the code for this particular problem so bear with me if things aren't clean and clever. I have done a lot of searching before resulting to asking here, so hopefully ALMOST everything is accounted for. I have a conditional statement I just CANNOT get to run correctly. (entire code for context at the bottom)

            if (pyramid < 1 || pyramid > 8) {
                var dennis = document.getElementById("dennis");
                var showdennis = "#ahahah{display: block}";
                dennis.appendChild(document.createTextNode(showdennis));
                document.getElementById("giza").innerHTML = "";
                return;
            }

I am most concerned with (pyramid < 1 || pyramid > 8) but if you can help me account for an input value of zero (due to complexities with 0 being false-y), bonus points.

<!DOCTYPE html>
<html lang="en-US">

<head>
  <meta charset="UTF-8" />
  <style id="dennis">
    #ahahah {
      display: none;
    }
  </style>
</head>

<body>
  <h1>Text Box Input and Output</h1>
  <form action="">
    <fieldset>
      <label>write how tall </label>
      <input type="number" id="numberin" min="" max="" step="1" />
      <input type="button" value="Make the Pyramid" onclick="makepyramid()" />
    </fieldset>
  </form>

  <script type="text/javascript">
    function makepyramid() {
      var numberin = document.getElementById("numberin");

      var pyramid = numberin.value;
      var spaceincrement = numberin.value;
      var octoincrement = numberin.value;
      var spaces;
      var octothorps;
      var bringittogether = "";


      //WHY YOU NO WORK?! I'd like to make 0 work as well but I am more concerned with the range first.
      //first if statement is the ideal, second is bare minimum.
      //if (pyramid === null || pyramid < 1 || pyramid > 8) {
      //if (pyramid < 1 || pyramid > 8) {
      //Put in this if statement to show what SHOULD happen
        if (pyramid > 8) {
        var dennis = document.getElementById("dennis");
        var showdennis = "#ahahah{display: block}";
        dennis.appendChild(document.createTextNode(showdennis));
        document.getElementById("giza").innerHTML = "";
        return;
      } else {
        document.getElementById("ahahah").innerHTML = "";

        //decide how many lines to make
        for (var a = 0; a < pyramid; a++) {

          //number of spaces loop
          for (var b = 1, spaces = ""; b < spaceincrement; b++) {
            spaces += "_";
          }

          //number of octothorps in one line loop
          for (var c = pyramid, octothorps = ""; c >= octoincrement; c--) {
            octothorps += "#";
          }

          //print spaces, hashes, 2 spaces, start new line
          bringittogether += spaces + octothorps + "__" + octothorps + "<br/>";
          document.getElementById("giza").innerHTML = bringittogether;
          //increment to change next line's number of spaces (one less) and octothorps (one more)
          spaceincrement = [spaceincrement - 1];
          octoincrement = [octoincrement - 1];
        }
      }
    }
  </script>
  <hr />
  <div id="giza"></div>

  <div id="ahahah">
    <p><img src="https://i.imgur.com/1A8Zgnh.gif" /> You must select a number between 1 and 8
    </p>

  </div>
</body>

</html>

'If' condition doesn't work with the stack pop and peek methods inside the if condition in java

    Stack<Integer> st = new Stack<Integer>();
    Stack<Integer> st2 = new Stack<Integer>();
    st.push(-1024);
    st2.push(-1024);
    if (st.pop() == st2.peek()) {
        System.out.println("same");
    }

The above code should print "same" but fails to do as the if condition fails.

Stack<Integer> st = new Stack<Integer>();
    Stack<Integer> st2 = new Stack<Integer>();
    st.push(-1024);
    st2.push(-1024);
    int temp = st.pop();
    int temp2 = st2.peek();
    if (temp == temp2) {
        System.out.println("same");
    }

But when I store the pop and peek function values in a temporary variables then the if condition returns true. The problem seems to exist for pop and pop functions.

Things I have done to find my silly mistake(cause I know I make many):

  • Change the pushed value to different values. I have found that When I use any number above 127 or any number below -127 the if condition fails.

  • Store the pop and peek values in a temporary values that seems to solve the problem. But still doesn't explain the problem why the if condition fails.

Can someone help me out why this is happening like this. Am I missing something silly? Thanks in advance tho.

Is there any possibility to simplify the nested condition into non nested in C#?

I have 3 conditions to check before returning true or false. Here is the table:

enter image description here

This can be achieved using below logic

if(!COND1 && !COND2)
{
    if(COND3)
    {
        return False
    }
    else
    {
        return True
    }
}
else
{
    return true
}

Can this be simplified without using nested if ?

Input and output values for php into the browser?

I just started my module on php for school, having completed Javascript two months ago I am familiar with a lot of the elements but a bit rusty. Basically I setup a form with html and added a bit of css to make it pretty. The school is making us do some generic exercices. I now how to grab values etc using this with Javascript

document.getElementById("textBox").value;

and to return the output through my div I created with

document.getElementById("return").innerHTML = ... ;

I honestly can't figure out how to do this with php and I am sure it's real easy but can't for the life of me find a solution online and the schools videos are very vague.

The exerciser is "Create an application that ask the user for number (1-7) and return the day of the week associate with the number entered. You must validate the number"

This is the code I have so far....

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <title>PHP exercise 1</title>
    <link rel="stylesheet" type="text/css" href="./styling1.css"/>
</head>



<body>
    <!--E X C E R S I S E 3 !-->
    <section id="allContent">
        <section>
            <button  class="hide" id="clic">  <h4> E X E R C I C E  1 </h4></button>
        </section>

        <div id="container" class="hidden">
            <div id="Barbox"><p class="pClass"> Create an application that ask the user for number (1-7) and return the day of the week associate with the number entered. You must validate the number</p>
            </div>
            <div id="background"></div>
            <div class="ball"></div><div id="ball2"></div>
            <div id="titleBox">
                <p id="titlePRG">Enter a number!</p>
            </div>

            <form>
                <input type="text" value="<?php echo $number = 1 ; ?>" id="textField">
                <input type="button" value="Enter" class="button" onclick="return_day()">   
            </form>

            <div id="valueReturned">
                <p id="returnText"><p>
            </div>
            <a href="index4.html" id="jButton"><h3> Next Exercise </h3></a>
                   
        </div>
    </section>


    <?php
    
    function return_day(){

    $number = 1 ;

    if ($number == 1){
        echo "The day of the week is Monday";
    }

    else if ($number == 2){
        echo "The day of the week is Tuesday";
    }

    else if ($number == 3){
        echo "The day of the week is Wednesday";
    }

    else if ($number == 4){
        echo "The day of the week is Thursday";
    }

    else if ($number == 5){
        echo "The day of the week is Friday";
    }

    else if ($number == 6){
        echo "The day of the week is Saturday";
    }

    else if ($number == 7){
        echo "The day of the week is Sunday";
    }

    else{
        echo ("Wrong input, try again!");
    }

}//end of function


    ?>

This is what the browser looks like if it makes any difference so you understand my question

enter image description here

The answer is supposed to display in the white box at the bottom which is

mutate new column based on conditions in another row in R

I am working with a dataset of animal behaviors, and am trying to create a new column ("environment") based on conditions fulfilled in another row. Specifically, I want the new column to return "water" if the behavior falls between the start/stop times of the behavior "o_water", and "land" if it falls outside these bounds. If this is unclear here is a minimal example:

library(dplyr) 
library(magrittr)

otters <- data.frame(
  observation_id = 1,
  subject = 1,
  behavior = c("o_water", "run", "sit", "o_land", "walk"),
  start_time = c(1,1,2,6,6),
  stop_time = c(5,3,4,10,9)
)

#this does it, but manually. I need to go over a large dataset and search for conditions
otters <- otters %>%
  group_by(subject, observation_id, behavior) %>%
  mutate(environment = ifelse(start_time >= 1 & stop_time <= 5, "water", "land"))

This is the output desired.

Groups:   subject, observation_id, behavior [5]
  observation_id subject behavior start_time stop_time environment
           <dbl>   <dbl> <fct>         <dbl>     <dbl> <chr>      
1              1       1 o_water           1         5 water      
2              1       1 run               1         3 water      
3              1       1 sit               2         4 water      
4              1       1 o_land            6        10 land       
5              1       1 walk              6         9 land       
> 

The second set of commands is sort of what I want, but I need this to search out and apply it to an entire dataset rather than typing out each parameter. The grouping is so the functions are performed over the applicable rows; in the full dataset, there are multiple subjects and observation_id's.

I've tried using when() and case_when() to no avail, but I am very novice level at R so would appreciate any help!

Apologies for any missteps I've done. I haven't been able to find a problem quite like this elsewhere on stackoverflow.

I want to create a draggable game

I want to drag #nisip and #ciment in #betoniera then to run a function like to reset #betoniera, create another #ciment and #nisip... Can you help me? I want to create a little game, drag 2 elements in one then create another 2 elements...

<!DOCTYPE html>
<html>
<head>

    <Style> body{background-color: black;}
#betoniera{ 
    background-color:yellow;
    width:100px;
    height:100px;
    position: absolute; 
    top: 50%; 
    left:50%; 
    transform:translate(-50%,-50%);
}
#nisip{
    background-color: gray; 
    width: 15px; 
    height: 15px;
    position: absolute; 
    top:35%;
    transform:translate(-50%,-50%);
}
#ciment{
    background-color: gray; 
    width: 15px; 
    height: 15px;
    position: absolute; 
    top:85%;
    transform:translate(-50%,-50%);
}


    </Style>
    <script>
function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
    <div id="betoniera" draggable="true" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
    <div id="nisip" draggable="true"  ondragover="allowDrop(event)" ondragstart="drag(event)"></div>
<div id="ciment" draggable="true" ondragover="allowDrop(event)" ondragstart="drag(event)"> </div>
</body>
</html> 

if else statement in D3.js for custom colour scale

I'm working with the code below:

 let sizeBands = data.map(({size, count}) => size / count);

  sizeBands.forEach(function(colorBand){      
        if (colorBand < 60) {
           console.log(colorBand + " Under 60!")            
        } if (colorBand >= 60)
           console.log(colorBand + " Over 60!")         
      }) 

The console.log()s work fine and are displaying the correct numbers.

I am appending a 'rect' which needs to have the fill returned based on those numbers.

    .attr('fill', function(d) {
      if (d.colorBand <= 55) {
        return "red";
      } else if (d.colorBand >= 56 && d.colorBand <= 60) {
        return "blue";
      } else {
        return "green"
      }
    });

But all I am getting is green 'rects'. How do I get the code to fill the 'rects' with the correct colours?

How to hide show for condition in jQuery

I am trying to create a responsive menu. In the code below the element with class menu_show_mb will be hidden (I used CSS to hide this class) and I want to show the element span.menu_click by default.

When a user clicks span.menu_click the content in .menu_show_mb will be shown and hide the element span.menu_click then show span.menu_close.

How can I do this?

if ($(".menu_show_mb").show()) {
  $("span.menu_click").hide();
  $("span.menu_close").show();
} else if ($(".menu_show_mb").hide()) {
  $("span.menu_click").show();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menu_icon_mb">
  <span class="menu_click"><i class="fa fa-bars" aria-hidden="true"></i></span>
  <span class="menu_close" style="display:none;">X</span>
  <div class="menu_show_mb">
    The list of content
  </div>
</div>

Getting NULL Value in ifnull() instead of set value

I'm trying to do the majority of my work in SparkSQL so I'm trying to figure out a solution using just sparksql.

Goal I'm trying to achieve is: When Src_Column2 = 'Hello' then load Target_Column as Src_Column1 else set Target_column = 0.00

So I tried but it loads the column as NULL is the condition isn't met:

(SELECT FIRST(IFNULL(Src_Column1, '0.00'))
FROM dfLookup Src_Table_1
WHERE     Src_Column2 = 'Hello')
AS Target_Column

Any help would be greatly appreciated.

Coccinelle rule to match foo() call inside an if

So, the problem I stumble upon is that code inside if can be pretty complex, it can be stuff like if (NOT(ret = foo())) and also if (foo() == NULL), and other variations are possible.

To me the obvious answer is the rule line if (...foo()...), but Coccinelle says it fails to parse this.

I tried everything I managed to find or to guess, so far to no avail.


As a demo example, here's a test.c

#include <stddef.h>
#include <stdbool.h>

#define NOT(expr) (!(expr))

void remove_this_call_if_foo_is_called() {}
const char* foo() { return "hello"; }
const char* bar() { return "hello"; }

int main() {
    const char* ret;
    if (NOT(ret = foo())) {
        remove_this_call_if_foo_is_called();
    }

    if (foo() == NULL) {
        remove_this_call_if_foo_is_called();
    }

    if (foo()) {
        remove_this_call_if_foo_is_called();
    }

    if (bar()) {
        // Do not remove if something different from foo() is called.
        remove_this_call_if_foo_is_called();
    }
}

And I want to remove remove_this_call_if_foo_is_called() calls whenever they're in an if () body and the if condition has foo() call.

A Coccinelle example that unfortunately always removes these lines is:

@ rule1 @
@@
if (...) {
    ...
-   remove_this_call_if_foo_is_called();
    ...
}

taking the information out of another column [duplicate]

I have two dataframes as follows

Team Value
A  0.6 
B  0.5
C  0.5
D  0.5

Group 
B
D
A
B
C 

I want to get the information from the second column used in an if else function I think

if (Team == Group) {take Value next to the column of Team corresponding to the Team/Group letter}

and in a forloop

for(i in 1:5) {DataGroup [i] }

I am not sure if I can explain myself well but those two functions I guess I need

Conditions with comparison operators and numbers only JavaScript

I would like a user to input a number. If number is between 1 and 100, I would alert with message "Great". If input is below 1 and more than 100, I would alert "Please, only numbers between 1-100. I am having two problems here:

  1. My conditions with comparison operators do not work. No matter what number I enter more than 100 or less than 100, I still get the same message. I just wonder if someone could point where is the error.

  2. The second problem is that I can even enter letters. When I enter letters, it just goes to the second alert message "Please, only numbers from 1-100".

What is the easiest way to make user to enter numbers only, not letters or other symbols, and alert them to enter only digits.

 var userInput = prompt('Enter a number'); // asking user to input a number

  if (userInput<=100 || userInput>=1) {
  alert ('Great !');}
if(userInput <1 && userInput > 100);
{
  alert('Please, only numbers betwen 1-100'); }

Why "R help" does not work for some commands? [duplicate]

I wanted to use "help in R" in order to see some information about some commands such as "for", "if", "while", "repeat" etc. But there is no information in "R help" regarding such commands. I would like to know why?

I use "R help" for the above commands like below:

?for
?while
?if
?repeat

Python function: Avoid using if clauses for parameter check

this is my function:

def save_to_mongo(self, df, collection, additional_variable):
    for index, row in df.iterrows():
        result = row.to_dict()
        collection.update_one(
            {"_id": str(row['date']) + "_" + str(row['sector']) + "_" + str(row['caseid']) + str(row[additional_variable])},
            {
                '$set': result
            },
            upsert=True)

I have many similar functions where parameters like the additonal_variable can be None.

I would really like to avoid to bloat up the codebase with a style like this:

if additional_varibale is None:
    collection.update_one(
        {"_id": str(row['date']) + "_" + str(row['sector']) + "_" + str(row['caseid'])},
        {
            '$set': result
        },
        upsert=True)
else:
    collection.update_one(
        {"_id": str(row['date']) + "_" + str(row['sector']) + "_" + str(row['caseid']) + str(row[additional_variable])},
        {
            '$set': result
        },
        upsert=True)

I think this code is ugly and hard to maintain. Are there any better ways or best practices to avoid using these long if and else statements?

Delete rows of dataframe according to condition (comparing data in two columns)

I have a dataframe with trade flows (exports) between countries of origin and countries of destination (which are specified in two different columns of the df). I need to clean the data and delete rows where the country of destination matches the country of destination. I used the following code:

dfn = dfn[dfn["Destination"] != dfn["Origin"]]

However, I realized I actually need to keep the lines where "World" is both in destination and origin (i.e. total world exports towards the world). How can I delete all rows where destination == origin except for the rows where world == destination == origin?

I was thinking of interating through my ~2 million rows and delete only those where a certain conditionality applies. I tried something along those lines, but it doesn't really work. Could you please help me?

for index, row in dfn.iterrows():
         if row['Destination'] == row['Origin'] and row['Destination'] =! 'World':
            df.drop(index, inplace=True) 

Many thanks in advance

How to conditionally check string in IF condition python [duplicate]

I am have a variable called vol_dev value will be like this (it can be any value out of these )

/dev/sda1 or /dev/sdb or /dev/sdc like this , I need to perform set of action based on above values in if condition.

so I using re module to like below. the idea is to check if there is pattern like sda1 in vol_dev or not. any other pattern other than sda1 in vol_dev I need to do different set of action.

vol_dev = res_vol['Volumes'][0]['Attachments'][0]['Device']    
if re.search(r'sda1', vol_dev):
   print(vol_dev)

How to specify NOT condition in search pattern ? i.e search other than sda1 in above if condition. The problem i need to decide based on pattern in vol_dev variable.

Any suggestion would be highly appreciated

Auto completed late jobs, refund amount to user with php

This is long, so be patient with me.

here is a link to full code: https://pastebin.com/xGJ9J9i2

I am trying to create a script that will handle the late jobs of my recent project. the script will select all late jobs from the database and then we will check for job applicants. if there are no applicants, we will cancel the job and refund the amount to the job poster. If there are applicants, we will check to see if they have delivered the work. otherwise, mark applicant job as cancelled and refund the amount to the user. if the work was delivered and the delivery status is waiting_for_approval, we will accept the work and mark the applicant's work as completed and add funds to his account.

but I am confused about my code because only some part works. right now if no user applied to the job this code refunds amount to the user. If the user applied for the job, someone submitted the job, and if some deliveries are under review, it does nothing.

What works:

  • Select all jobs where delivery time is less than 4 hours
  • Select all job applicants.
  • If there are no applicants, refund the amount to the user

What doesn't work:

  • if there are applicants and they did not deliver the job or if the delivery status equals in_revision, cancel the job and provide the user with the refund and mark the applicant's job status as cancelled

  • if the delivery status equals wait_for_approval, the job automatically completes, adds funds to the requester's account

  • marks the requester's job status as completed

  • Finally, the status of the job as completed

Any suggestions?

<?php

require_once('includes/initialize.php');

$jobs = get_all_late_jobs();

if (mysqli_num_rows($jobs) > 0) {

    while ($job = mysqli_fetch_assoc($jobs)) {

        $job_id = $job['job_id'];

        // get all job applicants
        $applicants = get_job_applicants($job_id);

        if (mysqli_num_rows($applicants) > 0) {

            while ($applicant = mysqli_fetch_assoc($applicants)) {

                $applicant_id = $applicant['applicant_id'];

                // get job deliveries of this applicant
                $deliveries = find_all_by_id($applicant_id, 'applicant_id', 'job_deliveries', 'DESC', 's', 0);

                if (mysqli_num_rows($deliveries) > 0) {

                    while ($delivery = mysqli_fetch_assoc($deliveries)) {

                        // if the applicants has delivered the job auto complete the job

                        if ($delivery['status'] === 'waiting_for_approval') {
                            // mark delivery accepted
                            update_by_id('accepted', $delivery['delivery_id'], 'status', 'delivery_id', 'job_deliveries');

                            // update applicant job status
                            mark_seller_job_status('completed', $job_id, $applicant_id);

                            // update seller wallet
                            $wallet = [
                                'action' => 'add',
                                'user_id' => $delivery['applicant_id'],
                                'amount' => round($job['budget'] / $job['required_freelancers']),
                                'used_for' => 'completed_job'
                            ];

                            update_user_wallet_history($wallet);
                        }

                        // if the delivery is in revision cancel the job and provide user refund
                        if ($delivery['status'] === 'in_revision') {
                            cancel_seller_job_give_refund($applicant_id, $job);
                            add_review_to_user_profile($job['posted_by'], $applicant_id, $job_id, 'Cancelled job. Seller failed to deliver on time!', '1');
                        }
                    }
                } else {
                    // if the applicants didn't delivered the job cancel the job and provide user refund
                    cancel_seller_job_give_refund($applicant_id, $job);
                    add_review_to_user_profile($job['posted_by'], $applicant_id, $job_id, 'Cancelled job. Seller failed to deliver on time!', '1');
                }
            }
        } else {
            // if there are no applicants provide user full refund mark the job as cancelled
            give_user_full_refund($job);
        }

        // mark the job as completed
        update_by_id('completed', $job['job_id'], 'status', 'job_id', 'jobs');
    }
} else {
    return false;
}

Perl if Statement only specific length of numbers

is it possible to have an if-statement where I look if my $expression has less than 12 integers and only integers. Like if($expression> less than 12numbers and only integers).

dimanche 28 juin 2020

My if statment and else if statment is not getting executed, but there is not error

So i'm writing a calculator and I'm struggling with the equal sign, I'm trying to do some simple bedmas (no brachets and no exponents), but my code keeps returning 0 as if the if statment ar egetting totally skipped

I have no idea what is causing this as I'm getting no errors

function equal(){
        let exp = document.form.textview.value;
        let expArray = exp.split(/\b/);
        console.log(expArray);   //<-if something doesn't work check this
        let total = 0;
        var lastOperator = "+";
        var lastDig = 0;
        for(let i = 0 ; i < expArray.length; i++){
          var dig = expArray[i].trim(); //value of "i", the item currently in the loop
          if(isNaN(dig) == true){
             console.log("string")
           }
          else if(isNaN(dig) == false){
            console.log('not string');
              if (dig == "/"){ //this whole section gets skipped :(
                var a = i + 1;
                var p = i - 1;
                var aDig = parseFloat(expArray[a].trim); //value after "i"
                var bDig = parseFloat(expArray[p].trim); // value before  "i"
                var sDig = aDig / bDig;
                total = expArray.splice(bDig, 3, sDig);
              }

              else if ( dig == "*"){
                var a = i + 1;
                var p = i - 1;
                var aDig = parseFloat(expArray[a].trim); //value after "i"
                var bDig = parseFloat(expArray[p].trim) // value before  "i"
                var sDig = aDig * bDig;
                total = expArray.splice(bDig, 3, sDig);
              }
              else if ( dig == "+"){
                var a = i + 1;
                var p = i - 1;
                var aDig = parseFloat(expArray[a].trim); //value after "i"
                var bDig = parseFloat(expArray[p].trim)// value before  "i"
                var sDig = aDig + bDig;
                total = expArray.splice(bDig, 3, sDig);
                console.log(expArray.splice(bDig, 3, sDig));
              }
              else if( dig == "-"){
                var a = i + 1;
                var p = i - 1;
                var aDig = parseFloat(expArray[a].trim); //value after "i"
                var bDig = parseFloat(expArray[p].trim) // value before  "i"
                var sDig = aDig - bDig;
                total = expArray.splice(bDig, 3, sDig);
            }
          }

            }
            document.form.textview.value = total;

        } ```

If-statement does not work inside Arrow-function [duplicate]

$('#title').keyup( () => {
    const title_val = $(this).val();
    console.log('before');
    if (title_val.length >= 20){
        console.log(title_val);
    }
    console.log('after');
});

console.log('before') and console.log('after') works. If-statement only works if I use function() instead of () => {...}, even if the condition is satisfied. Why does it behave like this?

Multiple bools in if statement being ignored

I have been trying to figure this out for over a week. I have the player set up with no rigid body because that would not work with the mechanics of the game. The player (a rectangular prism) has two empty child objects one on each end to detect collisions using raycasts. But every time i use the raycast in the player movement script the player just ignore the collisions and rolls right through the wall. The raycasts are working fine. When i use on bool in the if statement the player stops when he hits the wall. But when i use two bools in the if statement the player just rolls right through it...

Here is the raycast script i have on an empty game object on the left side of the player:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CollisionDetectionLeft : MonoBehaviour
{
    public static bool hit_L_Right;
    public static bool hit_L_Left;
    public static bool hit_L_Forward;
    public static bool hit_L_Backward;


    private void FixedUpdate()
    {
        hit_L_Right = Physics.Raycast(transform.position, Vector3.right, 0.67f);
        Debug.DrawRay(transform.position, Vector3.right * 0.67f, Color.green);
        if (hit_L_Right)
            Debug.Log("Hit Right");

        hit_L_Left = Physics.Raycast(transform.position, Vector3.left, 0.67f);
        Debug.DrawRay(transform.position, Vector3.left * 0.67f, Color.green);
        if (hit_L_Left)
            Debug.Log("Hit Left");

        hit_L_Forward = Physics.Raycast(transform.position, Vector3.forward, 0.67f);
        Debug.DrawRay(transform.position, Vector3.forward * 0.67f, Color.green);
        if (hit_L_Forward)
            Debug.Log("Hit Forward");

        hit_L_Backward = Physics.Raycast(transform.position, Vector3.back, 0.67f);
        Debug.DrawRay(transform.position, Vector3.back * 0.67f, Color.green);
        if (hit_L_Backward)
            Debug.Log("Hit Back");
    }
}

Here is the collision script on the right child:

using System.Collections.Generic;
using UnityEngine;

public class CollisionDetectionRight : MonoBehaviour
{
    public static bool hitRight;
    public static bool hitLeft;
    public static bool hitForward;
    public static bool hitBackward;


    private void FixedUpdate()
    {
        hitRight = Physics.Raycast(transform.position, Vector3.right, 0.67f);
        Debug.DrawRay(transform.position, Vector3.right * 0.67f, Color.green);
        if (hitRight)
            Debug.Log("Hit Right");

        hitLeft = Physics.Raycast(transform.position, Vector3.left, 0.67f);
        Debug.DrawRay(transform.position, Vector3.left * 0.67f, Color.green);
        if (hitLeft)
            Debug.Log("Hit Left");

        hitForward = Physics.Raycast(transform.position, Vector3.forward, 0.67f);
        Debug.DrawRay(transform.position, Vector3.forward * 0.67f, Color.green);
        if (hitForward)
            Debug.Log("Hit Forward");

        hitBackward = Physics.Raycast(transform.position, Vector3.back, 0.67f);
        Debug.DrawRay(transform.position, Vector3.back * 0.67f, Color.green);
        if (hitBackward)
            Debug.Log("Hit Back");
    }
}

And here is the player movement script:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using UnityEngine;

public class Rectangle : MonoBehaviour
{
    public float rotationPeriod = 0.3f;
    Vector3 scale;

    bool isRolling = false;
    float directionX = 0;
    float directionZ = 0;

    float startAngleRad = 0;
    Vector3 startPos;
    float rotationTime = 0;
    float radius = 1;
    Quaternion fromRotation;
    Quaternion toRotation;

    private void Start()
    {
        scale = transform.lossyScale;
    }

    private void Update()
    {
        float x = 0;
        float y = 0;
        

        if (Input.GetKeyDown(KeyCode.D) && (!BoxCollision.right || !BoxCollision.left))         // not working  
        {
            y = Input.GetAxisRaw("Horizontal");
        }

        else if (Input.GetKeyDown(KeyCode.A) && (!CollisionDetectionRight.hitLeft || !CollisionDetectionLeft.hit_L_Left))       // not working  
        {
            y = Input.GetAxisRaw("Horizontal"); 
        }

        if (x == 0)
        {
            
            if (Input.GetKeyDown(KeyCode.W) && !CollisionDetectionRight.hitForward)
            {
                x = Input.GetAxisRaw("Vertical");
            }

            else if (Input.GetKeyDown(KeyCode.S) && !CollisionDetectionRight.hitBackward)
            {
                x = Input.GetAxisRaw("Vertical");
            }
        }

        if ((x != 0 || y != 0) && !isRolling)
        {
            directionX = -y;
            directionZ = x;
            startPos = transform.position;
            fromRotation = transform.rotation;
            transform.Rotate(directionZ * 90, 0, directionX * 90, Space.World);
            toRotation = transform.rotation;
            transform.rotation = fromRotation;
            setRadius();
            rotationTime = 0;
            isRolling = true;
        }
    }

    private void FixedUpdate()
    {
        if (isRolling)
        {
            rotationTime += Time.fixedDeltaTime;
            float ratio = Mathf.Lerp(0, 1, rotationTime / rotationPeriod);

            float thetaRad = Mathf.Lerp(0, Mathf.PI / 2f, ratio);
            float distanceX = -directionX * radius * (Mathf.Cos(startAngleRad) - Mathf.Cos(startAngleRad + thetaRad));
            float distanceY = radius * (Mathf.Sin(startAngleRad + thetaRad) - Mathf.Sin(startAngleRad));
            float distanceZ = directionZ * radius * (Mathf.Cos(startAngleRad) - Mathf.Cos(startAngleRad + thetaRad));
            transform.position = new Vector3(startPos.x + distanceX, startPos.y + distanceY, startPos.z + distanceZ);

            transform.rotation = Quaternion.Lerp(fromRotation, toRotation, ratio); 

            if(ratio == 1)
            {
                isRolling = false;
                directionX = 0;
                directionZ = 0;
                rotationTime = 0; 
            }
        }
    }

    void setRadius()
    {
        Vector3 dirVec = new Vector3(0, 0, 0);
        Vector3 nomVec = Vector3.up;

        if (directionX != 0)
        {
            dirVec = Vector3.right;
        }

        else if (directionZ != 0)
        {
            dirVec = Vector3.forward;
        }

        if (Mathf.Abs(Vector3.Dot(transform.right, dirVec)) > 0.99)
        {
            if (Mathf.Abs(Vector3.Dot(transform.up, nomVec)) > 0.99)
            {
                radius = Mathf.Sqrt(Mathf.Pow(scale.x / 2f, 2f) + Mathf.Pow(scale.y / 2f, 2f));
                startAngleRad = Mathf.Atan2(scale.y, scale.x);
            }

            else if (Mathf.Abs(Vector3.Dot(transform.forward, nomVec)) > 0.99)
            {
                radius = Mathf.Sqrt(Mathf.Pow(scale.x / 2f, 2f) + Mathf.Pow(scale.z / 2f, 2f));
                startAngleRad = Mathf.Atan2(scale.z, scale.x);
            }
        }

        else if (Mathf.Abs(Vector3.Dot(transform.up, dirVec)) > 0.99)
        {
            if (Mathf.Abs(Vector3.Dot(transform.right, nomVec)) > 0.99)
            {
                radius = Mathf.Sqrt(Mathf.Pow(scale.y / 2f, 2f) + Mathf.Pow(scale.x / 2f, 2f));
                startAngleRad = Mathf.Atan2(scale.x, scale.y);
            }

            else if (Mathf.Abs(Vector3.Dot(transform.forward, nomVec)) > 0.99)
            {
                radius = Mathf.Sqrt(Mathf.Pow(scale.y / 2f, 2f) + Mathf.Pow(scale.z / 2f, 2f));
                startAngleRad = Mathf.Atan2(scale.z, scale.y);
            }
        }

        else if (Mathf.Abs(Vector3.Dot(transform.forward, dirVec)) > 0.99)
        {
            if (Mathf.Abs(Vector3.Dot(transform.right, nomVec)) > 0.99)
            {
                radius = Mathf.Sqrt(Mathf.Pow(scale.z / 2f, 2f) + Mathf.Pow(scale.x / 2f, 2f));
                startAngleRad = Mathf.Atan2(scale.x, scale.z);
            }

            if (Mathf.Abs(Vector3.Dot(transform.up, nomVec)) > 0.99)
            {
                radius = Mathf.Sqrt(Mathf.Pow(scale.z / 2f, 2f) + Mathf.Pow(scale.y / 2f, 2f));
                startAngleRad = Mathf.Atan2(scale.y, scale.z);
            }
        }
    }
}

If anyone can figure this out please let me know. This is doing my head in.

Java If statment problem with Scanner and trying to read user input [duplicate]

I am brand new to Java moving from Python, can someone explain what I need to be doing differently to make this code work? This is my first Java project, I am trying to make a very simple calculator to get an understanding of the basics.

import java.util.Scanner;
public class calculatortest {

    private static Scanner scan;

    public static void main(String args[]) {

        //This is a test for a calulator to see if I can code this without any help. 

        Scanner typeofcalc = new Scanner(System.in);

        System.out.println("What type of calculation would you like to do?: ");

        String calctype = typeofcalc.nextLine();
        if calctype == "add", "addition"{
            
        }
        
    }
    
}

Need assistance with this if statement

first, let let me show you the code:

    // calculate grand total
if(unitsPurchased >= 10,19)
{
    discount = .20;
    totalCost = totalCost - (totalCost * discount);
    cout << fixed << setprecision(2);
    cout << "\tBecuase you purchased " << unitsPurchased << " Units,\n\tYou get a 20% discount!" << "The grand total is: $" << totalCost << endl;
}

I'm trying to apply a 20% discount if a person buys between 10 to 19 items. how can I alter my if statement to reflect this? I've tried using AND (&&) but that didn't work. how can I set the range between two numbers?

Python3: what are faster, nested function calls or if statements (try/excepts are pretty fast)

In python3, let's say I got a situation where I need a integer. Is it faster to do something like

processed_number = int(round(float(some_input)))

or should I do this:

if some_input is int:
    processed_number = some_input
else:
    processed_number = int(round(float(some_input)))

or perhaps

try:
    some_statement_taht_needs_int(some_input)
# except TypeError:
#    processed_number = int(round(float(some_input)))
#    some_statement_taht_needs_int(some_input)
# Apparently, it's better to cut down on exception handling: I might handle something the wrong way
except ValueError:
    # The same thing
    processed_number = int(round(float(some_input)))
    some_statement_taht_needs_int(some_input)

I'm sorry if that was a dumb question since both use function calls. I'm just wondering if there is a significant time difference between each method. I know I shouldn't be optimizing python code too much but this is just a question (a possibly dumb one) that I had for a long time. Please don't burn me down if this is dumb.


I'm not really making code that needs this optimization (for now); this is just a question so I can improve my code in the future.

Negative & Positive sum

I'm pulling activity data from Oura ring into a Google Sheet. I'm pulling Target kilometers (in 0.0) en Actual KM (in 0.0) then format them in an output sheet to meters (0.000).

The problem is that if I beat my Target kilometers (say 10.0), with for example 3 kilometers, then it will say -3 instead of 13 kilometers. However, if I don' beat it, it will just say i.e. 7.

Is there a way, like a formula, that can do like =IFnegative, count target KM + actual KM so it says 13 in the Output sheet?

Switch case of object in PHP

I don't have a good knowledge in PHP. Will you please, anyone help me to implement a switch case or if else statement in a set of objects.

For example I have set of JSON object like below

 {"car":[{"colour":"black", "brand":"BMW", "owner":"rob"}]}
 {"bike":[{"colour":"red",  "brand":"Bajaj", "owner":"john"}]}
 {"cycle":[{"colour":"blue",  "brand":"Hero", "owner":"mike"}]}

My requirement is need to check it's car, bike or cycle. in the below example message is the random JSON object

$smsobj = json_decode($message, true);
switch ($smsobj) {
    case $smsobj->bike:
      $this->bike($smsobj);
      break;
    case $smsobj->car:
      $this->car($smsobj);
      break;
    case $smsobj->cycle:
      $this->cycle($smsobj);
      break;
      defualt: $resolver->acknowledge($message);
  }

when I received a car object I will get some error like this Trying to get property 'bike' of non-object

Thank you.

If a row matches a criteria do paste in R

Let's imagine you have a dataframe with two columns ID and POSITION. I want to paste some text depending on the ID value.

In Excel I can do this being A as ID and B as POSITION using =IF(A2<10,CONCATENATE("GK00000",A2,".2:",B2,"..",B2+1),CONCATENATE("GK0000",A2,".2:",B2,"..",B2+1)) but I want to add it to my R script line.

I give you a short example of my input data just ilustrative

ID <- c(1,2,3,4,5,6,7,8,9,10,11,12)
POSITION <- c(10,20,30,40,50,60,70,80,90,100,110,120)
df <- cbind(ID,POSITION)

and the result I'm expecting is

CONCAT <- c("GK000001.2:10..11","GK000005.2:50..51","GK000009.2:90..91",
            "GK000010.2:100..101","GK000012.2:120..121")
dfResult <- cbind(ID,POSITION,CONCAT)

Iteration over columns problems on condition

I have a Dataset with several columns and a row named "Total" that stores values between 1 and 4. I want to iterate over each column, and based on the number stored in the row "Total", add a new row with "yes" or "No".
I also have a list "columns" for iteration. All data are float64

I´m new at python and i don't now if i'm doing the righ way because i´m getting all "yes".

for c in columns:
  if dados_por_periodo.at['Total',c] < 4:
    dados_por_periodo.loc['VA'] = "yes"
  else:
    dados_por_periodo.loc['VA'] = "no"

Thanks.

Why am I having syntax unexpected 'else' (T_ELSE) error? [closed]

I am following the instructions on PHP Documentation and I am trying the codes out in different ways. Somehow I got stucked somewhere I couldn't understand why I am getting T_ELSE error. According to No 12th Comment here: https://www.php.net/manual/en/control-structures.if.php one can call PHP variable from outside If function because IF doesn't have a scope, Below is what I did: Anyone please? Why is it not working this way?

<?php
// Your code here!

$foo = 89;

if ($foo <= 90)
{
    $h = "this is not right";
}
echo $h;

else {
    echo "this is true";
}
?>

Well the above doesn't work because the block else must follow if in this scenario and not other wise. The below code works however.

If condition doesn't output properly yet it compiles in C

So it compiles ok, but the output it is not the expected. The issue I think is in the OR operator which does not work properly, or it conflicts with the && operator. But perhaps it's bad written or something. Please let me know. Thanks in advance.

Here's the code:

if((len == 16) && secDigit == (51 | 52 | 53 | 54 | 55)
{
    printf("MASTERCARD\n");
    exit(0);
}

else if((len == 15) && secDigit == (34 | 37))
{
    printf("AMEX\n");
    exit(0);

}

else if((len == (16 | 13)) && firstDigit == 4)
{
    printf("VISA\n");
    exit(0);
}

else
{
    printf("INVALID\n");
    exit(0);
}

IF-nesting in c++

heyall, just going through some textbook examples for my introductory c++ course and I would really appreciate it if somebody could clarify why the following code produces an output of 51 (I would expect it to not produce any output whatsoever), many thanks!:

#include <iostream>
using namespace std;

int main()
{
  constexpr int a{9};
  constexpr int b{1};
  constexpr int c{5};

  if (a < b < c)
    if (c > b > a)
      if (a > c) cout << 91;
      else cout << 19;
    else
      if (b < c) cout << 51;
      else cout << 15;
  else 
    if (b < a < c)
      if (a < c) cout << 95;
      else cout << 59;
    else
      if (b < c) cout << 57;
      else cout << 75;

  return 0;
}

My factorising program in c++ is not working with 10 digit input

my program in c++ to factorise a given number is breaking down and giving me negative numbers when i give it a 10-digit input. can anyone tell me what's wrong with my code and how to fix it. HERE's my code: https://code.sololearn.com/c3EqRhMW93rh/?ref=app

If statement don't works in sh file

Good day.

I want to automatize certain process with linux and bash. And I stuck in a IF statement.

This is the code:

#!/bin/bash
result=$(
 sqlplus -s /nolog << EOF
 CONNECT admin/password@server;

 whenever sqlerror exit sql.sqlcode;
 set echo off
 set heading off
 @processQuery.sql
 exit;
 EOF
)
echo $result
if [ "$result" != "no rows selected" ]
then echo "Please, clean up"
else echo "All Ok"
fi

And the output is:

no rows selected
Please, clean up

Thanks so much for the help.

samedi 27 juin 2020

Avoiding incrementing in if statement in C++

I would like to avoid incrementing and decrementing in if-statement since there is a segmentation fault error in the following code while checking conditions (if we start with p = 1 and k = 1 for example):

if (((heights[k--][p--] < heights[k][p]) || (heights[k--][p--] == heights[k][p])) &&
        ((heights[k--][p++] < heights[k][p]) || (heights[k--][p++] == heights[k][p])) &&
        ((heights[k++][p--] < heights[k][p]) || (heights[k++][p--] == heights[k][p])) &&
        ((heights[k++][p++] < heights[k][p]) || (heights[k++][p++] == heights[k][p]))){
                    width[k][p] = 3;
    }

For example, the second check fails with k = -1. I would like to check neighbouring elements of a two-dimensional array heights in an if-statement and than run some logic in case it was true.

How can I optimise it and generally rewrite it to make it look (and work) better? I haven't found any information on it.

appending on ifelse in R

I am trying to append new text to an existing column if it fits within the parameters.

Here is the dataset I am working on:

      Kod     PC1_05 Rank_05     PC1_18 Rank_18      PC_Chg Rank_Chg Zcore_rank_change Status
1 1010110 -1.6952721      21 -1.7914811      10 -0.09620898      -11        -0.2724456 Stable
2 1010120 -1.3518838      67 -1.4729535      59 -0.12106977       -8        -0.1981423 Stable
3 1010130 -0.7793791     138 -0.9511099     114 -0.17173080      -24        -0.5944268 Stable
4 1010140 -0.2219527     192 -0.6900887     145 -0.46813601      -47        -1.1640857 Stable
5 1010201 -1.4540743      55 -1.6195653      41 -0.16549094      -14        -0.3467489 Stable
6 1010210 -1.4193512      57 -1.5769924      43 -0.15764116      -14        -0.3467489 Stable

and trying to filter out the ones above the 70th percentile and append 'accending' to the Status column.

I tried this below but it seems to change all of the status columns to 'accending' and not just those above the 70th percentile.

composite_index_merge <- composite_index_merge %>%
  mutate(Status =  ifelse(PC_Chg > quantile(PC_Chg , c(.70)), Status  <-   'Accending', Status))

Javascript, trying to add a line brake within a while loop

Need to create a chessboard with the following rule set:

Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a "#" character. The characters should form a chessboard.

Passing this string to console.log should show something like this:

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

Here is the code i wrote for it:

    var chessBoardSize = 8;
        var chessBoard = " ";
        var lineBreakCount = 0;

        while (chessBoard.length <= chessBoardSize * chessBoardSize) {

            lineBreakCount++;

            if (lineBreakCount === chessBoardSize) {
                chessBoard += "\n";
                lineBreakCount = 0;
            }

            if (chessBoard.slice(-1) === " ") {
                chessBoard = chessBoard + "#";
            } else if (chessBoard.slice(-1) === "#") {
                chessBoard = chessBoard + " ";
            }

        }

        console.log(chessBoard);

I'm having trouble to get the string on a new line once 8 characters have been used on that line. This is the part of the program i'm trying to figure out:

lineBreakCount++;

        if (lineBreakCount === chessBoardSize) {
            chessBoard += "\n";
            lineBreakCount = 0;
        }

When i run the code, i get back this:

 # # # #

But, it should be this:

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

Js variable of span classes undefind in if statment [duplicate]

Here's my entire js code:

var htmlLang = document.documentElement.getAttribute("lang");
var en = document.getElementsByClassName("en");
var es = document.getElementsByClassName("es");

if(htmlLang == "en"){
    es.style.display = "none";
} else if(htmlLang == "es"){
    en.style.display = "none";
}

And here are the HTML elements I'm trying to modify:

<td><a href='register.php'><span class='en'>Register</span><span class='es'>Registrar</span></a></td>
<td><a href='about.php'><span class='en'>About Me</span><span class='es'>Sobre mi</span></a></td>
<td><a href='login.php'><span class='en'>Log In</span><span class='es'>Iniciar sesi&otilde;n</span></a></td>

When I launch the page, I get the error:

Uncaught TypeError: Cannot set property 'display' of undefined at main.js:6 < Which is at the "es.style..." in the js.

To me everything looks right and I thought it had to do with scope, but putting the whole variable (document.getElements...) in the if statement I get the same error.

Thanks to anyone who can help!

Spreadsheets IF Greater than 0, make another cell equal this

I'm new to spreadsheets and I'm trying to do something like this:

If cell H86 > 0, then make cell J93 have the same value as H86. However, if H86 < 0, then make the cell H93 equal H96.

I tried doing it like this:

=IFS(H86 > 0, J93 = H86, H86 < 0, H93 = H86)

I keep getting the output "False" in the cell I'm trying to do this in, instead of it changing the values in the other cells. If what I'm doing isn't possible is there something I can do to achieve this?

What is the problem with my else if statements?

I'm doing this code for a class, which consists on finding the lowest integer inserted by a user. However, when the variable thirdInt is supposed to be the lowest number, the console doesn't print out the result. Can anybody tell me what is wrong with that part of my code?

import java.util.Scanner;

public class FindMinimum {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the first integer:");
        int firstInt = input.nextInt();
        System.out.println("Enter the second integer:");
        int secondInt = input.nextInt();
        System.out.println("Enter the third integer:");
        int thirdInt = input.nextInt();

        if(firstInt<secondInt || firstInt == secondInt) {
            if(firstInt<thirdInt || firstInt == thirdInt) {
                System.out.println("The minimum is " + firstInt);    
            }  
        }
        else if(secondInt<firstInt || secondInt == firstInt) {
            if(secondInt<thirdInt || secondInt == thirdInt) {
                System.out.println("The minimum is " + secondInt);    
            }
        }
        else if(thirdInt<firstInt || thirdInt == firstInt) {
            if(thirdInt<secondInt || thirdInt == secondInt) {
                System.out.println("The minimum is " + thirdInt);    
            }
        }
    }
}

Why is it unable to sum the profits? Is there a problem with the list values?

profits = 0
losses = 0
netprofits = 0


with open(csvpath) as csvfile:
    csvreader = csv.reader(csvfile, delimiter =',')
    csvheader = next(csvreader)

for row in csvreader:
    if (int(row[1])) > 0:
        profits += float(row[1])
    profits = (profits)
    print(sum(profits))

I keep getting an error that says it is unable to iterate the float() object. Any advice would be greatly appreciated.

changing constraints of object based on ipad or iphone

In my code to reach the desired effect i can only do it if I change the constraints based on whether the using a iphone or ipad. So i need to create something like if iphone constraints = and then if ipad constraints. I wrote a example of what I needed to do. I just need to change the the last line of the 4 statments controlling the bottom ancor.

     //ipad
     NSLayoutConstraint.activate([
        
        box.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.25),
        box.widthAnchor.constraint(equalTo: view.widthAnchor,multiplier: 0.10),
        box.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        box.centerYAnchor.constraint(equalTo: view.centerYAnchor),

      ])

 //iphone
     NSLayoutConstraint.activate([
        
        box.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.25),
        box.widthAnchor.constraint(equalTo: view.widthAnchor,multiplier: 0.10),
        box.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        box.bottomAnchor.constraint(equalTo: view.centerYAnchor),

      ])

Which method is more efficient and better to do this task, also why? Please guide

Method A : In this method I have performed decision making without converting the 'line' from a string to list.

def isVariable(line):
    if not ';' in line:
        return False

    if ('public' in line or 'private' in line or 'protected' in line) and ('int' in line or 'String' in line or 'float' in line):
        return True
    else:
        return False


line = 'private int name;'
print(isVariable(line))

Method B : This method involves performing decision making after converting the 'line' to a list.

def isVariable(line):
    if not ';' in line:
        return False

    modifiers = ['private','protected','public']
    datatypes = ['int','float','String']
    linelist = list(line.split())

    if linelist[0] in modifiers and linelist[1] in datatypes:
        return True
    else:
        return False

line = 'private int name;'
print(isVariable(line))

VBA IF statement

I'm using the below code to tell me when emails have been sent and display the text "sent" so I know there were no errors. But i was testing the code and I use a vlookup to display emails once i add the vendor name. My goal is to not let the macro debug and to let it keep going on to the next but at the same time let me know there was an error on one row either because that vendor did not have an email listed and I need to fill an email in. When i listed the vendors I left a cell blank to test code. Even tho i have valid emails and those emails sent the vba displays "Not sent" to the ones that were sent out. Since the macro could not find an email due to one cell being blank it debugged and next to all the valid emails the text "Not sent" populates. What am I missing or doing wrong? I just want to avoid debugs to tell me there is an error and just tell me that one row was "not sent" and to just keep sending the rest and populate those that do send with a "sent" text.

If Issent = True Then
Range("G" & i).Value = "Sent"
Else
Range("G" & i).Value = "Not Sent"
End If

Arduino timer with set/reset buttons

i'm building an automatic hay feeder for my horse,something like this but with just two floors enter image description here

every 24hrs the plate in the middle should fall and let the hay fall down for the horse to eat,the interface should be very simple,3 buttons one to start the timer, one to stop it and deploy the hay and one to reset the servo in his initial position to lock the plate again, i'm having some problems with the timer,it starts when i press the green button but after it finishes to count it stops and i have to press the green button again, instead it should go endlessly unless i press the red button to reset it

const int greenB = 2; 
const int redB = 3;        

int inAction = 0;
int greenState = 0;
int redState = 0;         
void setup() {

Serial.begin(9600);
pinMode(greenB, INPUT);
pinMode(redB, INPUT);
}

void loop() {

  greenState = digitalRead(greenB);
  redState = digitalRead(redB);

  if(greenState == HIGH){
    inAction = 1;
    while(inAction == 1){
      for(int i = 0; i<10;i++){
        if(redState == HIGH){
          Serial.println("timer stopped");
          goto stopTimer;        
        }
        if(i == 9){
          Serial.println("Cycle completed");
        }
         
        Serial.println("10 seconds timer");
        delay(1000);  
      }
      stopTimer: inAction = 0; 
      
    }
  }
}

I can't figure out how to stop this from being printed

First time on here and pretty much my first time coding, sorry if this doesn't fit but nothing I've tried has worked. Basically, the program is supposed to print numbers 1-100 but every time there is a multiple of 3 it prints Fizz, every 5 it prints Buzz and for both it prints FizzBuzz. At the very end of the print, it always puts 101 and I can't figure out how to stop this. The whole thing is a lot of guesswork because I don't really know what I'm doing, so help is appreciated.

answer = int(1)
limit = int(100)
three: int = (3)
five: int = (5)
while answer < 100:
    if limit >= answer:
        if answer >= three and answer >= five:
            print("FizzBuzz")
            answer = answer + 1
            three = three + 3
            five = five + 5
        if answer >= three:
            print("Fizz")
            answer = answer + 1
            three = three + 3
        if answer >= five:
            print("Buzz")
            answer = answer + 1
            five = five + 5
        if not answer >= five or answer >= three:
            print (answer)
            answer = answer + 1

This is the result:

1
2
Fizz
4
Buzz
6
Fizz
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
21
Fizz
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
36
Fizz
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
51
Fizz
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
66
Fizz
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
81
Fizz
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
96
Fizz
98
Fizz
Buzz
101

Pygame Sprite unresponsive, mac

First time building a game in , let alone . When I launch the code the window with the desired BG comes up, and my Sprite loads where I want. However, the Sprite doesn't move despite all efforts. I've scoured this site and other for resolutions but to no avail.

Note: I am using an upgraded mid-2009 mac book with OS X 10.11.6 and I am launching the code via terminal (python boss_fight.py). Also, I downloaded[tag: pygame] via homebrew.

Other things I've tried:

  1. elif then if vs. if then if statements
  2. Adding print functions after if statements regarding key input to see if the input is registered, does not print.
  3. List item adding print functions after if statements regarding key input to see if input is registered, does not print.
  4. Updating
  5. Updating
  6. Launching with command pythonw boss_fight.py (this yields: ImportError: No module named pygame) which is weird because running the prompt python boss_fight.py runs the game.
  7. I've tried a few other things but can't remember them all

Here's the code:

import pygame  # load pygame keywords
import sys     # let  python use your file system
import os      # help python identify your OS

class Player(pygame.sprite.Sprite):
    
    # Spawn a player
    
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.movex = 0
        self.movey = 0
        self.frame = 0
        self.images = []
        img = pygame.image.load(os.path.join('images','hero.png'))
        self.images.append(img)
        self.image = self.images[0]
        self.rect  = self.image.get_rect()

    def control(self,x,y):
        
        # control player movement
        
        self.movex += x
        self.movey += y

    def update(self):
        
        # Update sprite position
        

        self.rect.x = self.rect.x + self.movex
        self.rect.y = self.rect.y + self.movey

        # moving left
        if self.movex < 0:
            self.frame += 1
            if self.frame > 3 * ani:
                self.frame = 0
            self.image = self.images[self.frame//ani]

        # moving right
        if self.movex > 0:
            self.frame += 1
            if self.frame > 3 * ani:
                self.frame = 0
            self.image = self.images[(self.frame//ani)+4]



# Setup

worldx = 960
worldy = 720

fps = 40        # frame rate
ani = 4        # animation cycles
clock = pygame.time.Clock()
pygame.init()
main = True

BLUE  = (25,25,200)
BLACK = (23,23,23 )
WHITE = (254,254,254)
ALPHA = (0,255,0)

world = pygame.display.set_mode([worldx,worldy])
backdrop = pygame.image.load(os.path.join('images','stage.jpeg')).convert()
backdropbox = world.get_rect()
player = Player()   # spawn player
player.rect.x = 0
player.rect.y = 0
player_list = pygame.sprite.Group()
player_list.add(player)
steps = 10      # how fast to move


# Main loop

while main:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit(); sys.exit()
            main = False

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player.control(-steps,0)
                print('left')
            
            elif event.key == pygame.K_RIGHT: 
                player.control(steps,0)
                print('right')

            elif event.key == pygame.K_UP:
                print('up')

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                player.control(steps,0)

            elif event.key == pygame.K_RIGHT: 
                player.control(-steps,0)

            elif event.key == pygame.K_q:
                pygame.quit()
                sys.exit()
                main = False

    world.blit(backdrop, backdropbox)
    player.update()
    player_list.draw(world)
    pygame.display.update()
    clock.tick(fps)

why if statement not running?

i need some help:

i have if function in my controller :

if (!empty($match_results)){

 $merge = $merged = array_replace_recursive($match_results, $data);
 return  $merge;
}else {
  //
} 

i want check $match_result value, if array $match_result is not empty execute the code and return the value, if empty do nothing.

i dont know why this is not working, do i something wrong ? im newb please help, very grateful if someone helps. sorry for my broken english.

my If Else statement isnt working in javascript [closed]

hi I am new here to ask a question, what my question is, is that my code javascript code isnt working, and I am quite sure that my error is because of my javascript's if else statement.

my code :

<!DOCTYPE html>
<html>
<head>
<title>practice</title>
</head>
<body>

<div id="mydiv"><p>Lorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem 
IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem 
IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem 
IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem 
IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem 
IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem 
IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem 
IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem Ipsum</p></div>

<button onclick="myfunc()">use dark/white theme</button>
<script type="text/javascript">

function myfunc()
 {
if (document.getElementById('mydiv').style.background-color == 'white') 
    {
document.getElementById('mydiv').style.background-color = 'black'
    }
else {
document.getElementById('mydiv').style.background-color = 'white'   
}
}           
 </script>
</body>
</html>

PHP - Not to execute specific code on specific page

I have one common page: default.php

<?php 

________Some Codes________

?>

And my project has 100+ .php files. (Yes all files have require_once 'default.php'; on the first line of all pages)

Now, I am deciding to display alert in all the files except 2. (say 1.php & 2.php).

Of course, I'll add that alert in my default.php.

So now my default.php will look like:

<?php

________Some Codes_______


echo $comn_alert = "<script>alert('Hi');</script>";

?>

Question:

How can I stop $comn_alert from executing on 1.php & 2.php?

inventory calulcation

i have table a and table b table a has qty and itemnames table b has qty and itemnames and yes/no

i need to display all the itemnames in table a and sumtotal of qty of table a and table b if table b column is yes

Using if else with R for three conditions [duplicate]

Apologies for the basic question, I am still a beginner with R!

I have a variable like this: ethnicity <- c(1A, 1B, 1C, 2A, 2B, 3A, 3C, 99, 98)

I want to create a new dichotomous variable, with one exception. I want to recode the values beginning with a 1 as 1, and the values 2A, 2B, 3A, and 3C as 0. 99 and 98 I want to be recoded into 99.

I have this.

testdata %>%
        mutate(ethnicitydi = ifelse(ethnicity %in% c("1A","1B","1C"), 1, 0))

This gives me a new variable with two levels, 1 and 0. The only problem is that I also want 99 and 98 recoded into 99.