Affichage des articles dont le libellé est Newest questions tagged if-statement - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Newest questions tagged if-statement - Stack Overflow. Afficher tous les articles

mercredi 8 décembre 2021

UI Button "if" statement in swift

when I type the code in, there is an error saying this:

picture of the error: https://i.stack.imgur.com/ixFaM.png

How can I fix it?

 @IBAction func nextQuestionButton(_ sender: Any) {
        if (nextQuestionButton.isSelected == true) {
            
        }

How do I write a Python Function to display a message to indicate the progress of an operation [closed]

The function should display a message in the following format: '{operation} {status}.'

Where {operation} is the value of the parameter passed to this function
and
{status} is 'has started' if the value of the parameter 'value' is 0
{status} is 'is in progress ({value}% completed)' if the value of the parameter 'value' is between,
but not including, 0 and 100
{status} is 'has completed' if the value of the parameter 'value' is 100

R: unexpected behaviour adding two if(){}else{} constructs

Consider the following R input:

if(TRUE){1}else{0} + if(TRUE){1}else{0}

The result is 1, but I was expecting 2. If I enclose each if-else statement in parentheses,

(if(TRUE){1}else{0}) + (if(TRUE){1}else{0})

then the result is 2.

Can someone explain this behaviour?

Change elevated button color via radio buttons in flutter

I want to change the Elevated button color when I press the radio buttons. 1.button -> red, 2.button -> yellow, 3.button -> green. In the Elevated.stylefrom if condition did not work. Just ternary condition works but it is only for one condition. I want to add 3 conditions. I hope it was clear.

Or do I need to create a model for this?

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:task_shopping_app/const/const.dart';
import 'package:task_shopping_app/screens/city_input_screen.dart';
import 'package:task_shopping_app/screens/weather.dart';

class RadioButton extends StatefulWidget {
  @override
  _RadioButtonState createState() => _RadioButtonState();
}

class _RadioButtonState extends State<RadioButton> {
  int selectedValue = 0;
  final enteredCityInfo = TextEditingController();
  String name = '';
  // if selectedValue and group value matches then radio button will be selected.
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          ButtonBar(
            alignment: MainAxisAlignment.center,
            children: <Widget>[
              Radio<int>(
                  value: 1,
                  groupValue: selectedValue,
                  onChanged: (value) => setState(() {
                        selectedValue = value!;
                        print(selectedValue);
                      })),
              Radio<int>(
                  value: 2,
                  groupValue: selectedValue,
                  onChanged: (value) => setState(() {
                        selectedValue = value!;
                        print(selectedValue);
                      })),
              Radio<int>(
                  value: 3,
                  groupValue: selectedValue,
                  onChanged: (value) => setState(() {
                        selectedValue = value!;
                        print(selectedValue);
                      })),
            ],
          ),
          Padding(
            padding: const EdgeInsets.all(25.0),
            child: TextField(
              controller: enteredCityInfo,
            ),
          ),
          ElevatedButton(
            onPressed: () {
              setState(() {
                name = enteredCityInfo.text;
                //Here we want to see user entry for the text field area in the debug console.
                print(name);
                // Get.to(() => WeatherScreen());
              });
            },
            child: Text('Create'),
            style: ElevatedButton.styleFrom(
              primary: selectedValue == 1 ? Colors.red : Colors.yellow,
            ),
          )
        ],
      ),
    );
  }
}

enter code here

C++ name format [closed]

I am new to C++ and would appreciate some guidance. Before I reveal the problem, let me emphatically state that I am looking for GUIDANCE, not an answer; having the answer given to me will not benefit me any! I know other people have asked similar questions on here, but the answers given included coding to which I have not been exposed yet- I'm not trying just to pass the class, I am taking this course to actually learn C++. Ok, here are the instructions:

Write a program whose input is:

firstName middleName lastName

and whose output is:

lastName, firstInitial.middleInitial.

My code is:

if (middleName.size() == 0 ) {
    cout << lastName << ", " << firstName[0] << "." << endl; }
else {
    cout << lastName << ", " << firstName[0] << "." << middleName[0] << "." << endl; }

I have the closing } and return 0; but didn't copy them. It works as expected when there is a middle name, but if there's not then it outputs this:

