mercredi 30 juin 2021

Dynamic conditions inside foreach loop to create a new array by specific values

Is there a better way to shorten this code and create "dynamic" conditions on a loop to create a new array by specific values if an variable is not null ?

$data = $csv->data;
$result = [];

$advertiserId = null;
$country = 'DE';
$status = null;

foreach ($data as $item){
    if($advertiserId !== null && $country !== null && $status !== null) {
        if ($item['Membership Status'] === $status && $item['Primary Region'] === $country && $item['Advertiser ID'] === $advertiserId) {
            $result[] = $item;
        }
    }
    if($advertiserId !== null && $country !== null && $status === null) {
        if ($item['Primary Region'] === $country && $item['Advertiser ID'] === $advertiserId) {
            $result[] = $item;
        }
    }
    if($advertiserId !== null && $country === null && $status !== null) {
        if ($item['Membership Status'] === $status && $item['Advertiser ID'] === $advertiserId) {
            $result[] = $item;
        }
    }
    if($advertiserId === null && $country !== null && $status !== null) {
        if ($item['Membership Status'] === $status && $item['Primary Region'] === $country) {
            $result[] = $item;
        }
    }
}

IF statement for numeric picture format switch in MS Word Mail Merge

Good day,

I have trouble getting this formula to work,

{IF{ MERGEFIELD ABC } <= 1 "{ MERGEFIELD ABC \ # 0.000}" "{ MERGEFIELD ABC \ # 0.00}}

I require the value of ABC to be displayed in 3 decimal places if it is below 1 and 2 decimal places if it is equal or above 1.

Thank you in advance!

Why my IF statement and OR operator doesn't give me the expected output?

I'm actually not sure what is wrong here, but the code just doesn't give me what I want.

Technically, what I want it to do is if I write '0' which will be in the dictionary (can be more depending how many items it has) or 'N', it will stop. But it doesn't work. It always run the if instead of the else.

Is it something obvious that I can't see or just a bug (unlikely)

from time import sleep

inventory = {}
character = {'Energy': 180}
inventory['Red Mushroom'] = {'Quantity': 1,
                                   'Description': 'It looks good for the Energy, but also a tasteful snack...',
                                   'Effect': 35}

def show_inve():
    sleep(1)
    mapear = {}
    if inventory == {}:
        print('Its empty...\n')
    else:
        for i, pos in enumerate(inventory):
            print(f'[{i}] {pos:<10}: {inventory[pos]["Quantity"]:>0}')
            mapear[str(i)] = pos

        while True:
            sleep(1)
            decision = input('Type the number of the item or N to leave: ').strip()
            if decision not in mapear or decision != 'N':
                sleep(1)
                print('Not an option.')
                continue
            else:
                break


show_inve()

If statement within a loop, result always returning True

First post and I'm sorry if this is a very beginner error but I've been scratching my head over this all evening and can't for the life of me work out what the issue is.

I'm trying to run the below if statement within a double for loop which is iterating through a list and can't get it to return false. I've tried looking it up and thought it may be a data type comparison issue but I've double checked that (hence why everything is declared as an int) and it doesn't seem to be an issue. Everything is in integers so I'm sadly a bit lost!

Any help you can give would be most appreciated! Thankyou!

for search_site in range(len(search_list)):
    for product in range(len(product_list)):
        if search_site != int(1) or int(10) or int(13):
            print(search_site)
            print("True")
        else:
            print("False")

I've used the prints to see what's being compared and I generally get something like this (duplicates deleted for simplicity sake):

0 True 1 True 2 True 3 True 4 True 5 True 6 True 7 True 8 True 9 True 10 True 11 True 12 True 13 True

Trouble saving images into train and test sets using np.where in python

I have been trying to save images from a column consisting of image urls in my dataframe into Train and Validation folders in google drive. Now this code is disregarding the where statement and putting all 1560 images into both the folders.

df1 dataframe Number of train and validation images

def url_to_png(i, url, file_path):
  filename = '{}{}image{}.png'.format(df1['Patient Number'][i], df1['Abnormality'][i],i)
  full_path = '{}{}'.format(file_path, filename)
  urllib.request.urlretrieve(url, full_path)
  #print('{} saved.'.format(filename))
  return None

FILEPATH1 = path + 'Images/Train/'
FILEPATH2 = path + 'Images/Validation/'

urls = df1["Bone Image"]

for i, url in enumerate(urls.values):
  np.where(df1.loc[df1['Dataset Assigned'] == 'Validation'], url_to_png(i, url, FILEPATH2), url_to_png(i, url, FILEPATH1))

I have tried using if-else statement too, but didn't work. Please help me resolve this issue.

SAS adding an incremental counter based on a condition

I have the following dataset in SAS

Id   date        order   amount
101  5/20/2020     1       25
101  5/20/2020     2       25
101  5/20/2020     3        0
101  5/21/2020     1       25
101  5/21/2020     2       25

I need to add a counter only amount=25 based on ‘Id’, ‘Date’ and ‘Order’

Id   date        order   amount  Ctr
101  5/20/2020     1       25   1
101  5/20/2020     2       25   2
101  5/20/2020     3        0   0
101  5/21/2020     1       25   1
101  5/21/2020     2       25   2

Code:

Data want:
Set have;
By id date order;
Ctr+1;
If first.id and first.date and first.order) and amount=25 then ctr=1;
Run;

I am not getting the desired result. Any help is appreciated.

Python: if-else statement, printing 'Weird' if a given integer is odd or it's even but within a particular range shown below, and 'Not Weird' if not

I'm trying to create an if-else function which will print 'Weird' if an integer n is odd, 'Not Weird' if it's even and between 2 and 5 inclusive, 'Weird' if it's lies between 6 and 20 and not weird if it's an even integer more than 20. I tried the following code but it wouldn't run, can you tell me what the issue is?

#!/bin/python

import math
import os
import random
import re
import sys

if __name__ == '__main__':
    n = int(input().strip())

if n % 2 = 1:
    print ("Weird")

else:
    if n range(2,5):
        print:("Not Weird")

    else:
        if n range(6,20):
            print("Weird")

        else:
            print("Not Weird")

Number guessing game always returns the same output

I'm making a simple number guessing game from 1 - 10 using an if...else statement, it worked the first time, but it seems it always outputs "You didn't guess it correctly." when I'm guessing or the other way around. Would be great for some help, so here are the solutions I made as of asking this question:

//This is the first solution I've come up with.
#include <stdio.h>
#include <stdbool.h>

int main() {
  int guessingNumber = '5';
  printf("Guess from 1-10: ");
  scanf("%d", &guessingNumber);

  if (guessingNumber == true) {
    printf("You guessed it!\n");
  }
  else {
    printf("You didn't guess it correctly.\n");
  }
  return 0;
}


//Here is the second one.
#include <stdio.h>

int main() {
  int guessingNumber = '5';
  int guess;
  printf("Guess from 1-10: ");
  scanf("%d", &guess);

  if (guessingNumber == guess) {
    printf("You guessed it!\n");
  }
  else {
    printf("You didn't guess it correctly.\n");
  }
  return 0;
}

I'm sure that the problem causing this is in this lines from the first solution:

printf("Guess from 1-10: ");
      scanf("%d", &guessingNumber);
    
      if (guessingNumber == true) {
        printf("You guessed it!\n");

and this from the second solution that I'm sure the problem (might also) came:

printf("Guess from 1-10: ");
  scanf("%d", &guess);

  if (guessingNumber == guess) {
    printf("You guessed it!\n");

How can i use VLOOKUP in excel with equality condition?

Excel dataset

i want to change data layout by filtering the left table from redundancies i tried typing the below formula =IF(VLOOKUP(K8,$A$8:$E$82,5,FALSE)=$N$7,VLOOKUP(K8,$A$8:$E$82,4,FALSE),"na") it just works with the date 3/1/2021 but not for the rest of the columns for the rest of dates

anyone can help me with this problem? enter image description here

Segmentation Fault(core dumped) In IF Condition with && operator [closed]

Basically I'm starting with C with IF else statement .I'm getting error when I use && operator inside IF statement but not when I use || operator inside IF condition. Question: The program must accept three integers as input N,X,Y. The prog must print 1 if N is multiple of both X and Y. else print -1

enter image description here

Check every other week using if statement

I have the following if statement:

if date.weekday() != 0:

How can I change this if statement to check every other Monday (one day every other week)?

Thanks in advance for your help!

Newbie C++ Questions - Why doesn't this if statement execute?

I have been trying to solve a problem on Codewars and ran into a problem with an if statement executing. If I test the following code, I get the error: "error: use of undeclared identifier 'out'", but if I use the conditional operator instead (see the commented line) everything works fine! I'm probably missing something obvious but could somebody point out why this is?

#include<cmath>
using namespace std;
class Suite2
{
    public:
      static string game(unsigned long long n){
      
      ostringstream os1, os2;
      os1 << pow(n,2)/2;
      os2 << pow(n,2);
      
      if(n%2==0){
        std::string out = "[" + os1.str() + "]";
      }
      else{
        std::string out = "[" + os2.str() + ", " + "2]";
      }
      
      //return (n%2==0) ? "[" + os1.str() + "]" : "[" + os2.str() + ", " + "2]";
      return out;
    }
};

Add multiple columns to my dataframe (if statement)

I have the following Pandas DataFrame:

factor_A factor_B factor_C
0.0384 -0.0565 0.0964
-0.0598 0.0967 0.9156
0.8795 0.0254 -0.0853

I now want to create some new columns or a new df (factor_A_signal_A, factor_B_signal_B and so on) with the following if statement: If the factor_x is > 0, than 1, otherwise -1.

So far so good. But the problem is, that at the moment I don't know how many factors I will put into my dataframe and I can't do an if/else statement for example 100 columns.

Could you please help me? I need this step to multiply each factor with each signal.

Bash script, if statement in while loop, unwanted duplicate output

I'm doing a script to parse m3u files. The goal is to retrieve the variable tag and the url. I tested with this file.

#!/bin/bash

echo "name,tvg-id,tvg-name,tvg-country,group-title,languages,url"
while IFS= read -r line; do
    tags_detect="$(echo "$line" | grep -Eo '^#EXTINF:')"

    if [[ -n ${tag_detect} ]]; then
        get_chno="$(echo "$line" | grep -o 'tvg-chno="[^"]*' | cut -d '"' -f2)"
        get_id="$(echo "$line" | grep -o 'tvg-id="[^"]*' | cut -d '"' -f2)"
        get_logo="$(echo "$line" | grep -o 'tvg-logo="[^"]*' | cut -d '"' -f2)"
        get_grp_title="$(echo "$line" | grep -o 'group-title="[^"]*' | cut -d '"' -f2)"
        get_title="$(echo "$line" | grep -o ',[^*]*' | cut -d ',' -f2)"
        get_tvg_name="$(echo "$line" | grep -o 'tvg-name="[^"]*' | cut -d '"' -f2)"
        get_country="$(echo "$line" | grep -o 'tvg-country="[^"]*' | cut -d '"' -f2)"
        get_language="$(echo "$line" | grep -o 'tvg-language="[^"]*' | cut -d '"' -f2)"

        phrase="${get_title},${get_id},${get_tvg_name},${get_country},${get_grp_title},${get_language}"
    else
        url="$line"

    fi
    echo "${phrase},${url}"

done <"${1}"

So, Without "If" it works but i don't have url. I add a "IF" and ... :

,#EXTM3U
4 Turk Music,4TurkMusic.fr,4 Turk Music,FR;TK,Music,Turkish,#EXTM3U
4 Turk Music,4TurkMusic.fr,4 Turk Music,FR;TK,Music,Turkish,http://51.210.199.30/hls/stream.m3u8
Alpe d’Huez TV,AlpedHuezTV.fr,Alpe d’Huez TV,FR,,French,http://51.210.199.30/hls/stream.m3u8
Alpe d’Huez TV,AlpedHuezTV.fr,Alpe d’Huez TV,FR,,French,https://edge10.vedge.infomaniak.com/livecast/ik:adhtv/chunklist.m3u8

... It's broken and I don't found my error.

desired output:

4 Turk Music,4TurkMusic.fr,4 Turk Music,FR;TK,Music,Turkish,http://1.2.3.4/hls/stream.m3u8
Alpe d’Huez TV,AlpedHuezTV.fr,Alpe d’Huez TV,FR,,French,https://edge10.vedge.infomaniak.com/livecast/ik:adhtv/chunklist.m3u8

I don't understand my mistake.

mardi 29 juin 2021

Need to send an email to Form respondents based on question answer

I need some help! I am trying to automate sending an email to the form respondent if they select any of the AcLab Session Full answers. The possible answers range from blank up to AcLab Session Full19

I successfully got it to send an email on every response, only problem is I need it to send only when the respondent selects a particular thing, and not everything.

Now I've messed up the code and it isn't working at all!

Here is where I think I've messed up (keep in mind, I'm not a developer or coder, this is pieced together from many different places and is likely incorrect)

function AutoConfirmation(e)
{
      var theirFirst = e.values[2];
      var theirEmail = e.values[1];
      var theirSession= e.values[4];
      var subject = "Action Required: Your Selected AcLab Session is Full";
      var message = "Thank you " + theirFirst + ",<br> <br> The AcLab session that you have selected for this week is full. " 
      var cosmetics = {htmlBody: message};
      
 if (SpreadsheetApp.getActive().getSheetByName('Form Responses 1').getRange('Form Responses 1!E2:E10000').getValue(theirSession)=""||"AcLab Session Full1"||"AcLab Session Full2"||"AcLab Session Full3"||"AcLab Session Full4"||"AcLab Session Full5"||"AcLab Session Full6"||"AcLab Session Full7") return;
MailApp.sendEmail (theirEmail, subject, message, cosmetics);}

how can i print value out of if condition when i get value from isset post?

PHP now i'm trying to echo tha variable value out of if and isset area.

if(isset($_POST['submit'])){
  $today_date = date("Y-m-d");
  $id_user = $_POST['id_user'];
  $fullName_user = $_POST['fullName_user'];
}
echo $today_date;

//how can i print out of if condition.

how would I convert the string into the dictionary and have it check it

how would I add an if statement that check if it's already in the dictionary.

def betterCompression(s):
    
    d = {}
    
    for i in range(0, len(s)):
        result = ""
        count = 1
        result += s[0]
        
        for i in range(len(s)-1):
            if (s[i] == s[i+1]):
                count += 1
            else:
                if(count > 1):
                    result += str(count)
                result += s[i+1]
                count = 1
            
                
        if(count > 1):
            result += str(count)
        return result

Method not executing if statement in C#

I have a method to start a process and if the output contains a certain string it will execute a different method, but it doesn't seem to be executing the if statement

    public static void installerD(String[] args)
    {
        Parallel.For(0, args.Length, (i) =>
          {
              Console.WriteLine($"Installing {args[i]}");

              String repoPath = $@" Repositories/repo{i}";

              ProcessStartInfo p = new ProcessStartInfo();
              p.FileName = gitcommand;
              p.Arguments = "clone " + args[i] + $@" Repositories/repo{i}";
              p.UseShellExecute = false;
              p.RedirectStandardOutput = true;

              using (Process run = Process.Start(p))
              {
                  using (StreamReader Reader = run.StandardOutput)
                  {
                      String ifmethod = Reader.ToString();
                      
                      if (ifmethod.Contains("already exists"))
                      {
                          gitCheck(repoPath, args[i]);
                      }
                  }
              }

          });
    }

In Android Studio, I have used a speech to text. I want it to verify the word that the user speaks, but something is wrong. Help is appreciated

My project in Android Studio is written in Java. I have implemented a mic button that when clicked, prompts the user to a (Google) speech to text that will display the user's words in an XML TextView. I have a Button (submit) that the user should click after speaking, so it can verify the word that the user spoke. I would like it to verify if the user has spoken the word 'office', and in another TextView, display either 'Correct' or 'Incorrect'. I have created code for this, but no matter what word I speak, even 'office', it says it is incorrect. I used an if else statement and a setText for this. If this is relevant, I am testing on a phone, not an emulator because the emulator wouldn't allow speech to text. I would really appreciate any assistance with this as I have been struggling to find help for a while now.

 button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                String wordText = (String) word.getText();
                if (wordText == "office") {
                    responseText = "Nice job, that is correct!";

                } else {
                    responseText = "Sorry, that is incorrect.";


                }
                response.setText(responseText);


            }
        });


    }

The button, when clicked, should determine whether the user has spoken the word 'office' or not. The TextView 'word' displays the word that the user has spoken in the mic. The String 'responseText' is the response for whether the user has spoken the right word or not. The TextView 'response' is set to the text of 'responseText' to show either 'correct' or 'incorrect'.

What's is the wrong in the program

import random
random_Number = random.randrange(1, 4)

support = input('Write help to support ')

if support == "help":
    print("this is Rock, Paper, Scissors game ")
    play_Game = input('-enter 1 to Rock\n-enter 2 Paper\n-enter 3 to Scissors \n')
    if random_Number == 1 and play_Game == 1 :
        print('The game is draw\n Try Again!')

    elif random_Number == 2 and play_Game == 1:
        print('You lose!\n Hard luck')

    elif random_Number == 3 and play_Game == 1:
        print('You won!\n Good luck')

    elif random_Number == 1 and play_Game == 2:
        print('You won!\n Good luck')

    elif random_Number == 2 and play_Game == 2:
        print('The game is draw\n Try Again!')

    elif random_Number == 2 and play_Game == 2:
        print('The game is draw\n Try Again!')

    elif random_Number == 3 and play_Game == 2:
        print('You lose!\n Hard luck')

    elif random_Number == 1 and play_Game == 3:
        print('You lose!\n Hard luck')

    elif random_Number == 2 and play_Game == 3:
        print('You won!\n Good luck')

    elif  random_Number == 3 and play_Game == 3:
        print('The game is draw\n Try Again!')
    else:
        print('please, enter a correct number ')


else:
   print("write the true keyword")

Comment: When I type 1, 2, or 3 it tells me to enter the correct number I think the wrong is in if statements. I have learned python and this is my first project. please, tell me is it a clean code?

If - else if statement - JavaScript

I am new to coding and I have a doubt with respect to if - else if statements for props

The following code snippet is working, but I want to add another property in props and if 'abc' is unavailable, only then props value 'pqr' should be added to path.

 render() {
    if (this.props.abc?.status !== 'available') return null;
      console.info('Log value= ',this.props);

    const path = this.props.abc.value;
    
    return (
      <View
        getfile={path}   
       console.info('finished loading:', path); 
        }
      />
    );
  }

I want to write something like

render() {
        if (this.props.abc?.status !== 'available') return null;
        else if (this.props.pqr?.status !== 'available') return null;
          
          console.info('Log value= ',this.props);
          
        if (this.props.abc != null) {
        const path = this.props.abc.value;
        }
        else if (this.props.pqr != null) {
        const path = this.props.pqr.value;
        }
/* I know the above if -else if statement will fail as props value for 'abc' might not be null yet not have the required value in which case it would never go to the else if statement. */
        
        return (
          <View
            getfile={path}   
           console.info('finished loading:', path); 
            }
          />
        );
      }

Here, I want to check if props value is available for abc or pqr and then it should assign that value. How do I code better?

Any suggestion appreciated.

loop gives me error. If i have error i wana go for next cell

i have this code. I need a help. When in pivot tabel3 vba couldnt find this: Sheets("EXO").Range("N" & y).Value i wana go for next cell until vba do not find this this Sheets("EXO").Range("N" & y).Value and after then vba should do copy and paste part of loop Could u please help me ?

Sub FILL_vALUES_EXO()
i = 1
y = 9
rng = Application.WorksheetFunction.CountA(Worksheets("EXO").Range("N9:N67"))


Do While i < rng
    
    
    Application.CutCopyMode = False
    
    Sheets("EXO").Range("N" & y).copy
    ActiveSheet.PivotTables("PivotTable3").PivotFields("RootCause").ClearAllFilters
   ActiveSheet.PivotTables("PivotTable3").PivotFields("RootCause").CurrentPage = _
       Sheets("EXO").Range("N" & y).Value
      

    
    Range("B6").Select
    Selection.End(xlDown).Select
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.copy
    Range("O" & y).Select
    ActiveSheet.Paste

   Range("O4").Select
    Application.CutCopyMode = False
    Selection.copy
    Range("O" & y & ":R" & y).Select
    Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False
    Application.CutCopyMode = False
y = y + 1
i = i + 1

end sub

Check descending order in a column using FOR loop and IF ELSE in python

   time           1           2  ...          10          11          12
0    114         NaN         NaN  ...         NaN         NaN         NaN
1    115         NaN         NaN  ...         NaN         NaN         NaN
2    116         NaN         NaN  ...         NaN         NaN         NaN
3    117         NaN         NaN  ...         NaN         NaN         NaN
4    118         NaN         NaN  ...         NaN         NaN         NaN
5    119  441.352927         NaN  ...         NaN         NaN         NaN
6    120  441.832005         NaN  ...         NaN         NaN         NaN
7    121  429.159441  414.695159  ...         NaN         NaN         NaN
8    122  426.640083  409.350283  ...         NaN         NaN         NaN
9    123  405.895463  391.782682  ...         NaN         NaN  595.583477
10   124  348.333084  330.328054  ...         NaN         NaN  558.149675
11   125  269.575895  244.929717  ...  498.792684  174.485133  501.917091
12   126  206.326517  183.591386  ...  483.946063  159.790946  388.633450
13   127  164.460509  146.675092  ...  468.012384  143.278498  289.948133
14   128  136.459238  124.173664  ...  445.790269  126.418644  216.911347
15   129  118.142130  109.840042  ...  429.640427  114.967589  158.156775
16   130  106.305034  102.602261  ...  456.978328  105.465703  125.695873
17   131   95.334029   95.655744  ...  436.670517   98.330257  103.816534
18   132   86.695439   89.980695  ...  436.020305   90.027712   90.845685

I want to check,

for col in df.columns [1:]: #Check from column name 1 until 12 (skip the NaN)

if first 5 values are descending =TRUE, startpoint = the largest value from these 5 else, take next set of 5 values and do the same.

Create a separate dataframe for all the startpoint values until the end value for every column and also include the time column.

How to use ifelse to extract last word of a string in R?

I'm new to R and I could use some help.

I have two different datasets with people's names.

First database looks something like this:

    NAME            
JOSE SANTOS         
MIRIAM RIOS          
JULIANA SILVA
  

The second one looks like this:

         NAME                      
TIAGO MELO                         
JOSE FRAGOSO SANTOS               
JULIANA DOS SANTOS SILVA           
MARIANA RIOS 

Then I created a key using the first letter of the first name + the last name so I could merge the two datasets and see if the person from dataset1 is present in dataset2. It looks something like this:

  KEY               NAME_DB1              NAME_DB2
J SANTOS           JOSE SANTOS       JOSE FRAGOSO SANTOS
M RIOS             MIRIAM RIOS       MARIANA RIOS
J SILVA            JULIANA SILVA     JULIANA DOS SANTOS SILVA
T MELO                 NA            TIAGO MELO

Then I created another key that gets the first 2 letters from the first name + last name because M RIOS could stand for either Miriam Rios or Mariana Rios.

       KEY2               NAME_DB1              NAME_DB2
    JO SANTOS           JOSE SANTOS       JOSE FRAGOSO SANTOS
    MI RIOS             MIRIAM RIOS                NA
    JU SILVA            JULIANA SILVA     JULIANA DOS SANTOS SILVA
    TI MELO                 NA            TIAGO MELO
    MA RIOS                 NA            MARIANA RIOS

What I need to do now is merge those 2 datasets by these 2 keys. The logic I need to follow is:

if LAST NAME == "RIOS", then it uses the second key (2 letters + last name). If LAST NAME is different from "RIOS", then i'll use the first key (1st letter + last name).

I don't know how to do that. I can't use the second key (two letters + last name) for everything because some names of my datasets are like this: R D RODRIGUES, for example.

How to increment a variable within a if statement python IDLE

I am trying to increment a variable based on a condition in the if statement. Every time I attempt to do so, I get a Syntax error on the equal sign, and I'm not sure why. I am writing this in the Python IDLE

You can click on this link to access the image of the code

VBA If/And formula with multiple criteria. Code is triggering when only meeting one of two criteria

I am trying to have my macro check certain criteria before running. In this example, I want to make sure a quantity is entered for each fruit. Sometimes fruit will not be entered all the way down to cell C94... it might stop at C15. When I run the macro the message box will appear beyond where any fruit is entered.

Sub Check_fruit()

Dim x As String
Dim y As Integer
Dim rSearch As Range
Dim rSearch1 As Range
Dim cell As Range, cell1 As Range
Dim matchRow As Integer

Set rSearch = Sheets("Import").Range("C05:C94")
Set rSearch1 = Sheets("Import").Range("D05:D94")

For Each cell In rSearch
    x = cell.value
    For Each cell1 In rSearch1
    y = cell1.value

         
                If y = 0 And (x = "apple" _
                Or x = "orange" _
                Or x = "pear" _
                Or x = "grape" _
                Or x = "peach" _
                Or x = "banana" _
                Or x = "strawberry") Then
                    MsgBox "You must specify how many fruit."
                    Exit Sub
                    End If
            Next cell1
        Next cell
    

End Sub

My Toast only goes through else statement Android Java

Still a beginner in Android development. I'm trying to create a simple 'score results' app where the user has to enter their score and their results appear as a toast accordingly. The problem is my Toast only goes for an else statement regardless of what score the user entered. What am I doing so wrong? Please help.

int score = 100;

public void checkResults (View view){

    Log.i("Results","Button Tapped");

    Button button = (Button) findViewById(R.id.button);

    TextView editTextNumber = (TextView) findViewById(R.id.editTextNumber);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(score < 29){

                Toast.makeText(getApplicationContext(), "You got an F", Toast.LENGTH_SHORT).show();
            }
            else if (score >= 30 && score <= 39){

                Toast.makeText(getApplicationContext(), "You got E", Toast.LENGTH_SHORT).show();
            } else {

                Toast.makeText(getApplicationContext(), "You failed", Toast.LENGTH_SHORT).show();
            }
        }
    });


}

