Why must I push IBAction Button twice for action to occur? - xcode

I'm making an app that does a calculation when the IBAction button is pressed. It works fine, but I have to press it twice for the Action to occur. Anyone have experience with this? Below is some code from the #IBAction button in question:
#IBAction func CalculateGPA(sender: AnyObject) {
gpa = (gp + gp2 + gp3
+ gp4 + gp5 + gp6
+ gp7) / (ch + ch2
+ ch3 + ch4 + ch5
+ ch6 + ch7)
gpaLabel.text = NSString(format: " Your GPA is %.2f", gpa) as String
//added if textField == ">9" after first submission
if textField1.text == "10"{
gpaLabel.text = "Enter 1-9 Credit Hours"
}
if textField2.text == "10"{
gpaLabel.text = "Enter 1-9 Credit Hours"
}
And for your info, this Button makes a calculation and changes the input of a label. My guess why I have to press it twice is that the first press does the calculation, the second press changes the label to show the result.

First of all, the formula that you are using to calculate GPA is incorrect. You should not add up total grades and divide by total credit hours as it appears that you are doing. You have to multiply each grade by the the number of credit hours, add that up, then divide by total credit hours:
gpa = (gp * ch + gp2 * ch2 + gp3 * ch3 + gp4 * ch4 +
gp5 * ch5 + gp6 * ch6 + gp7 * ch7) /
(ch + ch2 + ch3 + ch4 + ch5 + ch6 + ch7)
Also, you might want to use an array in a for loop so that if the number of classes changes you can process any number of classes. Imagine if you had 100 classes, putting all this in a giant statement would be silly and time-consuming:
gpa = (gp * ch + gp2 * ch2 + gp3 * ch3 + gp4 * ch4 +
gp5 * ch5 + gp6 * ch6 + gp7 * ch7 ... gp100 * ch100) /
(ch + ch2 + ch3 + ch4 + ch5 + ch6 + ch7 + ... ch100)
Instead say:
var numerator: Int = 0
var totalCh : Int = 0
var gpa : Double = 0.0
// gp and ch should be arrays that are instance variables;
// they should already be filled in either in this function or
// from another location
for (var i: Int = 0; i < gp.count; i++) {
numerator += gp [i] * ch [i]
totalCh += ch [i]
}
if (totalCh > 0) {
gpa = Double (numerator) / Double (totalCh)
} else {
gpa = 0.0 // can't divide by 0. Might want an error message to user here
}
// ...
Also, you should do your validation of user input at the top of your function instead of after you have done the calculation. If the user made an error, you should give some feedback to the user on what he did wrong and how to fix it (as you have done), but do not do the calculation at all until all validations are good.
To answer your original question, we need to see all the code for that function. If textfield1 and textfield2 are filled elsewhere, it would help to see where they fit in.
It is possible that you don't have the IBAction hooked up correctly to your button. Go into the Connections Inspector and click on the button in your StoryBoard, and make a screenprint of what you see and post it here so that we can check to see if you did the connections correctly.
However, since you have to press the button twice to see any results, there is a higher probability that you failed to initialize something, so it had a value of zero or null the first time you pressed the button, but then it got initialized by the end of the function, so when you pressed the button again, it did the calculation and entered an answer into the label.
To see exactly what is going on, you should try stepping through the debugger. If you don't have any experience with that, you could put a bunch of print statements at key locations in your IBAction function to see what is being calculated and to see what statements are executing and to make sure that the function got started at all; at least enter one at the beginning of the function that says "entering IBAction calculateGPA".

Related

Pine script strategy open at second open candel and no when EMA crossover

