Questions tagged [conditional-operator]
The conditional operator is a ternary operator that is part of the syntax for a basic conditional expression in several programming languages. It is also commonly referred to as the ternary operator or inline if. Different languages have different syntax for the same construct, but all select between one of two options based on a condition.
conditional-operator
1,999
questions
1
vote
1
answer
51
views
Ternary operator not working inside Lambda function Ruby
I am trying to write a Lambda function in Ruby, to calculate the nth Fibonacci number.
fib = -> (n) { n in [1, 2] ? 1 : fib.[n - 1] + fib.[n - 2] }
This gives me the error,
./fib.rb:3: warning: ...
-2
votes
0
answers
51
views
ternary operator is not working in a javascript code [closed]
This is the task:
Next to the Nickname: text, add an embedded expression that will show the player's nickname if they have one.
Use a ternary operator to check if nickname is not null. If the player ...
1
vote
3
answers
82
views
python pandas dataframe select rows with ternary operator
I have what has to be considered a syntax question. I am doing some data scrubbing. My data contains date time fields. The date is always present, but sometimes the time is missing. Like this:
3/1/...
-1
votes
1
answer
54
views
dplyr returning NA in new column and not following conditions
I have one data frame about animal sightings (more than 300), with species of whales, dolphins, pinipedes and penguins.
And I want to create a new column reino, which would be misticeto for whales, ...
0
votes
1
answer
39
views
Unexpected token '?' in expression or statement
I'm trying to run a script I didn't write and I'm getting this issue:
Unexpected token '?' in expression or statement.
The line of code causing this is:
$configuration = $Env:ASPNETCORE_ENVIRONMENT -...
6
votes
1
answer
205
views
Why does this ternary generate more Assembly than an equivalent if?
So someone on a forum asked why this C function (which I added const and restrict to, just in case):
void foo(int *const restrict dest, const int *const restrict source) {
*dest = (*source != -1) ?...
15
votes
2
answers
543
views
Moving after copying in assignment of conditional operator result
Simplified program as follows
struct S {
S() {}
S(const S &) {}
S(S &&) = delete;
};
S x;
S y = false ? S() : x;
is accepted just fine by GCC and Clang, but the latest Visual ...
1
vote
1
answer
51
views
Why is it saving the whole mongodb clause not the timestamp?
When I am running it it's saving this whole clause
“$cond”: bson.M{
“if”: bson.M{“$eq”: bson.A{“$date”, nil}},
“then”: time.Now(),
“else”: “$date”,
},
in the document. ...
2
votes
2
answers
81
views
On this Conditional Expression, what the syntax error about?
I get:
return r.group() if r := re.match(rx,l) else None
^
SyntaxError: invalid syntax
whereas
return r.group() if (r := re.match(rx,l)) else None
is accepted.
What ...
0
votes
1
answer
46
views
Inserting Javascript array elements into another array with ternary operator
I have an array of objects where each object defines a field in a React form. I want to display different sequence of fields depending on a boolean state. This means that I need to insert either one ...
0
votes
1
answer
35
views
How to use ternary operator for function calls and button text in vuetify vue js 3?
I'm trying to have login button which toggles between icons "loginIcon/logoutIcon", tooltip toggles between Login/Logout and also the corresponding function onclick changes to login/logout.
...
0
votes
1
answer
21
views
Conditional rendering not working for flutter widgets
Inside the build method 👇🏽
Widget build(BuildContext context) {
final provider = Provider.of<StateProvider>(context, listen: false);
// Get the selected question details from the ...
0
votes
2
answers
41
views
Understanding the use of bitwise-operator in ternary-operator
I'm just learning how to code and while studying sorting algorithms I was asked to "see if you can combine the two lines in your if and else blocks into one line to make your code look a little ...
0
votes
0
answers
35
views
Cannot apply condition to grep output in bash script [duplicate]
The data for this script comes from curl and then I grep a few specific response headers. For this example let's focus on "cf-cache-status". This header has 4 potential values (EXPIRED, HIT, ...
1
vote
2
answers
99
views
Why the result type of conditional expression is const reference?
There's a snippet of code:
int x = 0;
const int y = 0;
decltype(auto) z = true ? x : y;
static_assert(std::is_same_v<const int&, decltype(z)>);
According to [expr.cond], the second operand ...
0
votes
1
answer
36
views
Conditionally generate HTML based on the value of database using JavaScript
I'm new to JavaScript and I'm at a loss to why this isn't working.
I have a .csv files that fills a chart using its data, I want to apply a certain CSS class/id when one of the value in the database ...
-4
votes
1
answer
75
views
Conditional filter javascript (react) - combining two logical operators - || and && or && and &&
Basically in my react app I want to filter an array that meets 3 conditions, but if I use && (and) two times it doesn't work, only if I use || (or) and && (and) together.
Example of ...
-3
votes
2
answers
129
views
How can I write more efficient code? Or, why does a decompiler produce code that appears less efficient than what I wrote?
When writing my library, I used a series of ternary expressions:
public INumber Level1()
{
INumber number = Level2();
Next();
return
txt == "-" ?
new Subtraction(number, Level1(...
0
votes
2
answers
57
views
Simplify expression with ternary operator
Can the following code be shortened/simplified without introducing a division?
a, b, c and y are arbitrary integer values:
int x = 0;
if (y > 0) {
x = c < y * a ? 1 : c < y * b ? 2 : 4;
}
...
0
votes
1
answer
62
views
annotating an object with a list of objects related to it but filtered down
I have the following objects (simplified just for this question)
class Object1(models.Model):
users_assigned_to_object1 = models.ManyToMany(Users, related_name='objects')
sub_object = models....
0
votes
0
answers
29
views
How to prevent ternary operator indentation in swiftlint?
I want to break the ternary operator into separate lines like this:
first < second
? return 1
: return 2
But the SwiftLint configurations always tries to add extra indentation like this:
first <...
0
votes
1
answer
36
views
Explanation of the associativity of nested conditional operators
I do know that conditional operators have right associativity, but can't understand how the flow of condition1 , condition2 , expression1 , expression2 , expression3 are all happening one after ...
-1
votes
1
answer
78
views
Why did I get a warning "expression is assigned to nothing" in ternary?
I have some simple age classification code in which I try to use ternary operator. It worked, but VS Code shows a yellow line underneath the code saying that "expression ... is assigned to ...
0
votes
1
answer
38
views
Convert items in Vec that match an if-condition to NaN [duplicate]
I have a Vec<f32> with zero values that I'd like to convert into NaN. Is there a way to do this by modifying the Vec in-place with a conditional statement?
This is what I tried so far:
let mut ...
-1
votes
1
answer
89
views
Finding the max negative number, min postive number in C using ternary operato (no while loop, for loop )
int main() {
int a, b, c, d, e, f;
scanf("%d %d %d %d %d %d", &a, &b, &c, &d, &e, &f);
int max = (a < 0 ? a : 0);
int mmin = (a > 0 ? a : 0);
...
1
vote
1
answer
28
views
Conditional Expression for variable is not working in ZSHVER=5.9
Any idea why -v is not working in version 5.9?
% unset foo;
% [[ -v foo ]] && echo "foo";
zsh: unknown condition: -v
Directly from section "12 Conditional Expressions" in ...
0
votes
1
answer
34
views
Ternary Operator not displaying row when condition is false but displays when true
I usually don't post on here but I've been scratching my head at this for a couple days now. I have a tabbed table that's suppose to display applicants that have been accepted in one and applicants ...
1
vote
1
answer
59
views
Initializing a Variable for Strings Using Ternary Operators in C
So I want to set strings as my variables' value which is dependent on some other test cases.
const char* trial_1;
const char* trial_2;
const char* trial_3;
trial_1 = (...
2
votes
1
answer
75
views
How to decide on type in template argument (i.e. ternary operator at compile time)? [duplicate]
I want some easy, light solution to such syntaxis:
template <bool is_true>
class A {
B<is_true ? int : float> var; // B is just some other templated class
};
And I do not want ...
0
votes
1
answer
67
views
How to play rotate-clockwise animation when slide-out-tl animation ends also final keyframe position is to be maintained before roatation
Certainly! I am seeking assistance with synchronizing CSS animations within a React component. Specifically, you want to ensure that one animation (`slide-out-tl`) plays immediately upon component ...
0
votes
1
answer
149
views
is there a predefined functor for conditional operator in c++?
Predefined functors are used as wrappers for operators in c++ to use, for example, in STL algorithms. There seems to be a wrapper for all operators except conditional. Is it missing? If yes, why?
...
0
votes
1
answer
199
views
Getting token from a context in Next js
I'm encountering this error in my Next.js application:
Error: Hydration failed because the initial UI does not match what was rendered on the server.
Inside my Navbar component, there's an li tag that ...
0
votes
0
answers
45
views
jakarta.el.PropertyNotWritableException: Illegal Syntax for Set Operation for the PrimeFaces <p:selectOneMenu /> component [duplicate]
Currently we are migrating the Jakarta Faces application from WildFly to Spring Boot v.3.1.1 using JoinFaces v.5.1.1. The version of PrimeFaces is 12.0.0. The implementation of Jakarta Faces is ...
-1
votes
1
answer
103
views
best way refactoring the ternary operator Java
isCredit is the common boolean value. Please pay attantion that we put the same values, (but crossing) on debet and credit side depends on boolean
.setDebetSide(new DebetSideDto()
...
2
votes
1
answer
174
views
Which compiler is correct for this subtle ternary operator code example, gcc or clang?
Consider the following code:
#include <unordered_map>
#include <iostream>
template<template<class, class, class...> class Map, typename Key, typename T, typename KeyP, typename......
0
votes
1
answer
221
views
Trying to use the ternary operator to display the value of a variable if the variable is greater than a given number
I am going through the JavaScript curriculum of FreeCodeCamp and I am stuck trying to get a return value for the 'hit' variable by using a ternary operator.
What FCC wants me to do to pass the ...
-4
votes
4
answers
235
views
Conditional Operator vs if else
Can we use multiple lines of statements inside the true section of conditional operator like in if else?
(a>b)? large = a; printf("%d",a) : large = b; printf("%d",b);
Can we ...
-1
votes
2
answers
74
views
Multiple actions for true (or false) in JS ternary shorthand syntax?
I have been picking up JavaScript recently, and was wondering what the proper syntax would be for setting multiple variables for each outcome in a shorthand ternary.
Here is an example of what I ...
-3
votes
2
answers
74
views
C# ternary operator + convert in CHAR not working [closed]
I'm currently learning C#, I am a beginner, so I'm not really familiar with the particularities of this language.
My problem is:
I have this piece of code which is supposed to convert an INTEGER to a ...
0
votes
1
answer
81
views
ProjectEuler Problem 17: I change this one line of code, and my answer changes drastically, even though I think it should work fine
I am working on Project Euler problem 17. I am supposed to write a program that will count up the total number of characters in the numbers 1-1000 written out. You ignore whitespace and hyphens. The ...
5
votes
2
answers
193
views
Weird behaviour of ternary Operator with cascade dart
Why do both of the results print the same?
final list1 = [ "a", "b", "c" ];
final result1 = true ? list1 : list1..removeWhere((e) => e == "a");
print(result1)...
1
vote
0
answers
55
views
Divide by zero in ternary statement in bash on RHEL6 but not RHEL7
UPDATE:
RHEL7 bash version: 4.2.46(2)-release (x86_64-redhat-linux-gnu)
RHEL6 bash version: 4.1.2(1)-release (x86_64-redhat-linux-gnu)
Okay, so here's a weird one....
I'm remotely executing a bash ...
0
votes
1
answer
56
views
Ternary operator logic not working for boolean, evaluating to false when it's not false
I'm mapping a little block of project objects for a set of footer links and I want each project name to be followed by a | EXCEPT the last one. Here's the code.
const projects = [
{
lastOne: ...
0
votes
1
answer
74
views
Conditional statements-Nested statements
Men Women Category
<0.90 <0.80 Normalweight
0.90 to 0.99 0.80 to 0.84 Overweight
1.0+ 0.85+ Obesity
Given ...
-4
votes
3
answers
122
views
C#: String.Format Can i use "If" statement inside? [closed]
Im creating a C# program that uses String.Format to create a string that show a lot of information from a collected Windows Forms to a textbox. To simplify if-else treatment im thinking in using ...
1
vote
1
answer
112
views
Why does a ternary operator make a character variable print an integer rather than a character?
char g = 'G';
int i = 0;
System.out.print(1 == 1 ? g : 0);
System.out.print(" ");
System.out.print(1 == 0 ? i : g);
In theory, this should print out "G G" as it prints the value ...
0
votes
2
answers
70
views
Condition operator, doesn't react on condition changes, I guess
I have a React component representing a form with inputs (Text, Number, Date). The date input has a default value - today. I use this component for two functions: creating an object and editing an ...
0
votes
0
answers
34
views
Why is the conditional operator in java behaving diffrently with conversions? I want to print float as integer form if the decimal part is 0 [duplicate]
I wanted to make a type of formatted printing (without using the printf() method) so that I can print a float varible without decimal point if the number does not contain a decimal part. I chose to ...
0
votes
2
answers
256
views
Typescript is complaining about ternary operator
I have a simple function in component:
const Button = ({text}: Props) => {
const {t, ready} = useTranslation();
const [title, setTitle] = useState('');
useEffect(() => {
if (ready) {
...
0
votes
2
answers
501
views
Filter a sheet to keep rows only when they have a value in one column OR another column
I've got an array of 5 rows, 5 columns (as an example, my spreadsheet has 500 rows). I would like // to set a filter on that sheet to keep only rows which column 4 or clumn 5 equal to a value.
I don't ...