dimanche 30 juin 2019

Difference between if and for syntax in Python

I'm new to coding and confused about situations in which to use if vs. for.

In a recent Kaggle micro-lesson, I first tried using for where if was the correct use. The question: "In the cell below, define a function called sign which takes a numerical argument and returns -1 if it's negative, 1 if it's positive, and 0 if it's 0."

My original answer was this:

def sign(num):
    for num < 0:
        return -1
    for num > 0:
        return 1
    for num == 0:
        return 0

The correct answer used if where I used for. So I was wondering, what is the distinction between the two? I couldn't find anything really comparing the two.

bug with if statements and vuejs reestart counter

I'm writing a simple piece of code that increases a counter everytime you click a specific button and it reestarts when you reach 3, the number is shown in each button, it seems to work ok however I have a weird bug: if the first button isnt set to 0 when you press any other button it restarts the first button back to 0. It seems the buttons are linked somehow?

<div id="app">
 <button @click="chooseOne(1,one)">
  
 </button>
 <button @click="chooseOne(2,two)">
   
 </button>
 <button @click="chooseOne(3,three)">
  
 </button>
 </div>

JS

new Vue({
  el: "#app",
  data: {
    one: 0,
    two: 0,
    three: 0
  },
  methods: {
    chooseOne: function(x, y) {
      if ((x == 1) && (this.one < 3)) {
        this.one++;
      } else {
        this.one = 0
      }
      if (x == 2) {
        if ((x == 2) && (this.two < 3)) {
          this.two++;
        } else {
          this.two = 0
        }
      }
      if (x == 3) {
        if ((x == 3) && (this.three < 3)) {
          this.three++
        } else {
          this.three = 0
        }
      }
    }
  }
})

Does is switch/case faster than if/else in PHP +7.3?

I read that switch/case is faster than if/else, but after i searched a bit more i found this question (from 2012) saying that if/else is faster (according to https://phpbench.com/) if use === instead of ==.

I found this article saying that on PHP +7.2 switch/case was optimized to use jump table, but only if all the case statements are either integers or strings.

What about a code like this one bellow?

Which one is faster?

switch(true){
    case($a === 'a'):
        //
        break;
    case($b === 'b'):
        //
        break;
    case($c === 'c'):
        //
        break;
}

vs

if($a === 'a'){
    //
}elseif($b === 'b'){
    //
}elseif($c === 'c'){
    //
}

Would the first snippet use the jump table? I rather use switch/case instead of if/else when there's more than 2 conditions, i felt that it's faster but i'm not sure.

JavaScript: Create a function that returns the frequency distribution of an array

I am trying to create a function that returns the frequency distribution of an array. This function should return an object, where the keys are the unique elements and the values are the frequency in which those elements occur.

My code is below:

function getFrequencies(arr) {

  let obj = {}; 

  for (let i=0; i<arr.length; i++){
    let element = arr[i]; 

    console.log(element)

    // check if key exists in object already

    // if it exists, add 1 to the value
    if (obj[element] !== undefined){
      obj[element] += 1;
    }

    // if it does not exist, add 1 to setup future elements
    else {
      obj[element] === 1; 
    }
  }
  return obj
}

getFrequencies(["A", "B", "A", "A", "A"])

My code returns: {} when it should return:

{ A: 4, B: 1 }

What am I doing wrong?

validating password user enters and check for the rules

The password length should have a minimum length of 6 and maximum of 15 characters Some characters aren’t allowed in the password including “space” and “-”. If user includes these two characters in the input, the program should display “invalid password”.

Python Regex: Check for match and capture groups

I want to ensure that a string matches a regular expression using an if statement, and store capture groups simultaneously. I think the following code shows what I want, but it is syntactically invalid. Is there a way to achieve the following elegantly?

yyyyq_format = "19984"

if regex_match = re.search("^(\d{4})(\d)$", yyyyq_format):
    found_q = regex_match[2]
else:
    raise ValueError("Format \"yyyyq\" is not followed.")

I know the following works (is this my only option?):

yyyyq_format = "19984"
regex_match = re.search("^(\d{4})(\d)$", yyyyq_format)

if regex_match:
    found_q = regex_match[2]
else:
    raise ValueError("Format \"yyyyq\" is not followed.")

If Then Loop in AutoHotkey to switch between desktops

Let's say ^RButton switches to my right desktop and ^LButton to my left desktop. The probelm then is, that whenever I switch to the right desktop a dropdown menu will open, because I'm using the right mouse button as a hotkey. To counteract this problem, I can add sleep 500 and then send, {Escape} to exit the dropdown menu. So far so good. However, if I now want to switch from desktop 1 to desktop 5 I cannot just do 5 ^RButtons in a row but instead have to wait half a second between each click. That's annoying! I'd be grateful for any ideas on how to avoid having to wait 500 milisecond between each click? My idea was to work with an if statement. Though I have no idea how to program one... It would look like this:

If ^RButton = True, go to right desktop, 
if after 500 miliseconds there were no further ^RButton clicks, 
then send, {Escape}. 
If there were ^RButton clicks, 
go to the right desktop and wait 500 miliseconds for another ^RButton click,
then send, {Escape}.

Would be awesome if someone could transform my text code into AutoHotkey code :D

samedi 29 juin 2019

How to substitute in R "Ethiopia" with "Ethiopia (-1992)" and "Ethiopia (1993-)" based on the year?

I am trying to substitute "Ethiopia" in location_1 with "Ethiopia (-1992)" if location_1 says "Ethiopia" and the years correspond to all years up to and including 1992 and with "Ethiopia (1993-)" if location_1 says "Ethiopia" and the years correspond to all years from 1993 forward.

Unfortunately, the code I came up with substitutes all with "Ethiopia (-1992)" even for those years after 1992.

The following is the code:

if (mydata$year >= 1992) {
  mydata$location_1 <- sub("Ethiopia", "Ethiopia (-1992)", mydata$location_1)
} else mydata$location_1 <- sub("Ethiopia", "Ethiopia (1993-)", mydata$location_1)

I was hoping that I would have all "Ethiopia" turned into either "Ethiopia (-1992)" or "Ethiopia (1993-)" based on the year. Instead, the results are that all "Ethiopia" become "Ethiopia (-1992)".

Stuck in else if loop in Javascript

I'm doing an exercise for a class and we are creating a todo list. My issue is that when I type in my todo and press enter I get the message "Enter new todo", instead of "Added todo". It seems I'm stuck in this else if loop and it won't go to the next else if statement.

var todos = ["Buy New Turtle"];

window.setTimeout(function() {

  var input = prompt("What would you like to do?");

  while(input !== "quit") {

    if(input === "list") {
      console.log("**********");
      todos.forEach(function(todo, i) {
        console.log(i + ": " + todo);
      })
      console.log("**********")
    }
    else if(input === "new") {
      var newTodo = prompt("Enter new todo");
      todos.push(newTodo);
      console.log("Added todo");
      }

    else if(input === "delete"){
      var index = prompt("Enter index of todo to delete");
      todos.splice(index, 1);
      }
  }
    input = prompt("What would you like to do?");

  console.log("OK, YOU QUIT THE APP");
}, 500);

How to format an If Statements with multiple conditionals inside a function

I'm working on creating a function that will evaluate two conditions from a dataframe and pass a series of prearranged return values given the inputs back to the dataframe should it encounter a NaN. The first condition I'd like to have is a check to see if the value of one column is a NaN (obviously) and then check to another column to see what key the id that has been assigned (1,2,3 etc). The eventual goal is to use the .apply method on the function to fill the NaN values with the values from the function back to the original dataframe or to leave the existing values (if present) alone. What's getting me hung up is that this is the first time I've written anything like this to call within a dataframe and I'm having issue of assignment within the control flow.

This is using python 3.6. I've tried playing around with multiple forms of the below but everything consistently gives me the same type error as it tries to apply the function to the dataframe. This is not the actual dataframe but I made quickly to give you a gist of the issue I'm running into.

Obviously something is off in the function but the result would've ideally updated the NaN value with the 40 value

So far I've tried amending the function in all the ways I can think to make sense to get it to be able to iterate over the dataframe.

import pandas as pd
import numpy as np

frame = {'key' : [1,2,3,4,5],
    'height' : [70, 68, 74, 67, 72],
    'age' : [29,45,'N/A',51,34]}

frame = pd.DataFrame(frame)

frame.replace('N/A',np.nan)

def age (x):
    if (x['age'].isnull()) & (x['key'] == 3):
        return x.replace(np.nan, 40)
    else: 
        return x

result = frame.apply(age) 

Here's a snapshot of the dataframe that I would like to amend

How to compare the two different positions in the file in C?

I am implementing the program to zip a file using a run-length encoding compression method. Are there any ways you can compare the characters in the file or compare two file pointers to do that?

I opened the file(zipfilename) that I want to zip and set the file pointer named ftozip to it. Then, I tried to count the number of each character using this file pointer as shown in the code below (if condition).

    FILE *ftozip;
    ftozip = fopen(argv[1],"r");//open the file that we are zipping
    if (ftozip == NULL) {//if there is an error opening
            perror("File cannot be opened ");
    }
    char zipfilename[30];
    strcat(zipfilename, argv[1]);
    strcat(zipfilename,".zip");
    FILE *zipfilep = fopen(zipfilename, "a"); //zipfile openned to write

    int count = 1;
    while(1){ //incrementing the characters and storing in the zip  file
            if(*ftozip == *(ftozip +1)) {
                    count++;
                    char countchar[] = (char)count+(*ftozip);
                    fputs(countchar, zipfilep);
                    ftozip++;
                    continue;
            }
            else {
                    count = 1;
                    countchar = (char)count + (*ftozip);
                    ftozip++;
                    if (feop(ftozip){
                            break;
                    }
                    continue;
            }

}

That resulting in this error "invalid operands to binary == (have ‘FILE’ and ‘FILE’)".

Remove rows that have inexact duplicates in R

I have some sales data where mistakes recorded at the point of sale are corrected afterward and the data set still contains records for the initial mistake then a duplicate of the mistake but with a negative price value. However, there are multiple duplicate lines for some sales which are valid and must be retained.

DATE MODEL TYPE COUNT PRICE WEIGHT TOTAL ABS_COUNT ABS_WEIGHT ABS_TOTAL replicate 20140211 JBL A 1 4.5 15 67.5 1 15 67.5 1 20140211 JBL A 1 4.5 15 67.5 1 15 67.5 2 20140211 JBL B 1 6.5 27 175.5 1 27 175.5 1 20140211 JBL A 1 4 11 44 1 11 44 1 20140211 JBL B 1 11.2 44 492.8 1 44 492.8 1 20140211 JBL B 1 6.5 27 175.5 1 27 175.5 2 20140211 JBL B 1 11.2 44 492.8 1 44 492.8 2 20140211 JBL A 1 4.5 15 67.5 1 15 67.5 3 20140211 JBL A 1 4.5 15 67.5 1 15 67.5 4 20140211 JBL B -1 -11.2 44 -492.8 1 44 492.8 3 20140211 JBL B 1 10.9 82 893.8 1 82 893.8 1 20140211 JBL A 1 4.5 15 67.5 1 15 67.5 5 20140211 JBL A 1 4.5 15 67.5 1 15 67.5 6 20140211 JBL A 1 4.5 15 67.5 1 15 67.5 7 20140211 JBL B 1 11.2 44 492.8 1 44 492.8 4 20140211 JBL A 1 3.2 15 48 1 15 48 1 20140211 JBL B 1 11.2 44 492.8 1 44 492.8 5 20140211 JBL B 1 11.2 44 492.8 1 44 492.8 6 20140211 JBL A 1 4.5 15 67.5 1 15 67.5 8 20140211 JBL A 1 4.5 15 67.5 1 15 67.5 9 20140211 JBL B 1 11.2 104 1164.8 1 104 1164.8 1 20140211 JBL A -1 4.5 -15 -67.5 1 15 67.5 10 20140211 JBL A 1 4.5 15 67.5 1 15 67.5 11 20140211 JBL A 1 4.5 15 67.5 1 15 67.5 12 20140211 JBL B 1 11.2 44 492.8 1 44 492.8 7

What I have done is calculated the abs() for each of the COUNT, WEIGHT, and TOTAL columns then counted the number of replicates. I am now trying to figure out how to remove the negative observations as well as the corresponding duplicate where column replicate=n-1

test$ABS_COUNT <- abs(test$COUNT) test$ABS_WEIGHT <- abs(test$WEIGHT) test$ABS_TOTAL <- abs(test$TOTAL)

test2 <- test %>%

dplyr::group_by(DATE, MODEL, TYPE, PRICE, ABS_COUNT, ABS_WEIGHT, ABS_TOTAL) %>% dplyr::mutate(replicate=seq(n()))%>% ungroup()

Use IF with multiple ELSEIF and ELSE in a spreadsheet cell

I am trying to make this statement applicable to some cells in my google spreadsheet :

if ((B29 - B36) > 0) {
    (B29 - B36) * (D36 / 100) + F35 + F34 + F33
} else if  ((B29 - B35) > 0) {
    (B29 - B35) * (D35 / 100) + F34 + F33);
} else if (B29 - B34 > 0) {
    (B29 - B34) * (D34 / 100) + F33);
} else {
    0
}