PHP checkdate() with multiple conditions

I am trying to use checkdate() in an IF statement with other conditions:

if ( $segment[1] == 'living-life-lab' && 
     $segment[2] == 'activities' && 
     $segment[3] == 'letter-scramble-game' && 
    ( checkdate( $segment[5] , $segment[6] , $segment[4] ) === true ) ) 
{

But checkdate() returns a warning instead of just moving to the next IF when the value of $segment[4] is "printables" , $segment[5] is "rss" and $segment[6] is "feed".

Warning: checkdate() expects parameter 1 to be integer, string given in /home/vhosts/rons-home.net/LivingLifeLab/url/url.php on line 709

What change do I need to make to the IF statement to allow a date but move to the next IF when $segment[4] , $segment[5] & $segment[6] do not form a date?

Why aren't all conditions checked in nested 'if statements'?

score = 50

if score >= 60:
  print('elon')
  if score <= 50:
      print('please type number bigger than 0')
else:
  print('please type a number next time')

Can anyone try to help me understand the mechanics of why the second condition is met, but not executed, because it is nested behind a false first condition. I'm struggling with understanding how and when to nest "things". Why isn't the ELSE statement nested?

For loop in TI-Basic won't repeat

I'm trying to make an interactive Pythagorean Theorem calculator which displays

What is displayed

and waits for you to press the keys A, B, or C (41, 42, 43). The following code works fine, it lets me press exactly 2 keys:

ZStandard
84→Xmin
72→Ymax
ZInteger
FnOff 

{0,100,100,0}→L1
{0,60,0,0}→L2
Plot1(xyLine,L1,L2

Text(60,130,"C"
Text(90,250,"A"
Text(148,150,"B"

DispGraph

0→A
0→B
0→C

For(I,1,2
:0→K
:1→L
:While L
::getKey
::If Ans=45:Then
:::0→L
::End
::If Ans=41 or Ans=42 or Ans=43:Then
:::Ans→K
:::0→L
::End
:End

:If K=0:Then
::Stop
:End

:Disp K,I,A,B,C," "
End

But when I add the following if-else-statement

:If K=41:Then
::Input "A=",A
:Else:If K=42:Then
::Input "B=",B
:Else
::Input "C=",C
:End

in the code, like this:

ZStandard
84→Xmin
72→Ymax
ZInteger
FnOff 

{0,100,100,0}→L1
{0,60,0,0}→L2
Plot1(xyLine,L1,L2

Text(60,130,"C"
Text(90,250,"A"
Text(148,150,"B"

DispGraph

0→A
0→B
0→C

For(I,1,2
:0→K
:1→L
:While L
::getKey
::If Ans=45:Then
:::0→L
::End
::If Ans=41 or Ans=42 or Ans=43:Then
:::Ans→K
:::0→L
::End
:End

:If K=0:Then
::Stop
:End

:If K=41:Then
::Input "A=",A
:Else:If K=42:Then
::Input "B=",B
:Else
::Input "C=",C
:End

:Disp K,I,A,B,C," "
End

It only repeats once. Any help would be highly appreciated.

Why does the && operator works differently when values are replaced? [duplicate]

Why is the Second console displaying? As per my knowledge both of them must not be displayed because none of the condition includes 'd' in the array.

var arrayNew = ['a','b','c'];
if(arrayNew.includes('b' && 'd'))
  console.log("First",arrayNew);
else if(arrayNew.includes('d' && 'b'))
  console.log("Second",arrayNew);

R: paste() a certain string only if bool is TRUE (conditional strings)?

I have the following code:

run_name = paste("run", "_", gsub(" ", "_", gsub(":", "", Sys.time())), sep="")
if(ROUNDING) run_name =  paste(run_name, "_R", sep="")

which generates a name like run_2021-06-29_101105 and for ROUNDING = TRUE it will add "_R": run_2021-06-29_101105_R

I'd like to include other parameters in the run_name and could do so with a line for each. But I vaguely remember (though maybe it was another programming language) that this is possible in one line with something like this (ROUNDING|"R"|"") :

run_name = paste("run", "_", gsub(" ", "_", gsub(":", "", Sys.time())), (ROUNDING|"R"|"") , sep="")

Is there such a thing (syntax for "conditional strings"?!) in R?

lundi 28 juin 2021

is there a better way to write this if statement in laravel

good day i am new in laravel and i am still learning as i go.

my question is this code works but i feel like it unnecessary and can be written much better please can someone assist would a switch case be better or is there a better way to write this and please explain to me thank you.

debtorscontroller.php

    $debtors_created_at = $debtors->created_at;
    $now = Carbon::now();
    $created_at_in_days = $debtors_created_at->diffInDays($now);


     if ($created_at_in_days >= 0 and $created_at_in_days <= 10){

         Debtor::whereId($debtorid)->update(['collection_level' => 'Pre Collection']);
     }elseif ($created_at_in_days >= 11 and $created_at_in_days <= 30){

            Debtor::whereId($debtorid)->update(['collection_level' => 'Collection Level 1']);
        }
     elseif ($created_at_in_days >= 31 and $created_at_in_days <= 60){

         Debtor::whereId($debtorid)->update(['collection_level' => 'Collection Level 2']);
     }
     elseif ($created_at_in_days >= 61){

         Debtor::whereId($debtorid)->update(['collection_level' => 'Collection Level 3']);
     }

this just check wheter the debtor was created at and if it is 1-10 days old it changes

its level

days 1-10 is pre collection 11-30 is collection level 1 31-60 is collection level 2 61-90+ is collection level 3

this is a field in my debtors table collection_level

In Android Studio, I have used a speech to text. I want it to verify the word that the user speaks, but something is wrong. Help is appreciated

My project in Android Studio is written in Java. I have implemented a mic button that when clicked, prompts the user to a (Google) speech to text that will display the user's words in an XML TextView. I have a Button (submit) that the user should click after speaking, so it can verify the word that the user spoke. I would like it to verify if the user has spoken the word 'office', and in another TextView, display either 'Correct' or 'Incorrect'. I have created code for this, but no matter what word I speak, even 'office', it says it is incorrect. I used an if else statement and a setText for this. If this is relevant, I am testing on a phone, not an emulator because the emulator wouldn't allow speech to text. I would really appreciate any assistance with this as I have been struggling to find help for a while now.

Why does the else condition is being executed no matter what?

correct_answer = "Tushar"
hidden_answer = "------"
lives = 7
correct_answer = correct_answer.split()
hidden_answer = hidden_answer.split()


while lives > 0 :
  guess = input("Please enter your guess \n")
  if guess in correct_answer:
    for characters in correct_answer:
      if guess == characters:
        position = correct_answer.index(characters)
        hidden_answer[position] = guess
    print(hidden_answer)
  else:
    print(hidden_answer)
    lives = lives - 1
    print(lives)
    if lives == 1:
      break

Why does in the above code my else condition is being executed even if correct answer contains my guess?

Can you have an email subject line vary depending on results of an If Len statement?

Is it possible to have the subject line include the names of those worksheets that were deemed true by the If statements? Would be very helpful. I can't seem to figure it out. Would like it to automatically change and list the worksheets that prompted the email. This code works perfectly for me, except for that one "bug" i'm having. I tried putting & shtsRotation after the typed subject line, but it was kind of omitted when the code was ran.

 Sub Main()
Dim sh As Worksheet, i As Long, shtsRotations As String
Dim shtsFunctions As String, shtsOK As String

For Each sh In ActiveWorkbook.Worksheets
    If Application.CountIf(sh.Range("L3:L70"), "<1") > 0 Then
        shtsRotations = shtsRotations & vbLf & sh.Name
    Else
        shtsOK = shtsOK & vbLf & sh.Name & " (Rotations)"
    End If
    
    If Application.CountIf(sh.Range("M3:M70"), "<1") > 0 Then
        shtsFunctions = shtsFunctions & vbLf & sh.Name
    Else
        shtsOK = shtsOK & vbLf & sh.Name & " (Functions)"
     End If
     Next sh

If Len(shtsRotations) > 0 Then
    SendReminderMail "test@test.com", "Equipment rotations are due!" & shtsRotations, _
           "Hello Team, " & vbNewLine & vbNewLine & _
           "Check customer sheets: " & shtsRotations & vbLf & vbNewLine & _
           "In the attatched workbook, you will see which equipment needs to be rotated by the red dates of their last rotation."

End If

If Len(shtsFunctions) > 0 Then
    SendReminderMail "test@test.com", "Equipment functions are due! ", _
           "Hello Team, " & vbNewLine & vbNewLine & _
           "Check customer sheets: " & shtsFunctions & vbLf & vbNewLine & _
           "In the attatched workbook, you will see which equipment needs to be functioned by the red dates, indicating their last function."
End If

If Len(shtsOK) > 0 Then
    MsgBox "These sheets are OK: " & vbLf & shtsOK, vbInformation
End If

End Sub

Sub SendReminderMail(sTo As String, sSubject As String, sBody As String)

Dim wb1 As Workbook
Dim wb2 As Workbook
Dim sh As Worksheet
Dim TempFilePath As String, TempFileName As String
Dim FileExtStr As String, OutApp As Object, OutMail As Object

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

Set wb1 = ActiveWorkbook

TempFilePath = Environ$("temp") & "\"
TempFileName = "Copy of " & wb1.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")
FileExtStr = "." & LCase(Right(wb1.Name, Len(wb1.Name) - InStrRev(wb1.Name, ".", , 1)))

wb1.SaveCopyAs TempFilePath & TempFileName & FileExtStr
Set wb2 = Workbooks.Open(TempFilePath & TempFileName & FileExtStr)
wb2.Worksheets(1).Range("A1").Value = "Copy created on " & Format(Date, "dd-mmm-yyyy")
wb2.Save

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

On Error Resume Next
With OutMail
    .To = sTo
    .CC = ""
    .BCC = ""
    .Subject = sSubject
    .Body = sBody
    .Attachments.Add wb2.FullName
    .Display
End With
On Error GoTo 0
wb2.Close savechanges:=False

Kill TempFilePath & TempFileName & FileExtStr

Set OutMail = Nothing
Set OutApp = Nothing

With Application
    .ScreenUpdating = True
    .EnableEvents = True
End With

MsgBox "Your Automated Email was successfully ran at " & TimeValue(Now), vbInformation

End Sub

If/Else Program wont print index

I am writing a program that will print a list of numbers 1:n. However, every number divisible by 2 should be replaced with 'x' and every number divisible by 3 should be replaced with 'y'. Lastly, every number both divisible by 2 and 3 should be replaced with 'xy'. This is my code so far, I can get the function to print the correct result with my input. But it wont print the entire list of numbers. Instead I am just getting the end result (x,y, or xy) for the given input. Here is my code thus far with the output.

def replace(n):
    
    for i in range(n):
        print(i)

        if n%2== 0 and n%3 == 0:
            return 'xy'

        elif n%2==0:
            return 'y'

        elif n%3 == 0:
            return 'x'

        else: 
            print(i)
replace(12)

This is my output:

0
'xy'

I would like the output to be something like:

1
x
y
x
5
xy
7
x
y
x
11
xy

Any advice would be appreciated, you guys rock!

Using if else condition with promises and fetch [closed]

The code flow is as follows (javascript):

function getData(){
  return new Promise((resolve,reject)=>{
    fetch(`some_url`)
    .then(
      //some code
    )
    .then(
      //some code
      resolve(d)
    )
  })
}

Then the above function is called:

getData().then((data)=>{

  //some code that stores necessary values from the fetch api into variables

  if(condition){
    //check for condition and uses variables fetched from api
    //some code
  }
  else{
    //some code that uses variables fetched from api
  }
}))

The problem is that 'if' as well as 'else' both the blocks are executed. Can someone please help me with this

Python - printing message if something in a list is not working

Screenshot from shell of this code not working I've been banging my head against the wall for over an hour on this super simple problem, but for the life of me, I cannot make it work. All I want is this ultra simple program to return the line "blah blah has already been added" if the user input IS in the list already. I've tried the common sense "if blah in blah_blah: print("blah blah)" but python is just pretending like that doesn't work. I already tried "if blah in blah_blah and blah not in blah_blah_blah" but python continues to pretend that doesn't work either. I'm going insane with this problem that makes zero sense to my still learning, rookie brain. Please help me. Here is my super stupidly simple code, including two super common sense ways to accomplish my problem. I've left both in because neither one does literally anything anyway, so python apparently doesn't care what I've typed at this point:

prompt = "\nEnter a topping for your pizza:"

prompt += "\n(Enter 'done' when you've finished) "

pizza_toppings = []

available_toppings = ['pepperoni','extra cheese','black olives','red onions',
    'green peppers','sausage']

while True:

    topping = input(prompt)

    if topping == 'done':
        break
    elif topping in pizza_toppings:
        print(f"{topping} has already been added.")
    else:

        if topping in available_toppings and topping not in pizza_toppings:
            pizza_toppings.append(topping)
        elif topping not in available_toppings:
            print(f"{topping} is not an available topping.")
        else:
            print(f"{topping} has already been added.")

print(f"Your selected toppings are: {pizza_toppings}")

No matter what I type, this program still lets me enter the same topping 50 times, and will add it to the list pizza_toppings every single time. Why isn't my program catching this?

Compiling condition across multiple worksheets to output 1 "solution". Also call out which worksheets(s) fit the condition

I am new to vba and struggling with trying to accomplish having a single overall email send out if any worksheet column L/M have a value below 1 and want it to call out which sheet (or sheets) had the value <1 in the email body or subject line. I have spent countless hours searching the web, but nothing so far has really worked for me. The MsgBox function is working fine, just having issues with compiling the results to 1 email naming which worksheet had the <1 value and 1 "solution" for the whole workbook, instead of having an email sent for every single worksheet that the conditions fit. Thank you in advance.

   Option Explicit
   Sub Main()
   Dim sh As Worksheet, i As Long

  For Each sh In ActiveWorkbook.Worksheets
   With WorksheetFunction
    If .CountIf(sh.Range("L3:L26"), "<1") > 0 Then
        Call SendReminderMail1
    Else
        MsgBox "Rotations NOT needed for """ & sh.Name & """."
    End If
    If .CountIf(sh.Range("M3:M20"), "<1") > 0 Then
        Call SendReminderMail2
    Else
        MsgBox "Functions are NOT needed for """ & sh.Name & """."
    End If
End With
  Next
  End Sub
  Sub SendReminderMail1()

Dim wb1 As Workbook
Dim wb2 As Workbook
Dim sh As Worksheet
Dim TempFilePath As String
Dim TempFileName As String
Dim FileExtStr As String
Dim OutApp As Object
Dim OutMail As Object

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

Set wb1 = ActiveWorkbook


TempFilePath = Environ$("temp") & "\"
TempFileName = "Copy of " & wb1.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")
FileExtStr = "." & LCase(Right(wb1.Name, Len(wb1.Name) - InStrRev(wb1.Name, ".", , 1)))

wb1.SaveCopyAs TempFilePath & TempFileName & FileExtStr
Set wb2 = Workbooks.Open(TempFilePath & TempFileName & FileExtStr)

wb2.Worksheets(1).Range("A1").Value = "Copy created on " & Format(Date, "dd-mmm-yyyy")

wb2.Save


Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

On Error Resume Next
With OutMail
    .To = "test@test.com"
    .CC = ""
    .BCC = ""
    .Subject = "Rotations are due for  """ & sh.Name & """."
    .Body = "Hi there bud, ya need to take a good ole look at this here document. You've been slackin', let's fix that."
    .Attachments.Add wb2.FullName

    .Display   'or use .Display
End With
On Error GoTo 0
wb2.Close savechanges:=False

Kill TempFilePath & TempFileName & FileExtStr

Set OutMail = Nothing
Set OutApp = Nothing

With Application
    .ScreenUpdating = True
    .EnableEvents = True
End With

MsgBox "Your Automated Email for Rotations was successfully ran at " & TimeValue(Now), vbInformation

 End Sub

 Sub SendReminderMail2()

Dim wb1 As Workbook
Dim wb2 As Workbook
Dim sh As Worksheet
Dim TempFilePath As String
Dim TempFileName As String
Dim FileExtStr As String
Dim OutApp As Object
Dim OutMail As Object

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

Set wb1 = ActiveWorkbook


TempFilePath = Environ$("temp") & "\"
TempFileName = "Copy of " & wb1.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")
FileExtStr = "." & LCase(Right(wb1.Name, Len(wb1.Name) - InStrRev(wb1.Name, ".", , 1)))

wb1.SaveCopyAs TempFilePath & TempFileName & FileExtStr
Set wb2 = Workbooks.Open(TempFilePath & TempFileName & FileExtStr)

wb2.Worksheets(1).Range("A1").Value = "Copy created on " & Format(Date, "dd-mmm-yyyy")

wb2.Save


Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

On Error Resume Next
With OutMail
    .To = "test@test.com"
    .CC = ""
    .BCC = ""
    .Subject = "Functions are due for """ & sh.Name & """."""
    .Body = "Hi there bud, ya need to take a good ole look at this here document."
    .Attachments.Add wb2.FullName

    .Display   'or use .Display
End With
On Error GoTo 0
wb2.Close savechanges:=False

Kill TempFilePath & TempFileName & FileExtStr

Set OutMail = Nothing
Set OutApp = Nothing

With Application
    .ScreenUpdating = True
    .EnableEvents = True
End With
 MsgBox "Your Automated Email for Functions was successfully ran at " & TimeValue(Now), vbInformation

 End Sub

R - excel match/index alternative

I have this dataframe

t1 <-
    data.frame(
      amt = c(13500, 12500, 11500, 10500, 9000, 0),
      "0" = seq(0.8, 1.3, by = 0.1),
      "50" = seq(0.7, 1.2, by = 0.1),
      "56" = seq(0.6, 1.1, by = 0.1),
      "61" = seq(0.5, 1, by = 0.1)
    )

And this second dataframe

t2 <-
    data.frame(
      id = seq(1, 5),
      percentage = c(0, 50, 55, 80, 61),
      created_amount = c(12000, 9000, 50, 40000, 10000)
    )

My goal is to create third table, that will compare created amount from t2 dataframe with first column in t1 dataframe and return first higher or equal row and also compares percentage with 0, 50, 56 and 61 columns and if percentage is equal or higher, then it will select this colum.

Result should be

result <-
    data.frame(
      id = seq(1, 5),
      percentage = c(0, 50, 55, 80, 61),
      created_amount = c(12000, 9000, 50, 40000, 10000)
      result = c(1.0, 1.1, 1.0, 0.5, 0.5)
    )

In excel I would you match and index function, in R it could be solved via dome if else cution, but if else solution doesnt seem to be robust enough.

I found some tutorials for that but I need one that works with dataframes.

Error when atempting to get a key press (A, B, or C) and storing their letter

I am trying to make an interactive Pythagorean Theorem calculator which shows some graphics and then waits for you to press the keys A, B, or C so you can enter their respective values for the calculation.

But I get the following error:
ERROR: DATA TYPE

It worked fine until I tried some If-else statements.
Here's my code:

ZStandard
84→Xmin
72→Ymax
ZInteger
FnOff 

{0,100,100,0}→L1
{0,60,0,0}→L2
Plot1(xyLine,L1,L2

Text(60,130,"C"
Text(90,250,"A"
Text(148,150,"B"

DispGraph

"N"→P
Repeat Ans≥41 and Ans≤43
getKey
If Ans=41
"A"→P
If Ans=42
"B"→P
If Ans=43
"C"→P
End

Disp P

I would like it to ignore any keys that aren't A, B, or C, but if they are any of those three, then save the letter to a variable P. So if I press A, which is 41, then P=41.

Disable button when touched for certain amount of time

I want a button, that gets disabled for a certain amount of time when it is touched.

I am trying to get this done with an if statement

if //button is touched/tapped { //disable button for 30 seconds and then enable again } else { // button is enabled}

But all my if statements are not working. What shall I do? Also I do not want the user to reset the timer by simply relaunching the app, how do I manage to do that?

SQL IF ELSE WITH MULTIPLE SELECT STATEMENT

I want to optimize these SQL queries using if-else but how I should use it? . if this query result contain 'ALL'

SELECT
bdsubcategory.subcategoryID as ID,
bdsubcategory.subcategoryName as Name
FROM
phonebook.newsms_subscription
INNER JOIN bdsubcategory ON bdsubcategory.subcategoryID = newsms_subscription.subcategoryID
INNER JOIN newsms_client ON newsms_subscription.clientID =newsms_client.clientID
INNER JOIN newsms_person ON newsms_subscription.personID = newsms_person.personID
WHERE
newsms_subscription.isActive = 1 AND
newsms_person.personID = '856'

Then i want to query this

SELECT
bdsubcategory.subcategoryID as ID,
bdsubcategory.subcategoryName as Name
FROM
phonebook.newsms_subscription
INNER JOIN bdsubcategory ON bdsubcategory.subcategoryID = newsms_subscription.subcategoryID
INNER JOIN newsms_person ON newsms_subscription.personID = newsms_person.personID
WHERE
newsms_subscription.isActive = 1
GROUP BY subcategoryName
ORDER BY subcategoryName

otherwise take query1 result .

Subset condition within category in R

I'm using a survey dataset (ESS) that includes several countries per wave, and several individuals within each wave. It looks something like this:

Country Wave
AT 1
AT 1
AT 1
AT 2
AT 3
AT 3
AT 4
AT 4
AT 5
AT 6
AT 7
AT 8
AT 9
AT 9
BE 1
BE 2
BE 2
BE 3
BE 4
BE 5
BE 6
BE 7
BE 7
BE 9
BE 9

I would like to filter/subset the data to get a new clean dataframe that includes only countries that are included in all of the waves, which range from 1 to 9. In other words, I would need to select countries based on the condition that they have observations in all 9 waves. In the example above, only "AT" would be selected as "BE" is missing wave #8.

This sounds rather straightforward but I am struggling to find a simple way to go about it (likely due to the fact that I am new in R).

Many thanks for your help.

If condition in pandas dataframe and matiching two columns and updating a new column based on condition [duplicate]

I am trying to write a condition check for tagging Technical terms. I have used a dictionary to look up to and do a fuzzy match. My dataframe is something like this-

   Word      Entity     Score   Tag     technology  similarity
Stonetrust      CRR     0.90     MISC    xxx         90
Wilkes          CRR     0.80     ORG     xxx         60
linux           xxx     0.70     LOC     xxx         70
SILVER  INC     xxx     0.88     PER     xxx         80
PO BOX 988      xxx     0.99    MISC     xxx         70
LA 70520        xxx     0.67     PER     xxx         50
02/12/2019      xxx     0.23     MISC    xxx         100

I need to check for below condition and create a new column with final tags-

  1. if similarity score = 100 then final_tag = TECH
  2. if Tag = MISC and similarity score >=95 then final_tag = TECH

To do this I did wrote below code

df['new column name'] = df['column name'].apply(lambda x: 'value if condition is met' if x condition else 'value if condition is not met')
df1['Final_NER'] = df1['similarity'].apply(lambda x: 'TECH' if x == 100 else df1['NER_Tag'])
df1['Final_NER'] = df1['similarity'].apply(lambda x: 'Tech' if df1['NER_Tag'] == MISC and if x >= 95 else df1['NER_Tag'])

I am not getting correct output and getting below error-

AttributeError: 'builtin_function_or_method' object has no attribute 'get_indexer'

dimanche 27 juin 2021

check the value of a String in if statement [duplicate]

As you know, a real interval is a set of real numbers that contains all real numbers lying between any two numbers of the set. I'm writing a program to calculate the Intersect and Union of two intervals. The interval can be (-∞,n) or it can be (n1,n2). For simplification, the user only needs to type "-" instead of "-∞". In a part of my program, I put an if statement to declare if the interval starts with a number or "-". Here's my code:

import java.util.Scanner;

public class myProgram {

    public static void main(String[] args) {
        Scanner s1 = new Scanner(System.in);
        System.out.println("Please type in your first interval:");
        String i1 = s1.next();
        String i1s = i1.substring(1, i1.indexOf(','));
        if(i1s != "-") {
            int e = Integer.parseInt(i1s);
            System.out.println("e = " + e);
        } else if (i1s == "-") {
            System.out.println("i1s = " + i1s);
        }
    }

}

My input is: (-,8) and I see this Error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "-"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
    at java.base/java.lang.Integer.parseInt(Integer.java:642)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at myProgram.main(myProgram.java:11)

It seems like the if statement doesn't work correctly... but why?

Tableau SUMIF statement

I have a dataset of movies with the amount of views per day, I want to sum total views per movie and I am doing the following:

SUM(IF [Title] = [Title]
    THEN [Views]
    END)

But is not giving me the right numbers, can anyone please help me?

Where do I mess up with boxplot in a for function?

I am fairly new to R (I am student) and I need to make an algorithm that returns the lowest outlier for each numeric (or integer) variable. If the variable does not have an outlier, it should return the string “Nooutliers”. If the variable is not numeric, it needs to print the most common value. I started it this way:

for (n in seq_along(london)) { 
  if  (class(london[[n]]) == "numeric") { 
    out <- boxplot.stats(london[[n]])$out

but this way it messes up when I try to paste the informations at the end. I did not find any other good way for this ( to find it for columns, select the minimum value and so on.) Is there some other way I should do it or did I just mess it upp?

If else function not consistently working

I cannot get this if/else to replace more than one row of of the column at a time. I have tried

spreadSheet.getRange(2, 38, 4000)

spreadSheet.getRange(2, 38, spreadSheet.getLastRow()-1)

and

spreadSheet.getRange(2, 38, sheet.getMaxRows())

It's not returning anything if it's not set up like below (and that only returns one cell.

function calculateHitPoints(){
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1");
var setHP = spreadSheet.getRange(2, 38).getValues();

if(setHP == "Fighter"){
spreadSheet.getRange(2, 38).setValue("14");
}
else if(setHP == "Ranger"){
spreadSheet.getRange(2, 38).setValue("13");
}

}

How to append a column value to a list based on another column's condition from a dataframe (Python)?

I'm performing a classification task so out of all my features, I'd like to plot only BB against DD (see snippet of image). However, if the 't' value = 0, I'd like the data points to be yellow and if the 't' value = 1, I'd like the data points to be blue.

enter image description here

To accomplish this, I tried the following:

BB_0 = []
BB_1 = []
DD_0 = []
DD_1 = []
for i in range (len(data)):  #'data' is my dataframe
    if (data['t']==0):
        BB_0.append(data[BB]) # I'd like to append the vlaue of BB to BB_0 when 't'=0
    else:
        BB_1.append(data[BB])

# Then, I'd plot BB_0 and DD_0 using one color and BB_1 and DD_1 using another color. 

However, when I run this, it gives me a syntax error at the if statement. Is there an easier way to accomplish this?

setting state with if else

long time listener, first time caller. I am not a developer, but trying to make a useful program for myself and some colleagues. The app is used to display pdf's that I have saved on firebase, but I want the UI to vary based on if the file has been downloaded or not. The pdf would be displayed on a card with options to view online or download, while a second car would have options to view, share, and delete. To do this I am trying to use an if else after a check if the file exists. But I don't really know how to manipulate the set state to change my isDownloaded variable to alter the state. Here is the code snippet that I'm working with, I don't get an error, just the isDownloaded state never changes unless hardcoded. localPath is a variable for the local documents directory. Thanks for the help with this!

class RefCardType extends StatefulWidget {
  const RefCardType(
  {Key? key,
  required this.urlPath,
  required this.fileName,
  required this.page,
  required this.title,
  required this.cardTitle,
  required this.cardSubTitle})
  : super(key: key);
   final String urlPath;
   final String fileName;
   final int page;
   final String title;
   final String cardTitle;
   final String cardSubTitle;

   @override
   _RefCardTypeState createState() => _RefCardTypeState();}

class _RefCardTypeState extends State<RefCardType> {
  void checkFile() async {
  File file = File('$localPath/${widget.fileName}');

  if (await file.exists() == true) {
  setState(() {
    isDownloaded = true;
  });
  {
    setState(() {
      isDownloaded = false;
    });
   }
  }
 }

bool isDownloaded = true;

@override
 Widget build(BuildContext context) {
  if (isDownloaded == true) {
  return refFileCard(context,
      urlPath: widget.urlPath,
      fileName: widget.fileName,
      page: widget.page,
      title: widget.title,
      cardTitle: widget.cardTitle,
      cardSubTitle: widget.cardSubTitle);
   } else {
   return refUrlCard(context,
      urlPath: widget.urlPath,
      fileName: widget.fileName,
      page: widget.page,
      title: widget.title,
      cardTitle: widget.cardTitle,
      cardSubTitle: widget.cardSubTitle);
   }
  }
 }

how can I write a code in python using if condition doing this tips :

If n is odd, print Weird If is even and in the inclusive range of 2 to 5, print Not Weird If is even and in the inclusive range of 6 to 20 , print Weird If is even and greater than 20, print Not Weird

I have a problem with an if an else statement, and I need help for if a condition is not met, to stop the entire program

Whenever I run the following code, the outcome is always an if statement outcome, even if its meant to be for else. For example, I am asking the user to enter the unlocking charm (in Harry Potter), and if they do so, they can proceed with the rest of the quiz, but if they fail to do so, the quiz does not come up and they cannot complete the rest of it. However, in my program even if the person has done the wrong spell, they get a message saying good luck on the quiz and the quiz starts for them. How do I make it that if the person enters the wrong spell, the quiz ends for them, and they get a message telling them they failed the quiz instead of giving them luck on completing it. This is the piece of code that I have written and i can not find out where the issue is.

revealingcharm = input("Enter the unlocking charm to reveal the quiz:")

if revealingcharm == "alohomora": print ("Here is one bottle of Felix Felicis for luck.") else: print("You failed to reveal the quiz and have no quiz to complete.") (exit)

Use Table Header as Content In a Cell

Can someone please help me with using the column header titles as the comma separated content in another cell. I am using Excel 2016. I have a table named StudentCourse and for a better illustration please see the below example layout:

[Name]     [Math]     [Geo]     [Bio]     [Fees]     [Fixes]
Ram         Very Bad   Neutral   Bad       Yes        Urgent: Math, Geo, Bio, Fees
Dam         Neutral    Good      Neutral   No         Urgent: Math, Bio
Rik         Good       Good      Good      No         OK: Not Urgent
Nik         Good       Good      Good      Partial    Urgent: Fees

The values for the subject columns are from a drop down menu which has the options Good, Neutral, Bad and Very Bad and if the values Neutral, Bad or Very Bad are selected then the Fixes column will be updated with the prefix Urgent: and the column header name (Math, Geo or Fees) depending on what needs to be fixed. If, no fixes are needed then the Fixes column's value will be Ok: Not Urgent. The Fees column also follows the same concept and if No or Partial is selected from the Fees column dropdown options then likewise that will be added to the fixes column.

I would greatly appreciate any assistance at all.

I should also mention that I am new to Excel.

(Julia) Not able suppress output using semicolon when assigning variable inside an IF statement

Assigning variable to dataframe output with semicolon does not suppress the display inside an IF statement.

Mastermind Python

Im currently working on an assignment of mastermind mini game on python, but for the code below, when i try to run it, it shows that the first line of my if statement ":" invalid syntax, but in previous lines i had something similar too but that didn't face any problem

     while True:
        try_again = str(input('Do you want to try again?[Y/N]: ')
        if try_again.lower() == 'y':
            print('Alright ', user_name, " let's try again!")
            break

        elif try_again.lower() == 'n':
            break

        else:
            print("Sorry, I don't understand, please type Y/N")
            continue

Why is my do while loop only happening once? [duplicate]

I wrote a do while loop and there is are if else statements that determine if the loop happens again. The problem is the loop is not happening again when it is supposed to.

    public static void checkGuestOut(Scanner console, String[] guestLog, String guestName) {
        int capsuleNumber;
        boolean availableCapsule = true;
        do {
            System.out.println("Let's get the guest checked out!");
            System.out.print("What is the guest's capsule number? ");
            capsuleNumber = Integer.parseInt(console.nextLine());
            if (guestLog[capsuleNumber-1].equalsIgnoreCase("[unoccupied]")) {
                System.out.println("That room is not occupied.");
                availableCapsule = false;
            }
            else{
                System.out.printf("%s is now checked out of capsule number %s.", guestName, capsuleNumber);
                guestLog[capsuleNumber - 1] = "[unoccupied]";
                availableCapsule = true;
            }
        } while(availableCapsule = false);
    }

Showing lowest outliers

I'm currently looking to return the lowest outlier in my dataset and when there is no outlier the script should return "No outliers". The problem is I get an error message "Error in vec_minout[[n]] <- paste(names(london[[n]]), outs, outlier, sep = ", ") : more elements supplied than there are to replace"

Any help?

vec_minout <- NA

for (n in seq_along(london)) { 
  if  (class(london[[n]]) == "numeric") {
   outs <- boxplot(london[[n]], plot=FALSE)$out
    outlier <- min(london[[n]], na.rm = TRUE)
    vec_minout[[n]] <- paste(names(london[[n]]), outs, outlier, sep = ", ") 
  }
  else {
    vec_minout[[n]] <- tail(names(sort(table(london[[n]]))), 1, )

   
    
  }
}

vec_minout

How to use SPSS if condition for various variables?

Here the variable V4_15 is corralated to V4_15_0, V4_15_1, V4_15_2, V4_15_3, V4_15_4, V4_15_5, V4_15_6, V4_15_7.

If any of those later variables is 0 then V4_15 is 0 (Absent) and if any of those variables is 1 then V4_15 is 1 (present).

Any idea how can I do this using Transform > Compute variable?

I am a beginner level user. enter image description here

A section of code loops itself before proceeding

I just figured out a way to remember the users last menu selection by utilizing a Python list, but after implementing and running it, after the code has cycled through once, I choose an option from the menu and it loops itself once then proceeds as normal.

To begin with, I thought it might have to do with the python list needing to bear cleared, but I tried thislist.clear() and no luck. Then, I thought it had to do with the number input variable needing to be used in the main section of the code, however it did not work. Unfortunately, I have had no further inspiration of what it could be, so your help would be greatly appreciated, please!

Here is my code:

import random 
global thislist
thislist = []

def menu(): 
    print(""" 
Which account would you like to access? 
            
            1. Balance 
            ----------    
            2. Savings 
            ----------""")    
    number = int(input("\nEnter option: ")) 
    return number

def balance(): 
    while True: 
        try:
            while True: # not sure why but this works 
                print("""
What would you like to do?
                        
            1. View
            ---------
            2. Update
            ---------""")
                selected_option_01 = int(input("\nEnter option: "))
                if selected_option_01 == 1:
                    view_bal = open("current_balance.txt", "r")
                    print("\nBalance: " + view_bal.read())
                    view_bal.close()
                    thislist.append("balance")
                    break
                elif selected_option_01 == 2: 
                    new_bal_entry = input("\nEnter amount: ") 
                    bal_file = open("current_balance.txt", "r") 
                    existing_val = bal_file.read()
                    bal_file = open("current_balance.txt", "w")
                    if existing_val != "":
                        val = float(new_bal_entry) + float(existing_val)
                        bal_file.write(str(val) + "\n")
                    else:
                        bal_file.write(new_bal_entry)
                    bal_file = open("current_balance.txt", "r")
                    print("New balance: " + bal_file.read())
                    bal_file.close()
                    break
                elif selected_option_01 >3: 
                    print("\n######      Not an option. Try again.      ######")
                    continue 
        except ValueError: 
            print("\n######      Not an option. Try again.      ######")
            continue
        finally: 
            add_trans()
        break

def savings():
    while True: 
        try: 
            print("""
What would you like to do?
          
            1. View
            ---------
            2. Update
            ---------""")
            select_option_02 = int(input("\nEnter option: "))
            if select_option_02 == 1:
                view_savings = open("current_savings.txt", "r")
                print("\nBalance: " + view_savings.read())
                view_savings.close()
                thislist.append("savings")
                break
            elif select_option_02 == 2: 
                new_savings_entry = input("\n" + " Enter figure: ") 
                savings_file = open("current_savings.txt", "r")
                existing_savings = savings_file.read()        
                savings_file = open("current_savings.txt", "w")         
                if existing_savings != "":
                    savings_val = float(new_savings_entry) + float(existing_savings)
                    savings_file.write(str(savings_val) + "\n")
                else: 
                    savings_file.write(new_savings_entry)        
                savings_file = open("current_savings.txt", "r")
                print("\nNew savings: " + savings_file.read())
                savings_file.close()
                thislist.append("savings")
                break    
            elif select_option_02 >3: 
                print("\n######      Not an option. Try again.      ######")
                break
        except ValueError: 
            print("######      Not an option. Try again.      ######")
            continue 
        finally: 
            add_trans()
        break             
    
def add_trans(): 
    while True:
        try: 
                print("Would you like to do anything else?")
                print("""   
            1. Menu
            ----------------------
            2. Another transaction
            ----------------------
            3. Quit
            ----------------------""")
                more_trans = int(input("\n" + "Enter option: "))
                if more_trans == 1:   
                    menu()
                elif more_trans == 2:
                    if "balance" in thislist:
                        balance()                        
                    elif "savings" in thislist:
                        savings()
                elif more_trans == 3:
                    print("\nTransaction ID:", random.randint(0,9999))
                    break
                else:
                    print("\n######      Not an option. Try again.      ######")
                    continue
                break
        except ValueError:
            print("######      Not an option. Try again.      ######")
            continue 

while True: # main code that decides where user needs to go (this is where it is looping)
    try:
        option_chosen = menu()
        if option_chosen == 1:
            balance()
        elif option_chosen == 2: 
            savings()
        else: 
            print("\n######      Not an option. Try again.      ######")
            continue
    except ValueError:
        print("\n######      Not an option. Try again.      ######")
        continue
    break

The range() function not indices for items sequence [closed]

When I use the range() function between two values, it is not generated the sequence. range(5, 10) Returned range(5, 10)

how to shift english characters but NOT any other character in python

I'm trying to shift every english character by 2, but leave any other character(such as !, *, ^, etc) just the way it is. However, my code keeps on shifting all characters, why?

Here's my code:

sample = 'abcdefghijklmn-op+qr!stuvwxyz'

shift = 2

result = []

for i in range(len(sample)):
    print(f'ascii code of {sample[i]} is: {ord(sample[i])}')

print('#######################################')
ascii_code = 97

for j in range(len(sample)):
    if 96 < ord(sample[i]) < 123:
        ascii_code = ord(sample[j])
        ascii_code += shift
        if ascii_code > 122:
            ascii_code = ascii_code - 25 - 1
        
        print(f'Converted value: {chr(ascii_code)}')
    

Expected Output

ascii code of a is: 97
ascii code of b is: 98
ascii code of c is: 99
ascii code of d is: 100
ascii code of e is: 101
ascii code of f is: 102
ascii code of g is: 103
ascii code of h is: 104
ascii code of i is: 105
ascii code of j is: 106
ascii code of k is: 107
ascii code of l is: 108
ascii code of m is: 109
ascii code of n is: 110
ascii code of - is: 45
ascii code of o is: 111
ascii code of p is: 112
ascii code of + is: 43
ascii code of q is: 113
ascii code of r is: 114
ascii code of ! is: 33
ascii code of s is: 115
ascii code of t is: 116
ascii code of u is: 117
ascii code of v is: 118
ascii code of w is: 119
ascii code of x is: 120
ascii code of y is: 121
ascii code of z is: 122
#######################################
Converted value: c
Converted value: d
Converted value: e
Converted value: f
Converted value: g
Converted value: h
Converted value: i
Converted value: j
Converted value: k
Converted value: l
Converted value: m
Converted value: n
Converted value: o
Converted value: p
Converted value: -
Converted value: q
Converted value: r
Converted value: +
Converted value: s
Converted value: t
Converted value: !
Converted value: u
Converted value: v
Converted value: w
Converted value: x
Converted value: y
Converted value: z
Converted value: a
Converted value: b

Code Output

ascii code of a is: 97
ascii code of b is: 98
ascii code of c is: 99
ascii code of d is: 100
ascii code of e is: 101
ascii code of f is: 102
ascii code of g is: 103
ascii code of h is: 104
ascii code of i is: 105
ascii code of j is: 106
ascii code of k is: 107
ascii code of l is: 108
ascii code of m is: 109
ascii code of n is: 110
ascii code of - is: 45
ascii code of o is: 111
ascii code of p is: 112
ascii code of + is: 43
ascii code of q is: 113
ascii code of r is: 114
ascii code of ! is: 33
ascii code of s is: 115
ascii code of t is: 116
ascii code of u is: 117
ascii code of v is: 118
ascii code of w is: 119
ascii code of x is: 120
ascii code of y is: 121
ascii code of z is: 122
#######################################
Converted value: c
Converted value: d
Converted value: e
Converted value: f
Converted value: g
Converted value: h
Converted value: i
Converted value: j
Converted value: k
Converted value: l
Converted value: m
Converted value: n
Converted value: o
Converted value: p
Converted value: /
Converted value: q
Converted value: r
Converted value: -
Converted value: s
Converted value: t
Converted value: #
Converted value: u
Converted value: v
Converted value: w
Converted value: x
Converted value: y
Converted value: z
Converted value: a
Converted value: b

How can I fix this? It's strange to me how the code shifts -, +, ! despite the conditions.

How `(1U << 1) | (1U << 5)` is different from `0x22`?

Would someone please explain me how having the same value VAL1 and VAL2 behave differently? For the first if statement VAL1 is equal to zero? Thanks!

#include <stdio.h>

#define VAL1 (1U << 1) | (1U << 5)
#define VAL2 0x22

int main()
{
    printf("VAL1: %d\r\n", VAL1);
    printf("VAL2: %d\r\n", VAL2);

    if (VAL1 == 0)
    {
        printf("TRUE 1\r\n");
    }

    if (VAL2 == 0)
    {
        printf("TRUE 2\r\n");
    }

    if (VAL1 == VAL2)
    {
        printf("TRUE 3\r\n");
    }
}

Output:

VAL1: 34
VAL2: 34
TRUE 1
TRUE 3

Checking for an empty string and a value in it in a mysql query on php

Good afternoon, dear experts. I have a sql request for php

$id = 10;
$row = $db->super_query( "SELECT * FROM " . PREFIX . "_news WHERE id = '{$id}'" );

I have two cells in the db - allowed_countries and notallowed_countries. How do I add conditions to the request so that it works like this:

(if allowed_countries not empty and allowed_countries == 'en' then show result of query, else if allowed_countries is empty then show result of query) AND (if notallowed_countries not empty and notallowed_countries != 'fr' then show result of query, else if notallowed_countries is empty then show result of query)

$id = 10;
$allowed_countries = 'en';
$notallowed_countries = 'fr';
    $row = $db->super_query( "SELECT * FROM " . PREFIX . "_news (if allowed_countries not empty and allowed_countries == '{$allowed_countries}' then
show result of query, else if allowed_countries is empty then show
result of query) AND (if notallowed_countries not empty and
notallowed_countries != '{$notallowed_countries}' then show result of query, else if
notallowed_countries is empty then show result of query) WHERE id = '{$id}'" );

Thanks for your answers and have a nice day.

How to print zigzag star pattern within the if-else using Java. I've been trying but I couldn't figure it out

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

for(int i=1;i<=4;i++){
    System.out.print("*");
} 
System.out.println("");


for(int j=1;j<=4-2;j++)
{
   for(int i=1;i<=4;i++)
   {
    if(i==1 || i==4) 
      {
 System.out.print("*");           
      } 
      else 
      {
       System.out.print("");
       }
      } 
      System.out.println();
     } 
 
 
 for(int i=1;i<=4;i++){
       System.out.print("*");
  } 
  System.out.println();

} 

}

My Output:


** **


I badly need to know how to get this Expected Output:


** **


samedi 26 juin 2021

C# Path.GetExtension 'If' Statement

My previous question was closed due to the fact that there are supposedly tied to Path.GetExtension.

Apparently, you may be able to get a file extension by Open Dialog using this function, however, may I know how to use Path.GetExtension in 'If' Statements/ 'If Statement'-like functions?

// SAMPLE CODE 1
OpenFileDialog1.Filter = "Image Files (JPG,PNG,GIF)|*.JPG;*.PNG;*.GIF";


// SAMPLE CODE 2
if (OpenFileDialog1.ShowDialog() == DialogResult.OK)
   string ext = Path.GetExtension(OpenFileDialog1.FileName); 



// SAMPLE CODE 3
if(DialogResult.OK == saveDialog.ShowDialog())
{
    var extension = Path.GetExtension(saveDialog.FileName);

    switch(extension.ToLower())
    {
        case ".jpg":
            // ToDo: Save as JPEG
            break;
        case ".png":
            // ToDo: Save as PNG
            break;
        default:
            throw new ArgumentOutOfRangeException(extension);
    }
}

So in this case, how can this code be organized as to create if statements for different file extensions?

Function with a nested loop in R

I'm trying to write a function that returns "Fail" if all 3 valves at a given location (x) are open (1), but returns "Pass" if any valve is closed (0). My code is below, but it doesn't work and I get the error---unexpected 'else' in:"else"--- And I can't figure out where my code is wrong.

systemFail <- function(x) {
  
if(df$valveOne[df$location == x] == 1) {        
    if(df$valveTwo[df$location == x] == 1) {  
      if(df$valveThree[df$location == x] == 1) {
        print("Fail")}}}
      else {            
        print ("Pass")}
    else {            
    Print("Pass")}
else {
  Print("Pass")}
}

The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() on this "==" operator Python Pandas

I have a script like this

if vms2['STATUS'] == 1:
    vms2['entry']=vms['STATUS']+vms2['status_after']
else :
    vms2['entry']=vms['STATUS']+vms2['status_before']

it shows error like this:

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

I am new in Python, so I can'f figured the source of the error. Please help.

Excel 2016 - Combing Several Colum Titles as Comma Separated Values in a Cell

Please help me someone! I would like to use the column header titles as 'the comma separated value' content in another cell. For a clear example please see the below table structure:

[Name]     [Breathing]     [Posture]     [Health]     [Correction(s)]
Roy         Bad             Bad           Bad          Breathing, Posture, Health
Pam         Good            Good          Bad          Health
Joy         Good            Good          Good         None
Sam         Good            Bad           Good         Posture

I tried using if conditions but I could only get it to fill in the value for a single column. I need to read the values across multiple columns. These value(s) will then be used as the comma separated content for another cell. If only one correction is needed in terms of the 'Breathing, Posture, Health' for those column headers then the 'Correction(s)' column value for that row will be the column name with the bad value. I read up about visual basic code solutions but that will not work on the excel online browsers version, which I need for team collaboration.

Any feedback at all will be greatly appreciated, because I am sort of new to excel.

Thank you in advance.

Create a dictionary using "if... else" in Julia?

I'm working with a sample CSV file that lists nursing home residents' DOBs and DODs. I used those fields to calculate their age at death, and now I'm trying to create a dictionary that "bins" their age at death into groups. I'd like the bins to be 1-25, 26-50, 51-75, and 76-100.

Is there a concise way to make a Dict(subject_id, age, age_bin) using "if... else" syntax? For example: (John, 76, "76-100"), (Moira, 58, "51-75").

So far I have:

#import modules
using CSV
using DataFrames
using Dates

# Open, read, write desired files 
input_file = open("../data/FILE.csv", "r")
output_file = open("FILE_output.txt", "w")

# Use to later skip header line
file_flag = 0

for line in readlines(input_file)
    if file_flag==0
        global file_flag = 1
        continue
    end

    # Define what each field in FILE corresponds to
    line_array = split(line, ",")
    subject_id = line_array[2]
    gender = line_array[3]
    date_of_birth = line_array[4]
    date_of_death = line_array[5]

    # Get yyyy-mm-dd only (first ten characters) from fields 4 and 5:
    date_birth = date_of_birth[1:10]
    date_death = date_of_death[1:10]

    # Create DateFormat; use to calculate age
    date_format = DateFormat("y-m-d")
    age_days = Date(date_death, date_format) - Date(date_birth, date_format)
    age_years = round(Dates.value(age_days)/365.25, digits=0)

    # Use "if else" statement to determine values
    keys = age_years
    function values()
        if age_years <= 25
            return "0-25"
        elseif age_years <= 50
            return "26-50"
        elseif age_years <= 75
            return "51-75"
        else age_years < 100
            return "76-100"
        end
    end
    values()

    # Create desired dictionary
    age_death_dict = Dict(zip(keys, values()))

end 

This is a program to search a number and also display its index position if found in an array

This is a C++ program to search a number and also display its index position if found in an array.
Program works fine. I just wanted to ask why we used k=1 in if statement because if we don't use it, then program won't work. Please explain the significance of k=1 in 2nd for loop in if statement.

#include<iostream>
using namespace std;
int main(){
int n;
cout<<"Size of Array: ";
cin>>n;
int arr[n];
cout<<"Type Elements of Array: ";
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
int k;
cout<<"Enter No to be found: ";
cin>>k;
for(int i=0; i<n; i++)
{
if(arr[i]==k)
{
    k=1;
    cout<<"No is found at index position: "<<i<<endl;;    
    break;
}
else
{
    cout<<"No is not found"; 
    break;   
}
}
return 0;
}

I can't get the value of interest_rate in the if else [closed]

Variable 'interest_rate' might not have been initialized Write a program Loan Calculator that input customer name, principal loan, term or period. Compute the interest per annum, total interest, the total payable loan and the monthly amortization.

Rate     Interest Rate
1-3 year 6.500%
5 year   7.270%
10 year  8.035%
15 year  8.585%
20 year  8.800%
25 year  9.050%
import java.util.Scanner;

public class Assessment15 {

    public static void main (String [] args){

        String sname;
        double p_loan,term,interest_rate,interest_per_annum,t_interest, amortization;

        Scanner sc = new Scanner(System.in);
        System.out.println("Customer name:");
        sname = sc.nextLine();

        System.out.println("Principal loan:");
        p_loan = sc.nextDouble();

        System.out.println("Term or period");
        term = sc.nextInt();

        if (term >= 1 && term <= 3 ) {
            interest_rate = 6.500;
        }else if (term >= 4) {
                interest_rate = 7.270;
        }else if (term >= 10) {
            interest_rate = 8.035;
        }else if (term >= 15) {
            interest_rate = 8.585;
        }else if (term >= 20) {
            interest_rate = 8.800;
        }else if (term >= 25) {
            interest_rate = 9.050;
        }

        interest_per_annum = interest_rate / term;


        t_interest = p_loan * interest_rate;
        amortization = (p_loan + interest_rate) / term;
        System.out.println("Customer Name: " + sname);
        System.out.println("Interest per annum: " + interest_per_annum);
        System.out.println("Total payable loan: " + term / interest_rate );
        System.out.println("Monthly amortization: " + amortization );
    }

}

Best way to replace empty userinput with 0

I have three userinputs which takes any number. If a user leaves an input empty then clicks the submit button I would like that input to return 0.

What would be the best way to handle this?

I have created an if statement that individually looks for if input 1 or input 2 or input 3 is empty, but what if input 1 and 2 are empty or if input 3 and 1 are empty, this will lead to quite a long if statement

I wanted to know what would be the best way to go about solving this?

*.js

If( hours === 0  ){
hours = 0
}else if ( minutes === 0 ){
minutes = 0
}else if ( seconds === 0 ){
seconds = 0
}
// more if statement with different combination of minutes seconds and hours being 0

finding occurences of each element in an array and aranging them according to the count of occurences in ascending or descending order

Q)Given an array of N elements.find the number of occurences of each character and print it in the decreasing order of occurences, if 2 or more number occurs the same number of times, print the numbers in decreasing order. Input Size : |N| <= 100000 Sample Testcase : INPUT 3 3 4 4 7 8 OUTPUT 4 3 8 7

--------------------------------------------------

i was able to convert it to map ,what further steps should i implement to get the answer

--------------------------------------------------

function asc(arr) 
{
let map=new Map
 let c=1;
  for(let i=0;i<arr.length;i++){
if(map.has(arr[i])){
  map.set(arr[i],map.get(arr[i])+1)
 }
else{
       map.set(arr[i],c)
    }
  }
let narr = [...map];
let tmp;
for(i=0;i<narr.length;i++){
  for(j=i+1;j<narr.length;j++){
    if(narr[i][1]>narr[j][1])
{
  tmp = narr[i];
  narr[i]=narr[j];
  narr[j]=tmp;
}
else if((narr[i][1]=narr[j][1])) {
    if(narr[i][0]>narr[j][0])
{      
  tmp = narr[i];
  narr[i]=narr[j];
  narr[j]=tmp;
      }
}
  }
}
return narr;
}
arr=[3,8,7,4,7,3,4];
console.log(asc(arr)); 

Having problems understanding following simple algorithm

public class Test1 {
    public static void main(String[] args) {
        
        int number = 0;
        for(int i=0; i<5; i++){
            if(number != 0){
            number = i * number;
            }
            else {
             number = i;
            }
            }

        System.out.println(number);
    }
}

I'm not quite sure how this algorithm works. My thought process is:

  1. We set the number to 0 by default.
  2. In the for loop we are just saying, continue counting i till it's no longer smaller than 5.
  3. We say that if the number isn't 0, we update the number by multiplying it with i. So in our case, i is 0,1,2,3 and 4, or am I missing something?
  4. Else we are saying the number is I and "i" is what we were counting?
  5. Last we print number.

If I run this code why do I get 24 as output? I don't know how this simple algorithm works.

find field between two documents with condition in python

   def method(class, doc): # read and fetch data from coll1 and get required fields
        id = doc['id']
        type = doc['type']
        startdate = doc['startDate']
        endDate = doc['endDate'])
        match = class.mongo_db['coll2'] # match fields in coll1 and coll2 and fetch data from coll2
        tar_value = sag.find({'id': id, 'type': type,'startDate':{'$lte': startdate},'endDate':{'$gte': endDate}})
        target = []
        for tar_value1 in tar_value:
            target.append(tar_value1)
        if len(target) == 1:
          ---------------
          ----------
          ----
          --
        else:
          skip

      
      
      

i need to match data from both collections and fetch required data, if two documents got fetched from coll2 then we need to skip else proceed am sucessful in this with out having an issue if coll2 has proper 'endDate' to match, but in some senarios the the 'endDate' would be 00 then i need to consider it has 20500202(IF end data was 00) how can i do this in above mongo find querry,am unable to achive this if 'endDate' is 00

for ex- if enddate of coll1 is 20210303 and end date od coll2 is 00 then we should consider it as (20500202 > 20210303) not (00 > 20210303)

Php while loop ends after continue

I have problem with my script. I need send mail when my $sended variable is set on 0, if is set to 1 than i need to ignore this statemant

<?php
while ($result = $pdo->fetch(PDO::FETCH_ASSOC)) {

        if($result['howMany'] == "0") {
          if ($sended == "0") {
            //send mail to admin with info that product was end.
            //this is work fine
            if($mail->send()) {
              //change in my database variable $sended to 1;
              //this is work fine to.
              //if i live it empty, it is work, but if I change $sended to 1, it is not working
            }
          }
          // if variable $result['howMany'] is equal to 0 than i need to end this iteration of while loop.
          continue;
        }

        //rest of script that should work when $result['howMany'] != "0"
}
?>

Problem is when $sended variable is set to 0, continue is ending whole loop not only this one iteration. When $sended == 1, than everything is working just fine. Continue work fine. What do I do wrong? Where's error because i dont see it. Sorry for my english. It is not my native language.

How to declare the Type of a variable dynamically in GO, using if-else-like conditions?

Given two types

type A struct {
    ID         string
    Content    []int
}

and

type B struct {
    ID         string
    Content    map[string][]int
}

and I need a function to tell me which type to use hereafter according to conditions (the purpose is to unmarshal a json string properly). I want a function like

func assign_typed_data(header string) interface{} {
    switch header {
    case "A" :
         d := new(A)
         fmt.Printf('inner type is %T \n', *d)      // inner type is A
         return *d
    case "B" :
         d := new(B)
         fmt.Printf('inner type is %T \n', *d)      // inner type is B
         return *d
    default:
    }
}

and in the outer code I can call it and unmarshal the json like follows, but the returned value turns to "map[string]interface{}".

header := "A"
data := assign_typed_data(header)
fmt.Printf('outter type is %T \n', data)      // outter type is map[string]interface{}
json.Unmarshal(json_data, &data)

I also tried simple if-else statements in the outter code directly without calling a function, like follows, but failed as well because of defined scope is local.

if header == "A" {
    data := *new(A)
}else if header == "B" {
    data := *new(B)
}
json.Unmarshal(json_data, &data)

Is there a possible way to achieve this goal in GO?

Why is the objects underlined when I define them in an if statement?

I don't know why my code is not working

enter image description here

vendredi 25 juin 2021

what is the scope of string Variable in a JAva Method? [duplicate]

I have a simple Java method here Below , which passes a string , but inside the method another string variable is to be assigned a value. But its not assigning new value- based on the String Input. Instead returning "NA".

Kindly have a Look and help me find the fault in the code. Suppose if h is "NRM" even then aId = "NA", not "01"

 private static String getAID(String h) {

    System.out.print("AId : 01 to 25 for "+h);     
     String aId = "NA";
     if(h == "NRM") {
        aId= "01";
        System.out.print("inside Nrm of fn"+aId);
     } 
     Scanner scanner = new Scanner(System.in);
     if(h=="EPB") {
            System.out.print("Emergency ON/OFF press 1 or 0  - ");
             String in= scanner.next();
             if(in == "0") aId="11";
             else if(in=="1") aId="10";
             else { aId="10";}           
        }
     if (h=="CRT") {
            aId="16";
            System.out.print("Critical Alert Enter 16/03/17/22/23/20/21 - ");
            String in= scanner.next();
            String[]  arr = {"16","03","17","22","23","20","21","13","14","15","06","04","05","09","18","19"};
            for(String i : arr) {
                if( i.equals(in) ) aId=in;
            }   //aId="04";   
    }
    if(h=="BTH" || h=="ALT") {
            aId="13";
            System.out.print("AId Enter :/13/14/15/06/04/05/09/18/19 - ");
            String in= scanner.next();
            String[] arr = {"16","03","17","22","23","20","21","13","14","15","06","04","05","09","18","19"};
            for(String i : arr) {
                if( i.equals(in) ) aId=in;
            }               
    
    }
    switch(aId) {
    case "01":System.out.println("Normal 2"); 
        break;
    case "02":System.out.println("l History");
    // remaining cases

    // remaing cases //

    case "23":System.out.println("IMPACT"); 
    
    default: System.out.println(" Wrong Entry -is"+aId ); 
    }
    
    return aId;
    
}

Here when I checked , It s never Entering the If Statements at all... But instead entering default part of the Switch case and return aId = "NA" ;

IF Statement in File Input Loop

I trying to get the user to open a file on this assignment for school. Everything was going according to the instructions that my professor gave. But in this step: "To determine to which of the four files to write the data for the current student, use a decision structure (a series of if statements or a switch structure). Compare the variable storing the character representing the student’s major to each of the four values, one in each if statement or case. The statement executed for each if statement or case should be an output statement that uses the ofstream variable for the corresponding file and each of the five variables (excluding the major code character) to be written for the student." Basically, writing "if" statement in a "while" loop. Now the question is "WHAT GOES IN THE BOOLEAN EXPRESSION??!!" The professor did not specify what goes into the expression.

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main ()
{
  int gpa, studentnumber;
  string lastname, firstname;
  char middle, majorcode;
  ifstream cisdegree;
  ofstream appmajors, netmajors, progmajors, webmajors;

  cisdegree.open ("cisdegree.txt");
  if (cisdegree.fail ())
    {
      cout << "Error opening input file. \n";
      exit (1);
    }

  appmajors.open ("appmajors.txt");
  netmajors.open ("netmajors.txt");
  progmajors.open ("progmajors.txt");
  webmajors.open ("webmajors.txt");

  appmajors.setf (ios::fixed);
  appmajors.setf (ios::showpoint);
  appmajors.precision (2);

  netmajors.setf (ios::fixed);
  netmajors.setf (ios::showpoint);
  netmajors.precision (2);

  progmajors.setf (ios::fixed);
  progmajors.setf (ios::showpoint);
  progmajors.precision (2);

  webmajors.setf (ios::fixed);
  webmajors.setf (ios::showpoint);
  webmajors.precision (2);

  cisdegree >> studentnumber >> lastname >> firstname
    >> middle >> gpa >> majorcode;

  while (!cisdegree.eof ())
    {
      cisdegree >> studentnumber >> lastname >> firstname
    >> middle >> gpa >> majorcode;
      if (appmajors)
        {
            studentnumber << lastname << firstname
            << middle << gpa << "A";
        }

    }



  appmajors.close ();


  return 0;
}

Thanks in advance