Compute the index to assign the variable to, instead of which variable to use for each index. int cLocation = a < b ? 0 : 1; array[cLocation] = c; array[1 - cLocation] = d; ...
For this specific case where there are only two possible values to be chosen, you can choose a random number and check whether it's even or odd: int random = (rand() % 2) ? 0 : 3; More generally, you can make a list of the values that are eligible...
java,boolean,ternary-operator,boxing,unboxing
You guessed it right. For a formal explanation, the answer lies in the JLS: If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression...
c++,arrays,function,struct,boolean
The function needs an object or a reference to an object of type Machine. bool drinksRemaining(Machine const& m); and can be implemented very simply: bool drinksRemaining(Machine const& m) { return (m.drinks > 0); } You can use it as: if (selection == 1) { if ( drinksRemaining(drink[0]) ) { cout...
objective-c,boolean,objective-c-literals
@YES is a short form of [NSNumber numberWithBool:YES] & @NO is a short form of [NSNumber numberWithBool:NO] and if we write if(@NO) some statement; the above if statement will execute since the above statement will be if([NSNumber numberWithBool:NO] != nil) and it's not equal to nil so it will be...
javascript,boolean,boolean-logic
The expression operands to && are evaluated left to right. The value of the && expression is the value of the subexpression last evaluated. In your case, that'll be the right-most expression in both cases. So, with (true && {}), the && operator first evaluates true. It's not falsy, so...
Use Bool#values() to iterate over possible values of your enum: for (Bool large : Bool.values()) for (Bool medium : Bool.values()) for (Bool small : Bool.values()) boosters.add(new Boosters.Builder().setLarge(large).setMedium(medium).setSmall(small)); ...
Here's one implementation, but whether it is the one you are after is completely impossible to say, because you have not specified what you think the answer should be: let answer = map(zip(array1,array2)){$0.0 == $0.1} That gives you a list of Bool values, true if the answer matches the right...
If looks like you are assigning to f[0] the following : (lastLine!=null) // есть следующая строка || (f[1]=isEdgeTime) // конец сессии || (f[2]=td.getHour() <10) // или уже утро, после полуночи все свечки хороши || (f[3]=(td.getHour() == 23 && td.getMinute() >=50)) || (f[4]=currServerHour > lineHour) // или час сменился || (f[5]=currServerMinutesPeriod...
You probably want to use: while ((ans != 'N') && (ans != 'Y')) { That checks to see that ans is not N and not Y. If you use || (or) there, then it will check to see that ans is either not N, or not Y (which is true...
You can pad x with Falses (one at the beginning and one at the end), and use np.diff. A "diff" of 1 means transition from False to True, and of -1 means transition from True to False. The convention is to represent range's end as the index one after the...
You could use a where clause: if let number = value as? NSNumber where someBool { // ... } ...
python,select,filter,boolean,limit
I Have improvised code from @FunkySayu. def questionHairstyle(): while True: questionsH = [" 1, for bald;", " 2, for crew-cut;", " 3, for curly;", " 4, for wearing a hat" ] print("Please enter a hairstyle:") print("\n".join(questionsH)) hairchoice = raw_input("-->") #This will take even spaces print() if hairchoice in ["1", "2",...
c++,class,methods,vector,boolean
The problem is that your variable is a vector of a vector of strings: vector<vector<string>> sudoku_; When you call find, you are searching for a string, so you should call it on a simple vector<string>, not on a nested data type. So you must first find the right item in...
c#,boolean,unmarshalling,unions
This is an inevitable side-effect of the way a structure is marshaled. Starting point is that the structure value is not blittable, a side-effect of it containing a bool. Which takes 1 byte of storage in the managed struct but 4 bytes in the marshaled struct (UnmanagedType.Bool). So the struct...
java,oop,boolean,encapsulation
A boolean value is a primitive data type and is thus passed by value only. Only objects are passed by reference. So there are two options for you. Either make your primitive boolean value a Boolean object (as this will be passed by reference). Or have the method return a...
javascript,boolean,warnings,lint
Ok, I've done some research myself since asking this and actually stumbled upon some very similar questions (with answers) to the double negative trick in JavaScript. Here and here I found some explanation of the need of double boolean negative trick itself. To cut the long story short it's like...
"Z" is smaller than "a". If both sides must to be +, and you check for mismatch, the logical connection is OR (= if either of those things are true). if ((str_array[i-1] != "+") || (str_array[i+1] != "+")) note: you don't need to split, you can index into strings....
I Don't know if that helps anybody else, but I was able to fix it by doing 2 things. In Every Radio button I was have to declare 3 different group names(which for me this is wrong but to make it work I didn't have other way), for example <RadioButton...
Your condition is wrong: while(!valid && !before) Your condition tries to get a new birthday if the one entered is invalid and is after the current date. I think you want: while(!valid || !before) Which gets a new birthday if the one entered is invalid or is after the current...
you can put this on your controller. I would assume that the form is on controller#create where you would have: boolean = true if @model.value > x boolean2 = true if @model.value < y then save it on db with @model.save...
This is a perfect use case of sets. The following code will solve your problem: def only_uses_letters_from(string1, string2): """Check if the first string only contains characters also in the second string.""" return set(string1) <= set(string2) ...
Try this: cols <- 12:20 NArows <- which(apply(df[cols],1,function(y)sum(!is.na(y))==0)) It slices your df to just the 'cols' you care about,then applies to each row the test is.na() and if it finds all values in those cols are NA it adds that row number to NArows. Or based on david arenburg's answer,...
while !Reachability.isConnectedToNetwork() { println("Internet connection FAILED") var alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK") alert.show() } println("Internet connection OK") While this answers your question, it is a truly terrible idea. Please don't actually use this in any...
excel,excel-vba,for-loop,boolean,conditional-formatting
You are using Cells notation within your Range. Cells has the form ([RowNumber],[ColNumber]). Range has the form ([CellAddress],[CellAddress]) or (Cells(1,1),Cells(1,2)). For your code, I'd recommend replacing your Ranges with Cellss....
First you're putting the output variable textBox2.Text, then you are replacing the textBox2.Text with err and I believe you're getting nothing from err variable, that's why TextBox2 is not displaying what you're expecting. try to run the snippet below to check how output and err variable are getting: string userName...
I think you are getting null at value assignation desg.ModifiedBy.UserName = userNames.SingleOrDefault(name => ...
objective-c,c,xcode,pointers,boolean
As it became apparent in the comments, you have some function taking a BOOL * parameter, for example void foo(BOOL *boolPtr) { *boolPtr = NO; } and you need to pass the address of your BOOL variable to that function: BOOL isWhiteTurn = YES; foo(&isWhiteTurn); // Now isWhiteTurn == NO...
excel,if-statement,boolean,conditional-operator
To get expected output please try: leave formula in G2 as it is in G3 enter: =IF(OR(F3="Craps",F3="$$$",F3="PtEst"),"ComeOut",IF(G2="ComeOut",E2,G2)) and fill it down. If the the previous value in G column is "ComeOut", then take corresponding E value. If not - copy previous G column value....
ruby-on-rails,ruby,curl,boolean
probably because the parameter is passed as a string instead of as a boolean. Correct. The way I handle this in generic Ruby way is as follows: class String def to_b() self.downcase == "true" end end Now any string will have the to_b method. You can you write def...
swift,int,boolean,type-conversion,bit-manipulation
@martin-r’s answer is more fun :-), but this can be done in a playground. // first check this is true or you’ll be sorry... sizeof(Bool) == sizeof(UInt8) let t = unsafeBitCast(true, UInt8.self) // = 1 let f = unsafeBitCast(false, UInt8.self) // = 0 ...
Two methods in a class which return BOOL values // definition of methodA which calls methodB and returns a BOOL value - (BOOL) methodA { BOOL flag = NO; flag = [self methodB:flag]; return flag; } // definition of methodB which takes a BOOL parameter and return a BOOL value...
The major problem with your code is that input >> select does not read a full line, but it stops at the first whitespace. You then read again what you believe is a bool from the next line, but which in fact is the next character from the first word...
You can simply del your custom name to set it back to the default: >>> True = False >>> True False >>> del True >>> True True >>> ...
java,swing,jtable,boolean,tablecellrenderer
myTable.setDefaultRenderer(Object.class, new MyTableRenderer()); You are creating a Boolean renderer, not an Object renderer. So you should be using: myTable.setDefaultRenderer(Boolean.class, new MyTableRenderer()); but shouldn't calling setDefaultRenderer on Object.class override the default for Boolean.class? No. The Object renderer is used as the default renderer if there is no renderer specified for a...
java,recursion,arraylist,boolean,compare
I think that this is a pretty good start for you. This looks through all your elements, assuming they are an array, and then checks if they are equal in size. public boolean isEqual(ArrayList<?> a, ArrayList<?> b) { if (a.size() != b.size()) return false; for (int i = 0; i...
java,boolean,micro-optimization,bitvector
A boolean uses 1 byte of memory (on hotspot). You could use alternatives: a BitSet: uses approximately 1 bit per boolean + the overhead of the class itself, the reference to the BitSet, the reference to the long[] in the BitSet and the unused space in the long[], i.e. around...
javascript,knockout.js,binding,boolean
You could use this custom bindingHandler, ko.bindingHandlers.YesNo = { update: function (element, valueAccessor) { // defaults to false var val = ko.utils.unwrapObservable(valueAccessor()) || false; if (val) $(element).text("Yes"); else $(element).text("No"); } } Use it like so, <td data-bind="YesNo: isAvailable"></td> Thanks...
java,class,methods,constructor,boolean
However I want this to be done as soon as an instance of the class is created. My question is then where this should be done. Should I do this in a constructor.. Yes, that is perfect place for it since purpose of constructor is to initialize newly created...
if (setting != (true && false)) doesn't do what you think it's doing. The expression (true && false) always evaluates to false: you're doing a logical AND on the literal values true and false. That means that your test reduces to if (setting != false). Since setting is not initialized,...
I always like to write a program for this sort of stuff to see if the logic reasoning will hold out: #include<stdio.h> int main (void) { puts ("A B C"); for (int a = 0; a < 2; a++) { for (int b = 0; b < 2; b++) {...
In your if conditions, you're using assignment instead of comparison. Change this if(ascii=false){ wynik+=slowo.charAt(licznik); } if(ascii=true){ wynik+=(int)slowo.charAt(licznik); } to this if(ascii==false){ wynik+=slowo.charAt(licznik); } if(ascii==true){ wynik+=(int)slowo.charAt(licznik); } ...
That's because value not False is not a valid Python syntax. You probably wanted value is not False The other issue is that you want element instead of value....
In C you can compare an int as a boolean and any non-zero value is considered TRUE. In Java, that is not the case. This if(k) System.out.println(i); should be something like if(k != 0) System.out.println(i); ...
vb.net,visual-studio-2008,boolean,infinite-loop,do-while
I believe the problem may be that you've missed that Rnd returns a value between 0 (inclusive) and 1 (exclusive), meaning when cast to integer, it will never return the upper bound value. So you will need to extend the upper bound to 52 to ensure that index #51 is...
Instead of if (isPrime == 0) { return false; } else { return true; } try return (isPrime != 0); It is the same thing, I'll show you the refactoring path. Starting with if (isPrime == 0) { return false; } else { return true; } is the same as...
Just so you know, in your full source you use the following code: if(lockchat == true) { s.sendMessage("unlocked"); lockchat = false; } else { s.sendMessage("unlocked"); lockchat = true; } more specifically, you are sending "unlocked" no matter which path the code follows. Edit: I reformatted your code to reduce some...
In this method test1, your forloop will traverse the whole line although it finds the letter into the string. so update it like this: public static boolean test1(String a, char b){ for(int i=0;i<a.length();i++) { if(a.charAt(i)==b) return true; } return false; } Because, if the letter is found into the string...
javascript,boolean,compare,boolean-expression
Because what is really happening is this: (a == a) == c Which is really just: true == "first" See Operator Precedence....
You can create a simple class to track the user's status, and by using singletone you can access it from anywhere in the app. SGUser.h #import <Foundation/Foundation.h> @interface SGUser : NSObject + (SGUser *) activeUser; @property BOOL loggedIn; @end SGUser.m #import "SGUser.h" @implementation SGUser + (SGUser *) activeUser { static...
Yes. You can compare boolean value to a boolean literal. It is, however, easier to simply use the bool value for the if statement. Doing that would look like this if(!Alphabet[i]) // Originally if(Alphabet[i]==false) and like this else if(Alphabet[i]) // Originally else if(Alphabet[i]==true) You don't even have to test for...
c++,vector,boolean,const,extraction-operator
Despite the name, vector<bool> contains no bools, and dereferencing its iterator doesn't give you a bool&. Instead, it gives you an object of type vector<bool>::reference, which tries to imitate the behavior of bool& as much as it can. There's no way to convert a vector<bool>::reference to a bool&, so the...
The last expression's value is used as the return so: def checkSimple(str1: String, str2: String): Boolean = { if (str1 > str2) { println("str1 > str2") true } else { println("str1 <= str2") false } } will behave the way you expect...
c#,char,boolean,type-conversion
char contains 2 bytes. you can convert bool array to a byte and then convert it to a character using Convert class. public byte ConvertToByte(bool[] arr) { byte val = 0; foreach (bool b in arr) { val <<= 1; if (b) val |= 1; } return val; } reference...
This is actually covered in the errata: Page 135, the interactive shell should look like this: >>> not False and False # not False evaluates first True >>> not (False and False) # (False and False) evaluates first False (Thanks to Omer Chohan) It has been corrected in the online...
list,python-3.x,boolean,sequence
You will get an error on num += i, because you are trying to add 1 to "". Instead, try the following: def list123(nums): desired = [1, 2, 3] if str(desired)[1:-1] in str(nums): return True return False >>> list123([1, 2, 3, 4, 5]) True >>> list123([1, 2, 4, 3, 5])...
sql,sql-server,select,sum,boolean
OK, Now that we have the DDL (unfortunately without the DML but only one row). we can provide a solution :-) firstly! I highly recommend NOT TO USE the solution above, THERE IS NO NEEDS for loops even you not use fixed data length we know the max len (50)....
What about writing a byte for each boolean and develop a custom parser? This will propably one of the fastest methods. If you want to save space you could also put 8 booleans into one byte but this would require some bit shifting operations. Here is a short example code:...
c++,arrays,constructor,boolean,destructor
GameOfLife::GameOfLife(int y, int x, bool state) { // board is a member variable that gets initialized // with the default constructor. // Then it gets replaced by assignment with a different // Grid object. The temporary object gets deleted at // the end of the line. board = Grid(y, x,...
The problem is this line: if (val = "true") { You're doing an assignment, rather than a comparison. It should be: if (val == "true") { (and then the same for the comparison with "false") As an aside, a better way to perform debug logging is to use console.log and...
aVal in aList The in operator does what you need, if I understand correctly. ...
Already you have done the best way,but if you are looking for a python solution you can use itertools.compress >>> from itertools import compress >>> list(compress(listOfTuples,bool_array)) [(0, 1), (3, 1)] One of the advantage of compress is that it returns a generator and its very efficient if you have huge...
A. b = n == 0; B. b = n != 0; C. b = 1 < n && n < 2; D. b = n < 1 || n > 2; ...
No, there is no reason to write that. a .eqv. .true. is the same as a. Just don't use ==, that is used for different data types. Regarding things found in legacy codes, don't forget that many, if not most, Fortran users are not professional programmers and never received thorough...
java,switch-statement,boolean,break
A break statement would terminate execution of the switch statement and continue in the method. A return statement would leave the method entirely. It's a matter of preference, really, as to which one is better. It comes down to method design. I would say in most cases like you have...
javascript,html5,boolean,local-storage
Local storage stores strings , I'm afraid, whatever the input (if you feed it with an object, it will be converted automatically with its standard toString() method)... So you're doing !! test on a string, which is always true. You should always use JSON.stringify() and JSON.parse() when dealing with what...
So, this is what I've come up with: //Firstly, define the size of the subsystem: int size = 0; for(int i = 0; i < TrueorFalseMatrix.m; i++) { if(TrueorFalseMatrix.data[i][0] != 0) size+= 1; } //Then we can assign the size values to the Matrix of the subsystem System_A = Matrix.matrizEmpty(size,size);...
I want to see a solution without iteration, selection, function calls, etc. ONLY boolean operators allowed. Why? I just want to know if that is possible or not. Looking for a combination of logical operations which provides the same result as the function above. You want to implement this...
java,boolean,variable-assignment
Only the first does not involve any boxing or unboxing. So on the face of it, the first would be the most efficient. However, most compilers (or just-in-time compilers, if present) are likely to optimize the other two assignments to be just as efficient. The story would be different, of...
java,arrays,multidimensional-array,boolean
Your question is rather poorly worded, but from what I understand, you need a method to tell you if your "grid" has something in it other than space. Maybe something like the below could help: private boolean isEmpty() { boolean empty = true; for (int i=1;i<myAsciiGrid.length-1;i++) { for (int j=1;j<myAsciiGrid[0].length-1;j++)...
java,swing,jtable,boolean,jcheckbox
The model's getColumnClass(int columnIndex) method should return Boolean.class for the appropriate column index so that the renderer knows to render a check box for that column. For example,... DefaultTableModel headermodel = new DefaultTableModel(){ @Override public Class<?> getColumnClass(int columnNumber) { if (columnNumber == 2 || columnNumber == 3) { return Boolean.class;...
ios,objective-c,properties,boolean
You should set the property to assign instead of weak for a non-object type such as BOOL. Example: @property (nonatomic, assign) BOOL isValid; ...
actionscript-3,if-statement,actionscript,boolean
Why? Whichever you do, the compiler will optimise it on whatever platform you are currently compiling on. If you need to check if it's 0, use (i == 0), if you want to know if it's less than zero, use that one instead. Write what you would read out loud....
Short answer: integral promotion. In numerical arithmetic, small integral types (including bool, char, unsigned char, signed char, short, unsigned short, etc) are promoted to int if all the possible values fit in int, otherwise they are promoted to unsigned int. On most machines today, int32_t is the same as int....
python,sqlite,python-2.7,sqlite3,boolean
You can use 'in' if condition else 'out': print row [1] + " has been checked " + ('in' if row[3] else 'out') ...
This can be achieved by using a helper. The first argument after the "?" is the true case; the false case follows the ":". The example below uses glyphicons, since you mentioned wanting a check mark, but you could insert "Yes" and "No" or any string or html you desire....
.net,vb.net,string,visual-studio,boolean
When a non Boolean expression is used in the IF statement, Vb.Net compiler will convert the expression to Boolean using Conversions.ToBoolean method. Your code is equal to If Conversions.ToBoolean(StringValueContainingTrueOrFalse) then 'Do Something End if If your value could be converted to a Boolean, all is well. Otherwise exception will be...
Since you are trying to access not a string, but a boolean it returns NULL. As from the manual: Note: Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL. ...
To answer your second issue: I have run into another issue in Line 22 from below You are comparing roadIsdry, which is a boolean, to roadCondition, which is a String, using ==. You used roadCondition earlier to hold the user's input and then parse it. In Java, comparing primitive types...
java,swing,jtable,boolean,bufferedwriter
Obviously the line bfw.write((String)(tabTask.getValueAt(i,j))); is not correct. If you have boolean column you can't cast it to string. Use e.g. bfw.write(""+tabTask.getValueAt(i,j)); Or check class and cast the value depending on the class. Like this Object value=tabTask.getValueAt(i,j); if (value!=null) { if (value instanceof String) { bfw.write((String)value); } else if (value instanceof...
For those who are searching for the solution: BoolToImageConverter.cs: public class BoolToImageConverter : IValueConverter { public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { return (bool)value ? "D:\\Test\\Test\\bin\\Debug\\img\\add.png" : "D:\\Test\\Test\\bin\\Debug\\img\\minus.png"; } public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { return false; // not needed }...
Every expression in Ruby is being evaluated to an object and every object has a boolean value. Many expressions can have a false value, but the only two objects in Ruby to have a boolean value of false are nil and false. That's why....
Assuming your existing data is in A1:B6, then in A10 enter: =COUNTIFS($A$1:$A$6, ROW()-9,$B$1:$B$6, COLUMN()) This will return a 1 or a 0 depending on whether person 1 likes person 1. They don't so you get a 0. It uses Row()-9 to return 1 and COLUMN() to return 1 to find...
c,function,boolean,return,backtracking
In given example what is different between return 1 and return 0? Judging by the following block code if(solve(a)) { return 1; } it seems that a return value of 0 indicates not solved yet and a return value 1 indicates solved. I us int fun() in place bool...
swift,parse.com,boolean,relation
One way you could do it is have a relation to User on Questions called answeredBy, and just add a user to that relation when they answer a question var relation = question.relationForKey("answeredBy") relation.addObject(aUser) question.saveInBackground() Then, to query questions that haven't been answered by the user just add a questionQuery.whereKey("answeredBy",...
If a var is undefined, null or the empty string then it is falsey. You can rely on that as it is part of the specification of the language. It is totally acceptable and widely practiced to check if something is undefined by checking its truthiness.
java,arrays,methods,reference,boolean
add returns an array. Arrays in Java are objects, but they do not override the toString() method. When printing, you'd print their default toString() call, which is implemented by Object as return getClass().getName() + "@" + Integer.toHexString(hashCode());. Luckily, Java provides a utility in the form of java.util.Arrays.deepToString(Ojbect[]) to generate a...
javascript,html,if-statement,onclick,boolean
What you are trying is to concatenate a list inside a paragraph and then splitting it again at run-time, this is not the best way to hide and show a dom element and also semantically incorrect since is not valid to have a list inside a paragraph on the HTML...
ruby-on-rails,ruby,boolean,nested-attributes,sidebar
You can update your Result as follows: class Result < ActiveRecord::Base # rest of the code scope :good, -> { where(good: true) } scope :good_count, -> { good.count } end Let's perform some tests in rails console: u = User.create({ user_attributes }) u.results.create(good: true) u.results.create(good: false) u.results.create(good: true) u.results.count #...