Blog

Drawing a Sinus in QT

by Thomas Spycher on October 31, 2010

I had to create an application which draws an Sinus in a Window. I needed to create this app in C++ and QT as Framework. So i decided to create my own specialized QWidget class.

sinus.h

#ifndef SINUS_H
#define SINUS_H
 
#include <QWidget>
#include <QPainter>
#include <QPen>
#include <iostream>
#include <cmath>
 
#define PI 3.14159265
 
class Sinus : public QWidget
{
    Q_OBJECT
public:
    explicit Sinus(QWidget *parent = 0);
signals:
 
protected:
    void paintEvent( QPaintEvent* );
public slots:
 
};
 
#endif // SINUS_H

sinus.cpp

#include "sinus.h"
using namespace std;
 
Sinus::Sinus(QWidget *parent) :
    QWidget(parent) { }
 
void Sinus::paintEvent ( QPaintEvent* pe){
    QPainter aPainter(this);
    int windowHeight = this->rect().height();
    int windowWidth = this->rect().width();
 
    int xg0 = 0;
    int yg0 = windowHeight/2;
    aPainter.translate (xg0,yg0);
 
    float x;
    float y;
    float angle;
    float radius = 100;
    float sinus;
    int steps = windowWidth;
    int labelAllxSteps = steps / 7;
 
    aPainter.drawLine(0,0,windowWidth,0);
 
    for(int i = 0;i < steps;i++) {
        angle = 360 / (float)steps * (float)i;                // Calculate the angle
        sinus = sin (angle*PI/180);
        y = sinus * radius;
        x = (float)i;
        //cout << "i: "<< i << " Angle: " << angle << " x: "<< x << " y: "<< y << "\n";
        aPainter.drawPoint((int)x,(int)y);
 
        // Draw the center vertical line
        if((int)y == 0 && x > 0) {
            aPainter.drawLine(x,0-(windowHeight/2),x,0+(windowHeight/2));
        }
 
        // Draw Label's
        if((i % labelAllxSteps) == 0 && x > 0 && x < steps) {
            QString str;
            str.sprintf("Sin: %f Angel: %f", y, angle);
            aPainter.drawText((int)x,(int)y,str);
        }
    }
}

main.cpp

#include <QtGui/QApplication>
#include "sinus.h";
 
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Sinus sinus;
    sinus.setGeometry (300, 300, 200, 200);
    sinus.show();
    return a.exec();
}

Forcing HTTP Auth in Cocoa

by Thomas Spycher on September 13, 2010

I’ve got asked how to implement an forced authentication in an URLRequest in Objective-C & Cocoa.
Adding the Auth Header to the Request is easy… Base64 encoding the string is more complicated, due to missing methods in Cocoa. The get this done, we need to implement our own base64 method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
-(char *)b64encode:(NSData *)plainText {  
    static char *alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";  
 
    // create an adequately sized buffer for the output.  every 3 bytes   
    // become four basically with padding to the next largest integer  
    // divisible by four.   
    char * encodedText = malloc((((([plainText length] % 3) +  
                                   [plainText length]) / 3) * 4) + 1);  
    char* inputBuffer = malloc([plainText length]);  
    inputBuffer = (char *)[plainText bytes];  
 
    NSInteger i;  
    NSInteger j = 0;  
 
    // encode, this expands every 3 bytes to 4  
    for(i = 0; i < [plainText length]; i += 3) {  
        encodedText[j++] = alphabet[(inputBuffer[i] & 0xFC) >> 2];  
        encodedText[j++] = alphabet[((inputBuffer[i] & 0x03) << 4)  
                                    | ((inputBuffer[i + 1] & 0xF0) >> 4)];  
 
        if(i + 1 >= [plainText length])  
            // padding  
            encodedText[j++] = '=';  
        else   
            encodedText[j++] = alphabet[((inputBuffer[i + 1] & 0x0F) << 2)  
                                        | ((inputBuffer[i + 2] & 0xC0) >> 6)];  
 
        if(i + 2 >= [plainText length])  
            // padding  
            encodedText[j++] = '=';  
        else  
            encodedText[j++] = alphabet[inputBuffer[i + 2] & 0x3F];  
    }  
 
    // terminate the string  
    encodedText[j] = 0;  
 
    return encodedText;  
}

And finally we add the Header Field to the Request:

1
2
3
4
5
6
7
8
9
10
11
12
13
    NSURL *url = [NSURL URLWithString:@"http://this.is-a-url.com"];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
 
    NSString *username = @"USERNAME";  
    NSString *password = @"PASSWORD";  
 
    // create a plaintext string in the format username:password  
    NSString *loginString = [NSString stringWithFormat:@"%@:%@",username,password];
    char *encodedLoginData = [self b64encode:[loginString dataUsingEncoding:NSUTF8StringEncoding]];  
    NSString *authHeader = [NSString stringWithFormat:@"Basic %@",[NSString stringWithCString:encodedLoginData encoding:NSUTF8StringEncoding]];
 
    // this is where the magic happens
    [request addValue:authHeader forHTTPHeaderField:@"Authorization"];

I appreciate any further hints to this topic.

Galton Board in ObjectiveC

by Thomas Spycher on September 12, 2010

Target was to build an application to simulation a “Galton Board“.

Galtonsches_Brett.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#import 
 
@interface Galtonsches_Brett : NSObject {
@private
 
}
 
- (void)Calculate:(double)numBalls field0:(NSProgressIndicator**)field0
                                        field1:(NSProgressIndicator**)field1
                                        field2:(NSProgressIndicator**)field2
                                        field3:(NSProgressIndicator**)field3
                                        field4:(NSProgressIndicator**)field4
                                        field5:(NSProgressIndicator**)field5;
 
