Flappy Bird Coding Error in Swift - xcode

I've encountered a coding error for my flappy bird project, in Xcode 6.1.
The code is to allow rotation of the bird, and it reads:
bird.zRotation = self.acotarMinMax(-1, max: 0.3, valor: bird.physicsBody?.velocity.dy * (bird.physicsBody?.velocity.dy < 0 ? 0.003 : 0.001))
the error occurs under dy, it reads:
value of optional type 'CGFloat?' not unwrapped; did you mean to use '!' or '?'?
How can I correct the error, or is there another way to generate rotation?
I am a total beginner of Swift, so I'm having a hard time figuring out if this is a syntax problem or something to do with the updated version.
I obtained the code from a online tutorial, and it worked in the video.

Read up on the Swift Optional class: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html
So it seems that dy is an Optional value, which means that it either has a value or it does not, but you don't know until you look into it (like Schroedinger's Cat). So if you need this value and you know it will not be nil, you unwrap it by writing bird.physicsBody?.velocity.dy! which will look into the "box" and take the value out but crash if there is nothing inside. If you write dy? it will look into the box but ignore it if the box is empty.
More on Optional Chaining (which is what you do) here: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html

So I just figured out my error.
As Sebastian correctly pointed out, it is to do with optional chaining.
The code that worked is:
bird.zRotation = self.acotarMinMax(-1, max: 1, valor: bird.physicsBody!.velocity.dy * (bird.physicsBody!.velocity.dy < 0 ? 0.002 : 0.002))
I used '!' to force a value on physicsBody. The precise mechanism of why this works is still a blur to me. But my guess is to do with the new version's correction method.

Related

gensim/models/ldaseqmodel.py:217: RuntimeWarning: divide by zero encountered in double_scalars

/Users/Barry/anaconda/lib/python2.7/site-packages/gensim/models/ldaseqmodel.py:217: RuntimeWarning: divide by zero encountered in double_scalars
convergence = np.fabs((bound - old_bound) / old_bound)
#dynamic topic model
def run_dtm(num_topics=18):
docs, years, titles = preprocessing(datasetType=2)
#resort document by years
Z = zip(years, docs)
Z = sorted(Z, reverse=False)
years_new, docs_new = zip(*Z)
#generate time slice
time_slice = Counter(years_new).values()
for year in Counter(years_new):
print year,' --- ',Counter(years_new)[year]
print '********* data set loaded ********'
dictionary = corpora.Dictionary(docs_new)
corpus = [dictionary.doc2bow(text) for text in docs_new]
print '********* train lda seq model ********'
ldaseq = ldaseqmodel.LdaSeqModel(corpus=corpus, id2word=dictionary, time_slice=time_slice, num_topics=num_topics)
print '********* lda seq model done ********'
ldaseq.print_topics(time=1)
Hey guys, I'm using the dynamic topic models in gensim package for topic analysis, following this tutorial, https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/ldaseqmodel.ipynb, however I always got the same unexpected error. Can anyone give me some guidance? I'm really puzzled even thought I have tried some different dataset for generating corpus and dictionary.
The error is like this:
/Users/Barry/anaconda/lib/python2.7/site-packages/gensim/models/ldaseqmodel.py:217: RuntimeWarning: divide by zero encountered in double_scalars
convergence = np.fabs((bound - old_bound) / old_bound)
The np.fabs error means it is encountering an error with NumPy. What NumPy and gensim versions are you using?
NumPy no longer supports Python 2.7, and Ldaseq was added to Gensim in 2016, so you might just not have a compatible version available. If you are recoding a Python 3+ tutorial to a 2.7 variant, you obviously understand a little bit about the version differences - try running it in a, say, 3.6.8 environment (you will have to upgrade sometime anyway, 2020 is the end of 2.7 support from Python itself). That might already help, I've gone through the tutorial and did not encounter this with my own data.
That being said, I have encountered the same error before when running LdaMulticore, and it was caused by an empty corpus.
Instead of running your code fully in a function, can you try to go through it line by line (or look at you DEBUG level log) and check whether your output has the expected properties: that, for example your corpus is not empty (or contains empty documents)?
If that happens, fix the preprocessing steps and try again - that at least helped me and helped with the same ldamodel error in the mailing list.
PS: not commenting because I lack the reputation, feel free to edit this.
This is the issue with the source code of ldaseqmodel.py itself.
For the latest gensim package(version 3.8.3) I am getting the same error at line 293:
ldaseqmodel.py:293: RuntimeWarning: divide by zero encountered in double_scalars
convergence = np.fabs((bound - old_bound) / old_bound)
Now, if you go through the code you will see this:
enter image description here
You can see that here they divide the difference between bound and old_bound by the old_bound(which is also visible from the warning)
Now if you analyze further you will see that at line 263, the old_bound is initialized with zero and this is the main reason that you are getting this warning of divide by zero encountered.
enter image description here
For further information, I put a print statement at line 294:
print('bound = {}, old_bound = {}'.format(bound, old_bound))
The output I received is: enter image description here
So, in a single line you are getting this warning because of the source code of the package ldaseqmodel.py not because of any empty document. Although if you do not remove the empty documents from your corpus you will receive another warning. So I suggest if there are any empty documents in your corpus remove them and just ignore the above warning of division by zero.

Parameters for dlib::find_min_bobyqa

