Monday, February 2, 2015

A quick Git tutorial part 4

Git notes
Normally, when you commit something, you add a short description to tell what's the commit about.
Such description should be short, with just one line.
But sometimes you'd like to give more information about the commit, something like a note.
Well, Git has a solution for that too. We can add a note like this:
$git notes add HEAD
This will bring you to a default editor to write your note.

Another easier approach is:
$git notes add HEAD -m "This is my note"
This way you can add a note right away.
The above way is comparable with a description for a commit "git commit -m 'this is my comment'".

This feature is added since version 1.6.6!
The note is not added in Sha calculation, so you don't need to amend a commit.


git show-branch
This one is very handy, if you want to compare commit revisions between two branches. Say you were working on a branch and you don't remember whether a feature has already included in the master branch. You can off course switch to the master branch and do a log, but that's not necessary now :) Just do the following in your working branch:
git show-branch master workingbranch
And you get a nice output about the difference between two branches.
Cool right?


For more information, read this link: http://git-scm.com/blog/2010/08/25/notes.html

Wednesday, September 3, 2014

Java - ByteBuffer



There are 2 states in a ByteBuffer object, read-mode and write-mode. There are 3 importantsvalues in a ByteBuffer:
position, limit and capacity.

Capacity: this gives us the maximum bytes a buffer can have, it's a buffer size.

Position: in write-mode it's the index of the next byte to write. If 4 bytes has been written into a ByteBuffer object, than the position is 4, which is the 5th element of a ByteBuffer's array. In read-mode it's the index of the next byte to read, the logic is the same as in write-mode.

Limit: is the space left to write or the amount of bytes yet to read, depending on the state.

Initial state of ByteBuffer is write-mode, why? Well, if you create a new buffer, the buffer is normally empty,
because you haven't filled it yet, so there's nothing to read also. So the first thing to do is to fill the buffer with data, that's why the first state of a ByteBuffer object is write-mode.

Write data to ByteBuffer:
byte[] data = new byte[48];
byteBuffer.put(data, 0, numBytes);

Remaining data means in this state (write-mode), how many bytes available in the buffer to write.
byteBuffer.remaining();

Switch from write-mode to read-mode
byteBuffer.flip();

Remaining data means in this state (=read-mode), how many bytes available left in the buffer to read.
byteBuffer.remaining();

Read data into the buffer:
byteBuffer.get(buffer);

This method means clear all the bytes, reset its states and switch to write-mode.
byteBuffer.clear();

This method means move the remaining bytes to the beginning of the buffer, update its states and switch to write-mode.
byteBuffer.compact();

This method resets its states after reading, so you can read again from the beginning.
byteBuffer.rewind();

mark its current states
byteBuffer.mark();
do some reading...
change it to its pervious states
byteBuffer.reset();

Source:
http://www.ibm.com/developerworks/java/tutorials/j-nio/j-nio.html
http://www.tech-recipes.com/rx/1438/java-working-with-buffers/
http://tutorials.jenkov.com/java-nio/buffers.html

Monday, August 25, 2014

Android - Developer options on Samsung S3

How to enable development on a Samsung S3?

It wasn't easy to enable developer options for the Samsung S3 (apparently also S4) as this feature is hidden. To make it unhidden you have to do the following steps:
  • Go to Settings -> More -> About Device
  • Scroll down to Build Number
  • Tap on it multiple times, it than shows a Toast how many times left to tap.
  • Finally you get a message that you've become a developer.
  • Now go to Developer options in Settings -> More.
Good luck :)

iOS - Ad Hoc distribution

Coming soon...

Thursday, April 10, 2014

iOS snippets part 1

Here are some snippets I use for the iOS platform. Since I work on several platforms (MS Windows, Linux, Android and iOS using languages like C, C#, C++, Obj-C, Java, PHP etc...) , I thought it would be better to put a bunch of useful and often used snippets on my blog, so I don't have to google a lot. Once you understand how to program, it's not important anymore what language you use or what platform you're developing for.

I hope those sinppets are useful for you, let's start :-)


Message Box

- (IBAction)btnExit:(id)sender {
    UIAlertView *messageBox = [[UIAlertView alloc] initWithTitle:@"Exit"
                                                      message:@"Are you sure?"
                                                     delegate:self
                                            cancelButtonTitle:@"No"
                                            otherButtonTitles:@"Yes", nil];
    [messageBox show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
   
    if([title isEqualToString:@"No"]) {
        NSLog(@"No was selected.");
    }
    else if([title isEqualToString:@"Yes"]) {
        NSLog(@"Yes was selected.");
    }
}




Timer 1

- (void) startTimer {
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: 0.1 target:self selector:@selector(fireMe) userInfo:nil repeats:YES];
}

- (void) fireMe {
    NSLog(@"I'm fired!");
}


By setting the repeats on YES, makes the timer execute every 0.1 sec which is 100 ms. By setting it to NO, will execute the timer just once.


Timer 2

- (void) startTimer {
    NSTimer *timer = [[ NSTimer alloc ] initWithFireDate: [NSDate dateWithTimeIntervalSinceNow: 0.0
                                                 interval: 0.1
                                                   target: self
                                                 selector: @selector(fireMe)
                                                 userInfo: nil
                                                  repeats: NO];
}


This is another way to start a timer.



Worker-thread using GCD (Grand Central Dispatch)

dispatch_queue_t myQueue = dispatch_queue_create("my queue",NULL);
...
...
...
dispatch_async(imageQueue, ^{
        // This will run the method in a separate thread
        [self doSomeLongRunningTask];
    });


- (void) doSomeLongRunningTask {
    dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"We finished a heavy task!");
        });
}