, t.d

My thinking was that if the middle name has no size, then it would output the last name and middle initial, but it does not. I tried outputting middleName.size() and keep getting zero, even if there is a middle name.

I appreciate any guidance, and know this is a long post, but I wanted to give as much info as I could.

mardi 7 décembre 2021

if else condition true it will run until it doesn't false, but when else condition is true it will run continuously until when it false

I have If - else condition,

High = [18365.5, 18979.25, 19297.4, 19874.8, 20288.0, 20504.65, 20398.2] 

Low = [17855.5, 18265.0, 18822.55, 18742.15, 19492.55, 20055.55, 20131.25] 

Close = [18317.05, 18969.95, 18857.6, 19804.0, 20260.15, 20285.0, 20215.7]

length = len(Close) - 1

i = 0
a = 1
Trend = ["No Trend"]
Difference = ["No Trend"]
while i<length:
    if Close[a] > Low[i]:
        trend = "Long"
        Trend.append(trend)
        difference = Close[a] - Low[i]
        Difference.append(difference)
    elif Close[a] < High[i]:
        trend = "Short"
        Trend.append(trend)
        difference = Close[a] - High[i]
        Difference.append(difference)
    i = i + 1
    a = a + 1
df = pd.DataFrame(list(zip(High, Low, Close, Difference, Trend, From_date, End_date)),
               columns =['High', 'Low', 'Close', 'Difference', 'Trend', 'From_date', 'End_date'])
display(df)

So i want if Close[a] > Low[i] condition is true so it will run continuously until it doesn't false, and when if condition will false so else Close[a] < High[i] condition start, so it will run continuously unitll it will not false.

I am showing you the below data frame, which will give you a clear-cut idea. enter image description here

In this Dataframe there are three columns which are High, Low, Close, and the rest of the columns are made by these three column.

So in if - condition is true so it's print "Long" continuously until It doesn't false, but when else condition start so else condition should run, and start checking this condition Close[a] < High[i]. until it doesn't false.

I'm trying my best to explain my question And Sorry, if my explanation is not good.

SQL: Is there a better way than "COALESCE on two selects" to find the first non-null result in an OR clause?

Let's say I have this table:

ID LANG NAME DEFAULT
1 ENG Cinderella false
1 ENG The Ash Bride false
1 FRE Cendrillon true
1 GER Aschenputtel false

("Ash bride" is just fabrication that the same ID can have several names in the same language) The SQL query should return the name in the wanted language, if it doesn't exist, the default language.

So a search for the book title if your settings are in German (GER), the result should be "Aschenputtel", but if your settings are Spanish, they should return "Cendrillon".

This question brings up the same issue, but the answer suggests a double join through the name list, one for "lang='[preferred]'" and one for the default value, with a COALESCE to find the first non-null result. I am worried this would cause performance issues if the names list is long, when there cannot be a primary key (as there can be many names per language), and the question is quite old, so wonder if there is a method more along the likes of

SELECT NAME WHERE ID=1 and (LANG='SPA' OR DEFAULT=true)

and return the first non-null result of the OR-clause. Ideally, something like:

(not functional)
SELECT COALESCE(SELECT NAME WHERE ID=1 and (LANG='SPA' OR DEFAULT=true));

Anything? Or is a coalesce on a double select the only answer?

Conditional looping in R like in Stata

I need to loop through the sequence of variables and create a newvar conditional on other variables. The logic is the following:

loop through values i = 09 11 12 13 14 15 15b 15 16b 17 18 19
tempvar = "prefix" + "i" + "_variable"
newvar = 1 IF newvar != 1 AND tempvar == 1 AND condition1 == 2 AND condition2 == i

I tried the ifelse logic, but it does not give me the numbers I expect. It seems there are some issues with NAs and I do understand how it works.

Example of code I tried is below. It gives weird numbers, probably because there are many NA's in tempvar. Maybe I should use other approach instead of ifelse?