I tried to make it with only IF, but the cells didn't like the syntax :

=IF((B29 - B36) > 0);((B29 - B36) * (D36 / 100) + F35 + F34 + F33);IF((B29 - B35) > 0);((B29 - B35) * (D35 / 100) + F34 + F33);IF((B29 - B34) > 0);((B29 - B34) * (D34 / 100) + F33);0

How can I achieve this?

Problems with indices and ifelse statements when trying to replace a for loop

I would like to replace the following for loop because there has to be an easier way and the for loop takes ages to compute. The data frame yearly consists of several columns. Each column has a length of 15,457 entries. Column Id contains alphanumeric identifiers while all other columns contain numbers and NAs.

yearly[, OA := "NA"]
yearly$OA = as.numeric(as.character(yearly$OA))
for(i = 2:length(yearly$WC03063)) {
  if(yearly$Id[i] == yearly$Id[i - 1]) {
    if(is.na(yearly$WC03063[i])) {
      yearly$OA[i] <-
      yearly$WC02201[i] - yearly$WC02201[i - 1] -
      yearly$WC02001[i] - yearly$WC02001[i - 1] -
      yearly$WC03101[i] - yearly$WC03101[i - 1] +
      yearly$WC03051[i] - yearly$WC03051[i - 1] -
      yearly$WC02999[i]
    } else {
      yearly$OA[i] <-
      yearly$WC02201[i] - yearly$WC02201[i - 1] -
      yearly$WC02001[i] - yearly$WC02001[i - 1] -
      yearly$WC03101[i] - yearly$WC03101[i - 1] +
      yearly$WC03051[i] - yearly$WC03051[i - 1] +
      yearly$WC03063[i] - yearly$WC03063[i - 1] -
      yearly$WC02999[i]    
    }
  }
}

I already made several attempts to solve this problem but always had problems with indices and ifelse statements. My most recent example looks like this:

i <- c(1:length(yearly$WC03063))
yearly[, OA := ifelse(i == 1, NA,
                      ifelse(yearly$Id[i] == yearly$Id[i - 1],
                             ifelse(is.na(yearly$WC0306),
                                    yearly$OA[i] <-
                                    yearly$WC02201[i] - yearly$WC02201[i - 1] -
                                    yearly$WC02001[i] - yearly$WC02001[i - 1] -
                                    yearly$WC03101[i] - yearly$WC03101[i - 1] +
                                    yearly$WC03051[i] - yearly$WC03051[i - 1] -
                                    yearly$WC02999[i],
                                    yearly$OA[i] <-
                                    yearly$WC02201[i] - yearly$WC02201[i - 1] -
                                    yearly$WC02001[i] - yearly$WC02001[i - 1] -
                                    yearly$WC03101[i] - yearly$WC03101[i - 1] +
                                    yearly$WC03051[i] - yearly$WC03051[i - 1] +
                                    yearly$WC03063[i] - yearly$WC03063[i - 1] -
                                    yearly$WC02999[i]),
                       NA))]

R’s error message (in this case) reads as follows:

1: In `==.default`(yearly$Id[i], yearly$Id[i - 1]) : Longer object length is not a multiple of shorter object length
2: In is.na(e1) | is.na(e2) : Longer object length is not a multiple of shorter object length

I already tried several variations of solutions but not a single one has worked so far.

vendredi 28 juin 2019

Python - Is it possible to use a list as a condition for an if statement?

I am in the process of learning Python and one of the exercises that I was tried to do was make a "guess the number" game. I made a very simple one, but now I want to take it a little bit further and set some boundaries for the inputs so that the program is error-proof. Here is my code:

# Guess the number game.

import random

print('Hello. What is your name?')

yourName = input() # collects user's name

solution = random.randint(1,20)

print('Well, ' + str(yourName) + ', I am thinking of a number between 1 and 20.')

acceptable = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20'] # acceptable answers

def game():

    for attempts in range(1,6):

                    print('Take a guess. You have ' + str(6 - attempts) + ' attempt(s) remaining')

                    # try:

                    guess = (input())

                    while guess:

                                if guess != acceptable:

                                    print("That is not a valid answer!")

                                    guess = (input())

                                else:

                                    moveon()

def moveon():

                    while guess != solution:

                                if guess < solution:

                                    print('Your guess is too low. Try again.')

                                elif guess > solution:

                                    print('Your guess is too high. Try again.')

                                else:

                                    endofgame()

'''
                    except ValueError:

                            print('Please enter a guess that is a number.')

                            attempts + 1 == attempts
'''

def endofgame():

    if guess == solution:

            print('You guessed it! It took you ' + str(attempts) + ' attempt(s)')

            playAgain()

    else:

            print('Game over! The number I was thinking of was ' + str(solution))

            playAgain()



# Option to play again with a new number

def playAgain():

    global solution

    print('Play again? Y/N')

    playAgain = input()

    if playAgain == 'Y':

            print('Okay, ' + str(yourName) + ', I have another number between 1 and 20.')

            solution = random.randint(1,20)

            game()

    else: print('Thanks for playing!')



# Start game
game()

So what I want to do is make sure that when the user is prompted to input a number between 1 and 20, entering answers like "22", "coffee" or "14.5" would be invalid and prompt them to try again and enter a valid answer. However, when I run this program right now, any answer that is entered is returned as invalid. How do I make it so that only certain answers are accepted, and others are not? I suspect that there is a way other than using a list that I do not know of yet. Thanks in advance!

Explanation for php code with if statement

I have code like this can some one help me figure out how the condition logic work in this

$environment = ( $this->environment == "yes" ) ? 'TRUE' : 'FALSE';
    // Decide which URL to post to
      $environment_url = ( "FALSE" == $environment )
                               ? 'https://api.ewaypayments.com/AccessCodes'
               : 'https://api.sandbox.ewaypayments.com/AccessCodes';

Checking For Empty Array in If/Else Block Strange Behavior

Within my if/else block, I wanted to check if a certain array is empty by using:

else if (emptyFieldNames.length === 0) {
  console.log('no empty fields');
}

I've consoled log 'emptyFieldNames' and can verify it is empty, but the code body won't run**.

If you fill in all input fields here in this codepen, and click submit, you'll see it console logging an empty array, but yet not logging the message. The interesting part is, **if you fill in a valid email, it will console log the message. However, I don't see why that would matter since array is still empty whether or not a valid email is inputted.

What am I missing?

The syntax for checking equality of a variable

Want to know if there is an option to optimize (to make it more competently) the syntaxes of the comparison

I have a simple code which checks the inputs to my function through the "if - else" conditional statements. I verify if the variable equals to one of the inputs or not using logical "OR" operator.


function cc(card) {
  // Only change code below this line
  if (card==2 || card==3 || card==4 || card==5 || card==6) {
    count+=1;
  }
  else if (card==7 || card==8 || card==9) {
count+=0;
  }
  else if (card==10 || card=="J" || card=="Q" || card=="K" || card=="A") {
    count-=1;
  }
  else {
  return "No such combination";
  }
  if (count>0) {
    return count + " " + "Bet";
  }
  else {
    return count + " " + "Hold";
  }
  // Only change code above this line
}

// Add/remove calls to test your function.
// Note: Only the last will display
cc(7); cc(8); cc(9);

I would like to know if I can replace this amount of "OR" operators with another syntaxes? I know about "switch" method, but now I'm interested in particular this approach.

Thank you!

Churn Labelling in Python

I need to create a Churn label (new column) that identifies clients that traded at least once a week for the past 4 weeks and then stopped trading for the next 4 weeks.

I figured I'd need something with a "for" and a "if" but I can´t come up with a way to do it.

On one hand I have a column with the week number and another column with the client ID

In the example below (image) the client 3689 would be labelled 0 and the client 5445665 would be labelled 1

I don´t know how to replicate this data on Python, sorry for uploading a image

enter image description here

How to efficiently check different date formats when converting month to number

I'm trying to convert a given month to a month number in integer format. There are three valid formats that I want to try to convert. A month number that's given as a string (input function returns a string), a month abbreviation, and a full month name.

While my function works as intended I feel like it's not that well written, despite my attempts to make it as clean as possible. In particular, I'm not happy that I have an except statement that just passes. Handling both a string conversion to an integer AND checking to see if the string is a valid month to convert to an integer was a tough task.

I tried to change the order of the try-excepts, removing the string-to-int to make it's on try-except block without going straight into the date formatting in the exception but that's about it. The function below is the best attempt I've had. I couldn't think of anything else except maybe create helper functions?

Code

def get_start_month_updated():
    date_formats = ['%b', '%B']
    while True:
        month = input("What is the starting month?")
        try:
            month_num = int(month)
            if 1 <= month_num <= 12:
                return month_num
        except ValueError:
            for date_format in date_formats:
                try:
                    month_num = strptime(month, date_format).tm_mon
                    return month_num
                except ValueError:
                    pass
            else:
                print("You must enter a valid month")
        else:
            print("You must enter a valid month")