I'm working on the C++ version of Matt Zucker's Page dewarping. So far everything works fine, but I have a problem with optimization. In line 748 of Github repo Matt uses optimize function from Scipy. My C++ equivalent is find_min_bobyqa from dlib.net. The code is:
auto f = [&](const column_vector& ppts) { return objective( dstpoints, ppts, keypoint_index); };
dlib::find_min_bobyqa(f,
params,
2 * params.nr() + 1, // npt - number of interpolation points: x.size() + 2 <= npt && npt <= (x.size()+1)*(x.size()+2)/2
dlib::uniform_matrix<double>(params.nr(), 1, -2), // lower bound constraint
dlib::uniform_matrix<double>(params.nr(), 1, 2), // upper bound constraint
1, // initial trust region radius
1e-5, // stopping trust region radius
4000 // max number of objective function evaluations
);
In my concrete example params is a dlib::column_vector with double values and length = 189. Every element of params is less than 2.0 and greater than -2.0. Function objective() returns double value and "alone" it works properly because I get the same value as in the Python version. But after running fin_min_bobyqa function I usually get the message:
Terminate called after throwing an instance of 'dlib:bobyqa_failure', return from BOBYQA because the objective function has been called max_f_evals times.
I set max_f_evals to quite big value to see if it optimizes at all, but it doesn't. I did some tweaking with parameters but without good results. How should I set the parameters of find_min_bobyqa to get the right solution?
I am very interested in this issue as well. Zucker's work, with very minor tweaks, is ideal for straightening sheet music images, and I was looking for ways to implement it in a mobile platform when I came across your question.
My research so far suggests that BOBYQA is not the equivalent of Powell's method in scipy. BOBYQA is constrained, and the one in scipy is not.
See these links for more information, and a possible way to compile the right supporting library - I would try UOBYQA or NEWUOA.
https://github.com/jacobwilliams/PowellOpt
https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#rdd2e1855725e-3
(See the Notes section)
EDIT: see C version here:
https://github.com/emmt/Algorithms/tree/master/newuoa
I wanted to post this as a comment, but I don't have enough points for that.
I am very interested in your progress. If you're willing, please keep me posted.
I finally solved this problem. I used PRAXIS library, because it doesn't need derivative information and is fast.
I modified the code a little to my needs and now it is faster around few seconds than original version written in Python.

Reflection Swift 2.0 XCode 7 beta 5

Apple has changed the Swift reflection in XCode 7 beta 5. The global reflect() function is gone, and you'll have to do this:
let mirror = Mirror(reflecting: object)
It gives more or less the same information in a nicer way (no more .1 og .2 for propertyname and value). But I can't find a way to explore if the mirrored item is an instance of a class.
The older implementation you could check the following:
reflectedProperty.1.objectIdentifier != nil || reflectedProperty.1.count > 0
But objectIdentifier seems to be gone and the count is always 2 regardless of type.
Help anyone?
Ok so I found a workaround. I was iterating over mirror.children.enumerate() which seemed to make all the properties of type String. Instead I dug into Apple preliminary documentation, and read that it could be a good idea to "upgrade" children to e.g. AnyRandomAccessCollection. Which made it possible to rely on the count of an objects children to determine if it's an object (after testing whether it's an array)
Currently I have a functioning Swift class to JSON Serializer working here on this gist if you are interested in the code:
https://gist.github.com/peheje/cc3618253d4f38ea4885
I am not sure if you are looking for this, but the output for the following is "Class"
mirror.displayStyle

Swift Compiler performance

I got this statement in Swift code which produces an error when executing in playground:
let colors: [String: [Float]] = ["skyBlue" : [240.0/255.0, 248.0/255.0, 255.0/255.0,1.0],
"cWhite" : [250.0/255.0, 250.0/255.0, 250.0/255.0, 1.0]]
The error is : expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions
Then I changed the arrays element type to Double which just works fine.
However I am asking myself why this happens ?
As I said using Double it works just fine. So my guess is that Swift tries to guess the type and therefore Double works better in this example than Float.
Similar issues have been reported before, and (as I understand it) the problem is the automatic type inference for "complicated" expressions. You should file a bug report at Apple.
It compiles with a dictionary of one color, but not with two.
In this concrete case, you can work around it by converting each number in the array to a Float explicitly:
let colors = [
"skyBlue" : [Float(240.0/255.0), Float(248.0/255.0), Float(255.0/255.0),Float(1.0)],
"cWhite" : [Float(250.0/255.0), Float(250.0/255.0), Float(250.0/255.0), Float(1.0)]
]

term does not evaluate to a function taking 1 arguments

Please have a look at the following OpenCV code
Mat *curent;
current = new Mat();
cv::Rect bRect = cv::boundingRect(Mat(*points).reshape(2));
Mat roi = *current(bRect);
Here, I am trying to get a ROI to the Mat called roi. But whenever I try to get execute the last line of the above code I get the error term does not evaluate to a function taking 1 arguments. I have followed the same technique of getting an ROI without pointers number of times before in C++ and they worked. I guess the issue is with pointer current ? current must be a pointer because local variable slowed the application in an unbelievable way.
So, how can I solve this issue and get the ROI ?
please, throw out those pointers!
you're going to wreck havoc on the internal Mat refcounts, produce undefined behaviour and memleaks
"local variable slowed the application in an unbelievable way."
really, you think, copying a 58 byte struct is the reason ? i just don't believe you.
well i'll give you a hint, anyway - the ( ) operator has a higher precedence than the * operator.

Resources