whith this strategy i would like to have the open trade in exactly moment of ema crossovers, but all time I have open trade when the next candle open.
It is often a problem because at the ema crossovers I have a bullish push but at the opening of the next candle can be bearish causing the loss of the trade.
Can you help me? thanks
//#version=5
strategy(title='MARCO 18/20', overlay=true)
// STEP 1:
// Make inputs that set the take profit % (optional)
FastPeriod = input.int(title='Fast MA Period', defval=18, group='Moving Average')
SlowPeriod = input.int(title='Slow MA Period', defval=20, group='Moving Average')
TPPerc = input.float(title='Long Take Profit (%)', defval=0.11, group='TP & SL')
SLPerc = input.float(title='Long Stop Loss (%)', defval=4.4, group='TP & SL')
TP_Ratio = input.float(title='Sell Postion Size % # TP', defval=100, group='TP & SL', tooltip='Example: 100 closing 100% of the position once TP is reached') / 100
// Calculate moving averages
fastSMA = ta.sma(close, FastPeriod)
slowSMA = ta.sma(close, SlowPeriod)
// Calculate trading conditions
enterLong = ta.crossover(fastSMA, slowSMA)
// Plot moving averages
plot(series=fastSMA, color=color.new(color.green, 0), title='Fase MA')
plot(series=slowSMA, color=color.new(color.red, 0), title='Slow MA')
// STEP 2:
// Figure out take profit price
percentAsPoints(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100.0 * strategy.position_avg_price / syminfo.mintick) : float(na)
percentAsPrice(pcnt) =>
strategy.position_size != 0 ? (pcnt / 100.0) * strategy.position_avg_price : float(na)
current_position_size = math.abs(strategy.position_size)
initial_position_size = math.abs(ta.valuewhen(strategy.position_size[1] == 0.0, strategy.position_size, 0))
TP = strategy.position_avg_price + percentAsPoints(TPPerc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
SL = strategy.position_avg_price - percentAsPoints(SLPerc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
// Submit entry orders
if enterLong
strategy.entry(id='Long', direction=strategy.long)
// STEP 3:
// Submit exit orders based on take profit price
if strategy.position_size > 0
strategy.exit('TP', from_entry='Long', limit=TP, stop=SL)
// Plot take profit values for confirmation
plot(series=strategy.position_size > 0 ? TP : na, color=color.new(color.green, 0), style=plot.style_circles, linewidth=1, title='Take Profit')
plot(series=strategy.position_size > 0 ? SL : na, color=color.new(color.red, 0), style=plot.style_circles, linewidth=1, title='Stop Loss')
Pine script makes the calculations (runs your code) when the bar closed. After that, if your code has an entry, you can enter a trade on the next trade. Since the bar where you run the script is already closed, the trade will be made on the next trade - open price of the next bar. This is basically how real trade will work, since you can't check a trade that already happened and then decide that this trade is good for you or not. You will have to enter on the next trade.
You can override this if you wish.
try enabling in settings: recalculate strategy on each tick

Recursion in Go for coding question: Product Sum

I've been practicing coding interview questions with this current example of Product Sum with Go. Basically, you need to take a nested array and return it's product sum.
Example: [1,3,[2,[5],-3],7] = 1 + 3 + 2*(2-3) + 3*(5) + 7 = 24
Which should also be equal to: 1 + 3 + 2*(2) + 2*(-3) + 3*5 + 7 = 24
However, when I try implementing this in code I can only get the first example.
func ProductSum(array []interface{}) int {
sum := productSum(array, 1)
fmt.Println(sum)
return sum
}
func productSum(array SpecialArray, multiplier int) int {
sum := 0
for _, el := range array {
if cast, ok := el.(SpecialArray); ok {
sum += productSum(cast, multiplier+1)
} else if cast, ok := el.(int); ok {
sum += cast
}
}
return sum * multiplier
}
If I change sum += cast to sum += cast * multiplier, and change return sum * multiplier to return sum - then the function doesn't work as expected. I've tried working through the recursive stack on this but am still confused.
According to your code the "array notation" should be transformed to following equation:
[1,3,[2,[5],-3],7] = 1*(1 + 3 + 2*(2 + 3 * (5) - 3) + 7) = 1 + 3 + 2*(2 - 3 + 15) + 7 = 11 + 14 * 2 = 39
or
[1,3,[2,[5],-3],7] = 1*(1 + 3 + 2*(2 + 3 * (5) - 3) + 7) = 1 + 3 + 2*(-1) + 6 * 5 + 7 = 11 - 2 + 30 = 39
In your interpretation each level of nesting increases the multiplier by one.
Could you paste the exact content of this exercise?
Edit:
To get 24 in result your code should look like this:
func ProductSum(array []interface{}) int {
sum := productSum(array, 1)
fmt.Println(sum)
return sum
}
func productSum(array []interface{}, multiplier int) int {
sum := 0
for _, el := range array {
if cast, ok := el.([]interface{}); ok {
sum += productSum(cast, multiplier+1)
} else if cast, ok := el.(int); ok {
// Multiplier is applied only to integers in current slice.
sum += multiplier * cast
}
}
return sum
}
The sum of an array is always multiplied by the its level of nesting.

work out how many seconds have expired in total during game play

~Why the hell has this had down votes.... you people are weird!
Ok so this is a very simply HTML5 and jQuery and PHP game. Sorry to the people who have answered, I forgot to say this is a php script, i have updated here to reflect.
the first level takes 1 minute. Every level after that takes an extra 10 seconds than the last level. like so;
level 1 = 60 seconds
level 2 = 70 seconds
level 3 = 80 seconds
level 4 = 90 seconds
and so on infinitely.
I need an equation that can figure out what is the total amount of seconds played based on the users level.
level = n
i started with (n * 10) + (n * 60) but soon realized that that doesn't account for the last level already being 10 seconds longer than the last. I have temporarily fixed it using a function calling a foreach loop stopping at the level number and returning the value. but i really want an actual equation.
SO i know you wont let me down :-)
Thanks in advance.
this is what i am using;
function getnumberofsecondsfromlevel($level){
$lastlevelseconds = 60;
while($counter < $level){
$totalseconds = $lastlevelseconds+$totalseconds;
$lastlevelseconds = $lastlevelseconds + 10;
$counter++;
}
return $totalseconds;
}
$level = $_SESSION['**hidden**']['thelevel'];
$totaldureationinseconds = getnumberofsecondsfromlevel($level);
but i want to replace with an actual equation
like so;(of course this is wrong, this is just the example of the format i want it in i.e an equation)
$n = $_SESSION['**hidden**']['thelevel']; (level to get total value of
in seconds)
$s = 60; (start level)
$totaldureationinseconds = ($n * 10) + ($s * $n);
SOLVED by Gopalkrishna Narayan Prabhu :-)
$totalseconds = 60 * $level + 5* (($level-1) * $level);
var total_secs = 0;
for(var i = 1; i<= n ;i++){
total_secs = total_secs + (i*10) + 50;
}
for n= 1, total_secs = 0 + 10 + 50 = 60
for n= 2, total_secs = 60 + 20 + 50 = 130
and so on...
For a single equation:
var n = level_number;
total_secs = 60 * n + 5* ((n-1) * n);
Hope this helps.
It seems as though you're justing looking for the equation
60 + ((levelN - 1) * 10)
Where levelN is the current level, starting at 1. If you make the first level 0, you can get rid of the - 1 part and make it just
60 + (levelN * 10)
Thought process:
What's the base/first number? What's the lowest it can ever be? 60. That means your equation will start with
60 + ...
Every time you increase the level, you add 10, so at some point you'll need something like levelN * 10. Then, it's just some fiddling. In those case, since you don't add any on the first left, and the first level is level 1, you just need to subtract 1 from the level number to fix that.
You can solve this with a really simple mathematical phrase (with factorial).
((n-1)! * 10) + (60 * n)
n is the level ofcourse.

