Golang switch statement only calls function once - go

I encountered a rather strange bug writing a program in Go.
Essentially, I have a switch statement where each case is supposed to call a function, setill, twice. But when the relevant case runs, it only calls the function once.
Here's the code snippet:
check := true
n, e, s, w := b.North, b.East, b.South, b.West
switch {
// NE (>)
case n.Closed && e.Closed:
check = check && p.setIll(s)
check = check && p.setIll(w)
// NS (\\)
case n.Closed && s.Closed:
check = check && p.setIll(e)
check = check && p.setIll(w)
// NW (^)
case n.Closed && w.Closed:
check = check && p.setIll(e)
check = check && p.setIll(s)
// ES (v)
case e.Closed && s.Closed:
check = check && p.setIll(n)
check = check && p.setIll(w)
// EW (//)
case e.Closed && w.Closed:
fmt.Println("Running setIll the first time")
check = check && p.setIll(n)
fmt.Println("Running it again")
check = check && p.setIll(s)
fmt.Println("And now we're done running")
// SW (<)
case s.Closed && w.Closed:
check = check && p.setIll(n)
check = check && p.setIll(e)
}
Here's setIll:
func (p Player) setIll(n *Node) bool {
fmt.Println("I'm running!")
p.Illegal.Nodes[n.Loc.X][n.Loc.Y].Closed = true
return !p.Forced.Nodes[n.Loc.X][n.Loc.Y].Closed
}
This produces the following output:
Running setIll the first time
I'm running!
Running it again
And now we're done running
Notice that "I'm running!" only appears once in the output. Any idea why this may be?

It's not the switch tripping you up, it's how && works.
&& and || are short-circuiting operators: they don't execute what's on the right-hand side at all if the left-hand result is enough to determine what the answer will be. If your expression were a && f() and a were false it's not necessary to run f() to see that the end result will be false too. The way the Go spec puts this is "The right operand is evaluated conditionally."
This is common across a lot of languages. It's helpful when your first check has to pass for it to make sense to run the others. For example, say you want to check user permissions in a Web app, but only if a user is logged in at all (user != nil): user != nil && user.HasPermission(requiredPerm) does what you need.
If you want to set the check var the same way you're doing it now, but with setIll always called twice, you can assign the setIll results to variables outside of any && expression:
ck1, ck2 := p.setIll(n), p.setIll(s)
check = check && ck1 && ck2

Related

Why atomic.Load not called to load gcphase in runtime.GC?

I wonder why gcphase is not protected with atomic.Load:
n := atomic.Load(&work.cycles)
if gcphase == _GCmark {
// Wait until sweep termination, mark, and mark
// termination of cycle N complete.
gp.schedlink = work.sweepWaiters.head
work.sweepWaiters.head.set(gp)
goparkunlock(&work.sweepWaiters.lock, "wait for GC cycle", traceEvGoBlock, 1)
} else {
// We're in sweep N already.
unlock(&work.sweepWaiters.lock)
}
Anyone knows?
Code excerpt:
func setGCPhase(x uint32) {
atomic.Store(&gcphase, x)
writeBarrier.needed = gcphase == _GCmark || gcphase == _GCmarktermination
writeBarrier.enabled = writeBarrier.needed || writeBarrier.cgo
}
while gcphase is a global variable, but all writes to gcphase are done through the above function.
There were several variables in runtime which aren't paired properly, but seems they have reason for it and were sure they were having the exclusive access to it.
Here is the issue https://github.com/golang/go/issues/21931 filed about the same and here https://go-review.googlesource.com/c/go/+/65210 GC developers had some discussions on changing the same.

C++: ambiguous overload for 'operator='