So, we create a dispatch queue handle for our separated thread, than pass a block ^{} to dispatch_async that will be executed in a separate thread ( NOT in the main thread). If you want to call a method in the main thread from another thread, you call:  dispatch_async(dispatch_get_main_queue(), ^{ }); As you see, dispatch_get_main_queue() gives you the queue handle of the main thread.
For more information, check: GDC



Thread with NSThread

NSThread *thread = [[NSThread alloc] initWithTarget:self
                                     selector:@selector(run:)
                                       object:nil];
[thread start];

...
...
- (void) run: (id) object{
    NSLog(@"I'm running in another thread :D");
}


This is a simple example to create another thread and run it by calling the start method.



TCP Sockets with streams

NSInputStream *inputStream;
NSOutputStream *outputStream;
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;


CFStreamCreatePairWithSocketToHost( NULL, (__bridge CFStringRef)hostIp, hostPort, &readStream, &writeStream );
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);


inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
...
...
// ope connection
[ inputStream open ];
[ outputStream open ];
...
int len = (int) [outputStream write: buffer maxLength: size];
len = (int) [inputStream read: buffer maxLength: size];


Using streams with NSRunLoop

[inputStream setDelegate:self ]; //This will call stream: handleEvent:

NSRunLoop *runLoop = [ NSRunLoop currentRunLoop ];
[inputStream scheduleInRunLoop: runLoop forMode:NSDefaultRunLoopMode];
[runLoop run]

// This will be called from runLoop
- (void) stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {
    switch ( eventCode ) {
        case NSStreamEventOpenCompleted: 

            break;
        case NSStreamEventHasSpaceAvailable:
            break;
        case NSStreamEventHasBytesAvailable:

            break;           
        case NSStreamEventErrorOccurred:
            break;
        case NSStreamEventEndEncountered:
            break;
        default:

    }
}




 

Monday, December 16, 2013

CMake - basic tutorial

This is a short tutorial about CMake with a practical example. CMake is a tool to generate build files but does not compile! So, if you use Linux, CMake creates Makefile which make tool uses it to actually build your C++ application. The advantage of CMake over the standard make, is writing a CMake script is relatively easy comparing to a Makefile script. Another advantage is, CMake can generate build files for other platforms, so if you want to build your application for another platform like MS Windows, CMake does that for you just by telling which platform you want to build for.

Unfortunately a lot of examples found on the internet is based on one simple Hello World file, which doesn't represent the real power of CMake and also doesn't represent a realistic directory structure of real projects.

Ok, below we see how a typical project folder looks like:
Project_folder
             |__ src
             |       |__ main.cpp
             |       |__ xxx.cpp
             |       |__ yyy.cpp
             |       |__ zzz.cpp  
             |__ include
             |__ libs
             |__ build
             |__ CMakeLists.txt
  
Now, we want to tell CMake that in the folder 'src' there is the source files, in 'include' there is the include files (in case of C/C++) and in the 'libs' we have the libraries. The build folder will contain the build files that CMake generates.
CMakeLists.txt is the script CMake will read to know how to build the project.
So, how would our CMakeLists.txt look like?
Below we have an example of CMakeLists.txt:



#------------------------------------
# Minimum CMake version required.

cmake_minimum_required(VERSION 2.6)


#------------------------------------
# Not necessary, but recommended, projectname:

project(MyBoostTest)

#------------------------------------
# The version number.
set (Tutorial_VERSION_MAJOR 1)
set (Tutorial_VERSION_MINOR 0)

set (CMAKE_CXX_FLAGS "-g -Wall")

#------------------------------------

# Declare var names for source path
#------------------------------------
set (INC ${PROJECT_SOURCE_DIR}/include)
set (SRC ${PROJECT_SOURCE_DIR}/src)
set (LIBS ${PROJECT_SOURCE_DIR}/libs)

#------------------------------------

# Add source files to SRCS variable
#------------------------------------
list(APPEND SRCS ${SRC}/main.cpp
${SRC}/xxx.cpp ${SRC}/yyy.cpp ${SRC}/zzz.cpp)
#------------------------------------

# Tell CMake where the include files are
#------------------------------------
include_directories(${INC})
#------------------------------------

# is the same as include_directories
# in this case, we have no real lib files
#------------------------------------
link_directories(${LIBS})
#------------------------------------


# name the executable 'MAIN' and tell
# CMake which files are used
#------------------------------------
add_executable(MAIN ${SRCS})
#------------------------------------

# Tell CMake what libraries to link
# with. For example the BOOST's regex

# but it could also a library in the libs folder,
# which can be built with:
# add_library(mylib ${LIBS}/lib_x)
#------------------------------------
target_link_libraries(MAIN boost_regex)
#------------------------------------


 
If we run CMake in the same directory as where the above CMakeLists.txt resides, a bunch of files and folder will be created in that same directory. This will clutter up our project folder, to prevent that we tell CMake to put the generated build files in the build folder:

cmake -Bbuild -H.
If everything went well, we'll see the build folder with the generated build files. If we than move to the build folder, we can run the following command to compile the sources (assuming this is a C++ project on a Linux machine with the 'make' tool):
make .
If your sourcecode is successfully compiled, you'll see the MAIN executable in the build folder.

So, it's quite easy, you just need to tell CMake where the source files and libraries are, what to build and CMake is doing the ugly work for you.
We also use just one CMakeLists.txt, normally you should have CMakeLists.txt in every sourcecode folder, but for the sake of simplicity, we use only 1 CMakeLists.txt. I'll punt another CMake example next time with multiple CMakeLists.txt. 

Thursday, December 12, 2013

Vim - Reminders part 1

On this page I show some commands which you might forgot. For me it's to quickly look up how to do it again. So let's start.

NSNotification example