VBA permutations of undetermined number of variables

Recently I am trying to get the permutation of undetermined number of variables. For undetermined I mean I was aiming to create an input box for users to put in the number.
Start from simple. Originally I was aiming to get a 4 digits permutations with each digit have different number of variables, i.e. 1st digit can only be A,B,C,D; 2nd digit be E,F; 3rd digit be G, H etc. Code are below:
Sub Permut()
Count = 1
For a = 1 To 4
For b = 1 To 2
For c = 1 To 2
For d = 1 To 2
For e = 1 To 2
'chr(97) is the alphabet "a"
Cells(Count, 1) = Chr(96 + a) & Chr(96 + Len(a) + b) & Chr(96 + Len(a) + Len(b) + c) & _
Chr(96 + Len(a) + Len(b) + Len(c) + d) & Chr(96 + Len(a) + Len(b) + Len(c) + Len(d) + e)
Count = Count + 1
Next
Next
Next
Next
Next
End Sub
This will give you 64 different combinations without repetition.
Just wondering is there a way to generalize this process so that people can choose how many variables in total as well as within each digit?
Thank you.
Here is a solution, where you would pass the Permut function the minimum value for each of the characters (digits) as one string, and the maximum characters also as a string. Both strings should have an equal number of characters of course:
Function Permut(min, max)
Dim str, nxt, count
str = min
count = 1
Do While str < max
Cells(count, 1) = str
count = count + 1
nxt = ""
For i = Len(str) To 1 Step -1
If Mid(str, i, 1) < Mid(max, i, 1) Then
nxt = ChrW(AscW(Mid(str, i, 1))+1) & nxt
Exit For
End If
nxt = Mid(min, i, 1) & nxt
Next
str = Left(str, Len(str) - Len(nxt)) & nxt
Loop
Cells(count, 1) = str
End Sub
You would call it like this:
Permut "abc", "bcf"
That example would produce this list on your sheet:
abc
abd
abe
abf
acc
acd
ace
acf
bbc
bbd
bbe
bbf
bcc
bcd
bce
bcf
How to Execute This with User Input and Button Click
If you want to call this code in response to an event, such as a button click, and want to pass it the contents of two cells where the user would first enter the min and max strings, then follow these steps:
Place an ActiveX command button on your sheet (put it somewhere in D1 to leave room for some other stuff)
Double click it to generate the empty click event handler. If that does not work, go to the code window and select the name of the button from the drop-down at the top of the window, and select Click from the next drop down.
Complete the code of that event handler as follows (I assume the button is called CommandButton1, but don't change the generated name):
Code:
Private Sub CommandButton1_Click()
Permut Range("B1"), Range("C1")
End Sub
This code assumes the user has to enter the min and max digits/characters in cells B1 and C1. The A column is of course reserved for the output of the code.
For a more complete explanation on how to add a command button and attach code to its click event, read "Add a command button (ActiveX control)" in the Office manual.
credit to the answer from trincot above.
I have tried to run the code with a bit modification coz I am not sure how to get set value into cells (0,1). It keeps saying error. But If I change the starting point to Cells(1,1) then I will miss the last permutation. So I just add an additional if statement to get the code work as I want.
Function Permut(min, max)
Dim str, nxt, count
str = min
count = 1
Do While str < max
Cells(count, 1) = str
count = count + 1
nxt = ""
For i = Len(str) To 1 Step -1
If Mid(str, i, 1) < Mid(max, i, 1) Then
'asc("a")=97; chr(97) ="a"
nxt = Chr(AscW(Mid(str, i, 1)) + 1) & nxt
Exit For
End If
nxt = Mid(min, i, 1) & nxt
Next
str = Left(str, Len(str) - Len(nxt)) & nxt
If str = max Then
Cells(count, 1) = str
End If
Loop
End Function

NESTED FOR LOOP - Swift 2

I have no coding experience other than this book
Programming Swift! Swift 2 Kindle Edition
by Nick Smith (Author)
I am currently at Chapter
5.3 Nested FOR LOOPS
// NESTED FOR LOOP #2
This code -
for var a = 0; a < 11; a++ {
print("")
for var b = 0; b < a; b++ {
print("*", terminator: " ")
}
}
GENERATES THIS PATTERN...
Now [after several/ 4 hours 'odd'] I SIMPLY CAN'T WORK OUT HOW TO CHANGE THE ABOVE 'simple' [if you know how] CODE TO GENERATE THIS PATTERN??
I (think I) can see Outer and Inner loops I just can't work out the rest!?? I have tried every variation I can think of!?? (and am aware that just doing 'permutations' doesn't mean I have true understanding of what I am trying to do!...)
Tried using --operators and changing [most/ all] values [but 'permutations' is a limited method]
I feel like a total fool but figure if it's the very first time I've seen this stuff maybe it's not so bad, these things take learning!??
Help (the answer LOL) would be GREATLY appreciated 😬 😬 😬
for var a = 10; a > 0; a-- {
for var b = 0; b < a; b++ {
print("*", terminator: " ")
}
print()
}
prints
* * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
UPDATE for nowadays Swift syntax, with the same functionality
for a in stride(from: 10, through: 0, by: -1) {
for _ in stride(from: 0, to: a, by: 1) {
print("*", terminator: " ")
}
print()
}
How to do this systematically: If you want to got for example user3441734's output: There are 11 lines. We number the lines from 0 to 10. So we have a loop that sets line to the values 0 to 10.
for var line = 0; line < 11; ++line
Next, what do we want to print in each line? In line 0 we want to print 11 * characters. In line 10 we want to print 1 star character. The number of stars is 11 - line. How do I get the expression 11 - line? The number of stars goes down as line goes up, so it must be something - line. When line = 0 there must be 11 stars, so something - 0 = 11, and something = 11. So the first line in the loop:
let starcount = 11 - line
Then we want to print (star count) times a star and a space character, follow by starting a new line.
for var star = 0; star < starcount; ++star {
print ("*", terminator: " ")
}
print ("")
All together:
for var line = 0; line < 11; ++line {
let starcount = 11 - line
for var star = 0; start < star count; ++star {
print ("*", terminator: " ")
}
print ("")
}
And we simplify the loops a bit:
for var line in 0 ..< 11 {
let starcount = 11 - line
for var star in 0 ..< starcount {
print ("*", terminator: " ")
}
print ("")
}
If you wanted a different pattern, all you have to do is change the number 11 if the number of lines is different, and change the calculation of starcount. Actually it would be better to have a variable for linecount as well, so changing for a different pattern is even easier:
let linecount = 11
for var line in 0 ..< line count {
let starcount = linecount - line
for var star in 0 ..< starcount {
print ("*", terminator: " ")
}
print ("")
}

Resources