My results are correct and the function works as intended, but I feel like the code is messy and there is a better way to do this without getting really convoluted.

How can I make an if and elif statement based on an outcome of random.choice and an input

I am trying to create a game that asks you what a certain character does in a book and I am using random.choice and an if and elif statement to do that however when I type my input to answer the question the output is always wrong even though i answered the question wright.

I have tried to make the if statement:

if 'The main character' in card_list and choice == person1:
  print("correct")

for every statement however the results are always correct even if i type in the wrong answer.

import random

card1 = 'The main character'
card2 = 'He brings aleem on holiday'
card3 = 'Dies in the middle of the book'
card4 = "She takes care of aleem while aleem's dad is in Ethiopia"
card5 = 'He helps take care of aleem with Miss Fitzgerald'
card6 = "He is in charge of aleem's court case"

person1 = 'aleem'
person2 = "aleem's dad"
person3 = "aleem's mum"
person4 = 'Miss Fitzgerald'
person5 = 'Mr Fitzgerald'
person6 = 'Nicolas'

card_list = [card1, card2, card3, card4, card5, card6]

print(random.choice(card_list))

choice = input('Who is this? ')

if 'The main character' == random.choice and choice == person1:
  print("correct")
elif 'He brings aleem on holiday' == random.choice and choice == 
person2:
  print('correct')
elif 'Dies in the middle of the book' == random.choice and choice == 
person3:
  print('correct')
elif "She takes care of aleem while aleem's dad is in Ethiopia" == 
random.choice and choice == person4:
  print('correct')
elif 'He helps take care of aleem with Miss Fitzgerald' == 
random.choice and choice == person5:
  print('correct')
elif "He is in charge of aleem's court case" == random.choice and 
choice == person6:
  print('correct')
else:
  print('wrong')

This is what I have been using to create the game.

Making a cell in column B display the largest value in column A

I have 2 columns, H&I with numbers. The values in H correspond to different ID numbers, and I has measurements.

I am trying to figure out a formula that would post in cell K3 the highest value in column I. I also want cell L3 to say the corresponding value in column H (relative to the new highest value/new value of cell K3).

I tried to figure out an if statement that works, but I couldn't get it just right.

If, elif, else conditions

I was dealing with CodingBat problems to learn better and more efficiently and the problem I've faced was:

Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative.


pos_neg(1, -1, False) → True
pos_neg(-1, 1, False) → True
pos_neg(-4, -5, True) → True

I wrote that code to run the desired process

def pos_neg(a, b, negative):
  if (a<0 and b>0) or (a>0 and b<0):
    return True
  elif negative and (a<0 and b<0)
    return True
  else:
    return False

but I get

Compile problems:


invalid syntax (line 4)

as an Error. Solution given by CondaBat is:

def pos_neg(a, b, negative):
  if negative:
    return (a < 0 and b < 0)
  else:
    return ((a < 0 and b > 0) or (a > 0 and b < 0))

I see that the example code given by is faster and more efficent compared to mine but I can't see why my elif statement returns an error.

I have a question about if else statements and raw_input statements

So my code isn't working, and just skipping straight to the else statement no matter what input the user uses.

start_over = 10

STONKS = raw_input("YESN'T? ")

if raw_input == "What?":
        start_over -= 1 
        print STONKS    
elif raw_input == "Yeah?":
        print "Nah, don't be a bully Ninja"
        start_over -=1
        print STONKS     
else:
        print "YOU ATE MY BEANS?!"


Can anyone help?

Google Sheets IF statement with OR logic error?

The formula I created for a Google Sheet is not working. Seems to be a logic error but I'm not sure what I'm doing wrong here.

This formula is being entered into F3:

=IF(OR(C3="",D3="",E3=""), "", TODAY())

I thought this would do it. If C3 is blank OR D3 is blank OR E3 is blank, then leave the cell blank, else show today's date. It's treating it like an AND statement and only putting today's date if all three cells (C3, D3, E3) have something in them.

I am having trouble removing zeroes from unused operators

.

I wrote this spreadsheet in Google Sheets, and I am using an entire column to get the calculations of A+B=C. ArrayFormula(E2:E*D2:D) <-- this is for the entire C column's formula, but I need to modify it to not calculate if either A or B is blank.

Why is my Ruby on Rails condition not working on view folder?

Regarding a Ruby on rails app, I'm using if statements on the different view files of the same view folder.

The condition is working well for all files in my folder except one for which it is not. Here is the code lines :

- else
  .row
    .col-xs-12.text-center
    - if @progress_board.cover_image.present? ##<--- This one is not working ##
      %h4[...]
    - else
      %h4[...]

Note : this is haml

  • I tested with another condition involving progress_board. It didn't work.

  • I tested with another condition from the issue file himself. Worked.

=> My syntax is good. The issue comes from @progress_board.

Since the file is using a JS tool to display charts it may be the origin of the problem.

Maybe it's a stupid issue but I'm new to RoR, trying to understand. Should I declare some variable at some points ?

Thank you for helping !

Calculations from multiple variables using SAS

situation

I have transactional data and I need to create a couple of variables in the dataset involving some complicated rules.

Here are the rules that I have:

  1. Amt is the transactional amount
  2. Limit amount is the same across serial numbers
  3. OBal is the Opening Balance
  4. New_Bal and PostBal are based on the type of transaction. If type='A' then New_Bal=OBal+Amt otherwise New_Bal=OBal-Amt
  5. For the first transaction PostBal=(Limit+OBal)+Amt and for the remaining transactions PostBal=OBal-Amt
  6. fee and fee_amt are to be created if the type='B' and Amt>5
    • If the Amt is greater than PostBal then we will keep the same New_Bal and Post_Bal and add fee=1, fee_amt=10 and fee_ind=N (Row 4 for id 101 from the desired output)
    • If the Amt is less than PostBal then we will add Post_Bal and fee=2, fee_amt=10 and fee_ind=Y (Row 5 for id 101 from the desired output)
  7. We will limit fee to 3 and subtract that amount from final transaction amount (Row 6 for id 101 -22-30=-52)

Here is the example of data for two different ids and serial numbers:

Initial Data

   id serial   type Amt    OBal    Limit
   101  1234     A    100    -50     100
   101  1234     B     25               
   101  1234     B     50               
   101  1234     B     80               
   101  1234     B     50               
   101  1234     B      3               
   101  5678     A    100            100 
   201  1234     A    100    -50     100
   201  1234     B     25               
   201  1234     B     50               
   201  1234     B     50               
   201  1234     B     50               
   201  1234     B     20                
   201  5678     B     50           100 

Code I have tried:

data want;
    set have;
    by id serial;

    /*Calculate OBal*/
    if first.serial and not first.id then OBal  =  New_Bal;
    if first.serial then do;
        New_Bal  =  OBal;
        PostBal  =  Limit + NewBal;
        fee  =  0;
    end;
    if type = 'A' then NewBal + AMt;
    if type = 'B' then NewBal + (-AMt);

    if type = 'A' then PostBal + AMt;
    if type = 'B' then PostBal + (-AMt);
run;

My code is creating NewBal and PostBal properly. However, I am unable to loop them to add the fee and fee_ind. This is a very complicated task for me and I know this group has some great talent who can help me in resolving this.

Thanks in advance

Desired result:

      id   serial   type Amt    OBal    Limit   New_Bal  PostBal    fee    fee_amt  fee_ind
       101  1234     A    100    -50     100      50       150
       101  1234     B     25                     75       125        1      10         Y
       101  1234     B     50                     25        75        2      10         Y 
       101  1234     B     80                     25        75                0         N
       101  1234     B     50                    -25       -25        3      10         Y
       101  1234     B     3                     -52       -28                          
       101  5678     A    100    -52     100      48       148 
       201  1234     A    100    -50     100      50       150
       201  1234     B     25                     75       125        1      10         Y
       201  1234     B     50                     25        75        2      10         Y 
       201  1234     B     50                    -25        25        3      10         Y
       201  1234     B     50                    -25        25                0         N
       201  1234     B     20                    -55        25                0         N
       201  5678     B     50    -55     100       5        -5

Creating a new variable in r using ifelse and %in%

I want to create a new variable where if the variable $Who.went.first is contained within the variable $Who.should.go.first then it will return TRUE for the new variable, else it returns FALSE. $Who.should.go.first and $Who.went.first both have the same set of car names as input, except for some reason all the $Who.should.go.first inputs have the text "(Aspect)" at the end, hence I want the function to check $Who.went.first is contained within $Who.went.first rather than looking for exact matches.

I'm trying to do this using the ifelse function and %in%, as shown below.

Cooperation_2clean$correct.go.first <- ifelse((Cooperation_2clean$Who.went.first %in% Cooperation_2clean$Who.should.go.first), "TRUE", "FALSE")

It will create a new variable, except every case returns FALSE. For example, if $Who.went.first is "AV_0_Blue" and $Who.should.go.first is "AV_0_Blue (Aspect)" then it returns FALSE when it should be true.

Should I be using a different function such as case_when?

If-else expression in slick run, update method scala function

I want to check with if-else statement if the variable newPsInfo.clearedCanLoadSC

is true then i want to make a Timestamp of Today else of some other Date so i tried the

ternary if-else with 
condition? true : false

newPsInfo.clearedCanLoadSc.equals(true) ? 
LocalDate.now() : LocalDate.of(2000,1,1)

but unfortunately doesn't work

First I .filter by _.id then I .map the results by productSettingsTable class to the new updated values of new productSettingsInfo parameter. So my question is can i insert an if - else statement into the .map or .update methods like this:

    newPsInfo.clearedCanLoadSc.equals(true) ? 
    LocalDate.now() : LocalDate.of(2000,1,1))

def update(employer: Employer, newPsInfo: PsInfo): Future[Int] =

    db.run(
      productSettingsQuery.filter(_.employerId === employer.id).map(productSettings =>
        (productSettings.enableSc, productSettings.enableConversion,
          productSettings.enableRefundDays, productSettings.enableOutOfPocketPayment,
          productSettings.clearedCanLoadSc, productSettings.enableL, productSettings.clearedAt)).
     update((newPsInfo.enableSc, newPsInfo.enableConversion,
          newPsInfo.enableRefundDays, newPsInfo.enableOutOfPocketPayment,
          newPsInfo.clearedCanLoadSc, newPsInfo.enableL,newPsInfo.clearedCanLoadSc.equals(true) ? LocalDate.now() : LocalDate.of(2000,1,1)))
    )

The problem is that my if else clause is not working the Intelli j shows errors Cannot resolve symbols ?

So is there a way to insert an if-else-statement into the .map or .update function?

jeudi 27 juin 2019

Better If statement with type checking C#

I'm currently working on a .NET 4.7.1 application. I have an If-statement to check the data type and call an handler method accordingly.

My current If statement looks like this:

// object msg = MyHelper.Deserialize(xmlString);

if (msg is Tomato) Handle_Tomato((Tomato)msg);
if (msg is Apple) Handle_Apple((Apple)msg);
if (msg is Banana) Handle_Banana((Banana)msg);
if (msg is Orange) Handle_Orange((Orange)msg);

msg is basically an object deserialized from a string.

I was wondering, if there is a better way to write my if statements?

Thank you very much!

I need some help for def if statments

I need to input as many grades until I press -1 to end it


def content (int[m])):
    if m < 50:
        g = 'Grade is F'
    else:
        if float m < 60:
            g = 'Grade is C'
        else:
            if float m < 70:
                g = 'Grade is B'
            else:
                g ='Grade is A'
    return g 

a=0
b= int(a)
c=0

while a != -1:
     a = input ('Enter Grade:')
     a += b
     if a == -1:
         print ('end')
         average = a/b
         break 
     else:
         content(a)


print (" The Average Grade {0}" .format(average))


It always comes out this error:

TypeError: can only concatenate str (not "int") to str

Conditional If / Else Statement Python

I am new to Python and need some assistance. I am trying to write a simple function that takes a int value from a column in my Dataframe (seconds_left) and creates an additional column of string values created from binning methods. I am referencing a separate Numpy Array (bins2) that contains the cut points for the bins.

I created a 1D Numpy Array with the cut points for each bin I'd like to reference to define my boundaries. These cut points were created from the Sturges binning method on one variable/column labeled 'seconds_left'. It is important to note that my seconds_left column in the Dataframe are int values and my array has continuous values. Not sure if that is okay or not.

# Turn Series into flattened np array
sec_left_nparray = dfb.loc[:,'seconds_left'].values

# Bin cut point based on Sturges Estimator
(n2, bins2, patches2) = plt.hist(sec_left_nparray, bins='sturges', range=(0,300), density=True)#,log=True)

# Binning function 
def bin_sec_left(row):
    if ((row >= bins2[0]) & (row < bins2[1])):
        return '0-18.75'
    elif ((row >= bins2[1]) & (row < bins2[2])):
        return '18.75 to 37.5'
    else:
        return 'NA'

#Add additional column to dab Dataframe 
df['sec_left_bin'] = df['seconds_left'].apply[bin_sec_left]

I simply want to return a Dataframe with the added computed string column based on the values in my array. I am trying to reference the array index as my boundaries in the conditional statement. However, I keep getting an error "'method' object is not subscriptable". Any idea what I am doing wrong? Thanks in advance.

How to cleanly handle multiple conditions that are very similar to one another

I'm trying to figure out a way to best handle multiple path files that are very similar to one another. While my code works, I feel like it's cumbersome, harder to maintain and difficult to scale without alot of manual work (For example suppose I need to keep adding more and more paths that are just slightly different.

Ideally, I would like to apply the DRY principle as much as possible and not have if-else statements all over the place if there is a better solution.

I thought that using dictionaries or a class might be some improvement but it felt cumbersome to also store paths in a dictionary. I'm not as experienced with classes so I couldn't get it to work without a ton of workarounds (I don't think I was constructing the class properly)

Code

def save_df(df, banner, year, month):
    base_path = r'common\path\{0}\for\all\banners\{1}'.format(banner.upper(), year)

    if banner in ('a', 'b'):
        if month < 10:
            # The zero is so I can have the file month in '01, 02, etc.' format
            default_path = os.path.join(base_path, '{0}-0{1}_TEST'.format(year, month))
        else:
            default_path = os.path.join(base_path, '{0}-{1}_TEST'.format(year, month))
    else:
        if month < 10:
            default_path = os.path.join(base_path, '{0}_{1}-0{2}_TEST'.format(banner.upper(), year, month))
        else:
            default_path = os.path.join(base_path, '{0}_{1}-{2}_TEST'.format(banner.upper(), year, month))

    saved_output = [df, default_path]
    return saved_output

No problems for the path, works as intended. I believe the code can be improved by refactoring, however, I'm not sure the best way to go about handling conditions that are very similar without repetition.

Setting an If Statement based on the second entry of an ID

This is a continuation of a question I asked earlier today. Got the answer to the initial question by a @ScottCraner however I am now required to make a second version.

So basically I have an excel sheet featuring a number of different id's, dates, and a column where I would like to specify beginning middle or end in a 3rd column depending on the SECOND DATE in the ID. However this should only apply to the block of the same ID. When the next ID passes through, the date of the first ID in the block will determine the rest of the 3rd column, and so on and so forth.

The issue is much better understood when looking at the dataset.

ID      DATE      formula_col
10R46   10/8/2011
10R46   2/18/2012
10R46   6/30/2012
10R47   2/4/2010
10R47   5/16/2010
10R47   8/8/2010
10R47   12/11/2010
10R47   1/4/2011
10R48   6/26/2011
10R48   9/11/2011
10R48   1/29/2012
10R48   4/20/2012
10R48   7/8/2012

So the formula_col column should be filled based on the SECOND DATE in the ID. Both the first and second will be "Beginning" and the third would follow the pattern:

The date in the second row of the same ID first month is beginning, next is middle, next is end, then it repeats.

So if the first month was February (2) (found in the second date of the ID block), then the formulas for these ID's would be: February: Beginning March: Middle April: End May: Beginning June Middle July: End August: Beginning September: Middle October: End November: Beginning December: Middle January: End And any could appear, not necessarily beginning, middle, end in that order. But they will always be in date order, no going back in time and such until the ID is over.

ID      DATE      formula_col
10R46   10/8/2011 Beginning
10R46   2/18/2012 Middle
10R46   6/30/2012 Beginning
10R47   2/4/2010  Beginning
10R47   5/16/2010 Beginning
10R47   8/8/2010  Middle
10R47   12/1/2010 End
10R47   1/4/2011  Beginning
10R48   6/26/2011 Beginning
10R48   9/11/2011 Beginning
10R48   1/29/2012 End
10R48   4/20/2012 End
10R48   7/8/2012  End

The code to do this based on the first ID (provided by @ScottCraner)

==CHOOSE(MONTH(B2)-MONTH(INDEX(B:B,MATCH(A2,A:A,0))),3)+1,"Beginning","Middle","End"))

This is great, but I would like to check on the second ID that appears. Something tells me VBA is required to do this.

I'm not sure if this is helpful but the first ID has a value next to it in a completely seperate column and the date ID column which sets the whole block in motion would follow below it.

ID      DATE      formula_col  extra
10R46   10/8/2011 Beginning    504444.27
10R46   2/18/2012 Middle   
10R46   6/30/2012 Beginning
10R47   2/4/2010  Beginning    1022.22
10R47   5/16/2010 Beginning
10R47   8/8/2010  Middle
10R47   12/1/2010 End
10R47   1/4/2011  Beginning
10R48   6/26/2011 Beginning    239.33
10R48   9/11/2011 Beginning
10R48   1/29/2012 End
10R48   4/20/2012 End
10R48   7/8/2012  End

So the months would be determined by the second date in the ID block, or in other words the row below a cell with values in "extra"

SAS Error: Null parameters for SUM are invalid

So I have a data named table1 as follows:

Obs  ID  M_201812  M_201901      M_201902    M_201903

1    X1     1         .             .           . 
2    X2     1         1             .           . 
3    X3     .         1             1           . 
4    X4     .         1             .           . 
5    X5     .         1             .           . 
6    X6     1         .             .           . 
7    X7     1         1             .           . 
8    X8     1         1             .           . 
9    X9     .         .             1           . 
10   X10    1         1             .           . 

Each column here is a month, which is dynamically generated based on some previously run macro. The months will be dynamic and will vary. What I need to do is calculate sums of last 3 months, last 6 months and last 12 months. The approach I had in my mind was as follows: A) Store the column names in a macro variable:

proc sql noprint;
    select distinct name
    into :cols2 separated by ','  
    from dictionary.columns
    where upcase(memname) = 'Table1' and name not in ('ID');
    ;
quit;
%put &cols2.

The output was as follows:

M_201812,M_201901,M_201902,M_201903

B) Create sums thereafter based on the number of items in the variable:

data table1;
set table1;

if count("&cols2",",") <=3 then do;
3m_total=sum(of &cols2);
6m_total=sum(of &cols2);
12m_total=sum(of &cols2);
end;
else if 3< count("&cols2",",") <=6 then do;
3m_total=sum(%scan(%superQ(cols2),-1,%str(,)),%scan(%superQ(cols2),-2,%str(,)),%scan(%superQ(cols2),-3,%str(,)));
6m_total=sum(of &cols2);
12m_total=sum(of &cols2);
end;
else if 6< count("&cols2",",") <=12 then do;
3m_total=sum(%scan(%superQ(cols2),-1,%str(,)),%scan(%superQ(cols2),-2,%str(,)),%scan(%superQ(cols2),-3,%str(,)));
6m_total=sum(%scan(%superQ(cols2),-1,%str(,)),%scan(%superQ(cols2),-2,%str(,)),%scan(%superQ(cols2),-3,%str(,)),%scan(%superQ(cols2),-4,%str(,)),%scan(%superQ(cols2),-5,%str(,)),%scan(%superQ(cols2),-6,%str(,)));
12m_total=sum(of &cols2);
else do;
    3m_total=sum(%scan(%superQ(cols2),-1,%str(,)),%scan(%superQ(cols2),-2,%str(,)),%scan(%superQ(cols2),-3,%str(,)));
    6m_total=sum(%scan(%superQ(cols2),-1,%str(,)),%scan(%superQ(cols2),-2,%str(,)),%scan(%superQ(cols2),-3,%str(,)),%scan(%superQ(cols2),-4,%str(,)),%scan(%superQ(cols2),-5,%str(,)),%scan(%superQ(cols2),-6,%str(,)));
    12m_total=sum(%scan(%superQ(cols2),-1,%str(,)),%scan(%superQ(cols2),-2,%str(,)),%scan(%superQ(cols2),-3,%str(,)),%scan(%superQ(cols2),-4,%str(,)),%scan(%superQ(cols2),-5,%str(,)),%scan(%superQ(cols2),-6,%str(,)),
    %scan(%superQ(cols2),-7,%str(,)),%scan(%superQ(cols2),-8,%str(,)),%scan(%superQ(cols2),-9,%str(,)),%scan(%superQ(cols2),-10,%str(,)),%scan(%superQ(cols2),-11,%str(,)),%scan(%superQ(cols2),-12,%str(,)));
    end;
    run;

Basically we get 12 months sum only if there are 12 monthly columns available. If only 3 months are available, then 3months sum=6months sum=12months sum. After running the code, I get the following error:

ERROR 159-185: Null parameters for SUM are invalid.

This happens at the last else do statement. I can't for the life of me figure out why won't sas be able to read a simple if-then-do-else statement. Is there an error in the if conditions or in calling the macro variable? Any help here would be appreciated. Thanks a lot.

Using a Vlookup formula within an Arrayformula