- (int)RandomField;
@end

Galtonsches_Brett.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#import "Galtonsches_Brett.h"
 
@implementation Galtonsches_Brett
 
- (void)Calculate:(double)numBalls field0:(NSProgressIndicator**)field0
           field1:(NSProgressIndicator**)field1
           field2:(NSProgressIndicator**)field2
           field3:(NSProgressIndicator**)field3
           field4:(NSProgressIndicator**)field4
           field5:(NSProgressIndicator**)field5 {
    // Set maximul value
    [*field0 setMaxValue:numBalls/2];
    [*field1 setMaxValue:numBalls/2];
    [*field2 setMaxValue:numBalls/2];
    [*field3 setMaxValue:numBalls/2];
    [*field4 setMaxValue:numBalls/2];
    [*field5 setMaxValue:numBalls/2];
 
    // Set current value
    [*field0 setDoubleValue:0];
    [*field1 setDoubleValue:0];
    [*field2 setDoubleValue:0];
    [*field3 setDoubleValue:0];
    [*field4 setDoubleValue:0];
    [*field5 setDoubleValue:0];
 
    // Start the animation and make the progressbar visible
    [*field0 startAnimation:self];
    [*field1 startAnimation:self];
    [*field2 startAnimation:self];
    [*field3 startAnimation:self];
    [*field4 startAnimation:self];
    [*field5 startAnimation:self];
 
    int field;
    for(double balls = 1; balls &lt;= numBalls; balls++) {
        // Get a field
        field = [self RandomField];
        // This whole shit should be done with a @selector
        switch (field) {
            case 0:
                [*field0 setDoubleValue:[*field0 doubleValue]+1];
                break;
            case 1:
                [*field1 setDoubleValue:[*field1 doubleValue]+1];
                break;
            case 2:
                [*field2 setDoubleValue:[*field2 doubleValue]+1];
                break;
            case 3:
                [*field3 setDoubleValue:[*field3 doubleValue]+1];
                break;
            case 4:
                [*field4 setDoubleValue:[*field4 doubleValue]+1];
                break;
            case 5:
                [*field5 setDoubleValue:[*field5 doubleValue]+1];
                break;
        }
        //[self performSelector:@selector(myTestWithAString:) withObject:myString];
    }
}
 
- (int)RandomField {
    int nail = 0;
    int rows = 5;
    for(int row = 0;row &lt;= rows-1;row++) {
        int random = ((int)rand() % 2) + 1;
        if(random == 1) {
            // go left
            nail = nail;
        } else {
            // go right
            nail++;
        }
        //NSLog(@"row: %d and leftRright: %d next nail: %d",row, random, nail);
    }
    return nail;
}

An this is how it gets called:

1
2
3
4
5
Galtonsches_Brett *brett = [[Galtonsches_Brett alloc] init];
 
[brett Calculate:[[numberBalls stringValue] doubleValue] field0:&amp;field0 field1:&amp;field1 field2:&amp;field2 field3:&amp;field3 field4:&amp;field4 field5:&amp;field5];
 
[brett release];

The whole Application is here: XGaltonsches Brett (176)

dec2bin function

by Thomas Spycher on September 10, 2010

This Function converts a decimal number into a 8bit long binary number.

 
std::string dec2bin(int dec) {
    int size = 8;
    bool bin[size];
    int counter = size-1;
 
    if (dec > 255) {
        return "Maximal 255";
    }
 
    // init the array
    for(int i = size; i >= 0; i--) {
        bin[i] = false;
    }
 
    // Calculate the shit
    do {
        if(dec % 2) {
            bin[counter] = true;
        } else {
            bin[counter] = false;
        }
        dec = dec / 2;
        counter--;
    } while (dec > 0);
 
    // and finally organize and return it
    std::stringstream binstr; 
    for(int i = 0; i <= size-1; i++) {
        binstr << bin[i];
    }
 
    return binstr.str();
}

sqrt() Function

by Thomas Spycher on September 10, 2010

This is the way sqrt works… Why do i have to code this by my own?

const float EPSILON = 1e-6;
 
float working = val;
    float diff = 0;
    float keep = 0;
    float result = 0;
    int counter = 0;
 
    do {
        result = (keep + working) / 2;
        //std::cout << "("<<keep<<"+"<<working<<") / 2 = " << result << "\n";
        diff = (result * result)-val;
        std::cout << "[ " << counter << " ] " << working << "\n";
        if(diff <= 0) {
            keep = result;
        } else {
            working = result;
        }
        counter ++;
    } while ( fabs(diff) >= EPSILON);
    return result;
}

Ultimate Project Status

by Thomas Spycher on August 24, 2010

I’ve just commited the version 0.1.1 of the Ultimate ProjectStatus Plugin for WordPress. With this Plugin you can show the status of all of your projects extremly cool on your website.

For more information and the download go to the official WordPress Plugin Site.

CoreData Model Migration

by Thomas Spycher on August 11, 2010

If you are working on your project in XCode you will mostly use CoreData to handle the whole Data stuff. For this you designed a DataModel. Especially in the beginning of your project you need to change Attributes etc. very often in your DataModel.
After changing something in your DataModel and build the project you will be faced with e message, that tells you something about an incompatible persistensstore.

Your need to remove your serialized Data from your Harddisk and enter all your Testdata again.

CoreData can handle small changes in de DataModel by itself. You just need to activate this first.

Continue Reading…

Coding Section of Zero-One is online

by Thomas Spycher on August 9, 2010

This Site is the coding playground of Zero-One. The founders of Zero-One are also students at the KTSI, Switzerland.

During the work in Zero-One and KTIS a lot of coding knowledge is flooding our brains. code.zero-one.ch is the central pod of collecting…