varnum <- c(paste0(sprintf("%02d", 9)), paste0(11:15), paste0('15b'), paste(16), paste0('16b'), paste0(17:19))
df$newvar <- NA
for (i in varnum) {
    tempvar <- df[[paste0('name',sprintf("%02s", i),'_variable)]]
    df$newvar <- ifelse(df$newvar != 1 & tempvar == "1" & df$condition1 == "2" & df$condition2 == i, 1, 0)
  }
table(df$newvar)

In Stata I would write it like that:

global varnum "09 11 12 13 14 15 15b 16 16b 17 18 19"
gen newvar = .
foreach i in $varnum {
        local tempvar = "name" + "`i'" + "_variable"
        replace newvar = 1 if `newvar' != 1 & `tempvar' == "1" & condition1 == "2" & condition2 == `i'
}
tab newvar

Due to restrictions I cannot share the actual data.

R: make this loop go faster

Currently I am working on a loop. I tried making this with a apply function but it would not work. This loop takes ages. Also I cannot work with the ifelse function as I have nested two functions within 1 statement.

Thanks in advance

I am trying to make a code which countsdown the values in the columns to 0. When a value hits 0 it has to reset to 7 and create a new column with a value of 8. (i'm doing this for the advent of code 2021 event)

dag6 <- data.frame(var1 = 2,
                  var2 = 5,
                  var3 = 6,
                  var4 = 1,
                  var5 = 3,
                  var6 = 6) # Example data as loaded from file

row <- as.data.frame(8)

for (j in 1:80) {
  print(j)
  for (i in 1:ncol(dag6)) 
  {if (dag6[1,i] == 0) {
    dag6[1,i] <- 7
    dag6 <- cbind(dag6, row)
  }
    else {dag6[1,i] <- dag6[1,i]-1}
  }
}

Syntax Else Error, but I can't find a problem with my indentation [closed]

I get a "syntax error" for my else-statement (commented the error) but I can't find anything wrong with my indentation.

The code is to download a batch of satellite images, and the error pops up when I try calling the function with a sat_imagery object.

Would really appreciate any help, thanks!

def download_satellite_imagery(sat_imagery): #satellite imagery object
  next_batch_size = 10 #set no. of new tasks to be added after reaching task limit
  target_count = 3000 - next_batch_size #Threshold before creating new tasks

  task_count = get_queued_task() #Execute function & store R/R tasks in var.
  queued_filenames = get_queued_task_filenames() #Execute function & store
  print('Number of active tasks: {: }.'.format(task_count)) #Print active tasks

  for i in range(1,imagery_count):
    imagery_file = DIMG + '_{:06d}'.format(i)
    imagery_filepath = '/content/gdrive/MyDrive/' + drive_folder + '/' + imagery_file + '.tif'

    if task_count == 3000: #Number of tasks has reached limit
    #Loop until task count has not reach target_count
      while task_count > target_count: 
        active_task = get_queued_task() #Get no. of tasks on list 

        if active_task < task_count:  #Check if there are finished tasks
          task_count = active_task
          print("*"*30)
          print("Number of current pending tasks in queue: {: }.".format(task_count))
          print("Remaining tasks before starting new batch: {: }.".format(task_count-target_count)

    else: #error found here
      
      if (os.path.exists(imagery_filepath)==False): #prevents duplication of tasks
        if (imagery_file not in queued_filenames): 
          print("-----------------------")
          print("Starting new task...")
          print("downloading "+ imagery_file)

          #Set var to store centroid coordinates obtained from centroid CSV
          c_lon = df['lon'][i]
          c_lat = df['lat'][i]
            
          #Employ centroid coordinates to define a geospatial circle using GEE point geometry
          #Buffer of 1920m - 1/2 grid size measured from centroid to grid boundary
          geometry = ee.Geometry.Point([c_lon, c_lat]).buffer(1920)

          #Redefine geom var with c of circle as its value
          geometry = geometry.getInfo()['coordinates'][0]

          scale =15 
          task_config = {
            'scale': scale, #satellite resolution 
            'region': geometry, #area coverage to download
            'driveFolder': drive_folder #folder path
          }
              
          #Describe image batch export object & name as task
          task = ee.batch.Export.image(sat_imagery, imagery_file, task_config)
          task.start() #Pass the task to GEE
          task_count += 1

          if task_count %1000 == 0: 
            task_count = get_queued_task() #Execute get_queued_tasks only after every 1000 tasks

          print('Number of active tasks: {: }.'.format(task_count))
        
        else: 
          print("On queue: " + imagery_file + ".tif")

      else: 
       print("Downloaded: " + imagery_file +".tif")````

Scanf function not taking input pls helpp [duplicate]

This is my code and in this the age, marital status and gender input are not working please help me fix this I am noob and new to stack overflow ;(

#include <stdio.h>
    
    int main(){
        int age;
        char ms;
        char gender;
        printf("\nEnter age: ");
        scanf("%d",&age);
        printf("\nEnter marital status: ");
        scanf("%c",&ms);
        printf("\nEnter gender: ");
        scanf("%c",&gender);
    
        if(ms=='M'||ms=='U'&&gender=='M'&& age>=30||ms=='U'&&gender=='F'&& age>=25)
        printf("Driver is insured.");
        return 0;
    }

lundi 6 décembre 2021

How to run if conditional, can meet twice

I have a condition like this, I want the first if conditional to have no reaction if you meet this condition again the second time give him a reaction, more or less like the example in the code below.

var x = -1;

if( x < 0){
  console.log("is okay")
}if( x < 0 AGAIN ){
  console.log("is not okay")
}

async python ignores if statment

My script works as expected except that it ignores the if condition inside async def get_item - no basic errors I can see, "==" is used for if, type for comparison are both string and proof (?) that the if test is being ignored is that there is no output from the line, print("INSIDE IF"). No error messages are output.

import asyncio



AList = [['A','R','M'],
      ['B','W','N'],
      ['C','W','O'],
      ['D','R','P'],
      ]

num_items = len(AList)   """ is 4 in this example - a list of lists"""

Asub = []                """ a yet to be nominated sub list of AList"""

List_out= []             """ output list - empty at start."""

N = 0

""" define a coroutine to simulate retrieval of an item"""

async def get_item(i):

    global N

    N = N + 1                   """ used to count passes"""

    Asub = AList[i]             """nominated sub list (i range 0 to 3 for     example)"""    
 
    value1 = Asub[1:2]          """ value of interest - second item  """   
    value1_str = str(value1)    """ being specific about type"""
    ref_val = 'W'               """being specific about type"""
    print("TYPE", type(value1_str),  value1_str)
    if value1_str == ref_val:   """ should be true in 2 cases for example"""
        print("INSIDE IF")      """debug check"""
        value1_str = 'Water'
    else:
        value1_str = value1_str
    
    await asyncio.sleep(0.1)

    print("PassCount", N, "ValueOut", value1_str)
    List_out.append(value1_str)                    
    OutLen = len(List_out)                       
    print( "InListLen:   ", num_items,"OutListLen   ", OutLen)

    return f'item {List_out}'               

""" define a coroutine which executes several coroutines """

async def get_items(num_items):

    print('getting items')

""" create a list of Tasks """

item_coros = [asyncio.create_task(get_item(i)) for i in range(num_items)]
print('waiting for tasks to complete')

""" wait for all Tasks to complete """

completed, pending = await asyncio.wait(item_coros)

"""access the Task results """

print(List_out)

"""create an event loop """

loop = asyncio.get_event_loop()

try:

"""execute the coroutine in the event loop """

loop.run_until_complete(get_items(num_items))  #num_items also works

finally:

loop.close()

Output from the above is more or less as expected - but without any evidence of the if condition being processed.

Outputs - with no change to 'W'

There seems to be little on the issue on line, and I have seen the same error in the work of a "professional" !!

This one has beaten me - any assistance much appreciated.

Execute all else if blocks on visual basic

I'm working in visual basic on visual studio 2019. There is a way to execute all ElseIf blocks even if the first "if" or one of the precessor were true? if is not possible with the ElseIf, there is any other command I could use? The final idea and the explanation of why I can't just do separated Ifs is because I need to give a error message if all the statements were false, and I don't know how to group them without the ElseIf command, so this is the only idea I have in mind right now to do so.

So, this is the ElseIf structure, it stops when it finds one of this statements true

If(boolean_expression 1)Then ' Executes when the boolean expression 1 is true ElseIf( boolean_expression 2)Then ' Executes when the boolean expression 2 is true ElseIf( boolean_expression 3)Then ' Executes when the boolean expression 3 is true Else ' executes when the none of the above condition is true End If

So, I want to execute every single ElseIf no matters if the predecessor was true of false. I hope you can help me resolve this, thanks!

How Ignore the if case (i.e., consider “The” and “the” as the same word)

Sorry if this is an obvious problem.

I'm trying to read strings from users and store them in an array. but I want to Ignore the if case (i.e., consider “The” and “the” as the same word)

Thanks a lot for any help!

Scanner fileScanner = new Scanner(file);
        fileScanner.useDelimiter("[^A-Za-z0-9]");
        ArrayList<String> words = new ArrayList<String>();
        while (fileScanner.hasNext()) {
            String nextWord = fileScanner.next();
            if (!words.contains(nextWord) ) {
                words.add(nextWord);
            }
        }

Change the Time in Date/Time Cells

I am trying to change the time in each Date/Time cell so that the time is 5:00:00. So that 05/10/2021 07:00:00 becomes 05/10/2021 05:00:00.

I have tried turning the cell into plain text, splitting it by the decimal and rejoining with the appropriate time, but it breaks my other formulas even though the format looks identical. I have also tried splitting the date and time, then using '''=CONCATENATE(text(A2,"M/D/YYYY")& " " &text($B$2,"H:MM:SS"))''' - the formulas still break.

Batch syntax for creating a file, putting a variable into it, and than reading the variable from it

I have the following code to create a file if it does not exist, creating a variable (hi), echo the variable into the file, and then read the text as a variable. If it does exist, it simply reads the text as a variable:

if exist hiscore.txt (
for /f "delims=" %%x in (hiscore.txt) do set /a hi=%%x
) else (
set /a hi=0
echo %hi%>"hiscore.txt"
for /f "delims=" %%x in (hiscore.txt) do set /a hi=%%x
)

if I create the file manually, and type 0 into it manually, it works. If I delete the file, and then run this, it says "Missing Operand" and echos "ECHO is off" into the file. What can I change?

I am trying to make word1 from the letters of word2 in Python

word1 = input() 
word2 = input()
a = len(word2)
b = len(word1)
count = b
while (word2[a-1] == word1[b-1]):
    count-=1
    a -= 1
    if count == 0:
        break
    else:
        print('it cant be made')
b-=1
print('it can be made')  

What I am trying to do is compare the last letter of word2 to the last letter of word 1 and if they are equal, - the count by 1 and move down a letter in word 2 until the count is == to 0 therefore suggesting the word can be made. if the 2 letters aren't equal it should just move onto the next letter of word1 and repeat the process. if the the count doesn't reach 0 then the word can't be made because it is the Len of the word you are trying to make.

Create a function that takes a word and returns true if the word has two consecutive identical letters

// Create a function that takes a word and returns true if the word has two consecutive identical letters.

What am I doing wrong?

module.exports = (word) => {
    for (let i = 0; i <= word.length; i++) {
        for (let j = i + 1; j <= word.length; j++) {
            if (word[j] == word[i]) {
                return true;
            }
        } return false;
        
    } 

};

Oracle drop table if exists is throwing an error starting at line 1: in command

We are trying to drop all tables in a database and then create them again, but oracle is throwing an error. the error report is:

Error report -
ORA-06550: line 12, column 1:
PLS-00103: Encountered the symbol "CREATE" 
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

and the code is:

BEGIN
   EXECUTE IMMEDIATE 'DROP TABLE ' || EMPLOYEE;
   EXECUTE IMMEDIATE 'DROP TABLE ' || ADDRESS;

EXCEPTION
   WHEN OTHERS THEN
      IF SQLCODE != -942 THEN
         RAISE;
      END IF;
END;

CREATE TABLE EMPLOYEE(
    EmployeeID int,
    FirstName varchar(225),
    LastName varchar(255),
    Position varchar(255),
    SSN int,
    Address varchar(255),
    Phone int,
    AddressID int,
    
    PRIMARY KEY (EmployeeID),
    FOREIGN KEY (AddressID) REFERENCES ADDRESS(AddressID)
);

CREATE TABLE ADDRESS(
    AddressID int,
    Street varchar(225),
    City varchar(225),
    State varchar(225),
    Zip int
);

We want to do this for all tables but so far it's not working for the two tables we are trying to drop at the start.