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.

How to stop IT loop in FOR loop without stopping the FOR loop

        for job in jobs:
            if int(dpr) <= int(user.dpr):
                if str(user.gender) == 'male:
                    if str(orpi) == 'yes':
                        if int(profil) >= int(user.profil):
                            bot.send_message(message.chat.id, str(name)
                        **now i want to exit the "if's" and go to next "job in for loop**
                else:
                    if int(profil) <= int(user.profil):
                            bot.send_message(message.chat.id, str(name)
                        **now i want to exit the "if's" and go to next "job in for loop**
            else:
                if str(orpi) == 'yes':
                    if int(profil_fem) >= int(user.profil):
                            bot.send_message(message.chat.id, str(name)
                        **now i want to exit the "if's" and go to next "job in for loop**
                else:
                    if int(profil_fem) >= int(user.profil):
                            bot.send_message(message.chat.id, str(name)
                        **now i want to exit the "if's" and go to next "job in for loop**

Hello, I want to make "now i want to exit the "if's" and go to the next "job in for loop" in the code, return to the for loop (job in jobs), and process to the next job. Is there any command for it?

How can I not order more than one bucket of popcorn (if statement)

Why can I type popcorn 2 or more times in a row

without giving me an error since I used set.add and second time when I type popcorn should give me an error since I can't have two same values in a set ? How can I do it so I can type only one time popcorn and give me an error second time when I try to type popcorn.

public void Popcorn() {
        boolean stop = false;
        while (!stop) {
            String s = scanner.nextLine();
            Set<String> set = new HashSet<>();
            if (s.equals("popcorn")&&!set.contains("popcorn")) {
                set.add("popcorn");
                int popcorn = 5;
                setPopCornValue(getPopCornValue() + popcorn);
                continue;
                }
     
            }
            if(s.equals("exit")){
                stop=true;
                break;
            }

    } ```

Why can't my Java code see doubles from if statements? [duplicate]

I'm taking a class for java at my Highschool and I'm trying to complete an assignment. Everything is completed except for the fact that my code isn't reading the integers I made in my if statement. If anyone has some solutions, that would be greatly appreciated. If needed I can add my full code, but I believe this snippet should be enough.

if (letter == A) {
      double mAF = 1.0;
      double fAF = 1.0;
    } else if (letter == B) {
      double mAF = 1.3;
      double fAF = 1.3;
    } else if (letter == C) {
      double mAF = 1.6;
      double fAF = 1.5;
    } else if (letter == D) {
      double mAF = 1.7;
      double fAF = 1.6;
    } else if (letter == E) {
      double mAF = 2.1;
      double fAF = 1.9;
    } else if (letter == F) {
      double mAF = 2.4;
      double fAF = 2.2;
    } else {
      test--;
      double mAF = 0;
      double fAF = 0;
    }
    double mCal = mAF * BMR;//error here, cannot sense mAF
    double fCal = fAF * BMR;//error here, cannot sense fAF

How I can simplify this?

I want to simplify these "if's", what are the variants? Thanks.

    user_id = message.from_user.id
    user = user_data[user_id]
    user.profil = message.text
    if not user.profil == '97':
        if not user.profil == '82':
            if not user.profil == '72':
                if not user.profil == '64':
                    if not user.profil == '45':
                        if not user.profil == '25':   
                            markup = types.ReplyKeyboardMarkup(one_time_keyboard=True)
                            markup.add('97', '82', '72', '64', '45', '25')
                            msg = bot.send_message(message.chat.id, 'אנא בחר פרופיל.', reply_markup=markup)
                            bot.register_next_step_handler(msg, process_profil_step)
                            return

Substitutions in variable name in java

Not sure if this is possible in JAVA, and also don't know what it's called so I'm not sure what to look for, but if it is possible I really wanted to implement the same in my logic. I know we can substitute value but how to substitute variable that I am not sure.

public interface Constants {
 GENDER_${MALE} = "where Gender = 'MALE' ";
 GENDER_${FEMALE} = "where Gender = 'FEMALE' ";
}

public class Impl {
  System.out.println(Constants.GENDER_MALE);
}

Expected O/P : where Gender = 'MALE';

I just don't want to use if else condition, if Male then return male specific where clause else female.. because in actual code there are almost 30-35 if else conditions, just want to reduce that, if possible.

Terraform Conditionals

I have 4 envs, qa and dev use one ID, uat and prod use another. I'm trying to do an if else, basically, if env is dev or qa, use id1, else use id2. This is what I tried:

locals{
  endpoint_id = "${var.env == "dev" || "qa" ? "id1" : "id2"}"
}

And this is what I get:

Error: Invalid operand
│ 
│   on ssm-parameters.tf line 2, in locals:
│    2:   endpoint_id = "${var.env == "dev" || "qa" ? "id1" : "id2"}"
│ 
│ Unsuitable value for right operand: a bool is required.

Apparently I can't do an "OR" here. How would I go about this? Thank you.

How do I find maximum change point in data columns and write this with a conditional statement

MATLAB. I have a (2559 x 16 x 3) array named ydisplacements. I use the 'ischange' command with a specified threshold, in a loop to find points of rapid change in the data in each column, for all three planes. This I record in a logical array TF(2559 x 16 x 3) in which '1' denotes points of sharp change. I want to have TF such that in each of its columns only the most extreme change from 'ydisplacements' is recorded in it as logical 1. In other words, everything else is a logical 0, I want only one logical 1 for each column of TF. This I can do easily by increasing the threshold till my desired outcome. But my question is how I can automate this so that for each column of ydisplacements(:,i,j), the threshold keeps increasing by a predetermined value until the desired outcome of only one logical 1 is achieved in TF, before moving to the next index. I have tried this code below. Any help is appreciated. Thank you..

increment = 100;
for i = 1:size(ydisplacements,2);
    for j = 1:size(ydisplacements,3);
        threshold = 100;
        TF(:,i,j) = ischange(ydisplacements(:,i,j),'Linear','Threshold',threshold);
        if sum(TF(:,i,j) == 1)>1; 
            threshold = threshold + increment;
            TF(:,i,j) = ischange(ydisplacements(:,i,j),'Linear','Threshold',threshold);
        else
            threshold = threshold;
            TF(:,i,j) = ischange(ydisplacements(:,i,j),'Linear','Threshold',threshold);
        end
    end
end

Powerapps - Nested If Statement, maybe Switch?

I'm trying to achieve the following:

Fill a textinput box in red or green depending on the value entered. It gets a little more complicated as the textinput is in a gallery and I only want it to go red or green if the selected question is 'FR Chlorine' or 'ph Actual'. The input box should be white if it is not one of those two questions.

To determine whether we want to fill in red or in green, there is another if statement which checks the value entered against predetermined variables which hold the comparison values. Can anyone help me to tidy this up as I seem to be in a bit of a pickle somewhere.

If(
    ThisItem.question = "FR Chlorine",
    If(
        Value(txtResult.Text) < ChlorineLowerLevel,
        Red,
        Value(txtResult.Text) > ChlorineUpperLevel,
        Red,
        Green
    ),
    White
);
If(
    ThisItem.question = "ph Actual",
    If(
        Value(txtResult.Text) < phLowerLevel,
        Red,
        Value(txtResult.Text) > phUpperLevel,
        Red,
        Green
    ),
    White
)

Bash if-statement gets stuck

I get this loop but for some reason, the if conditional get stucks. The while loop works perfectly.

The inputs are those:

name0="Car name 1"

name1="Car name 2"

name2="Car name 3"
        echo $name0
        echo $name1
        echo $name2
while [ $exit -eq 0 ]
do
    if [ "$name1" = "$name2" ]
    then
    exit=1
        name1="`shuf -n 1 cars.csv | cut -d";" -f1`"
        name1c=`echo $name1 | cut -d" " -f1`
        salir=1
    else
        :
    fi
done

It outputs somethink like this (without #):

Car name 1

Car name 2

Car name 3
#

And gets stuck in the #, I can enter more text but it does nothing.

Is there a way to tell an if statement to go back to a loop?

So for instance.

while(something){
    // ...
}

if(somethingElse){
   // do something and go back to while loop 
}

How do I do this?

Shorthand for many if statements

I need to do a lot of if statements to determine the way certain data is going.

if mean > 75 and avg <= 5:
  output = 'A'
elif mean > 75 and avg > 5:
  output = 'B'
elif mean > 75 and avg < -5:
  output = 'C'
elif mean > 65 and avg <= 5:
  output = 'D'
elif mean > 65 and avg > 5:
  output = 'E'
etc...

I found another article on Stack Overflow for this problem, but it's for a lot simpler if statements, using only one variable and using each number once. In my example I use single characters, but in the real application I need to use long strings that explain exactly what the numbers mean.

Is there any way I can do what the post I linked does, but using the numbers three times and negating it once like in my example?

Cannot declare the "else" statement in Java script Visual Studio Code? [closed]

New to coding and getting errors in basic coding. Following a youtube tutorial for learning but getting the error even after coding the same way as shown in my tutorial video.

var age = prompt ("what is ur age?");

`If ( (age>= 18)   &&   (age<= 35) ); {

var status = "my audience"; console.log (status);} else { var status = "not intrested"; console.log(status); }`

Upon running the program, the error generated is Unexpected token 'else'.

avoid negative values when resolving a ODE

I am trying to model the behavior of a made-up networks of 5 genes, but I have the problem that I get negative values, which it has not sense biologically speaking.

Is there a way to limit the values to zero?

I managed to do it when I represent the graph, but I don't know how to use the ifelse in the main equation.

Thank you very much-1

###################################################
###preliminaries
###################################################

library(deSolve)
library(ggplot2)
library(reshape2)

###################################################
### Initial values
###################################################

values <- c(A = 1,
            B = 1,
            D = 1,
            E = 20,
            R = 1)

###################################################
### Set of constants
###################################################

constants <- c(a = 1.2,
               b = 0.5,
               c = 1.2,
               d = 1.5,
               e = 0.3,
               f = 0.5,
               g = 1.5,
               h = 0.9,
               i = 1.3,
               j = 1.3,
               m = 0.8,
               n = 0.6,
               q = 1,
               t = 0.0075,
               u = 0.0009,
               Pa = 100,
               Pb = 0.05,
               Pd = 0.1,
               Pe = 10)

###################################################
### differential equations
###################################################

Dynamic_Model<-function(t, values, constants) {
  with(as.list(c(values, constants)),{
    
    dA <- Pa + a*D - j*A - R
    dB <- Pb + b*A + e*E - m*B 
    dD <- Pd + d*B + f*E - g*A - n*D
    dE <- Pe - h*B + i*E - q*E
    dR <- t*A*B - u*D*E 
    
    list(c(dA, dB, dD, dE, dR))
  })   
}

###################################################
### time
###################################################

times <- seq(0, 200, by = 0.01)

###################################################
### print ## Ploting
###################################################

out <- ode(y = values, times = times, func = Dynamic_Model, parms = constantser)

out2 <- ifelse(out<0, 0, out)

out.df = as.data.frame(out2) 

out.m = melt(out.df, id.vars='time') 
p <- ggplot(out.m, aes(time, value, color = variable)) + geom_point(size=0.5) + ggtitle("Dynamic Model")

dimanche 5 décembre 2021

both of the printf statements inside the while loop gets printed simultaneously [duplicate]

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

int main(){
    char x;
    int i=1,n,h,p,tot=0;
    printf("Enter the number of vehicles to be parked:");
    scanf("%d",&n);
    // using while loop to get the values for the number of vehicles
    while(i<=n){
        printf("\nEnter c for car,b for bus, t for 2 wheelers:");
        scanf("%c",&x);
        printf("\nno of hours:");
        scanf("%d",&h);
        if(x=='c'){
            p=10*h;
            printf("\n%d rupees for %d hour",p,h);
            tot=tot+(10*h);
        }
        else if(x=='b'){
            p=20*h;
            printf("\n%d rupees for %d hour",p,h);
            tot=tot+(20*h);
        }
        else if(x=='t'){
            p=5*h;
            printf("\n%d rupees for %d hour",p,h);
            tot=tot+(5*h);
        }
        else{
            break;
        }
    
        i=i+1;
    }
}

this code is not working as expected. before executing the scanf statement it executes the next printf statement. it executes both printf statement and then executes scanf statement.

Cell-Address with an IF Statement

I've been using =Cell("address",... to error check formulas I'm making to create a database and it's been working pretty well until I tried to scale up my index match formulas with some if statements.

I've narrowed the issue down to where I believe it's working as intended as long as the first statement in the if statement is true, yet if the calculation goes past that (even if the original formula is fine and returns a value) it will come back with #VALUE!.

EDIT: To be clear, the formula used above returns values without issue when not using the CELL-ADDRESS function involved. The formula also returns values when split up outside the IF-Statement.

I2=Valid

=CELL("address",IF($I$2="Valid",INDEX($I$2:$J$6,MATCH($U$1,$H$2:$H$6,0),MATCH($V$1,$I$1:$J$1,0)),IF($I$2="Invalid",INDEX($I$2:$J$6,MATCH($W$1,$H$2:$H$6,0),MATCH($V$1,$I$1:$J$1,0)),"Error")))

$I$2 is returned in the cell

I2=Invalid

=IF($I$2="Valid",INDEX($I$2:$J$6,MATCH($U$1,$H$2:$H$6,0),MATCH($V$1,$I$1:$J$1,0)),IF($I$2="Invalid",INDEX($I$2:$J$6,MATCH($W$1,$H$2:$H$6,0),MATCH($V$1,$I$1:$J$1,0)),"Error"))

#VALUE! is returned

Can anyone offer a fix for this or explain why it's happening and how to avoid it?

Any help would be appreciated.

Thanks!

Python if statement doesn’t work with me? [closed]

I want to check if the keys less than or greater than 10 My Code :

phones = {"1111111111": "Mohammed", "2222222222": "Ali", "3333333333": "Rami"}


def check(n):
    for n in phones.keys():
        if len(n) > 10 or len(n) < 10:
            print('This is invalid number')
        else:
            print("OK")
        break


check("1")

The output is "OK" while the length of the n is less than 10 where is the mistake exactly? and what's the difference between len(n) > 10 or len(n) < 10 and 10 < len(n) < 10 Thanks

match different message patterns from a user input in Python

I'm trying to match a message from a user input that follows a certain pattern. 1st pattern is a keyword 'data' followed by two digits, and the 2nd is the keyword 'status' followed by a word. I used if statements and it works only if there is a single pattern to be matched but not both as the second pattern would be skipped.

import re


message = input('Enter Your Message?\n')



trainee_data_pattern = re.compile(r"^(data)?\s?(\d\d)$")
data_match = trainee_data_pattern.search(message)
trainee_status_pattern = re.compile(r"^(status)?\s?(\w+)$")
status_match = trainee_status_pattern.search(message)

try:
    if data_match.group() == message:
        matched_num = trainee_data_pattern.search(message).group(2)
        
        list1 = [11,22,33]
        if int(matched_num) in list1:
            print(f"ID: {matched_num}")
                
        else:
            print('no data')
        
    elif status_match.group() == message:  
    
        matched_status = trainee_status_pattern.search(message).group(2)
        
        list2 = ['good','bad','refurbished']
        if matched_status in list2:
            print(f"the status is {matched_status}")
                
        else:
            print('no data')
            
except AttributeError:
      res = trainee_data_pattern.search(message) 
      print('wrong pattern')

The desired functionality of the program is when a user inputs: data 22 -> ID: 22

status good -> the status is good

data 133 -> wrong pattern

C, if statement still executing even when false

I'm having problems with this part of my program. The idea is to find the length (double function) between two points (out of 4 for a rectangle) and then to find the area. I'm having problems though, mainly with my if(Sa >= S && S<=Sa) function. Even if I write Sa>S it still goes through every time, no matter if Sa is equal to 999999 or -1. I'm beginning to believe space is at fault here, for always sending a neutron to shoot a 0 to a 1.

Other parts of my code work. It reads from a file, but that works perfectly to a T. My code also finds the length no problem.

double RastiIlgi(int Ax, int Ay, int Bx, int By) 
{
    double x = (Bx-Ax);
    double y = (By-Ay);
    double ilgis =sqrt(x*x + y*y);
    return ilgis;
}

int main()
{
    int Ax, int Ay, int Bx, int By
    scanf("%d %d %d %d", Ax, Ay, Bx, By);
    double x, y, S, Sa=100;
    x=RastiIlgi(Ax, Ay, Bx, By);
    y=RastiIlgi(Ax, Ay, Dx, Dy);
    if(x==y)
    {
         x=RastiIlgi(Bx, By, Cx, Cy);
         y=RastiIlgi(Cx, Cy, Dx, Dy);
    }
    printf("%f %f \n", x, y);
    S=x*y;
    if(Sa >= S && S<=Sa)
    {
        Sa = S;
        printf("%f \n", S);
        printf("%f \n", Sa);
        
    }
}```

IF stament return me FALSE when should return TRUE [duplicate]

Question:

    
    if ("sometext" == "SOMEtext") {
        echo "TRUE";
    } else {
        echo "FALSE";
    }
    

It is return me FALSE, when I use double equal.
The only diference are the capital leters...
This if should return TRUE ????

Pine script condition 1 and condition 2 fulfilled at up to n steps back

Say I have condition 1 and condition 2. If condition 1 was met at current close, and condition 2 was fulfilled 5 bars ago (and condition 3 was true 3 bars ago, ...), then I want to perform some action. How do I formulate that in Pine?

condition1 = ...
condition2 = ...

if condition1(close:close-5)==true and condition2(close:close-5)== true then ...

Pine Script Multiple Condition / if statement or for-loop

I have multiple conditions like;

Buy1 Buy2 Buy3 Buy4 Buy5 . . . Buy10

I want to change bar colors due to TRUE condition numbers Example: only buy1 true If 1 Condition True barcolor(color.red) Example: only buy1, buy3, buy5 true If 3 Condition True barcolor(color.blue) If 9 Condition True barcolor(color.green) . .

how can i code, thanks for your help

Validating ID Number C#

I am working on this method that validates a student Id number. The credentials of the ID number are; the first character has to be 9, the second character has to be a 0, there can not be any letters, and the number must be 9 characters long. The method will return true if the student id is valid. When I go to test the method manually through main it comes out as true, even when I put in a wrong input. In my code, I have the if statements nested, but I originally did not have them nested. What is a better way to validate the input to align with the credentials of the ID number? Would converting the string into an array be more ideal?

 public static bool ValidateStudentId(string stdntId)
        {
            string compare = "123456789";
            if (stdntId.StartsWith("8"))
            {
                if (stdntId.StartsWith("91"))
                {
                    if (Regex.IsMatch(stdntId, @"^[a-zA-Z]+$"))
                    {
                        if (stdntId.Length > compare.Length)
                        {
                            if (stdntId.Length < compare.Length)
                            {
                                return false;
                            }
                        }
                    }
                }
            }

screenshot of my main. The method was made in a class called student.

Pine script conditions / conditional-statements

I have 6 conditions:

condition1 = ...
condition2 = ...

Then if 4 of them are fullfilled, I will execute some command. How to do this?

E.g.:

if condition 1 == condition 2 == condition3 == condition4 == true then ...
elseif condition 1 == condition 2 == condition3 == condition5 == true then ... 
elseif condition 1 == condition 2 == condition3 == condition6 == true then ...
elseif condition 1 == condition 2 == condition4 == condition5 == true then ...
elseif condition 1 == condition 2 == condition4 == condition6 == true then ...
elseif condition 1 == condition 3 == condition4 == condition5 == true then ...
elseif condition 1 == condition 3 == condition4 == condition6 == true then ...
...
...
...

Run a function in the 'if statement'

When I run clear() as below it does not print the 'else' statement. It only works for the 'if' part. When I run it one indent outside, it clears without doing the print for both if and else. Please guide on where I should place it.

import random
from art import logo,vs
from game_data import data
from replit import clear

def game_question():
  return random.choice(data)

def format_data(account):
    account_name = account["name"]
    account_description = account["description"]
    account_country = account["country"]

    return f"{account_name}, {account_description}, {account_country}" 

  
def count(num_a, num_b):
    if num_a > num_b:
     return  "a"
    else:
      return "b"

win = 0

play_on = False

while not play_on:
  print (logo)

  account_a = game_question()
  account_b = game_question()

  if account_a == account_b:
    account_b = game_question()
  
  num_a = account_a["follower_count"]
  num_b = account_b["follower_count"]

  print(f"Account A : {format_data(account_a)}")
  print (vs)
  print(f"Compare to Account B: {format_data(account_b)}")

  ans = input("Which account has more followers? A or B: ").lower()

  if ans == count(num_a,num_b):
    win += 1
    print ("A win")

  else:
    print (f"Wrong. You lose. Win = {win}")
    play_on = True
  clear()  

How could be the String any keyboard in java? [closed]

I need to write a program which has 3 Parts. In the first past shall it have a password which 3 times should it run. In the first time when the pass is right so it would be printed "the pass is right" if it is not the case so it would be printed "the pass is wrong". At the third time should it be the same but it must be ended.

After that i should write Strings which must be able to give the user all possible spells and numbers.

How can i give a command in java to do that ? I have already tried In.readLine but it is not working. I would be happy if someone help me? Have a nice time!

Python best practices, use of None in comparison [duplicate]

What is wrong with this statement in Python? I am talking about the part where the comparison is done.

if object.result() != None:
    OtherObject.dosomething()

Console.ReadKey storing older keys and returning them after successful true return in c#

The code is pretty straightforward but not sure what the heck is going on. Any help is much appreciated.

I am a calling a validation function to check if user either entered 'c' or 'r' in Main method like this:

validation.ValidateInputChars(input, 'c', 'r');

and the validateInputChars function is like this:

public char ValidateInputChars(char actualInput, char input1, char input2)
       {
           if (char.Equals(actualInput, input1))
           {
               return 'c';
           }
           else if (char.Equals(actualInput, input2))
           {
               return 'r';
           }
           else
           {
               Console.WriteLine("\n You pressed " + actualInput + "\nYour input is incorrect, kindly press " + input1 + " or " + input2 + " to proceed");
               actualInput = Console.ReadKey().KeyChar;

               ValidateInputChars(actualInput, input1, input2);
               return 'z';
           }
       } 

The input is let's assume: 'q', 'w', 'e' and then 'c'.

It works all fine, until I press 'c'. It goes inside the first loop to return the correct input "c" but then the strange thing is it goes to the else loop as well, where the it's return 'z' 4 more times.

And at last the result it returns is the second input, so in this case it finally return 'w' (WTH!).

I've tried without if else statements, with List {'c', 'r'}, everything.

The only thins I need is to know if user entered 'c' or 'r' but it's not working.

Any Idea what's happening here?

Why can I not check if Flutter list isnotempty?

I have created a flutter list but how do I check if it is empty?
List<int> selectedItems = [];
However, selectedItems.isNotEmpty gives me Conditions must have a static type of 'bool'. error. How do I fix this?

I created a dropdown

SearchChoices.multiple(
                        clearIcon: const Icon(FontAwesomeIcons.times),
                        underline: Container(
                          color: const Color(0xffF0F0F0),
                        ),
                        items:
                            _list.map<DropdownMenuItem<String>>((String value) {
                          return DropdownMenuItem<String>(
                            value: value,
                            child: Text(value),
                          );
                        }).toList(),
                        selectedItems: selectedItems,
                        hint: const Padding(
                          padding: EdgeInsets.all(12.0),
                          child: Text("Select any"),
                        ),
                        searchHint: "Select any",
                        onChanged: (value) {
                          setState(() {
                            value = selectedItems;
                          });
                        },
                        closeButton: (selectedItems) {
                          return selectedItems.isNotEmpty
                              ? "Save ${selectedItems.length == 1 ? '"' + items[selectedItems.first].value.toString() + '"' : '(' + selectedItems.length.toString() + ')'}"
                              : "Save without selection";
                        },
                        isExpanded: true,
                      ),

The error is here

closeButton: (selectedItems) {
                          return selectedItems.isNotEmpty
                              ? "Save ${selectedItems.length == 1 ? '"' + items[selectedItems.first].value.toString() + '"' : '(' + selectedItems.length.toString() + ')'}"
                              : "Save without selection";
                        },

Error

The dropdown package I used is: https://pub.dev/packages/searchable_dropdown

UPDATE
It seems that flutter sees the List<int> as a dynamic type. Ever since I began the project it has been assigning every variable as dynamic even if I specified its type. enter image description here Screenshot of variable
enter image description here

how to translate an if condition to marie's assembly?

I am being asked to write a code that multiply 2 inputs from the user in Marie's assembly . I did everything right except that in the question there is a condition in pseudocode that I cannot quite imply in my code .. if x =0 then x=x+3 which means if the first input is zero I need to increment x by 3 . my original multiplication code works and this is it:

ORG 512
Input
Store x
Input
Store y
loop,Load z
 Add x
 Store z
 Load y
 Subt one
 Store y
 Skipcond 400
 Jump loop
Load z
Output
Halt
x, DEC 0
y, DEC 0
one, DEC 1
z, DEC 0

this code works for any x or y to multiply yet I cannot implement the condition above even though I tried this

ORG 512
Input
Store x
Skipcond 800   /in case of input x to 0
Add one    /adding one to x to reach 1
Add one     /adding one to x to reach 2
Add one      /adding one to x to reach 3
Store x
Input
Store y
loop,Load z
   Add x
   Store z
   Load y
   Subt one
   Store y
   Skipcond 400
   Jump loop
Load z
Output
Halt
x, DEC 0
y, DEC 0
one, DEC 1
z, DEC 0

but this messes up when I put both x and y as positives and it gives strange answer to multiplication .

If input is empty then assign None

If input is empty or zero it should get None.

This is what has been attempted:

The int is necessary.

number = int(input('Type an integer: ') or None )
number = number if number != 0 else None 
print(number)

How to avoid this issue:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

JAVA Checking if year is a leap year logical error returning 1924 is NOT a Leap Year when it is a leap year, [closed]

I'm creating a calculator that tells you if a year would be considered a leap year or not. I keep hitting a snag, when the year entered is 1924 the result = "is Not a Leap Year" when it should = "is a Leap Year". I've re-written this 3 different ways but am unable to resolve this portion, some fresh eyes would be appreciated.

  1. LeapYearCalculator class:
public class LeapYearCalculator {
    public static boolean isLeapYear (int year) {
        if ((year<=0) || (year>=1000)) {
            System.out.println(year+" is NOT a Leap Year");
        }
        if (year % 4 == 0) {
            if (year % 100== 0) {
                return (year % 400 == 0);
            }
            System.out.println(year+" is NOT a Leap Year");
            return true;
        }
        System.out.println(year+" is NOT a Leap Year");
        return false;
    }
}
  1. Main class:
public class Main {
    public static void main(String[] args) {
        LeapYearCalculator.isLeapYear(1924);
    }
}

Is there's a way to print only first and last value in loop when given condition become true?

Hello every one I am working on a project and I want to print only first and last value of given condition when condition become true ...

from astropy.time import Time
import swisseph as swe
from datetime import timedelta as td, datetime

swe.set_ephe_path('G:\Ephemeris')
swe.set_jpl_file('de440.eph')

start_date = '2021-01-01 00:00:00'
end_date = '2021-12-31 00:00:00'
d1 = datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S')
d2 = datetime.strptime(end_date, '%Y-%m-%d %H:%M:%S')

def get_delta(d1, d2):
    delta = d2 - d1
    return delta

delta = get_delta(d1,d2)

for i in range(delta.days * 1 + 1):
    x = d1 + td(days=i)
    jd = Time(x).jd
    eph = swe.calc_ut(jd, 2, swe.FLG_SPEED+swe.FLG_JPLEPH)[0][3]
    if eph < 0:
        print(x, eph)

Output ---

2021-01-31 00:00:00 -0.06355796829817034    <--- Condition true print this value (first value)
2021-02-01 00:00:00 -0.2516828089143771
2021-02-02 00:00:00 -0.4368855305400459
2021-02-03 00:00:00 -0.6135683390488923
2021-02-04 00:00:00 -0.7757942785174291
2021-02-05 00:00:00 -0.9177040258548256
2021-02-06 00:00:00 -1.0340083318420783
2021-02-07 00:00:00 -1.1204908143097292
2021-02-08 00:00:00 -1.1744351937165156
2021-02-09 00:00:00 -1.1948938876715327
2021-02-10 00:00:00 -1.1827399614722631
2021-02-11 00:00:00 -1.140494580853247
2021-02-12 00:00:00 -1.0719696672227224
2021-02-13 00:00:00 -0.9818037732776487
2021-02-14 00:00:00 -0.8749793418345923
2021-02-15 00:00:00 -0.7563965596976655
2021-02-16 00:00:00 -0.6305506630304736
2021-02-17 00:00:00 -0.5013285505901539
2021-02-18 00:00:00 -0.37191597325737136
2021-02-19 00:00:00 -0.24479140317840062
2021-02-20 00:00:00 -0.12177911524216488
2021-02-21 00:00:00 -0.00413500087411478      Print this value (last value)
2021-05-30 00:00:00 -0.004547066831108078     Condition True Print this value (first value)   
2021-05-31 00:00:00 -0.07962163144451284
2021-06-01 00:00:00 -0.15215400336574358
2021-06-02 00:00:00 -0.22137358654875092
2021-06-03 00:00:00 -0.28645563729756063
2021-06-04 00:00:00 -0.3465404682847117
2021-06-05 00:00:00 -0.4007583422689736
2021-06-06 00:00:00 -0.44825937136678057
2021-06-07 00:00:00 -0.48824672785691836
2021-06-08 00:00:00 -0.5200109481659706
2021-06-09 00:00:00 -0.5429628624480792
2021-06-10 00:00:00 -0.5566627097783102
2021-06-11 00:00:00 -0.5608427157269316
2021-06-12 00:00:00 -0.5554211491254732
2021-06-13 00:00:00 -0.5405060450116398
2021-06-14 00:00:00 -0.5163887400431304
2021-06-15 00:00:00 -0.4835277090835391
2021-06-16 00:00:00 -0.44252455305021243
2021-06-17 00:00:00 -0.394094049872733
2021-06-18 00:00:00 -0.3390307834305357
2021-06-19 00:00:00 -0.2781753626714067
2021-06-20 00:00:00 -0.21238292731356637
2021-06-21 00:00:00 -0.1424958524480665
2021-06-22 00:00:00 -0.06932129656902836          Print this value (last value)
2021-09-28 00:00:00 -0.08992145079448069          Condition True Print this value (first value)
2021-09-29 00:00:00 -0.2095165387227292
2021-09-30 00:00:00 -0.33367472841201334
2021-10-01 00:00:00 -0.460779986485703       
2021-10-02 00:00:00 -0.5885901793012869
2021-10-03 00:00:00 -0.7141710520264541
2021-10-04 00:00:00 -0.8338797124202194
2021-10-05 00:00:00 -0.9434261210721775
2021-10-06 00:00:00 -1.038038248150094
2021-10-07 00:00:00 -1.112746224561704
2021-10-08 00:00:00 -1.162778289034751
2021-10-09 00:00:00 -1.1840315451748653
2021-10-10 00:00:00 -1.1735509206575194
2021-10-11 00:00:00 -1.1299295237178415
2021-10-12 00:00:00 -1.0535472796478889
2021-10-13 00:00:00 -0.9465923196535948
2021-10-14 00:00:00 -0.812857555718251
2021-10-15 00:00:00 -0.6573542581978807
2021-10-16 00:00:00 -0.48582085619604937
2021-10-17 00:00:00 -0.30421497977143097
2021-10-18 00:00:00 -0.11826392085264098      Print this value (last value)

I don't know how can I print this values please help me I'm stuck here and I'm absolute beginner so please help me in this problem ... Thank You Very much in advance !

Should i use .equals or == [duplicate]

I've been wondering. I've heard from some developers that there's a difference between .equals() and ==. But I know it's quite the same. Should I use .equals or == when checking something? I usually use ==, It's not quite comfortable to use .equals() and that's why i'm asking this, People say that there are conditions that I should use .equals and condition I should use ==. Please help me answer this.

How can I display the computed average entered by the user and convert it into its equivalent GPA and equivalent verbal interpretation using c++?

This is my draft code. I need to compute for the average of the user. The written exam is consist of 40 items while the practical exam is consist of 60 items with a total of 100. Then, I need to display the average, its equivalent GPA and its verbal interpretation and determine if the student passed or failed using the GPA. My problem is that, in order to determine whether the user passed or failed, I need to use the corresponding GPA. But I don't know how I'm going to do it since the user input is on average and not on GPA format. So I'm asking whether it is possible that I can covert the average into the equivalent GPA or make it so that the average and GPA would be correlated so that I can use it to determine whether the user passed or failed.

#include <iostream>

using namespace std;

int main()
{
    float average, w_average, p_average, GPA, w_mathematics, w_science, w_english, w_filipino, 
    w_MAPEH, p_mathematics, p_science, p_english, p_filipino, p_MAPEH;
    int student_num;
    string fname;
    string mname;
    string lname;

    cout << "Enter your first name: ";
    getline(cin, fname);
    cout << "Enter your middle name: ";
    cin >> mname;
    cin.ignore();
    cout << "Enter your last name: ";
    getline(cin, lname);

    cout << "Enter your student number: ";
    cin >> student_num;

    cout << "Enter your written exam grade in Mathematics : ";
    cin >> w_mathematics;
    cout << "Enter your written exam grade in Science : ";
    cin >> w_science;
    cout << "Enter your written exam grade in English : ";
    cin >> w_english ;
    cout << "Enter your written exam grade in Filipino : ";
    cin >> w_filipino;
    cout << "Enter your written exam grade in in MAPEH : ";
    cin >> w_MAPEH;


    cout << "Enter your practical exam grade in Mathematics : ";
    cin >> p_mathematics;
    cout << "Enter your practical exam grade in Science : ";
    cin >> p_science;
    cout << "Enter your practical exam grade in English : ";
    cin >> p_english ;
    cout << "Enter your practical exam grade in Filipino : ";
    cin >> p_filipino;
    cout << "Enter your practical exam grade in in MAPEH : ";
    cin >> p_MAPEH;


    w_average = (w_mathematics + w_science + w_english + w_filipino + w_MAPEH) /5;
    p_average = (p_mathematics + p_science + p_english + p_filipino + p_MAPEH) /5;
    average = w_average + p_average;
    cout << "Name : "<< fname <<" "<< mname <<" "<< lname <<endl;
    cout << "Student Number : " << student_num << endl;
    cout << "Your average grade is : " << average << endl;

    if (average >= 95.50 && average <= 100)
    cout <<"Your GPA is 1.00" << endl;

    else if (average >= 91.50 && average <= 95.49)
    cout <<"Your GPA is 1.25" << endl;

    else if (average >= 85.50 && average <= 91.49)
    cout <<"Your GPA is 1.50" << endl;

    else if (average >= 81.50 && average <= 85.49)
    cout <<"Your GPA is 1.75" << endl;

    else if (average >= 75.50 && average <= 81.49)
    cout <<"Your GPA is 2.00" << endl;

    else if (average >= 71.50 && average <= 74.49)
    cout <<"Your GPA is 2.25" << endl;

    else if (average >= 65.50 && average <= 71.49)
    cout <<"Your GPA is 2.50" << endl;

    else if (average >= 61.50 && average <= 64.49)
    cout <<"Your GPA is 2.75" << endl;

    else if (average >= 55 && average <= 55)
    cout <<"Your GPA is 3.00" << endl;


    if (average <= 3.0){
    cout << "You passed" << endl;
    }
    else {
    cout << "You failed" << endl;
    }


    if (average >= 95.50 && average <= 100)
    cout <<"Excellent" << endl;

    else if (average >= 91.50 && average <= 95.49)
    cout <<"Very Satisfactory" << endl;

    else if (average >= 85.50 && average <= 91.49)
    cout <<"Very Satisfactory" << endl;

    else if (average >= 81.50 && average <= 85.49)
    cout <<"Satisfactory" << endl;

    else if (average >= 75.50 && average <= 81.49)
    cout <<"Satisfactory" << endl;

    else if (average >= 71.50 && average <= 74.49)
    cout <<"Satisfactory" << endl;

    else if (average >= 65.50 && average <= 71.49)
    cout <<"Needs Improvement" << endl;

    else if (average >= 61.50 && average <= 64.49)
    cout <<"Needs Improvement" << endl;

    else if (average >= 55 && average <= 55)
    cout <<"Highly Needs Improvement" << endl;


    return 0;
}

changing transform.position never equal to transform.position + transform.forward

I am creating a basic shooting mechanism, where the bullet ends at the end of a LineRenderer. My code for the instantiated bullet is as follows:

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

public class BulletScript : MonoBehaviour
{
    [SerializeField] PlayerAttacking PA;
    [SerializeField] float speed;
    Vector3 BulletEndDist;

    // Start is called before the first frame update
    void Start() {
        PA = GameObject.Find("AttackTrail").GetComponent<PlayerAttacking>();
        BulletEndDist = transform.position + (transform.forward * PA.TrailDistance) ;
    }

    // Update is called once per frame
    void Update() {
        if(transform.position == BulletEndDist)
        {
            Destroy(this.gameObject);
        }
        transform.Translate(new Vector3(0, 0, speed));
    }

    private void OnCollisionEnter(Collision collision) {
        if(collision.transform.tag == "Enemy")
        {
            // Decrease health
            Destroy(this.gameObject);
        }
        else
        {
            Destroy(this.gameObject);
        }
    }
}

The problem I am getting is the bullet never gets destroyed, and through some Debug.Logs I found its not entering the if condition in the Update. This makes no sense as surely the bullet should get to BulletEndDist eventually? Please help!

Problem with if statements, containing token from strtok in C

Here's the task: 1)07/21/2003 2)July 21, 2003

Write a program that reads a date in the first format and prints it in the second format.

I am supposed to use string methods, especially strtok.

Here's my code:

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

int main()
{
    char date[20];
    char month[20];
    char day[20];
    char year[20];
    char *token;
    char sep[1] = "/";

    printf("Enter the date (MM/DD/YYYY): ");
    gets(date);

    token = strtok(date, sep);

    if (token == "01")
    {
        strcpy(month, "Januray");
    }

    else if (token == "02")
    {
        strcpy(month, "February");
    }

    //continuing in this way
   
    }

    else if (token == "11")
    {
        strcpy(month, "November");
    }

    else
    {
        strcpy(month, "December");
    }

    token = strtok(NULL, sep);
    strcpy(day, token);

    token = strtok(NULL, sep);
    strcpy(year, token);

    printf("%s %s, %s", month, day, year);
}

The problem is that the month part always gives December, which means if statements do not work.

samedi 4 décembre 2021

Moving Between Rooms

The code I have is as follows:

rooms = {
    'Great Hall': {'South': 'Bedroom'},
    'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
    'Cellar': {'West': 'Bedroom'}
}

def show_instructions():
    print('The instructions are as follows: go north, go south, go east, go west')

def move_rooms(direction, room='Great Hall'):
    if direction == 'go south':
        room = 'Bedroom'
        return rooms[room]['South']
    elif direction == 'go north':
        if room == 'Great Hall' or 'Cellar':
            return 'Invalid direction please try again.'
        return rooms[room]['North']
    elif direction == 'go east':
        if room == 'Great Hall' or 'Cellar':
            return 'Invalid direction please try again.'
        return rooms[room]['East']
    elif direction == 'go west':
        if room == 'Bedroom' or 'Great Hall':
            return 'Invalid direction please try again.'
        return rooms[room]['West']





currentRoom = 'Great Hall'
gameInstructions = 'The instructions are as follows: go north, go south, go east, go west'
print(gameInstructions)
print(currentRoom)

userDirection = ''
while userDirection != 'exit':
    userDirection = input("Pick a direction, or type exit to exit the game.")
    if currentRoom == 'Great Hall':
        if userDirection == 'go south':
            currentRoom = move_rooms(userDirection, currentRoom)
            show_instructions()
            print(currentRoom)
    else:
        print('Invalid direction. Please pick another direction.')
        print(currentRoom)
        show_instructions()
elif currentRoom == 'Bedroom':
    if userDirection != 'go north' or 'go east':
        print('Invalid direction. Please pick another direction.')
        print(currentRoom)
        show_instructions()
    elif userDirection == 'go north':
        currentRoom = move_rooms(userDirection, currentRoom)
        print(currentRoom)
        show_instructions()
    elif userDirection == 'go east':
        currentRoom = move_rooms(userDirection, currentRoom)
        print(currentRoom)
        show_instructions()
elif 'Cellar' == currentRoom:
    if userDirection != 'go west':
        print('Invalid direction. Please pick another direction.')
        print(currentRoom)
        show_instructions()
    else:
        currentRoom = move_rooms(userDirection, currentRoom)
        print(currentRoom)
        show_instructions()
else:
    if userDirection == 'exit':
        print('Thanks for playing the game!')
        break

This is a small part of a larger text based game that I am supposed to develop as part of my college class. The goal of this program is to get user input to move between rooms. I used the template dictionary given and am trying to restrict inputs to the instruction list with the exception of the word 'exit'. So the major issue I am having is how to use the return function properly in the function I created to yield the correct result. It is giving me a 'KeyError' of 'South' in the console everytime I try to input go south as the first direction. Any help would be appreciated.

Confusion of nested ifelse expression

Consider below expression:

x$Y = ifelse(x$A<= 5 & abs(x$B) >= 2, 
            ifelse(x$B> 2 ,"YES","NO"),
            'NA')

What I understand is that, if A is <=5 and B >=2 then ALL are YES, if not then NO, but I am confused the second ifelse condition. Any help will be highly appreciated.

Thanks

Does anyone know why my code is not working? I am trying to write a series of if statements that determines the user's outputs [closed]

I have tried to rearrange the if statements and I'm sure the problem is a simple fix, anyone's help would be greatly appreciated. enter image description here

Substring search is failing...Any ideas?

I am trying to find the occurrence of a substring in an array. Here is the string:

$string = "🎥🎥🔥🔥🔥Watch the game at @TheGoalTX on #GoaltimeSaturdays!"

Here is the array:

$venues = array (
    [ "name" => "McDonalds", "slogan" => "Im Lovin It" ],
    [ "name" => "The Goal", "slogan" => "GoaltimeSaturday" ],
    [ "name" => "McDonalds", "slogan" => "McRibs are back" ],
    );

Im running an array search in which I want to run a script if either search condition is true:

foreach ($venues as $venue) {
    if ((stristr($string,$venue['name'])) OR (stristr($string,$venue['slogan'])) !== false) {
        include "do.stuff.php";
        }
    }

The two array rows with McDonalds obviously fails. No problem.

But for some reason, the search is failing for the "slogan" element "GoaltimeSaturday" and Im not quite sure why. It should meet the "if" criteria but "do.stuff.php" is never reached.

A little help here / any ideas? Are the ""🎥🎥🔥🔥🔥" emotes or the "#" or "@" characters in the string the issue perhaps? Im at a loss as to why Im not getting a true/positive search result in the foreach loop...

I appreciate the assistance on this...

Just started HTML, CSS, JS and im making something similar to cookie clicker to start off and learn. My auto cps is messed up and i dont know why

https://WearableExaltedModes.benjaminsegger9.repl.co if you spam the one that costs 100 and gives 1 per second you will see the problem. I'm new and this is probably a really simple and obvious mistake but I would be really grateful for some help. It looks liek my 'ifs' dont work for some reason.

JS script.

score = 0;

scoretext = 0;

cookie_increaser = 1;

var dosomething = function () {
  score = score + cookie_increaser;
 document.getElementById("H1").innerText = score;
};

var dosomethingelse = function () {
  if (score > 10) {
    score = score - 10;
    document.getElementById("H1").innerText = score;
    cookie_increaser = 2
  }
}

   var dosomethingelse2 = function () {
  if (score > 20) {
    score = score - 20;
    document.getElementById("H1").innerText = score;
    cookie_increaser = 3
  }
}


var starttimer = function () {
  if (score > 100) {
    score = score - 100
  }
  setInterval(function () {
    score = score + 1
    document.getElementById("H1").innerText = score;
  }, 1000)
  scoretext = scoretext + 1;
  document.getElementById("h3").innerText = scoretext;
}


var starttimer2 = function () {
  if (score > 200) {
    score = score - 200
  }
  setInterval(function () {
    score = score + 3
    document.getElementById("H1").innerText = score;
 }, 1000)
  scoretext = scoretext + 3;
  document.getElementById("h3").innerText = scoretext;
} 

document.getElementById("btn1").addEventListener("click", dosomething)

document.getElementById("btn2").addEventListener("click", dosomethingelse)

document.getElementById("btn3").addEventListener("click", dosomethingelse2)

document.getElementById("btn4").addEventListener("click", starttimer)

document.getElementById("btn5").addEventListener("click", starttimer2)

HTML script.

  <body>
    <h1>      </h1>
    <h1> Clicks <img  width = "50"  
    src="https://www.iconpacks.net/icons/2/free-click-icon-2384-thumb.png" </h1>   
    <h1 id="H1"> 0</h1>
    <button id="btn1">Press me!</button>
    <button id="btn2">Upgrade! -- Cost: 10 points (2 per click)</button>
    <button id="btn3">Upgrade! -- Cost: 20 points (3 per click)</button>
    <button id="btn4">Upgrade! -- Cost: 100 points (1 per second)</button>
    <button id="btn5">Upgrade! -- Cost: 200 points (3 per second</button>
    <h1> Automatic clicks per second</h1>
    <h2 id="h3"> 0</h2>
    <script src="script.js"></script>
  </body>

How to ask if the number is int or float for the user?

As I ask the user if the number is an integer, if he says yes, he will receive an int(input('text')) otherwise, it will receive a float(input('text')) ? ignore if i misspelled

Dealing with two cases when a condition is met?

If the number variable is an integer, an input that is equal to zero should become 'None' and any other value should stay as is. The code below works but for learning purposes I would like to see how this can be achieved differently?

while True:
    try:
        number = int(input('Type an integer: '))  
        if type(number) == int: # If the value is an integer, it proceeds.
            if number == 0: # Here is another 'if' in case the value is zero which has to turn to the 'None' value
                number = None
                break
            else:    # For any other case it should just keep the value from the input above
                break
    except ValueError:
        print("Type an integer")
print(number)

Create index.php that executes different statements if user inputs different folder in url

On my server i have everything redirected to index.php I have to My index.php works as user inputs url

http://ip:80/index.php
then it executes php script as follows

'$input = trim($_SERVER["REQUEST_URI"], "/")

if(){statement}else{statement}'

I want to edit that index file so it executes 2 different if statements 
For example if user inputs this url  http://ip:80/server1/index.php
then it executes statement 1

`if(){statement 1}
if(){statement 2}
else{statement}`

if user inputs url as http://ip:80/server2/index.php then it executes statement2

`if(){statement 1}
if(){statement 2}
else{statement}'

Need a blank cell when IF cell is blank

Long time listener, first time caller...

I'm sure this is simple, but I don't know how to do it.
I am putting together a very simple spreadsheet that will autopopulate the correct shift when a manager is input into a cell. I need to do this cell by cell, because some of the managers overlap shifts.

In place of "name" and "shift" I have the actual manager and shift, but for simplicity sake I have:

=IF(K21="NAME", "SHIFT1", "SHIFT2")

and that works just fine for this because there are only 2 managers with different shifts.

However, when there are no manager names in K21, it still gives me a shift in the other cell.

How do I leave that blank until the manager name is filled in?

(I will also need to have several other "IF" statements in other cells, as there are more managers on those shifts, and nested IF statements are telling me there are too many arguments. Not sure what I'm doing wrong.)

Memory/Flipping tiles Game - trouble looping through it

I am making a memory game. Below is a part of the program. It is the part that takes input from the user and loops until the user has found all the pairs. It is a memory with only two different words so four "tiles" in total.

As long as you choose the correct coordinates and find pairs on both attempts, it works, but if the user enters coordinates for different words (not pairs), I want the game board with these words to be displayed and then print the "previous" game board so that the user can try again. My hope is to solve this using an if statement in "ask_coordinates_and_print_list". But I have big problems making it work. Lines 61 and 63 I have commented on. I suspect that it is the lines that need some type of operator to fix the problem and make the game work.

If you select coordinates [1, 1] and [2, 1] first loop and then [1, 2] and [2, 2] in the second loop, you pass the game. But if you select eg [1, 2] and [1, 1] (different words) the first loop, I want to print the game board with these words and then print the "previous" game board and let the player try again. As it works now, the same game board is printed twice and then the player can try again. How do I make the game work if the player enters coordinates for different words over and over again?

def ask_coordinates_return_coordinates_and_correspondning_words(list_of_found_pairs, nested_word_list_with_full_grading):
    while True:
        try:
            selected_row_word_one = int(input("Which ROW do you choose for the FIRST word:"))
            selected_column_word_one = int(input("Which COLUMN do you choose for the FIRST word:"))
            word_one = (nested_word_list_with_full_grading[selected_row_word_one][selected_column_word_one])
            coordinate_one = []
            coordinate_one.append(selected_row_word_one)
            coordinate_one.append(selected_column_word_one)
            selected_row_word_two = int(input("Which ROW do you choose for the SECOND word:"))
            selected_column_word_two = int(input("Which COLUMN do you choose for the FIRST word:"))
            word_two = (nested_word_list_with_full_grading[selected_row_word_two][selected_column_word_two])
            coordinate_two = []
            coordinate_two.append(selected_row_word_two)
            coordinate_two.append(selected_column_word_two)
            if selected_row_word_one > 0 and selected_column_word_one > 0 and selected_row_word_one <= (len(nested_word_list_with_full_grading)-1) and selected_column_word_one <= (len(nested_word_list_with_full_grading)-1) and selected_row_word_two > 0 and selected_column_word_two > 0 and selected_row_word_two <= (len(nested_word_list_with_full_grading)-1) and selected_column_word_two <= (len(nested_word_list_with_full_grading)-1) and coordinate_one != coordinate_two:
                if coordinate_one not in list_of_found_pairs and coordinate_two not in list_of_found_pairs:
                    if word_one == word_two:
                        list_of_found_pairs.append(coordinate_one)
                        list_of_found_pairs.append(coordinate_two)
                        return word_one, word_two, coordinate_one, coordinate_two
                    else:
                        return word_one, word_two,coordinate_one, coordinate_two
                else:
                    print("You have entered the coordinates of words already found, please try again")
            else:
                print("Not valid choice. Keep in mind that the playing field is the size " + str((len(nested_word_list_with_full_grading)-1)) + "X" + str((len(nested_word_list_with_full_grading)-1)) + " and that you can not select the same coordinates")
        except ValueError:
            print("Not an optional alternative! You must enter a number.")
        except IndexError:
            print("You must select a coordinate on the playing field")

def add_words_to_list(list,words_and_coordinates):
    first_word_coordinate = words_and_coordinates[2]
    second_word_coordinates = words_and_coordinates[3]
    a = first_word_coordinate[0]
    b = first_word_coordinate[1]
    c = second_word_coordinates[0]
    d = second_word_coordinates[1]
    (list[a][b]) = words_and_coordinates[0]
    (list[c][d]) = words_and_coordinates[1]
    return list

def show_list_in_terminal(list):
    for row in list:
        for elem in row:
            print(elem, end=' ')
        print()
def ask_coordinates_and_print_list(nested_word_list, nested_word_list_with_full_grading, improvement_list):
    list_of_found_pairs = []
    while True:
        if len(list_of_found_pairs) < (len(nested_word_list)*2):
            words_and_coordinates =  ask_coordinates_return_coordinates_and_correspondning_words(list_of_found_pairs, nested_word_list_with_full_grading)

            if words_and_coordinates[0] == words_and_coordinates[1]:
                list = add_words_to_list(improvement_list, words_and_coordinates)
                show_list_in_terminal(list)
                print("YOU FOUND A PAIR")
            else:
                list = add_words_to_list(improvement_list,words_and_coordinates)
                show_list_in_terminal(list) # Here I want to print a list of the words that the user has entered
                print("DIFFERENT WORDS")
                show_list_in_terminal(list) #Here I want to print list without the words the user has entered, because the user entered the coordinates of different words. So I want to print the list of from one iteration earlier
        else:
            print("CONGRATULATIONS, YOU WON")
            name = input("enter your name: ") #"enter your name" I have only added to prevent "while true" from looping indefinitely

nested_word_list = [['dog', 'cat'], ['dog', 'cat']]
nested_word_list_with_full_grading = [['  1', '  2'], [1, 'dog', 'cat'], [2, 'dog', 'cat']]
nested_x_list_with_full_grading = [['  1', '  2'], [1, 'XXX', 'XXX'], [2, 'XXX', 'XXX']]
improvement_list = [['  1', '  2'], [1, 'XXX', 'XXX'], [2, 'XXX', 'XXX']]

def main_function():
    show_list_in_terminal(nested_x_list_with_full_grading)
    ask_coordinates_and_print_list(nested_word_list, nested_word_list_with_full_grading, improvement_list)

main_function()

How to Check if elements of two lists are equal or not using IF statement in python?

I have a multidimensional list. I want to check if the elements of different lists are equal or not using if statement only. I have written different versions using for loop and while loop. I am not getting how to do the same thing using if statement only.

Below are my codes.

A =      [[[1], [2]],
          [[3], [4]],
          [[5], [6]],
          [[7], [8]],
          [[7], [8]]]  

# Checking if two lists are equal or not using for loop
for i in range(len(A)-1):
    if A[i] == A[i+1]:
        print('iteration',[i],'=',A[i],'and','iteration',[i+1],'=',A[i+1],'are equal')

Output

iteration [3] = [[7], [8]] and iteration [4] = [[7], [8]] are equal

Using while loop

# # Checking if two lists are equal or not using while loop
i = 1
while i in range(0, len(A)-1):
    if A[i] == A[i+1]:
        print('iteration',[i],'=',A[i],'and','iteration',[i+1],'=',A[i+1],'are equal')
    
    i = i+1

Output

iteration [3] = [[7], [8]] and iteration [4] = [[7], [8]] are equal

How can I achieve the same result using if statement only?

Bash script mandatory option

I try to write a script with option mandatory

c, p and e options are mandatory. c can be any words p can be any words e can be only two values : aa or bb with help option

usage() {
 echo "Usage: Script -c <cons> -p <pri> -e <ert>"
  echo "options:"
                echo "-h      show brief help"

  1>&2; exit 1;
}

Help() {
  echo 'HELP'
}

while getopts "h?p:c:e:" args; do
case $args in
    h|\?)
        Help;
        exit;;
    p) pri=${OPTARG};;
    c) cons=${OPTARG};;
    e) ert=${OPTARG};;
  esac
done

if [[ -z "$pri" ||  -z "$cons" ]] || [[ ! ( $ert == 'aa' || $ert == 'bb' ) ]]; then usage; fi

echo "$pri"
echo "$cons"
echo "$ert"

I don't understant logical operation.

if statement must be false, like that I can echo the three strings, if statement is true, I print the usage function.

if [[ 1 ||  1 ]] && [[ ! ( 1 || 0 ) ]]; then usage; fi
     (1 + 1 ) && !(1 + 0)
       1 && 0
        0

       false, don't used usage function = correct


  if [[ 1 ||  1 ]] && [[ ! ( 0 || 0 ) ]]; then usage; fi
     (1 + 1 ) && !(0 + 0)
       1 && 1
        1

       it should use usage function, but it does't do

when I used e option equal cc, I don't get usage function, but the echo below. So I don't understand why

Idictionary if statements C++

I'm just asking in general. I have Idictionary with multiple values added to make a specific key from a normal dictionary variable. I am getting an error where it is saying I am adding something with the same specific key which I understand why. I am just confused on how to make an if-statement for the idictionary variable so like:

if idictionary cannot add key because it contains a key that is the same
{
    ignore adding value. 
}

How may I implement this? Thanks!

i have html code with JS in it, i have a problem that the submit button not giving me an alert window, can you correct my code?

this is part of my code:

Degree:

                <script>
                    function F2(){
                        var y = document.getElementById("dd");
                            if (y>=73){
                            window.alert("Your degree is less then required");
                            }
                    }
                </script>

it's in a form, i hope someone help me in my code.

Why i've this error in my discord.py code

I am developing a bot with discord.py and I have a bug that I cannot resolve. I don't think the latter is from discord.py but from python (I'm a newbie in this area)

My problem: I test a first condition in an "if". If this is true I test other conditions with another "if". On the other hand if the first "if" returns false, with I test other conditions with an "else" then "if" in this one.

In my very first "if", if true, all subsequent "if" statements are executed even when they shouldn't. I have the same problem with the "if" in the else.

a shema:

if ...:
   if ...:
        ...
   if ...:
        ...
else:
   if ...:
        ...
   if ...:
        ...

my real code:

@commands.command()
async def help(self, ctx, categorie = None)
        if categorie == None:

            await ctx.send(f"Mon préfixe sur ce serveur: `{pref}`\n\nSur quelle partie du bot voulez vous de l'aide ?\n`utile` | `fun` | `recherches` | `moderation` | `creator`")

            def checkMessage(message):
                return message.author == ctx.message.author and ctx.message.channel == message.channel

            partie = await self.client.wait_for("message", timeout = 20, check = checkMessage)
            if partie.content == "moderation" or partie.content == "Moderation":
                await ctx.send(embed=modembed)
            if partie.content == "utile" or partie.content == "Utile":
                await ctx.send(embed=utileembed)
            if partie.content == "fun" or partie.content == "Fun":
                await ctx.send(embed=funembed)
            if partie.content == "recherches" or partie.content == "Recherches":
                await ctx.send(embed=recherchesembed)
            if partie.content == "creator" or "Creator":
                creatorembed.set_thumbnail(url="https://zupimages.net/up/20/52/qpa0.png")
                await ctx.send(embed=creatorembed)
        else:
            if categorie == "moderation" or "Moderation" or "mod":
                await ctx.send(embed=modembed)
            if categorie == "utile" or "Utile" or "util":
                await ctx.send(embed=utileembed)
            if categorie == "fun" or "Fun":
                await ctx.send(embed=funembed)
            if categorie == "recherches" or "recherche" or "Recherches" or "Recherche" or "rech" or "Rech":
                await ctx.send(embed=recherchesembed)
            if categorie == "creator" or "Creator":
                    creatorembed.set_thumbnail(url="https://zupimages.net/up/20/52/qpa0.png")
                    await ctx.send(embed=creatorembed)

it return me: result 1

result 2

Cast a void pointer to another type based on an input parameter

I am trying to create a variable of type A or B based on an input parameter and assign a casted void pointer to it.

void set_info_param(void* info, bool req)
{
    ...
    if (req)
        struct info *capa_info = (struct info *) info;
    else
        struct info_old *capa_info = (struct info_old *) info;
    ... [Use capa_info]
}

When I try to compile it I get the following error:

expected expression before 'struct'

How make a if statement more correctly? (If the random number contains a number from the list, then...)

i want to make a code (Lucky ticket, aka lottery) - with can generate random 6-dight number, after that - programm will check a list (with contain a lucky numbers for win: '11', '22', '33' and etc.) and say - are you win or not. But - theres one problem, i cant make if statement correctly, it always gives me error, not right result with i want. List are contain 9 values: luckynumber = '11', '22', '33', '44', '55', '66', '77', '88', '99'.

vendredi 3 décembre 2021

Why is this Javascript 'if' statement not working?

I am trying to create an image viewer in javascript. So, there's this function where I am decreasing the size of image when '-' button is pressed or mouse wheel is scrolled downwards. But after the image's height goes below 10px, I can't enlarge it back anymore. So, to tackle that issue, I thought of putting an if statement where it'll check the height of the image and won't decrease the size if it's not above 10px. But, that if statement is not working. And I can't figure out why.

Below is a piece of my code. I tried to put an console.log() to check if it's going into the if statement or not. But, it's not going.

function decrease_image(){
    var img = new Image();
    img = image_viewer_pics[current_viewer_image];
    
    if (img.style.height < "100%"){
        img.style.margin = "auto 0px";
    }

    if (img.style.height > "10px"){
        img.height = img.height / 1.1;
        console.log("greater than 10px");
    }
    
}

If, else if and else syntax within for loop in R

This is the sample dataframe I'm working with:

numbers <- data.frame(value=c(-5000,1,2,100,200,300,400,500, 1000, 2000, 10000, 12000))

I'm looking to create a new column in this data frame called "output" that contains values as follows:
-Same value as in column "value" if value between 1 and 10000
-10000 if the value in column "value" is more than 10000 and
-1 if the value in column "value" is less than 1

Desired output in the new column "output": 1,1,2,100,200,300,400,500, 1000,2000, 10000, 10000.

I would really like to learn how to use for loop, if, else if and else statements to get this output and have tried the following:

for (i in 1:nrow (numbers$value)){
  if (numbers$value[i] >10000){
    numbers$output <- 10000)
  } else if (numbers$value[i] < 1){
    numbers$output <- 1)
  } else {
    numbers$output <- numbers$value)
  }
}

Unfortunately, this gives me an error, Error: unexpected '}' in "}"

Appreciate your help in fixing this code!

Java boolean "Unexpected return value"

I'm new to Java and I can't understand why the IDE says that "Unexpected return value" inside the forEach where I declared that the boolean is true or false by an If statement. My goal is to check that there is an object inside the "States" HashMap which already uses the name that I want to set to a new state. (The HashMap's key is a String which is called IdentifierOfState and the value is my State object which contains variables like its name.) Thank you for your help in advance!

public boolean isStateNameClaimed(String NameOfState)
{
    States.forEach((IdentifierOfState, ValueOfState) ->
    {
        if (ValueOfState.getNameOfState().equalsIgnoreCase(NameOfState)) {return true;}
        else {return false;}
    });
    return false;
}

Renew list for every iteration

I want to renew the "namelist" for each iteration and use "if" to compare "name" against "namelist". The first iteration will always replace the content of "namelist" because the "namelist" at the first iteration is empty. For iteration number x, I therefore want "name" to be compared with the list's content from the previous iteration, ie x - 1. I do not want to append "name" to "namelist" but replace the entire content so the comparison is always between "name" and the latest version of "namelist". The "#-line" in the code shows where I think the operator should be.

def loop():
    namelist = []
    a = 1
    while a < 5:
        name = input("enter your name")
        if name != namelist:
            # operator that replaces the contents of "name list" with "name"
        else:
            continue
        a += 1

loop()

Excel IF AND Statement 3 Conditions and 1 Outcome but formula populated Unwanted Results

Hello Everyone this is my first post asking for Excel help.

Please be patient with me.

Currently I am creating a spreadsheet tracking hours.

Maybe I am using the wrong formula?

=IF(AND([@[Date]]>=DATEVALUE("05/01/2021"),[@[Date]]<=DATEVALUE("05/31/2021"),[@[Present OR Absent]]="Absent"),"May Absent","May Present")

What I want to do for this Column is to show if for the Month of May if someone is physically at that location.

The Date column ranges from January 2021 - October 2021. My formula catches the May month both May Present and May Absent correctly....... BUT

For Row items outside of May, unwanted results populated for months outside of May ie in 06/01/2021 Row I will see "May Present"

Is there another formula better fitting for what I am looking for? If so what is it?

Secondly how can I eliminate "May Present" for months outside of May? I just want a blank cell maybe ""?

The date Column is the First Column (A). Present or Absent Column (H) is to the Right of the Date Column and the Month Absent/Present Indicator Column (M) is to the right of the

Thank you for reading this far.

how do i return variables in c# if [closed]

I have code like this and i want to use numbersB var in other if, how can i return it?

if ((n2 > 0 && n2 <= 10) && (m2 > 0 && m2 <= 10))
{
    for (int i = 0; i < (n2 * m2); i++)
    {
        var lineB = Console.ReadLine().Split(' ');
        var numbersB = Array.ConvertAll<string, int>(lineB, int.Parse);
        return numbersB;
    }
}

u-boot how to call command via "if" or "echo"

Problem description:

When I'm reading a register of my device via i2c all is fine and is showing status as expected:

*HOSTMCU> i2c md 0x52 0x32 1
0032: 10    .
STM32MP>* 

My target is to use this information in if statement, but I'm not able to do it. I tried to construct this statement in different ways by without success:

*HOSTMCU> if test i2c md 0x52 0x32 1 = 31; then; echo "TRUE"; else echo "FALSE"; fi; 
TRUE

HOSTMCU> if test `i2c md 0x52 0x32 1` = 31; then; echo "TRUE"; else echo "FALSE"; fi; 
TRUE

HOSTMCU> if test `i2c md 0x52 0x32 1` == 31; then; echo "TRUE"; else echo "FALSE"; fi; 
TRUE

HOSTMCU> if test i2c md 0x52 0x32 1 == 31; then; echo "TRUE"; else echo "FALSE"; fi;   
TRUE

HOSTMCU> if test 'i2c md 0x52 0x32 1' == 31; then; echo "TRUE"; else echo "FALSE"; fi; 
TRUE

HOSTMCU> if 'i2c md 0x52 0x32 1' == 31; then; echo "TRUE"; else echo "FALSE"; fi;

Unknown command 'i2c md 0x52 0x32 1' - try 'help'
FALSE

HOSTMCU> if 'i2c md 0x52 0x32 1' == 31; then; echo "TRUE"; else echo "FALSE"; fi; 

Unknown command 'i2c md 0x52 0x32 1' - try 'help'
FALSE

HOSTMCU> if i2c md 0x52 0x32 1 == 31; then; echo "TRUE"; else echo "FALSE"; fi;   
0037: 10    .
TRUE

HOSTMCU> if 'i2c md 0x52 0x32 1' == 31; then; echo "TRUE"; else echo "FALSE"; fi; 
Unknown command 'i2c md 0x52 0x32 1' - try 'help'
FALSE

HOSTMCU> if `i2c md 0x52 0x32 1` == 31; then; echo "TRUE"; else echo "FALSE"; fi; 
Unknown command '`i2c' - try 'help'
FALSE

HOSTMCU> if $(i2c md 0x52 0x32 1) == 31; then; echo "TRUE"; else echo "FALSE"; fi; 
Unknown command '$(i2c' - try 'help'
FALSE

HOSTMCU> if $(i2c md 0x52 0x32 1) == 10; then; echo "TRUE"; else echo "FALSE"; fi; 
Unknown command '$(i2c' - try 'help'
FALSE

HOSTMCU> if $(i2c md 0x52 0x32 1) -eq 10; then; echo "TRUE"; else echo "FALSE"; fi; 
Unknown command '$(i2c' - try 'help'
FALSE

HOSTMCU> if i2c md 0x52 0x32 1 -eq 10; then; echo "TRUE"; else echo "FALSE"; fi;    
0037: 10    .
TRUE

HOSTMCU> if i2c md 0x52 0x32 1 -eq 1e; then; echo "TRUE"; else echo "FALSE"; fi; 
0037: 10    .
TRUE

HOSTMCU> if i2c md 0x52 0x32 1 -eq 13; then; echo "TRUE"; else echo "FALSE"; fi; 
0037: 10    .
TRUE

HOSTMCU> if $(i2c md 0x52 0x32 1) -eq 13; then; echo "TRUE"; else echo "FALSE"; fi; 
Unknown command '$(i2c' - try 'help'
FALSE

HOSTMCU>*

Question: As I mentioned above, my target is to compare this read value from i2c register with the second value. What I'm doing wrong in this IF statement?