I'm using the Code::Blocks IDE and whenever I try to build the file this code brings up an error:
{
cin >> input ;
locale loc;
for (string::size_type i=0; i<input.length(); ++i)
input[i] = tolower(input[i],loc);}
{
if (input == "not")
"" != "";
else if (input == "and")
"" && "";
else if (input == "or")
"" || "";
else if (input == "yes")
input = true;
else if (input == "no")
input = false;
}
The error occurs where I try to make the word "no" equal to the Boolean operator false.
This brings up this error:
Projects\Samantha\main.cpp|40|error: ambiguous overload for 'operator=' (operand types are 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' and 'bool')|
Now I've tried searching for this problem but I haven't been able to find anything to help me. If someone could please help me to figure what the problem is and how I can fix it I would be very appreciative.
The problem is that you are trying to assign a Boolean to a string.
You have two options here
Create a bool variable where you will store your false value
assign a string literal instead of a boolean input = "false";
Please note that the first three ifs are doing nothing since you are performing logical operations on empty string literals and not storing the result anywhere.
I'd also recommend to avoid using if() conditions without following braces since that is an error-prone, difficult to maintain and difficult to read approach.
else if (input == "yes")
{
booleanVariable = true;
}

How to check for a Not a Number (NaN) in Swift 2

The following method calculates the percentage using two variables.
func casePercentage() {
let percentage = Int(Double(cases) / Double(calls) * 100)
percentageLabel.stringValue = String(percentage) + "%"
}
The above method is functioning well except when cases = 1 and calls = 0.
This gives a fatal error: floating point value can not be converted to Int because it is either infinite or NaN
So I created this workaround:
func casePercentage() {
if calls != 0 {
let percentage = Int(Double(cases) / Double(calls) * 100)
percentageLabel.stringValue = String(percentage) + "%"
} else {
percentageLabel.stringValue = "0%"
}
}
This will give no errors but in other languages you can check a variable with an .isNaN() method. How does this work within Swift2?
You can "force unwrap" the optional type using the ! operator:
calls! //asserts that calls is NOT nil and gives a non-optional type
However, this will result in a runtime error if it is nil.
One option to prevent using nil or 0 is to do what you have done and check if it's 0.
The second is option is to nil-check
if calls != nil
The third (and most Swift-y) option is to use the if let structure:
if let nonNilCalls = calls {
//...
}
The inside of the if block won't run if calls is nil.
Note that nil-checking and if let will NOT protect you from dividing by 0. You will have to check for that separately.
Combining second and your method:
//calls can neither be nil nor <= 0
if calls != nil && calls > 0

MQL5: how do I automatically delete all un-triggered pending orders before placing new orders?

I am working on a Project that requires me to place a BUYSTOP and a SELLSTOP pair of orders and then on the next bar if those orders are not triggered, then delete them and place fresh ones.
Here is my code:
if(logic == true && OrdersTotal() == 0)
{bool res = OrderSend(....);}
if(OrdersTotal() != 0)
{
if(ordertype == OP_BUY || ordertype == OP_SELL)
{
bool del = OrderDelete(....);
}
}
This code is properly placing orders and deleting them as well when I am testing.
But when the EA is active on the live server, it does not open orders because the platform already has orders of other instruments open.
I'm sure there would be quite an easy way to get around this but since I am a novice, I'm not able to figure that out.
it is not clear whether you use magic number and symbol check.
you should check sth like
int _ordersTotal = OrdersTotal()-1;
for (int i = _ordersTotal; i >= 0; i--){
if (OrderSymbol() != Symbol() || OrderMagicNumber() != magic) continue;
....
}
in different realization, i.e. you can create a function(String Symbol) that checks if you have some working orders placed of the indicated Symbol.
Old proverb says:Measure twice before cut onceThere are actually four values ( three for pendings ) to check before OrderDelete()
As your definition states to handle { OP_{BUY|SELL}STOP } orders, there are following three items to check:
Symbol() match ( not causing unwanted side-effects by deleting other EA's or manual orders )
OrderType() match ( not ignoring the actual state { PENDING | AT_MARKET } and direction { BUY | SELL } of the order )
OrderMagicNumber() match ( not ignoring the UUID selector utility available to be set for each individual OrderSend() )
So, let's sketch the detection process:
int myEaContextAwareMagicNUMBER = ...;
for ( int ii = OrdersTotal();
ii >= 0;
ii--
)
if OrderSelect( ii, SELECT_BY_POS, MODE_TRADES )
{
if ( OrderSymbol() != _Symbol
&& OrderMagicNumber() != myEaContextAwareMagicNUMBER
&& OrderOpenTime() >= Time[1] // Prev. Bar
&& !( OrderType() == OP_BUYSTOP
|| OrderType() == OP_SELLSTOP
)
) continue; // __^ __^ __^ __^ __^ __^ loop for next test
// -------------------------------------------+
// FINALLY PROCESS THE MATCHING OrderDelete() |
// -------------------------------------------+
...
..
.
// -------------------------------------------+
}
else Print( "WARN: OrderSelect() failed at db.POOL.SELECT(), RECORD_NUMBER == ", ii );
So how to delete un-triggered pendings is done.
Next comes the remark about
"... when the ea is active on the live server, it does not open orders because the platform already has orders of other instruments open."
There could hardly be any advice provided without delivering the exact { GetLastError() | _LastError } values.
Some Brokers for some account types do indeed restrict OrderSend() acceptance policies, and thus besides the GetLastError() value the respective Broker Terms and Conditions apply.
Do not hesitate to ask more & may enjoy other Questions/Answers in MQL4 domain.

For loop won't end. Don't know why

I'm writing a for loop for a project that prompts the user to input a number and keeps prompting, continually adding the numbers up. When a string is introduced, the loop should stop. I've done it with a while loop, but the project states that we must do it with a for loop also. The problem is that the prompt keeps running even when 'a = false'. Could someone explain javascript's thinking process? I want to understand why it keeps running back through the loop even though the condition isn't met. Thank you
var addSequence2 = function() {
var total = 0;
var a;
for (; a = true; ) {
var input = prompt("Your current score is " +total+ "\n" + "Next number...");
if (!isNaN(input)) {
a = true;
total = +total + +input;
}
else if (isNaN(input)) {
a = false;
document.write("Your total is " + total);
}
}
};
There is a difference between a = true and a == true.
Your for-loop is basically asking "can I set 'a' to true?", to which the answer is yes, and the loop continues.
Change the condition to a == true (thus asking "Is the value of 'a' true?")
To elaborate, in most programming languages, we distinguish between assignment ("Make 'x' be 4") and testing for equality ("Is 'x' 4?"). By convention (at least in languages that derive their syntax from C), we use '=' to assign/set a value, and '==' to test.
If I'm understanding the specification correctly (no guarantee), what happens here is that the condition condenses as follows:
Is (a = true) true?
Complete the bracket: set a to true
Is (a) true? (we just set it to true, so it must be!)
Try using the equal to operator, i.e. change
for (; a = true; ) {
to
for (; a == true; ) {
You should use a == true instead of a = true......= is an assignment operator
for (; a = true; ), you are assigning the value to the variable "a" and it will always remain true and will end up in infinite loop. In JavaScript it should a===true.
I suspect you want your for to look like this :
for(;a==true;)
as a=true is an assignment, not a comparison.
a == true. The double equal sign compares the two. Single equal assigns the value true to a so this always returns true.
for (; a = true; ) <-- this is an assignation
for (; a == true; ) <-- this should be better
Here's your fixed code :
var addSequence2 = function() {
var total = 0;
var a = true;
for(;Boolean(a);) {
var input = prompt("Your current score is " +total+ "\n" + "Next number...");
if (!isNaN(input)) {
total = total + input;
}
else{
a = false;
document.write("Your total is " + total);
}
}
};

Resources