I'm using the following formula to search a column for "Yes" and it works fine in the cell:

=VLOOKUP("Yes",INDEX(AH:AH,ROW()):INDEX(AI:AI,ROW()+30),2,FALSE)

However, my sheet is over 20000 rows and added to every day so I need to Arrayformula it. The following hasn't worked. I only want the range to search the next 30 rows OR return column two the next time it finds "Yes" in column one.

=arrayformula(IF($A4:$A<>"",VLOOKUP("Yes",INDEX(AH:AH,ROW()):INDEX(AI:AI,ROW()+30),2,FALSE),0))

Appreciate any help.

Different if statement based on the first ID in a block of ID's in Excel

So basically I have an excel sheet featuring a number of different id's, dates, and a column where I would like to specify beginning middle or end in a 3rd column depending on the FIRST ID date. However this should only apply to the block of the same ID. When the next ID passes through, the date of the first ID in the block will determine the rest of the 3rd column, and so on and so forth.

The issue is much better understood when looking at the dataset.

ID      DATE      formula_col
10R46   10/8/2011
10R46   2/18/2012
10R46   6/30/2012
10R47   2/4/2010
10R47   5/16/2010
10R47   8/8/2010
10R47   12/11/2010
10R47   1/4/2011
10R48   6/26/2011
10R48   9/11/2011
10R48   1/29/2012
10R48   4/20/2012
10R48   7/8/2012

As you can see here. There is a block of consecutive ID's and I need the 'formula_col" to read beginning for the first date, and the rest of the dates would follow the following rule:

The first month is beginning, next is middle, next is end, then it repeats.

So if the first month was February (2), then the formulas for these ID's would be: February: Beginning March: Middle April: End May: Beginning June Middle July: End August: Beginning September: Middle October: End November: Beginning December: Middle January: End

So for the aforementioned dataset, it would be:

ID      DATE      formula_col
10R46   10/8/2011 Beginning
10R46   2/18/2012 Middle
10R46   6/30/2012 End
10R47   2/4/2010  Beginning
10R47   5/16/2010 Beginning
10R47   8/8/2010  Beginning
10R47   12/1/2010 Middle
10R47   1/4/2011  End
10R48   6/26/2011 Beginning
10R48   9/11/2011 Beginning
10R48   1/29/2012 Middle
10R48   4/20/2012 Middle
10R48   7/8/2012  Middle

Here is code I created if the first month is January, April, July, or October. But this isn't exactly what I want, just a start.

=IF(OR(MONTH(B2)=1,MONTH(B2)=4, MONTH(B2)=7,MONTH(B2)=10),"Beginning",IF(OR(MONTH(B2)=2,MONTH(B2)=5, MONTH(B2)=8,MONTH(B2)=11),"Middle",IF(OR(MONTH(B2)=3,MONTH(B2)=6, MONTH(B2)=9,MONTH(B2)=12),"End",NA)))

So the tricky part is the start of the month pattern depends on the first entry of the unique ID. Then it begins following the rule which only applies to this ID. When the next ID appears, the rule resets based on the date of the first ID. They will always be consecutive though I would prefer not to rely on that.

How to logically check the shape of an array in an IF-statement?

Is it possible to check if an array is a certain shape using an IF-statement? I have tried the following with no success.

program main

   implicit none

 ! Local variables. 

   integer, dimension(3,3) :: a
   integer, dimension(3,3) :: b

  ! Check if a is a 3x3 array.

    if (shape(a) == shape(b)) print *, "Works"

end program main

But I get the error:

Error: IF clause at (1) requires a scalar LOGICAL expression

How do I use an if else statement in a loop?

I am trying to create an new column in a dataframe titled "Date2" which I will have to loop through previous iterations of the calculation.

The following is the logic.

If ID2 = Previous(ID2) then Previous(Date2) ELSE Date1 + 60

Copying data from another cell (if statement, maybe?)

I have two tabs of data & i want to be able to copy the data into one of the tabs if a certain criteria is met.

I know a v look up would suffice usually, however, one part of the data is going into a column within a pivot table.

Sheet 1 would contain:

Account Comment 1000
1000
1000
1000
1000
1000
1000
3000
3000
3000
3000
3000
3000
5000
5000
5000
5000
5000
7500
7500
7500
7500
7500
7500
7500

Sheet 2 contains:

Account Comment 1000 Test 3000 Test 1 5000 Test 2 7500 Test 3

I would like to be able to show the the comments on sheet 2 in sheet 1.

So against 1000 in sheet one it would say 'Test', 3000 would say 'Test 1' etc.

C# How to use if, else then [on hold]

I need to isolate a number between two parameters. How to use if, else (then?).

I have tried the statements, but get a whole lot of squiggly lines and do not know what to do next. In this case, let's use vert1dec only. The value of vert1dec is 93 degrees. if it is bigger than 90 degrees AND smaller than 120 degrees, the result should be: vert1dec - 90 degrees. Should vert1dec be smaller than 90 degrees, the result must be 90 degrees - vert1dec. I will appreciate any assistance.

      var vert1dec = Convert.ToDouble(Vert1Decimal.Text);
        var vert2dec = Convert.ToDouble(Vert2Decimal.Text);

        var sldist1 = Convert.ToDouble(SlDist1);
        var sldist2 = Convert.ToDouble(SlDist2);

       /*
         if vert1dec > 90 && < 120 then

                   {

                      vert1dec -90 

                   } else if

                    if vert1dec < 90 && then

                     {

                    90 - vert1dec

                    } else if

                   if vert1dec < 270 && > 120 then

                    {

                   270 - vert1dec

                   } else

                   if vert1dec > 270 then

                   {

                    vert1dec - 270

                   }
        */

The result should be as described in the query. Thank you in advance.

Copy files that have at least the mention of one certain word

I want to look through 100K+ text files from a directory and copy to another directory only the ones which contain at least one word from a list.

I tried doing an if statement with grep and cp but I have no idea how to make it to work this way.

for filename in *.txt 
do 
grep -o -i "cultiv" "protec" "agricult" $filename|wc -w 
if [ wc -gt 0 ]
then cp $filename ~/desktop/filepath
fi 
done

Obviously this does not work but I have no idea how to store the wc result and then compare it to 0 and only act on those files.

How to write if condition with using label text (Int) values

I am getting the dates from the server (response) and that values I an storing in an labels and I want to write a if condition using the labels I want to allow to next Viewcontroller if the used leaves should be greater that total leaves and I am getting error my code is

 if  ((self.totalLeaves.text) > (self.usedLeavesLbl.text)) {
            let alert = UIAlertController(title: "Alert", message: "You Dont have leaves to Apply", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
                switch action.style{
                case .default:
                    print("Please Enter Details")

                case .cancel:
                    print("cancel")

                case .destructive:
                    print("destructive")
                }}))
            self.present(alert, animated: true, completion: nil)
        }
     else {
        // Fallback on earlier versions
        let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "ApplyLeavesViewController") as! ApplyLeavesViewController
        self.navigationController?.pushViewController(secondViewController, animated: true)
    }

my error is compile error Cannot convert value of type 'String?' to expected argument type 'UIContentSizeCategory' Construct 'UIContentSizeCategory' from unwrapped 'String' value

Conditionally send responses in an Express app

I'm curious wether you can write if statements in an Express app to conditionally execute your code without providing else statements.

if(pred) {
  doSomething()
}
return foo;
calcBar(); // doesn't run.

Above is the synchronous code that stops execution after the return statement.

My Express function looks like this:

app.get('/matches', async function(req, res) {
  try {
    const data = await someGraphQLCall();
    if(data.length === 0) {
      res.json({ message: "No data." });
    }
    const someOtherData = await someOtherGraphQLCall(data.foo);
    res.json({ someOtherData });
  } catch (err) {
    res.json({err})
  }
}

I know because of this question that code after the first res.json might still be executed. Is there a way to stop that? I don't want the second GraphQL call to execute if the first if condition is met. Is that possible without using else ?

How to get function "X" to load only when "const pass == 'password'"? [duplicate]

This question already has an answer here:

I'm learning how to make prompts in js so when user types for example: "123" it tells that number is greater than 0, less than 0 or equal to 0, but only when user types correct password in (only when password is "number"). Otherwise it will tell "password incorrect".

I've tried googling but most of codes are in php but I just want simple js code without using servers. I'm trying for almost and hour now, different ID's, functions etc. I have no idea how to fix this.

JAVASCRIPT:

const haslo = document.querySelector('#password');
const btn = document.querySelector('button');

btn.addEventListener('click', function(){
    if(haslo=='liczba')
        function oknoPrompt(){
            const numbers=prompt('Podaj liczbe calkowita','12345');

            if(numbers < '0'){
                alert('ujemna');
            }else if(numbers > '0'){
                alert('dodatnia');
            }
            else if(numbers == '0'){
                alert('zero');
            }       
        }
    else {
        alert('incorrect pass')
    }
});

HTML:

<body>
<form>
    <input type="text" id="password">
    <button>przycisk</button>
</form>

    <script src="main.js"></script>
</body>

I expect the function which tells if number is greater/lower/equal to only work when password = 'liczba'. But when I type "liczba" it shows "incorrect pass".

Error creating a vector from a self-made function

Trying to make my problem reproducible, I have the following vector:

trialvector <- as.vector(c("K", "K", "m", "m", "K"))

And this function to try to convert this vector into one which transforms "K" into a numeric 3 and "m" into a numeric 6, I want to assign this vector to a variable called multiplier:

 Expcalc <- function(vector)  {
 multiplier <<- vector(mode = "numeric", length = length(vector))
 for (i in seq_along(vector)) {
   if (vector[i] == "K") {
     multiplier[i] <- 3
   } else if (vector[i] == "M" | i == "m") {
     multiplier[i] <- 6
   } else {
     multiplier[i] <- 0
   }
 }
}

Instead of getting the output I want (a Vector of 6 and/or 3 depending on which character was in trialvector, I get a vector full of zeros. and this error:

Warning messages: 1: In Expcalc(trialvector) : NAs introduced by coercion 2: In Expcalc(trialvector) : NAs introduced by coercion

What am I doing wrong?

A string is required here (If Else Statement) in Crystal 2008

Hi I am getting an error 'A string is required here' when trying the following in Crystal 2008:

If {InvPrice.SellingPrice} = 0 then "0" else

({InvPrice.SellingPrice}-ccur({?Pm-Documents/Document/Det

Can someone please give me a clue on how to resolve this?

Thanks

Dom

mercredi 26 juin 2019

If statement with a regex in bash not working

Have two if statements matching a filename with the dates of type YYYYMMDD and YYYY-MM-DD and the lease part has filenames that don't contain name. Now the if statements are not working, the code always goes to the else part.

Ex:

If [[ ${data-file} =~ ([12]\d{3}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])) ]]

Someone please help

if statement is being executed even when the condition is false

while executing the code only if statements are being executed even when the condition is false.

I tried DEBUGGING and the condition i'm giving is definitely giving a false back but not sure why

 if (
    $("#ship-to-different-address-checkbox").length != 0 &&
    $(".shipping_address").length == 0
  ) {
    postcode = $("#shipping_postcode").val();
  } else {
    postcode = $("#billing_postcode").val();
  }

Beginner needs help JAVA

I'm new to coding and Java. I learned the theory the past two days, now im trying to make it work getting some practice

i've tried moving it around and stuff, can't really still tell

import java.util.Scanner;
public class JavaLessonTwo
{
    static Scanner userInput= new Scanner(System.in);
    public static void main(String[] args)
    {
        System.out.print("Your favourite number: ");
        if(userInput.hasNext()) {
            int numberEntered=userInput.nextInt();
            System.out.println("You entered "+numberEntered);

        }  else {

            System.out.println("Enter an integer next time");
        }

    }
}

Error is :

Your favourite number: asd
Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at JavaLessonTwo.main(JavaLessonTwo.java:9)

Process finished with exit code 1

I want to make it so if you enter for example letters instead of integers you get a msg ''Enter an integer next time"

C#: How to #define within an #if?

I have a certain method that runs as a background task and does some fancy things. It is SLOW, because of the Thread.Sleep(500);. It doesn't need to do things faster, and it changes the behaviour of my application very subtle. Enter problem: When running my unit and component tests, I need to have the task run as it is supposed to be, for, like say 95 percent of my test cases. But of course I want to test the method itself. The subtle changes may arise after let's say half an hour or so. Not a good idea for a test suite. What I need is a way to speed things up for exactly this very test case.

Because #define isn't allowed to appear within code, the only way I see is to write an extra test case file for this test? I'd love something like this:

[TestMethod()]
public void Test_GetThisThingAndRunIt()
{
    // ...
    #if DEBUG
    #define CRV_TEST
    // run the test
    #undef CRV_TEST
    #endif
}

etc. and then, in the class to test, do something like

#if CRV_TEST
System.Threading.Thread.Sleep(1);
#else
System.Threading.Thread.Sleep(500);
#endif

How to? Thanks a lot!

ArrayFormula - If cell contains match, combine other cells with TEXTJOIN

I have a Google Sheet that contains names of characters, together with corresponding values for group name, "selected" and attack power. It looks like this:

Sheet1

| NAME     | GROUP NAME | SELECTED  | ATTACK POWER |
|:---------|:-----------|----------:|-------------:|
| guile    | Team Red   |         1 |          333 | 
|----------|------------|-----------|--------------|
| blanka   | Team Red   |         1 |           50 |
|----------|------------|-----------|--------------|
| sagat    | Team Red   |           |          500 |
|----------|------------|-----------|--------------|
| ruy      | Team Blue  |         1 |          450 |
|----------|------------|-----------|--------------|
| vega     | Team Blue  |         2 |          150 |

Sheet2

In my second sheet I have two columns. Group name, which contains names of each team from Sheet1 and names, which contains my current ArrayFormula:

=ARRAYFORMULA(TEXTJOIN(CHAR(10); 1; REPT('Sheet1'!A:A; 1*('Sheet1'!B:B=A2))))

Using this formula I can combine all characters into one cell (with textjoin, repeated with row breaks) based on the value in Group name. Result looks like the following:

| GROUP NAME | NAME                      |
|:-----------|:--------------------------|
| Team Red   | guile                     |         
|            | blanka                    |
|            | sagat                     |
|------------|---------------------------|
| Team Blue  | ruy                       |
|            | vega                      |
|------------|---------------------------|

The problem is that I only want to combine the characters with have a selected value of 1. End-result should instead look like this:

| GROUP NAME | NAME                      |
|:-----------|:--------------------------|
| Team Red   | guile                     |         
|            | blanka                    |
|------------|---------------------------|
| Team Blue  | ruy                       |
|------------|---------------------------|

I tried the following setup using a IF-statement, but it just returns a string of FALSE:

=ARRAYFORMULA(TEXTJOIN(CHAR(10); 1; REPT(IF('Sheet1'!C:C="1";'Sheet1'!A:A); 1*('Sheet1'!B:B=A2))))

Can this be one?

Stop variables from rolling over across a range of values (Arduino C++ and joystick)

I am PWM-controlling two CC-PSUs that control one LED each (one warm CCT, one cold CCT) in a range from 16 to 240, using a joystick as user interface. When the light comes on or is switched off and then on again, the default PWM value for both is 128. The PWM generator is an Adafruit Metro Mini (Arduino), but it's rather a code logic issue here.

What works with the code below is to blend between warm (left) and cold (right) or between bright (up) and dark (down), if the joystick is tilted strictly left/right (x) or strictly up/down (y). In those two cases, the PWM values don't roll over as per the if-statements, even if the joystick is kept tilted. It is acting like a "+"-shifter, if it were mechanically constrained. So far, so good.

However, if one has, for example, tilted the joystick left for slightly warmer light (PWM 176/80) and then wants it brighter from there and tilts the joystick up (and keeps it tilted), the PWM values do not "stop" at 240/144 (they should). The same goes for any other quadrant.

How would I have to enhance/change the if-statements to "stop" the PWM values from incrementing/decrementing as desired?

I hope the PWM value matrix below visualises the problem better than I can explain it verbally.

void changeBrightness()
{
  if (lightOn)
  {
    readJoystick();
    if (joyX < triggerLow) // Joystick tilted left
    {
      if ((leftPWM < 240) || (rightPWM > 16))
      {
        leftPWM += deltaPWM;
        rightPWM -= deltaPWM;
        setPWM(leftPWM, rightPWM);
      }
    }
    if (joyX > triggerHigh) // Joystick tilted right
    {
      if ((leftPWM > 16) || (rightPWM < 240))
      {
        leftPWM -= deltaPWM;
        rightPWM += deltaPWM;
        setPWM(leftPWM, rightPWM);
      }
    }
    if (joyY > triggerHigh) // Joystick tilted up
    {
      if ((leftPWM < 240) || (rightPWM < 240))
      {

        leftPWM += deltaPWM;
        rightPWM += deltaPWM;
        setPWM(leftPWM, rightPWM);
      }
    }
    if (joyY < triggerLow) // Joystick tilted down
    {
      if ((leftPWM > 16) || (rightPWM > 16))
      {
        leftPWM -= deltaPWM;
        rightPWM -= deltaPWM;
        setPWM(leftPWM, rightPWM);
      }
    }
  }
  else
  {
    setPWM(0, 0); // Turn the light off
  }
}

PWM value matrix

Ruby on Rails if/else condition not working

I have a Rails application view where I want to display one of two partials depending on the ENV variable setting. For some reason, the condition is always evaluated to false so the campaign_active partial is displayed. I've changed the ENV to true and tried switching the rendering statements around and found that only the statement after else gets executed. What am I missing?

Here's the view:

<% if Rails.application.config.ended %>
  <%= render "users/campaign_ended" %>
<% else %>
  <%= render "users/campaign_active" %>
<% end %>

Here's the application.rb setting:

config.ended = ENV['CAMPAIGN_ENDED'].to_s == 'true'

Here's the .ENV file:

CAMPAIGN_ENDED=true

The campaign setting in ENV is set to true so I expect the condition in my view to be true and render the campaign_ended partial. But instead, it renders the campaign_active partial. Now if I switch the statements around and put campaign active ahead of campaign ended, then the campaign ended partial renders.

Swift Switch access nested properties within 'case'

Following this code snippet. I'm trying to understand if it's possible to access nested properties of the object within Switch statement, without the need to unwrap properties inside the 'case' itself (avoid unneeded closures). Here's a stupid-simple example. of course, the compilers fail with (code snippet below image):

enter image description here

class Z {
    var common = 4
}

class A: Z {

}

class B: Z {

}

class C: Z {
    var specific: String? = "%"
}


let unknown = Z()

switch (unknown, unknown.common) {
case (let a as A, 4):
    break

case (let b as B, 4):
    break

case (let c as C, 4), let nonNilSpecific as? String:
    // use nonNilSpecific WITHOUT unwrap it within the case clousre
    break
default: break
}

How Can I use if/else for json ? I just wanna get 2 data , not all [duplicate]

This question already has an answer here:

I just need 2 data on json ,but I could not.How do I access the data with the use of an "if"?

JSONArray JA = new JSONArray(textview);
for (int i = 0; i < JA.length(); i++) {

  JSONObject JO = (JSONObject) JA.get(i);

  singleParsed = "" + JO.get("name") + "" +
    "/" + JO.get("code") + "\n" + "\n" +

    "Alış Fiyatı:" + JO.get("buyPrice") + "\n" +
    "Satış Fiyatı:" + JO.get("sellPrice") + "\n" +
    "En d. alış fiyatı:" + JO.get("todayLowestBuyPrice") + "\n" +
    "En y. alış fiyatı:" + JO.get("todayHighestBuyPrice") + "\n" +
    "En d. satış fiyatı:" + JO.get("todayLowestSellPrice") + "\n" +
    "En y. satış fiyatı:" + JO.get("todayHighestSellPrice") + "\n" +
    "Dünkü alım fiyatı:" + JO.get("yesterdayClosingBuyPrice") + "\n" +
    "Dünkü Satış fiyatı:" + JO.get("yesterdayClosingSellPrice") + "\n" +
    "Günlük değişim:" + "" + JO.get("dailyChange") + "\n" +
    "Güncellenme Tarihi:" + JO.get("lastUpdateDate") + "\n";

  dataParsed = dataParsed + singleParsed + "\n" +
    "-----------------------------------------------------------------" + "\n";

}
}

Ifelse with multiple conditions in sapply function

I need to check each row in two columns for the two conditions in the dataframe (basically, I'm substracting each row in one pair of columns from each row in another pair of columns to get two certain values (one of which is time interval), see code). The expected result is another column with 1 if both conditions are satisfied and 0 otherwise.

I've tried:

sapply(trades1, function(x) x$indicator3 <- x %>% ifelse(indicator2 - indicator == -1 & difftime(date2, date, units = "min"== 1), 1, 0))

This gives me

 Error in ifelse(., indicator2 - indicator == -1 & difftime(date2, date,  : 
  unused argument (0) 

python class self. name str is not equal to a string with the same value

I try to make a prototype of an inventory and item system with classes. in the "item" class it has a self.name and when I try to see if a string is equal to the self.name in the inventory class it is not equal to each other

I have printed out the info and it says that it is the same and I have tried to do str(variable but that does not work either)


class item:
    def __init__(self, name):
        #name variable
        self.name = name


class itemStack:
    def __init__(self, items=[]):
        self.items = items

    def useItem(self, _item):
        isTrue = False

        for i in self.items:

            #Here is were it is not working//
            if str(_item) == str(i.name):
                #Here is were it is not working//

#creata an item with name of stick
stick = item("stick")
#create a list of items
inventoryItems = [stick]
#create a itemstack with inventoryItems in it
inventory = itemStack(inventoryItems)

inventory.useItem("stick")


it is not an error it just says that it is not equal

Where is the problem that ifelse statement does not work

I am working with the following dataset:

a<-data.frame(cell<-c( 70,26.171255,79,18.725711,129,17.130182,                          7.073919))


And i tried to put missing values for the certain values with this code:

 for (i in 1:nrow(a)) {
      a[i,1] <- ifelse(a[i,1] %in% c(17.130182,18.725711,26.171255), NA,a[i,1])
    }


It is working well. However if I do from the another dataset (whole sample - 330 rows) using the code

a<-data.frame(value$tobinsq)

, it turns out that the code does not work. dataset value is put as a data frame in R.

Where can be the problem?

Condensing a data frame using multiple arguments from certain variables in R

I'm looking to condense a data frame based on various arguments from multiple variables and I'm not quite sure on how to achieve it in the easiest way possible. I'm thinking it's going to need some kind of personalised function but I don't have much experience in writing functions.

Basically, my data frame currently looks like this:

chainID     teamID        statID        startType       endType        

1           Team A     Effective Pass      TO              TO
1           Team A     Effective Pass      TO              TO
1           Team A     Effective Pass      TO              TO
1           Team A     Effective Pass      TO              TO
1           Team A     Ineffective Pass    TO              TO
2           Team B     Effective Pass      TO              SH
2           Team B     Entry               TO              SH
2           Team B     Effective Pass      TO              SH
2           Team B     Shot                TO              SH
3           Team A     Effective Pass      ST              TO
3           Team A     Entry               ST              TO
3           Team A     Ineffective Pass    ST              TO
4           Team B     Effective Pass      TO              ST
4           Team B     Effective Pass      TO              ST
4           Team B     Ineffective Pass    TO              ST
5           Team B     Effective Pass      TO              SH
5           Team B     Entry               TO              SH
5           Team B     Goal                TO              SH
6           Team B     Effective Pass      CB              TO
6           Team B     Effective Pass      CB              TO
6           Team B     Ineffective Pass    CB              TO
7           Team A     Effective Pass      TO              ST
7           Team A     Ineffective Pass    TO              ST

What I'm looking to do is whenever the word Entry appears in the statID column for any chainID, I want to keep that row and the last row for that chainID whilst removing all the other rows for that particular chainID (see chainID 2 and 5). In addition, if Entry appears in the statID for any chainID but the last row isn't a Goal or Shot I want to keep the rows following that data for the next chainID (see chainID 3 and 4). E.g.

chainID     teamID        statID        startType       endType        

2           Team B     Entry               TO              SH
2           Team B     Shot                TO              SH
3           Team A     Entry               ST              TO
3           Team A     Ineffective Pass    ST              TO
4           Team B     Effective Pass      TO              ST
4           Team B     Effective Pass      TO              ST
4           Team B     Ineffective Pass    TO              ST
5           Team B     Entry               TO              SH
5           Team B     Goal                TO              SH


How to parse dict to dict

I have two dict and I want to merge ip list but i could not solve I wanna result like this

result = {"src": 
          {
           "1":
           { 
            {"Communication": {"False":["1.1.10.13"]}}, 
            {"management": {"True": ["1.1.10.5", "1.1.10.7"]}}
           },
           "2":
           { 
            {"Communication": {"False": ["1.1.10.5", "1.1.10.7"]}}, 
            {"management": {"True": ["1.1.10.13"]}}
           }
          },
          "dst":
          {
           "1":
           {
            {"mfg": {"True":["1.1.151.12"]}}
           }
           "2":
           {
            {"Communication": {"False":["1.1.151.12"]}}
           }
          }

thanks for your time

src = [{'zone': 'Communication', 'ip': '1.1.10.13', 'fw': 1, 'l3': 'False'}, {'zone': 'Communication', 'ip': '1.1.10.5', 'fw': 2, 'l3': 'False'}, {'zone': 'Communication', 'ip': '1.1.10.7', 'fw': 2, 'l3': 'False'}, {'zone': 'management', 'ip': '1.1.10.5', 'fw': 1, 'l3': 'True'}, {'zone': 'management', 'ip': '1.1.10.7', 'fw': 1, 'l3': 'True'}, {'zone': 'management', 'ip': '1.1.10.13', 'fw': 2, 'l3': 'True'}]

dst = [{'zone': 'Communication', 'ip': '10.17.151.12', 'fw': 2, 'l3': 'False'}, {'zone': 'mfg', 'ip': '10.17.151.12', 'fw': 1, 'l3': 'True'}]

mardi 25 juin 2019

modifying a dataframe by adding additional if statement column

Modifying a data frame by adding an additional column with if statement. I created 5 lists namely: East_Asia, Central_Asia,Central_America,South_America, Europe_East & Europe_West. And I wanted to add a conditional column based on existing column. i.e if japan in Central_East, then the japan row in the adding column should contain Central East, so on.

df['native_region'] =df["native_country"].apply(lambda x: "Asia-East" if x in 'Asia_East' 
                                               "Central-Asia" elif x in "Central_Asia"
                                                "South-America" elif x in "South_America"
                                                "Europe-West" elif x in "Europe_West"
                                                "Europe-East" elif x in "Europe_East"
                                                "United-States" elif x in " 
United-States" 
else "Outlying-US"
                                                 )

File "", line 2 "Central-Asia" elif x in "Central_Asia" ^ SyntaxError: invalid syntax

I'm modifying a dataframe by adding an additional column named "native_region with if-statement

I'm modifying a dataframe by adding an additional column named "native_region with if-statement


How to use If-Then Conditional Across Workbooks in VBA?

I want to use if-then statement across two workbooks.

I've defined x as Long but x does not appear to hold the value of the sum of all cells in column B

But the code looks right, any thoughts?

Sub mycode()

   Dim x As Long


   myRange = Workbooks("Book2").Sheets("Sheet1").Range("B1", _ 
   Range("B1").End(xlDown))


   x = WorksheetFunction.Sum(myRange)    '<<does not seem to hold value



  If Workbooks("Book1").Sheets("Sheet1").Range("A1").Value = x Then

     MsgBox ("values equal")

  Else

     MsgBox ("please review values")

  End If

End Sub

panic: runtime error: index out of range in Golang

I have a function, which has to assign the index corresponding to rune of character to 1. I have a slice of alphabet, another slice of bytes with length of alphabet and for example, word "adel" will be assigned in byte slice as [100110000001000000....] like that, cause a-to first index, d-fourth index and so on. But if in the word 2 character of 'a' it has to be shifted to the next block of alphabet slice. How I have to set the function to this logic?

I have used for the beginning only slice of 2 blocks of alphabet and made length of 52 bits. Right now, I have this error:

''''
panic: runtime error: index out of range

goroutine 1 [running]:
main.getVector(0xc000080000, 0x1a, 0x1a, 0xc000080000, 0x1a, 0x1a)
        C:/Users/agi_a/code/CARDS/stem.go:90 +0x25b
main.main()
        C:/Users/agi_a/code/CARDS/main.go:18 +0x156
exit status 2
''''
{
<!-- language: golang -->: 

var alphabet = []string{
    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
    "s", "t", "u", "v", "w", "x", "y", "z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
    "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
}
var a = make([]byte, len(alphabet))

func converToChar(s string) (r rune) {
    new, _ := utf8.DecodeRuneInString(s)
    switch {
    case 97 <= new && new <= 122:
        return new - 96
    case 65 <= new && new <= 90:
        return new - 64
    default:
        return r
    }
}

func getVector(s []string) []byte {
    for _, alph := range alphabet {
        for _, str := range s {
            if str == alph {
                if a[converToChar(alph)-1] == 0 {
                    a[converToChar(alph)-1] = 1
                } else if a[converToChar(alph)-1] == 1 {
                    a[converToChar(alph)-25] = 1
                }

            }
        }
    }
    return a
}

}

I expect that slice of byte for word 'adele' will be as [10011000001000000....00001......] as in the next block second 'e' will be assigned to index as 1.

Conditional Statement Not Working in ie11 for Setting CSS Display

There's a strange occurrence with my conditional statement in ie11: if the first two conditions are false and code runs just the else, successMessage display is set to block as expected.

For some reason, let's say condition 2 is false, then is subsequently updated to true, the else code block doesn't set display to block, however the console did log the message.

Of course everything works well in modern browsers.

CSS:

.alert-success {
  display: none;
}

JS:

handleSubmit = () => {

  let successMessage = document.querySelector('.alert-success');

  if ( condition 1 ) {
   // do something
  } else if ( condition 2 ) {
   // do something else
  } else {
    successMessage.style.display = 'block'
    console.log('Did this render?');
  }

}

Quick Help Python if Statements

Sorry to ask a noob question but i am in the process of learning python as I go.

I have a random number picker and would like to add if statements into my script.

For Example if the random number picker picks the number 7 then the letters abcd will be sent to a "variation_id" variable.

How would I go about this. Can someone provide me with an example?

Equal splitting values in list and forcing for-loop to run after values

Straight to the problem, there is a value and a list. I want to run a for-loop and print after range of items inside the list.

Here is the code:

A, B = 3, [4,2]

for k, i in enumerate(B):
    if k == 0:
        for num in range(i):
            print('First item from list:', num)
    else:
        for num in range(i):
            print('Second item from list:', num)

Output:

First item from list: 0
First item from list: 1
First item from list: 2
First item from list: 3
Second item from list: 0
Second item from list: 1

What I want to achieve?

I want to run for-loop based on, split to equalsize or split based on length of item1 and item2 inside the list! for example A = 3 and first item inside list is 4 and second is 2, I want to split A-value to A1=2 and A2=1, then force for-loop to run 2 twice when it takes first item, and once when it takes second item, but keep in mind in case we have A= 3 and B=[1,2], my split value should be A1= 1 and A2=2, so it is depending on content of list. Keep in mind in case we have A=4, B=[4,2], splitting would be A1=2 and A2=2, or in case A=7 and B=[5,6], so it is evaluating and make some good splitting like A1=4, A2 =3 etc...

for more clarification in case we have,

A, B = 3, [2,2]

Output could be:

First item from list: 0
First item from list: 1
Second item from list: 0

How can I add points to a variable after certain buttons are selected

I have a set of buttons with ingredients and another set of the same but with the tools that can be used, and I want to give points when the correct tool and the ingredient that corresponds to it are selected.

gameViewController:

func givePoints () {
        let toolSelected = MainInfoManager.shared.getToolWith(name: ToolName(rawValue: toolSelectedId)!)
        let ingredientSelected = MainInfoManager.shared.getIngredientWith(name: IngredientName(rawValue: ingredientSelectedId)!)
        if let currentBowl = bowl, seconds > 0 {
            print("funciono")
            for ingredient in currentBowl.ingredients {
                print ("este tambien")
                if ingredient.id == ingredientSelected.id && toolSelected.ingredients.contains(where: { $0.id == ingredientSelected.id }) {
                    print("y este tambien")
                    pointsForChoices += 10
                }
            } 
        }
    }

please help me thank you

Google Sheets equation that doesn't go below zero

I have an equation that looks like this in Google Sheets:

= (x - 500) ^ 0.38

The problem is that any value of x under 500 results in a cell value of #NUM! since zero to the power of 0.38 is not a real number.

How can I modify this equation so that instead of showing #NUM! it just shows 0 when x < 500?

condition in a nested for loop in C won't work

I am new to C and I'm practicing for-loops and pointers. In this exercise I try to write a function that sorts array elements. the first part of the code (where I input the elements) is working, but everything below gives me a hard time. I don't understand if the problem is in the if/else statements or anywhere else in the loop structure. also the last loop doesn't work (I just want it to iterate over the sorted array and print the elements, like I did before with it unsorted.

Hope I can get some help, and also if you see anything more that I should pay attention to...

Thanks a bunch.

I tried checking if the way I defined the loop was accurate, that I put all the right values and that the basic "idea" that I had for sorthing the array was ok.

void sort_array_elements()
{
int x, i, j, k, temp;
printf("\n input the number of elements to store in the array: ");
scanf_s("%d", &x);

int arrnum[30];
ptr_int = &x;
printf("input %d elements in the array: \n", x);
for (i = 0; i < x; i++)
{
    scanf_s("%d\n", &arrnum[i]);
}

printf("the elements in the array before sorting: \n");
for (i = 0; i < x; i++)
{
    printf("element %d: %d\n", i, arrnum[i]);
}


for (i = 0; i < x; i++)
{
    for (j = 1; j < x; j++)
    {
        if (arrnum[i] > arrnum[j])
        {
            temp = arrnum[i];
            arrnum[i] = arrnum[j];
            arrnum[j] = temp;


        }
        else if (arrnum[i] == arrnum[j])
        {
            for (k = arrnum[i + 1]; k < x; k++)
            {
                if (arrnum[k] != arrnum[j])
                {
                    temp = arrnum[k];
                    arrnum[k] = arrnum[j];
                    arrnum[j] = temp;
                    break;
                }
            }
        }


    }

}

printf("the elements in the array after sorting: \n");

for (i = 0; i < x; i++)
{
    printf("element %d: %d\n", i, arrnum[i]);
}

}

POWER BI - Maximum value with if condition

I'm trying to calculate the maximum value with multiple conditions in Power BI.

The dataframe is:

Year    Company         Bond            Branch      Group     Type    Value
2016    BANCO DO BRASIL INDEPENDENTE    RISK        RETAIL    NOMINAL 4061567
2016    BANCO DO BRASIL INDEPENDENTE    ACUMULAÇÃO  RETAIL    NOMINAL 1901920
2017    BANCO DO BRASIL INDEPENDENTE    RISK        CORPORATE REAL    439499
2017    BANCO DO BRASIL INDEPENDENTE    RISK        RETAIL    REAL    356231
2016    BRADESCO        INDEPENDENTE    RISK        CORPORATE NOMINAL 347369
2016    BANCO DO BRASIL INDEPENDENTE    ACUMULAÇÃO  RETAIL    REAL    310920
2016    BANCO DO BRASIL LIGADO A BANCO  RISK        CORPORATE NOMINAL 12091
2016    BANCO DO BRASIL INDEPENDENTE    ACUMULAÇÃO  RETAIL    REAL    1021
2017    BANCO DO BRASIL INDEPENDENTE    RISK        CORPORATE REAL    446

I want to create a column with the maximum value by year, Bond, Branch, Group and Type disconsidering Company.

I've already tried the following code:

MAX = CALCULATE(MAX(data[Value]);
      FILTER(ALLEXCEPT(data;data[Company];
      data[Year] = data[Year] 
      && data[Branch] = data_segmento_anual[Branch]
      && data_segmento_anual[Group] = data_segmento_anual[Group]
      && data_segmento_anual[Bond] = data_segmento_anual[Bond]
      && data_segmento_anual[Type] = data_segmento_anual[Type]))

I'm expecting this result:

Year    Company             Bond            Branch      Group     Type    Value   MAX 
    2016    BANCO DO BRASIL INDEPENDENTE    RISK        RETAIL    NOMINAL 4061567 4061567
    2016    BANCO DO BRASIL INDEPENDENTE    ACUMULAÇÃO  RETAIL    NOMINAL 1901920 1901920 
    2017    BANCO DO BRASIL INDEPENDENTE    RISK        CORPORATE REAL    439499  439499
    2017    BANCO DO BRASIL INDEPENDENTE    RISK        RETAIL    REAL    356231  356231
    2016    BRADESCO        INDEPENDENTE    RISK        CORPORATE NOMINAL 347369  347369
    2016    BANCO DO BRASIL INDEPENDENTE    ACUMULAÇÃO  RETAIL    REAL    310920  310920
    2016    BANCO DO BRASIL LIGADO A BANCO  RISK        CORPORATE NOMINAL 12091   12091
    2016    BANCO DO BRASIL INDEPENDENTE    ACUMULAÇÃO  RETAIL    REAL    1021    310920
    2017    BANCO DO BRASIL INDEPENDENTE    RISK        CORPORATE REAL    446     439499

Is there a more compact way of writing these identical conditionals?

I want to check that the type of four variables is a particular type, and I have to do:

if (type(a) is not SomeType or
    type(b) is not SomeType or
    type(c) is not SomeType or
    type(d) is not SomeType):
    raise Exception("Not the correct types")

This feels repetitive. It seems there could be a better, less redundant way of doing this?

Ranking in Google Sheet

I have some data about people on my Google Sheet and they are given some points based on their activities. What I want in the next column is that their rank based on their points. I would change the points manually on a regular basis and accordingly, their rank should be changed automatically with a formula.

At present the data ranging from A1 to J50 where row 1 is the header. I need the rank in K.

I would like to know to rank in two ways. One in numerical. Like, Rank 1, 2, 3, etc. Other in text, 'Outstanding', 'Good', or any text.

How to use a for-loop to create a new variable based on differences between posixct for log files

I am trying to loop through a log file dataset I have, to add a variable in which a server session number is stored for every observation. For the first line, I want to create a new variable 'session number' with value 1. After that, I want a different session number for the following line if the 'ResearchNumber' differs from the line before. If it is the same 'ResearchNumber', I want to check whether the difference in the Posixct variable is larger than 18000 seconds (or 30 minutes). If that's the case, I want to create a different session number (by increasing this with 1). In all the other cases, I want the session number to be the same as the previous line. To summarize, I want to create session numbers based on inactivity for longer than 30 minutes per participant.

I have tried several things, but my code doesn't seem to loop over all the lines, and with other solutions the time difference doesn't calculate in the right way.

I hope someone can help me fix this problem. All help is appreciated!


# create example data

ResearchNumber <- c("AL001","AL002","AL003")

DateTimeTag <- c(
  as.POSIXct('2014-09-29 10:35:40', tz='GMT'),
  as.POSIXct('2014-09-29 10:35:42', tz='GMT'),
  as.POSIXct('2014-09-29 10:38:18', tz='GMT')
)

logdata <- data.frame(ResearchNumber, DateTimeTag)


# loop through logdata to add variable to every observation with a server session number

linecount <- 1
for (lines in logdata) {
  if (linecount == 1) {
    session_number <- 1
    logdata$session_number <- session_number
    datetime <- logdata$DateTimeTag
    participantbefore <- logdata$ResearchNumber
    linecount <- (linecount + 1)
  } 
  else if (linecount > 1) {
    difference <- (logdata$DateTimeTag - datetime)
    if (logdata$ResearchNumber != participantbefore) {
      logdata$session_number <- (session_number + 1)
      participantbefore <- logdata$ResearchNumber
      session_number <- (session_number + 1)
      datetime <- logdata$DateTimeTag
    }
    else if (difference > 18000) {
      logdata$session_number <- (session_number + 1)
      participantbefore <- logdata$ResearchNumber
      session_number <- (session_number + 1)
      datetime <- logdata$DateTimeTag
    }
    else {
      logdata$session_number <- (session_number)
      participantbefore <- logdata$ResearchNumber
      datetime <- logdata$DateTimeTag
    }
  }
}

Fn::If condition based on environment for Cloudformation Parameters

Based on the environment, I am trying to set the URL for a variable: It staging my URL should be https://staging.DNHostedZoneName , if prod - it should just be https://DNSHostedZoneName:

Here's my condition:

Conditions:
  IsEnvProd: Fn::Equals [ !Ref Env, 'prod']
  IsEnvStage: Fn::Equals [ !Ref Env, 'stage']

Here's where its been evaluated:

          Environment:
            - Name: NODE_ENV
              Value: !Ref NodeEnv
            - Fn::If:
              - IsEnvStage
              - Name: CORE_URL
                Value:
                  Fn::Join:
                    - ""
                    - - "https://"
                      - "staging"
                      - "."
                      - !Ref DnsHostedZoneName
              - Name: NCVCORE_URL
                Value:
                  Fn::Join:
                    - ""
                    - - "https://"

                      - !Ref DnsHostedZoneName

I am getting the following error:

 Template format error: Conditions can only be boolean operations on parameters and other conditions

how to paste together a vector element with the previuos according to a condition

I'm getting data from a web source with rvest and then I got a vector, say x, which has a length different from my other vectors (so I can't combine them into a table). Getting to the point: The reason is that everytime I see the element 'nuovo' (position x[11] ) in the vec, I know It should be pasted with exactly the previous, then i should also cancel out the element 'nuovo' because I need a 25 length vector.

x  = c("Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina" ,"Vetrina", "Vetrina",
"Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina" ,"nuovo" ,"Vetrina",
"Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina" ,"Vetrina", "Vetrina",
"Vetrina" ,"Vetrina", "Vetrina",
"Vetrina" ,"Vetrina")

length(x) = 26

and then I need x to be like:

x  = c("Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina" ,"Vetrina", "Vetrina",
"Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina nuovo","Vetrina",
"Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina" ,"Vetrina", "Vetrina",
"Vetrina" ,"Vetrina", "Vetrina",
"Vetrina" ,"Vetrina")

length(x) = 25

Alternative for huge if else statement

I have a huge data, and i need to filter them to get certain value according to Choices, i tried to use if else but it was so hard because it is really huge and nested.

    if(Type == "H" && Tech =="2A")
    {
       if(Level == "ground")
       {
        return "2AA";
       }
       else if (Level == "UP"){
        return "2AB";
    }

}
else if(Type == "H" && Tech =="3A"){
 if(Level == "ground"){
    return "3AA";
    }
    else if (Level == "UP"){
    return "3AB";

}

 else if(Type == "E" && Tech =="2B"){
 if(Level == "ground"){
    return "3BB";
    }
    else if (Level == "UP"){
    return "3BC";

}

How can I repeat if else innerHTML

How can I repeat this after click.

var maxResults = 0;
maxResults += 1;

if (maxResults < 7) {

  localStorage.setItem("example", id.innerHTML = "1" + id.innerHTML);

} else if (maxResults > 1 && maxResults < 8) {

  localStorage.setItem("example", id.innerHTML = "0");

}

Illustration the results as below:

111111
0
111111
0
111111
0

Thanks!