Monday, September 30, 2019
Tuesday, September 15, 2015
iOS - CocoaPod
CocoaPod
This is a short tutorial about how to use CocoaPod.
CocoaPod is a dependency manager, you can compare it with Gradle for Android projects (or Maven). CocoaPod makes it easy for you to manage libraries in your Xcode projects, because CocoaPod has a database servers with a lot of popular libraries. An advantage is you don’t have to clone a library from github and than include it to your project. This is all automated for you, but before it does all the work for you, you have to to configure a file to make it work for you.
First you need to install CocoaPod on your Mac, I provide you with the following link on how to do that:
To manage your project with CocoaPod, you have to create a Podfile, you can do this by issuing the following command in your project directory:
# pod init
This will create a ‘Podfile’ which will be used by CocoaPod to read what dependencies to manage.
If you want to use FMDB library, this is a wrapper library for managing SQLite db, you add the following line between “target ‘projectname’ do” and “end”:
pod ‘FMDB'
Save file and close your editor, than execute the following command:
# pod install
You’ll see the following output of the command:
Analyzing dependencies
Downloading dependencies
Installing FMDB (2.5)
Generating Pods project
Integrating client project
After that you have to do one more thing! Close your project in Xcode and open the project with the file name projectname.xcworkspace and NOT projectname.xcodeproj anymore.
Well that’s about it. This is the basic to quickly get you started. For more fancy stuff, Google is your friend.
Friday, August 28, 2015
What I think about AppleWatch
I’m lucky to have an AppleWatch at work to develop apps for it. But before I started to develop an app, I was playing with the watch to get to know the watch better and its functionality. To be honest I wasn’t really impressed, it didn’t gave me the ‘amazing wow’ feeling. To me, the watch felt so limited, maybe because my expectation was huge.
Friend button
First, I can’t do nothing with the side “friend” button (beneath the crown wheel). The button is there and every time I press on it, I get the message that I can add friends. That’s it, I tried to hard press on it, swipe up, swipe down, just nothing. None of my friends have an AppleWatch and not all of my friends have an iPhone. So this button is useless to me and it’s just there doing nothing.
Home screen
The home screen has a watch interface and you can change the face of the home screen by hard pressing on it. This way you can change the faces and customise its color and so on. So the home screen shows time, date, meeting reminders and so on and also shortcuts to agenda, alarm etc., like a normal watch should be.
Glances
You also have Glances, these are static screens to quickly launch the corresponding app. To show Glances you have to swipe up from the home screen. This gives you access to multiple Glances, by swiping left or right you can switch to other Glances. A Glance just shows you a short current status with no interaction, so it’s a read-only view. By pressing on it, the corresponding app will be launched. So if you want to quickly start an app from your home screen, you just swipe up and than swipe left or right to the desired Glance and than press on it. This is fine if you have just three or four Glances, but if you have a dozen or more, this will be clumsy, because you might have to swipe like 6 or 7 times before you find the right Glance and than press on it to launch the app. So Glances are ok if it’s limited to just 4 Glances.
To start an app without Glances, you press on the Digital Crown, this brings you to a bunch of balls (depending on how much apps you have) each representing an app. You can zoom in and out with the crown to find the app you want to launch. Well, it’s funny how it is designed and it’s unique comparing to other smartwatches, but after playing with it some time, the fun is gone. Some apps are not necessary, like the Map app, the screen is too small to show the map in a comfortable way. The same applies for the camera app, you need the iPhone anyway (it won’t work without the iPhone camera activated). Calling a phone is not a thing I’d do when I’m in public, I rather use handsfree. So it’s clearly obvious some things are not handy to use them on an AppleWatch.
If you want to see notifications from the home screen, you just have to swipe down and you get a list of received notifications that are not dismissed yet.
Another feature of AppleWatch is to use Siri. The thing is, I don’t feel comfortable to use Siri in a public environment. For example in a subway, in a library, or in a supermarket. I rather use Siri when I’m in a car or at home. So I’ll use Siri only in certain places (if I use it at all).
To me, a watch is to just have a quick view or a glance , that’s it. Because it’s a small device, you can’t expect to do a lot of things with your fingers and you can’t see a lot of details on a small screen. A watch should only show you a short information message. So I’m glad Apple payed attention on that. When your iPhone is in your pocket and your AppleWatch on your wrist, all the notifications are sent to your AppleWatch (depending on the settings). Messages like Twitter, WhatsApp, SMS, Email, Facebook posts and so on are perfect to read out from AppleWatch. Also controlling functions, like controlling your music, turn off/on lights of your house while you’re sitting on the couch, remote controlling the TV and so on can be perfectly done from AppleWatch.
So the AppleWatch is a nice thing to have and has nice stuff, but it’s not perfect. Some apps are too complex and overwhelming and thus not necessary to have it on AppleWatch (Map, Camera…). The user interface is not perfect too, it can be better. Also it’s too bad to charge battery every day.
If I would choose between a Pebble or an AppleWatch, I definitely would choose Pebble.
Tuesday, June 23, 2015
A quick Git tutorial part4
gitignore
A common problem when adding .gitignore file is some undesired files are already tracked by Git.
To solve this problem, you need to do the following:
git rm -r --cached .git add .git commit -m ".gitignore is now working"
Solution is found here: http://stackoverflow.com/a/1139797
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
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:
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.
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:
}
}
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.
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.
Thursday, December 5, 2013
Vim - Nice little handy tips and tricks
I found some nice little tricks to perform some actions a little bit faster
Toggle toggle toggle...
If you want to set line numbers you do like this:
:set number
you can even make it a bit shorter"
:se nu
To disable line numbers:
set no number
or
set no nu
But you can also toggle by adding an exclamation mark '!'
:se nu!
Another toggle:
:se cul!
This is to put a line under the cursor, some like it, some not. I really like it!
Sources: http://learnvimscriptthehardway.stevelosh.com/
Another one:
I often like to load a bunch of files at once and when I'm done editing with a file, I'll get another buffer to edit (":h buffer" for more information). But sometimes I want 2 files next to each other, just to see if they look similar (but not identical). In that case I'd like to have 2 files open next to each other, so I want the window split in two vertical windows. This is how we can do that:
:vert sb x
Where x is the buffer number you want, assuming you already loaded a bunch of files. Now you get two windows with current buffer on the right window and buffer x on the left. Cool!
Compare 2 buffers:
Ok, so the above one creates 2 windows, each containing a buffer. Suppose you have a big file like a few thousand lines and want to check the difference, no problem with Vim. On each window you execute the command:
:diffthis
or shorter,
:difft
To turn off:
:diffoff!
With the exclamation mark, it turns off for all windows.
To jump to the next difference:
]c
read as "go to the next compare". The other way around is:
[c
To obtain the difference from the other file to the current file:
do
Note, this is per difference, so not the whole file at once. The other way around:
dp
Exercise with it, you'll love it!
By the way, I mapped diffthis and diffoff as:
nmap
nmap [Leader]
replace [ with <, this blogger automatically removes '<', I guess because of security point of view (xss).
Other cute commands:
If you have multiple windows, you can close them all except the current one by this:
:only
There is also:
:hide
which closes the current window, but than I rather use Ctrl+w c, which is faster.
Follow the breadcrumbs:
One of the important things an editor should have is navigating forward and backwards my cursor positions. Say you edited a function or a method in your source code, than you jump to another function to do some other editions there or copy a snippet of code, the next thing you want to do is go back to the previous position. In normal mode you type:
Ctrl+o
for jumping back to the previous position, to jump forward again:
Ctrl+i
This is a very useful and powerful Vim command, a must-have desperately tool.
Forgot to sudo:
Very often I forget to add sudo if I want to edit a file with root permission, here is the remedy:
:w !sudo tee %
This one is hackish :)
Let's hex :
As a programmer, coder or hacker you need to check the binary data of a file. For example, you want to check the jfif segment (wiki-jpeg) of a jpeg file. To analyze the data, you can issue the command:
:%!xxd
to go back to the original view:
:%!xxd -r
So light, yet so powerful.
Load multiple files from within Vim:
Sometimes when writing code in Vim, I just need some other files to edit or maybe just to look at some code. Here's how you can do that:
:args somefolder/*.php
or if you want to browse to a folder and than load you can do the following:
:e .
This makes Vim as file browser, than you go to a certain folder, i.e. 'somefolder', than select those files with regular expression by first typing:
mr
than type:
*.php
and than type:
me
So by typing mr you open a regular-expression shell to select the matching files, than type the matching expression and than me to edit the files that match with the regular expression.
Insert date:
I like this one too, inserting date in the current file on the current cursorposition:
:r !date
Are you ready for this:
I sometimes accidentally close a file I was working on and to type
:e myfolder/subfolder/somecrazyfile.crz is just too annoying. But check out the power of Vim:
:ls!
shows you the recently closed files, than type:
:xb
and boom! Your recently closed file is back, where x is the id number of one of the closed files.
But this can be done faster! Check this, really amazing, hit the following keys:
Ctrl+o
You're back to the last cursor position in you last closed file! Amazing, just ONE key combination, amazing!
No plugins, just Vim! I'm sorry, I don't know if Emacs can do that :P
Copy/paste tricks:
I was a bit frustrated to copy a word and than replace another word with the copied one. I don't know why I didn't figured it out much earlier, but check this how to do it:
yiw is to copy the word where your cursor is on it, than do:
viwp this selects the word and than paste it with the yanked word earlier. Cool huh.
If you want to do this for another word, do this:
viw"0p meaning replace it with the word from register 0. When you yank or delete a word, the word is automatcially saved in register 0. You select the register by " and than a number. And of course, p is for paste.
When you yank a complete line with yy, you can than replace another line with:
Vp
To do this again for another line:
V"0p
I found this handy trick on: http://vim.wikia.com/wiki/Replace_a_word_with_yanked_text
Friday, July 5, 2013
Microcontroller - Which microcontroller to choose
For a long time I was thinking about building a robot, but never started to build one, until recently. A week ago me, my wife an my kids visited the Robocup2013 event in Eindhoven, the Netherlands. It was great to taste the enthusiasm during the event. So many young kids have built their little robots challenging other robots. 40 countries participated to the event but unfortunately Morocco was not one of the participants.
So I thought if I build a robot with very cheap components and share the result and knowledge with students from Morocco (and the rest of the world of course), maybe the schools and universities in Morocco will think about to participating to such events as the Robocup2013. We live in an era where knowledge is shared with the rest of the world over the internet. So the Moroccans have no excuse that they can't gain knowledge because it's expensive. Nowadays, knowledge is free and available on the internet.
To build at least an intelligent robot, I need a microcontroller to start with. But which microcontroller is suitable? Some criteria should be met, tom my opinion are I think:
After some time I found some projects based on Arduino. Arduino's are openhardware systems based on Atmel's AVR microcontroller, which also has a simple to use IDE including C compiler. The code can be flashed to an Arduino device through usb cable. There is no need for a special JTAG interface or self-built serialport loader. It supports also C++ and it's really easy to write code for it, to me it feels like writing code in Java. The builder of Arduino's really managed to create a microcontroller platform that is accessible to a large audience with no experience of microcontrollers. They really did a tremendous job to achieve that.
Another great advantage of Arduino is they are cheap comparing to others, people with low budget that want to learn or build a microcontroller project, are able to buy one. To program the controller, one just has to download the software for free and need an appropriate usb cable.
If you want to have more control over the AVR microcontroller, there is also a free compiler for it, free IDE and so on. So Arduino is a great way to jump to AVR, because Arduino is based on AVR.
Because as a father, husband and employee I have little free time, my choice is to start with Arduino and next AVR.That's my choice b.t.w. ;-)
So I thought if I build a robot with very cheap components and share the result and knowledge with students from Morocco (and the rest of the world of course), maybe the schools and universities in Morocco will think about to participating to such events as the Robocup2013. We live in an era where knowledge is shared with the rest of the world over the internet. So the Moroccans have no excuse that they can't gain knowledge because it's expensive. Nowadays, knowledge is free and available on the internet.
To build at least an intelligent robot, I need a microcontroller to start with. But which microcontroller is suitable? Some criteria should be met, tom my opinion are I think:
- it must be cheap, as cheap as possible
- great community to ask for help and lots of tutorials
- good development environment, like IDE, compiler, debugger (very important)
- cheap microcontroller programmer
After some time I found some projects based on Arduino. Arduino's are openhardware systems based on Atmel's AVR microcontroller, which also has a simple to use IDE including C compiler. The code can be flashed to an Arduino device through usb cable. There is no need for a special JTAG interface or self-built serialport loader. It supports also C++ and it's really easy to write code for it, to me it feels like writing code in Java. The builder of Arduino's really managed to create a microcontroller platform that is accessible to a large audience with no experience of microcontrollers. They really did a tremendous job to achieve that.
Another great advantage of Arduino is they are cheap comparing to others, people with low budget that want to learn or build a microcontroller project, are able to buy one. To program the controller, one just has to download the software for free and need an appropriate usb cable.
If you want to have more control over the AVR microcontroller, there is also a free compiler for it, free IDE and so on. So Arduino is a great way to jump to AVR, because Arduino is based on AVR.
Because as a father, husband and employee I have little free time, my choice is to start with Arduino and next AVR.That's my choice b.t.w. ;-)
Monday, July 1, 2013
Robots - Robocup2013
Last weekend I went to the Robots event Robocup 2013 in the city Eindhoven, in the Netherlands. I went there together with my wife and 3 kids and it was a bit fun. It was more fun for the participants of the event. There were participants from about 40 countries, including Turkey, Iran, China and so on... As a visitor you can only see the robots from a distance on a stand. So finally it wasn't more than watching to a bunch of robots who try to score with a colored ball. There were different leagues, categorized from small simple robots to artificially intelligent robots.
The more interesting robots are those humanoid robots, these robots look like humans, or they try to be.
Also there's some interaction, that makes a robot always interesting, especially for the kids. We saw the famous autonomous robot Asimo too, but it was very crowded and couldn't see much, so it wasn't a great success, but at least we saw something.
If you see how much research, effort and technology it was needed to build a robot like Asimo, how difficult and knowledge is needed to build a real human? That's why I believe in God as our creator and that there's a reason why we we're built.
I really hope the kids like it and that they're interested in building a robot too :-) Who knows, someday I'll post a robot built with my family.
The more interesting robots are those humanoid robots, these robots look like humans, or they try to be.
Also there's some interaction, that makes a robot always interesting, especially for the kids. We saw the famous autonomous robot Asimo too, but it was very crowded and couldn't see much, so it wasn't a great success, but at least we saw something.
If you see how much research, effort and technology it was needed to build a robot like Asimo, how difficult and knowledge is needed to build a real human? That's why I believe in God as our creator and that there's a reason why we we're built.
I really hope the kids like it and that they're interested in building a robot too :-) Who knows, someday I'll post a robot built with my family.
Wednesday, June 19, 2013
Java - Mail
How to send mail from Java sourcecode?
First you need to download the library mail.jar from oracle and add it to your Java project.
You can get it on the link below:
http://www.oracle.com/technetwork/java/index-138643.html
Than try out this code:
final String username = "username@gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-email@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
It's quite easy and it should work, unless your firewall blocks it, in that case open the port 587.
This is working for GMail accounts, but it should work with other accounts too, with just a little modification in the code.
This example code is copied from mkyong's website:
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/comment-page-4/#comment-135038
First you need to download the library mail.jar from oracle and add it to your Java project.
You can get it on the link below:
http://www.oracle.com/technetwork/java/index-138643.html
Than try out this code:
final String username = "username@gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-email@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
It's quite easy and it should work, unless your firewall blocks it, in that case open the port 587.
This is working for GMail accounts, but it should work with other accounts too, with just a little modification in the code.
This example code is copied from mkyong's website:
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/comment-page-4/#comment-135038
Thursday, June 6, 2013
Promising gadgets - Apple's Smartwatch vs. Google's Glass
Though smartwatches or smartglasses are not new, just like tablets before the iPads, they're still not a huge success. But Apple and Google are working hard to launch a new success device.
Apple, according to rumors on the internet, is working hard on a smartwatch, while Google is already demonstrating their smartglass called Glass. But which one will succeed?
Smartwatch
The advantage of a smartwatch is it's wearable as an ordinary watch. If you receive an sms or a whatsapp message, you can simply read it from your watch. Of course, if you just want to know what time it is, use your watch. You can even check photos and other viewing stuff
The disadvantage is it has a small display, so entering a text using your fingers is not a good idea. Also it's not a good idea to take a picture with your watch.
To summarize a smartwatch we could list the advantages and disadvantages as follows:
Advantage:
Disadvantage:
Seeing these advantages and disadvantages we can make following conclusions, a smartwatch should :
Smartglass
The big advantage of smartglasses is you have your hands free while recording videos with an integrated camera. Because a smartglass is mounted on your head, it works also as a headset. The big disadvantage is, you have to wear a smartglass the whole day and not everybody likes to wear such a device that's not coverable.
To summarize a smartglass we could list the advantages and disadvantages as follows:
Advantage:
Disadvantage:
My personal opnion
I think the smartwatch will be a success for normal people, because it's like a watch, but a smart one. Like there was a normal phone before, now you have a smart one. A glass is not an electronic device, wearing glasses is only for necessity (to be able to see better). So I think for the normal people, a Google's Glass won't be a huge success. However, it could be a success in the business industry or in the world of sport and games. For example, a referee of a soccer game could see real life video of an incident before taking real decision. Or in a hospital, a nurse could see a patient's dossier, take a quick picture and send it to the doctor. There are great possibilities with a smartglass, but I doubt it will be successful for the normal people.
My conclusion is, smartwatch will be successful for normal consumers and smartglass will be successful in the business industry.
Apple, according to rumors on the internet, is working hard on a smartwatch, while Google is already demonstrating their smartglass called Glass. But which one will succeed?
Smartwatch
The advantage of a smartwatch is it's wearable as an ordinary watch. If you receive an sms or a whatsapp message, you can simply read it from your watch. Of course, if you just want to know what time it is, use your watch. You can even check photos and other viewing stuff
The disadvantage is it has a small display, so entering a text using your fingers is not a good idea. Also it's not a good idea to take a picture with your watch.
To summarize a smartwatch we could list the advantages and disadvantages as follows:
Advantage:
- easily wearable
- coverable
- readable for messages and notifications
- viewable for photos
- see who's calling
- streaming video (or live video)
Disadvantage:
- small battery size
- small display size
- not useful for entering text
- not useful for taking pictures or recording videos
- not useful for calling session, like talking to your phone and using headphones connected to the smartphone.
Seeing these advantages and disadvantages we can make following conclusions, a smartwatch should :
- work as a client for a smartphone using bluetooth connection to communicate.
- have low energy consumption because of small battery capacity. It would be very annoying to charge your watch everyday.
- an api to write widgets for smartwatches.
- have a side trackpad for vertical scrolling, because of small display size, your finger will easily cover the display and thus not user friendly.
- copy UI from older gsm devices like the Ericsson G700. Cause these UIs were based on small display sizes.
Smartglass
The big advantage of smartglasses is you have your hands free while recording videos with an integrated camera. Because a smartglass is mounted on your head, it works also as a headset. The big disadvantage is, you have to wear a smartglass the whole day and not everybody likes to wear such a device that's not coverable.
To summarize a smartglass we could list the advantages and disadvantages as follows:
Advantage:
- easily wearable
- readable for messages and notifications
- viewable for photos
- see who's calling
- streaming video (or live video)
Disadvantage:
- small battery size
- not useful for entering text
- not coverable
- work as a client for a smartphone using bluetooth connection to communicate.
- have low energy consumption because of small battery capacity. It would be very annoying to charge your smartglass everyday.
- an api to write widgets for smartglasses.
- have a side trackpad for scrolling.
- have a suitable UI. Cause it's not a touch based device (i.e. a smartphone).
My personal opnion
I think the smartwatch will be a success for normal people, because it's like a watch, but a smart one. Like there was a normal phone before, now you have a smart one. A glass is not an electronic device, wearing glasses is only for necessity (to be able to see better). So I think for the normal people, a Google's Glass won't be a huge success. However, it could be a success in the business industry or in the world of sport and games. For example, a referee of a soccer game could see real life video of an incident before taking real decision. Or in a hospital, a nurse could see a patient's dossier, take a quick picture and send it to the doctor. There are great possibilities with a smartglass, but I doubt it will be successful for the normal people.
My conclusion is, smartwatch will be successful for normal consumers and smartglass will be successful in the business industry.
Tuesday, June 4, 2013
Soccer - Best soccer player of the world
Every year the FIFA soccer organization announce the best player of the year, the so called Ballon d'Or. It's often Messi, Christiano Ronaldo, Ronaldinho, Iniesta, Xavi and so on... If you see the big names, it's not fair to elect just the attackers. An attacker is not a defender, a defender is not a keeper, so it's not fair that Messi is the best football player of the year. I mean, Messi would not be so great without Xavi or Iniesta around him.
To make a fair election, the award should be divided into different groups. For example:
However, to me, Messi is NOT the best player of the world, he's the best attacker of the year.
In my opninion Diego Maradona is the best soccer player ever!
To make a fair election, the award should be divided into different groups. For example:
- best keeper award
- best defender award
- best midfielder award
- best attacker award
- best free kick award
- etc...
However, to me, Messi is NOT the best player of the world, he's the best attacker of the year.
In my opninion Diego Maradona is the best soccer player ever!
Tuesday, April 9, 2013
Android - When a process gets killed.
According to http://developer.android.com/guide/components/processes-and-threads.html,
the Android OS weighs the relative importance of processes to the user to determine which process is candidate for killing, if system resource (like memory) gets low.
For example, if a process has no visible activity running, it is than assumed to be less important to the user and so likely to get killed, when necessary. So depending on the state of components within a process, the OS makes a decision upon it to kill.
The theory is that Android OS tries to maintain a process as long as possible, but eventually needs to remove or kill old processes to reclaim system resource for a more important process. So the OS somehow holds a list of processes based on importance of components and the state of the components. And so a process with the lowest priority gets killed first and than next and next...
There seems to be 5 levels of importance:
1. Forground process
2. Visible process
3. Service process
4. Background process
But what if you want your service not to be killed by the OS, well there is a trick for that.
To do this, you need to call startForground() method of the Service. You have to pass a notification ID and a notification object. Like this:
startForeground(NOTIFICATION_ID, mNotification);
This tells the OS not to kill the service, though the OS will kill it in extreme situation. You can image that when you're listening to music, you don't want the OS to disrupt the music for some reason.
the Android OS weighs the relative importance of processes to the user to determine which process is candidate for killing, if system resource (like memory) gets low.
For example, if a process has no visible activity running, it is than assumed to be less important to the user and so likely to get killed, when necessary. So depending on the state of components within a process, the OS makes a decision upon it to kill.
The theory is that Android OS tries to maintain a process as long as possible, but eventually needs to remove or kill old processes to reclaim system resource for a more important process. So the OS somehow holds a list of processes based on importance of components and the state of the components. And so a process with the lowest priority gets killed first and than next and next...
There seems to be 5 levels of importance:
1. Forground process
- It hosts an Activity that the user is interacting with (the Activity's onResume() method
has been called). - It hosts a Service that's bound to the activity that the user is interacting with.
- It hosts a Service that's running "in the foreground"—the service has called startForeground().
- It hosts a Service that's executing one of its lifecycle callbacks (onCreate(), onStart(), or onDestroy()).
- It hosts a BroadcastReceiver that's executing its onReceive() method.
2. Visible process
- It hosts an Activity that is not in the foreground, but is still visible to the user (its onPause() method has been called). This might occur, for example, if the foreground activity started a dialog, which allows the previous activity to be seen behind it.
- It hosts a Service that's bound to a visible (or foreground) activity.
3. Service process
- A process that is running a service that has been started with the startService() method and does not fall into either of the two higher categories. Although service processes are not directly tied to anything the user sees, they are generally doing things that the user cares about (such as playing music in the background or downloading data on the network), so the system keeps them running unless there's not enough memory to retain them along with all foreground and visible processes.
4. Background process
- A process holding an activity that's not currently visible to the user (the activity's onStop() method has been called). These processes have no direct impact on the user experience, and the system can kill them at any time to reclaim memory for a foreground, visible, or service process. Usually there are many background processes running, so they are kept in an LRU (least recently used) list to ensure that the process with the activity that was most recently seen by the user is the last to be killed. If an activity implements its lifecycle methods correctly, and saves its current state, killing its process will not have a visible effect on the user experience, because when the user navigates back to the activity, the activity restores all of its visible state.
- A process that doesn't hold any active application components. The only reason to keep this kind of process alive is for caching purposes, to improve startup time the next time a component needs to run in it. The system often kills these processes in order to balance overall system resources between process caches and the underlying kernel caches.
But what if you want your service not to be killed by the OS, well there is a trick for that.
To do this, you need to call startForground() method of the Service. You have to pass a notification ID and a notification object. Like this:
startForeground(NOTIFICATION_ID, mNotification);
This tells the OS not to kill the service, though the OS will kill it in extreme situation. You can image that when you're listening to music, you don't want the OS to disrupt the music for some reason.
Monday, March 11, 2013
A quick Git tutorial part 3
Link to a well explained git tutorial
gitref.org
git remote
If you clone a project from another machine, Git automatically sets the remote machine as the origin of the project. So when you want to update with the latest updates of the project you simply do:
git pull
With 'git remote' you can list your remote aliases, so this also means you can add remote machines that has the same git repo:
git remote add alias url
This way you can push new changes to a specific machine by giving the remote alias argument, for example:
git push yozef
Of course, you can also remove the alias:
git remote rm yozef
To show the remote list with extra information:
git remote -v
You can change url of an existing alias:
git remote set-url origin git://some.remote.machine/repo.git
To remove untracked files and folders after hard reset:
git clean -f -d
gitref.org
git remote
If you clone a project from another machine, Git automatically sets the remote machine as the origin of the project. So when you want to update with the latest updates of the project you simply do:
git pull
With 'git remote' you can list your remote aliases, so this also means you can add remote machines that has the same git repo:
git remote add alias url
This way you can push new changes to a specific machine by giving the remote alias argument, for example:
git push yozef
Of course, you can also remove the alias:
git remote rm yozef
To show the remote list with extra information:
git remote -v
You can change url of an existing alias:
git remote set-url origin git://some.remote.machine/repo.git
To remove untracked files and folders after hard reset:
git clean -f -d
Tuesday, March 5, 2013
A quick Git tutorial part 2
git rm
With 'git rm' we remove a file from the staging index AND from disk. So be careful if you don't want to remove it from disk! If you only want to remove a file from the staging index, you should use:
git rm --cached file
This will remove a file from the staging index and leaves the file on the disk. Sometimes you accidentally added a file you don't wish Git to track it. So the most simple procedure is to perform 'git rm --cached file', than add this file name in the .gitignore file and than finally commit. But what if you have like hundreds of files added in a folder you don't want Git to track them. For this, you can get them out of the staging index like this:
git rm --cached -r folder
Don't forget to add a line in .gitignore file to tell Git to ignore all the files in that particular folder, something like: sources/somefolder/*
git reset
With 'git reset' you actually reset your changes back to the original HEAD (the last commit revision before adding changes). Sometimes you don't know what happened and you get frustrated as everything seems to go wrong. In that case, your last action to the rescue is to go back to HEAD and everything gets wiped out. There is no way in turning back, so be careful.
With 'git reset --hard', the changes in the staging index will be undone and thus completely removed. It's the same as going back to the last commit and no changes are made yet. Notice that HEAD could also be a commit revision. If you want to go back to a previous commit, you could also do:
git reset --hard HEAD^
or
git reset --hard b45ac81
The latter brings you back to the commit with the first seven characters of the sha (in that case ' b45ac81').
If you want to go to a previous commit BUT you want the changes stay in de staging index, than you can do:
git reset --soft HEAD^
With the --soft argument, the changes stays in the staging index.
git stash
Suppose we were editing some files and suddenly a bugfix need to be done. We could create a new branch from the current branch and fix the problem or we can save our work on a stack to get back later. The latter one is called stashing. By performing 'git stash' all the edits will be saved on a stack and you get a message like:
Saved working directory and index state WIP on master: 56490c0 cool stuff with git
HEAD is now at 56490c0 cool stuff with git
You can do some more edits and save this on a stack too. To see what work we have save, we can list them with the following command:
git stash list
result:
stash@{0}: WIP on master: c761ca7 experimenting with git
stash@{1}: WIP on master: 56490c0 cool stuff with git
The top of the stack is 0 and the stack is a LIFO.
WIP could mean Work In Progress, seems logic to me, but it could mean something else.
The master means the master branch, so the message is quite clear.
Anyway, now we want to get the edits back we saved earlier, as we solved a bugfix, this is how we do:
git stash apply
This will get the 'changes' back where we left off. We could also use:
git stash pop
The difference is that the latter one will remove WIP from the stack, while the first one keeps the WIP on the stack. After putting back the saved WIP, we can remove it from the stack with:
git stash drop
This will remove a WIP from the top. If you want to remove them all, you could also issue the following command:
git stash clear
git commit --amend
Oops, you wrote a wrong message for a commit and you want to change that?
git commit --amend -m "my new message"
git cherry-pick
This commands can be useful if you want to add a commit from another branch to your master branch. You can imagine that while you're working on a separate branch, you already want to commit some of the work already done and not waiting until you finished your big changes on the separate branch.
We can do this by 'picking' a commit from another branch and 'insert' it in the master branch.
So suppose we are in a branch called 'test' and we've already done some commits and we're still busy doing some edits in some files. We can merge the last commit that's already done to the master branch. So we switch to the master branch:
git checkout master
Than we pick a commit, i.e. '93e8ab7', from the 'test' branch and insert it in the master branch like this:
git cherry-pick 93e8ab7
You can do this multiple times, but chances are you'll get conflicts if the same files will be committed again. To solve this, we 'git rebase' the branch on to the master branch. It's like making a custom branch compatible with the master branch. You will see that the commit hashes are changed after a rebase. From there on, you can switch to the master branch and merge the commits from your custom branch to the master.
To rebase, you go to your custom branch and do the following:
git rebase --onto master 1234abcde^
where 1234abcde^ is the commit from where you want to rebase to the master branch.
After that, you'll notice that commit sha's from 1234abcde to the last commit, will be changed, so it fits to the master branch. Now, if we switch back the master branch and do: git merge custombranch
Than all the changes will be merged to the master branch.
Play with it, cause it's a bit confusing and you better should avoid cherry-picking if not necessary.
git format-patch, git apply
When developing with a team on a project, there is often the case that you have one central source repository (based on Git) where the latest source codes maintains. It would be a mess if all developers of the team starts pushing the new codes and bugfixes. To keep the situation organized, there should be some kind of source code maintainer who checks the new codes and bugfixes before it updates the repository. What you get is developers are forced to send patches of codes to the maintainer and the maintainer checks whether it's ok or not, this way you get a controlled process of developing on a project with a team.
Well, to create a patch in Git, it's best to create a seperate branch and do your editing there. If you made a little fix, or added a new feature and you tested well, you finally create a patch, to do this you do as follows (assuming you're on a different branch):
git format-patch master
This means, make a patch from the difference between master branch and the current branch.
We could also do this:
git format-patch HEAD^^...HEAD
This means, make a patch from two previous commits ago to the last commit.(^ means previous).
We could also use commit revisions instead of HEADs.
Often you want to give a patch a name, so others have an idea what the patch is about:
git format-patch master --stdout > fix_bug_123.patch
On the other side, if you want to apply a patch in your master branch, it's just simply this (assuming you're on the master branch):
git apply fix_bug_123.patch
Understanding difference between cherry-pick and merge
When you have a custom branch to do some edits on it, you might have made multiple commits. So when you're satisfied with the final result, you want to merge it to the master branch. So you switch to the master branch and do 'git merge custombranch'. What happens is all the commits are copied to the master branch, you can see them with 'git log --oneline'. If you want to cherry-pick a commit, you actually want to copy the changes of one commit to your master branch (or whatever branch you are). So you get a new commit based on the 'changes' of your custombranch which is a different hash!
I'll add some images to get a better understanding, as there is a saying "a picture says more than thousand words".
git diff
To show what files have changed, 'git diff' shows the content of the changes, for example:
git diff
this will show the difference between the last commit and the added changes that are NOT added in the staging index
To show the changes in the staging index, do this:
git diff --cached
If you want to show both of the changes, meaning the changes in your working directory, do this:
git diff HEAD
To show the difference between two commits:
git diff HEAD^ HEAD
Note that the HEAD's could also be the sha's of the commits.
With 'git rm' we remove a file from the staging index AND from disk. So be careful if you don't want to remove it from disk! If you only want to remove a file from the staging index, you should use:
git rm --cached file
This will remove a file from the staging index and leaves the file on the disk. Sometimes you accidentally added a file you don't wish Git to track it. So the most simple procedure is to perform 'git rm --cached file', than add this file name in the .gitignore file and than finally commit. But what if you have like hundreds of files added in a folder you don't want Git to track them. For this, you can get them out of the staging index like this:
git rm --cached -r folder
Don't forget to add a line in .gitignore file to tell Git to ignore all the files in that particular folder, something like: sources/somefolder/*
git reset
With 'git reset' you actually reset your changes back to the original HEAD (the last commit revision before adding changes). Sometimes you don't know what happened and you get frustrated as everything seems to go wrong. In that case, your last action to the rescue is to go back to HEAD and everything gets wiped out. There is no way in turning back, so be careful.
With 'git reset --hard', the changes in the staging index will be undone and thus completely removed. It's the same as going back to the last commit and no changes are made yet. Notice that HEAD could also be a commit revision. If you want to go back to a previous commit, you could also do:
git reset --hard HEAD^
or
git reset --hard b45ac81
The latter brings you back to the commit with the first seven characters of the sha (in that case ' b45ac81').
If you want to go to a previous commit BUT you want the changes stay in de staging index, than you can do:
git reset --soft HEAD^
With the --soft argument, the changes stays in the staging index.
git stash
Suppose we were editing some files and suddenly a bugfix need to be done. We could create a new branch from the current branch and fix the problem or we can save our work on a stack to get back later. The latter one is called stashing. By performing 'git stash' all the edits will be saved on a stack and you get a message like:
Saved working directory and index state WIP on master: 56490c0 cool stuff with git
HEAD is now at 56490c0 cool stuff with git
You can do some more edits and save this on a stack too. To see what work we have save, we can list them with the following command:
git stash list
result:
stash@{0}: WIP on master: c761ca7 experimenting with git
stash@{1}: WIP on master: 56490c0 cool stuff with git
The top of the stack is 0 and the stack is a LIFO.
WIP could mean Work In Progress, seems logic to me, but it could mean something else.
The master means the master branch, so the message is quite clear.
Anyway, now we want to get the edits back we saved earlier, as we solved a bugfix, this is how we do:
git stash apply
This will get the 'changes' back where we left off. We could also use:
git stash pop
The difference is that the latter one will remove WIP from the stack, while the first one keeps the WIP on the stack. After putting back the saved WIP, we can remove it from the stack with:
git stash drop
This will remove a WIP from the top. If you want to remove them all, you could also issue the following command:
git stash clear
git commit --amend
Oops, you wrote a wrong message for a commit and you want to change that?
git commit --amend -m "my new message"
git cherry-pick
This commands can be useful if you want to add a commit from another branch to your master branch. You can imagine that while you're working on a separate branch, you already want to commit some of the work already done and not waiting until you finished your big changes on the separate branch.
We can do this by 'picking' a commit from another branch and 'insert' it in the master branch.
So suppose we are in a branch called 'test' and we've already done some commits and we're still busy doing some edits in some files. We can merge the last commit that's already done to the master branch. So we switch to the master branch:
git checkout master
Than we pick a commit, i.e. '93e8ab7', from the 'test' branch and insert it in the master branch like this:
git cherry-pick 93e8ab7
You can do this multiple times, but chances are you'll get conflicts if the same files will be committed again. To solve this, we 'git rebase' the branch on to the master branch. It's like making a custom branch compatible with the master branch. You will see that the commit hashes are changed after a rebase. From there on, you can switch to the master branch and merge the commits from your custom branch to the master.
To rebase, you go to your custom branch and do the following:
git rebase --onto master 1234abcde^
where 1234abcde^ is the commit from where you want to rebase to the master branch.
After that, you'll notice that commit sha's from 1234abcde to the last commit, will be changed, so it fits to the master branch. Now, if we switch back the master branch and do: git merge custombranch
Than all the changes will be merged to the master branch.
Play with it, cause it's a bit confusing and you better should avoid cherry-picking if not necessary.
git format-patch, git apply
When developing with a team on a project, there is often the case that you have one central source repository (based on Git) where the latest source codes maintains. It would be a mess if all developers of the team starts pushing the new codes and bugfixes. To keep the situation organized, there should be some kind of source code maintainer who checks the new codes and bugfixes before it updates the repository. What you get is developers are forced to send patches of codes to the maintainer and the maintainer checks whether it's ok or not, this way you get a controlled process of developing on a project with a team.
Well, to create a patch in Git, it's best to create a seperate branch and do your editing there. If you made a little fix, or added a new feature and you tested well, you finally create a patch, to do this you do as follows (assuming you're on a different branch):
git format-patch master
This means, make a patch from the difference between master branch and the current branch.
We could also do this:
git format-patch HEAD^^...HEAD
This means, make a patch from two previous commits ago to the last commit.(^ means previous).
We could also use commit revisions instead of HEADs.
Often you want to give a patch a name, so others have an idea what the patch is about:
git format-patch master --stdout > fix_bug_123.patch
On the other side, if you want to apply a patch in your master branch, it's just simply this (assuming you're on the master branch):
git apply fix_bug_123.patch
Understanding difference between cherry-pick and merge
When you have a custom branch to do some edits on it, you might have made multiple commits. So when you're satisfied with the final result, you want to merge it to the master branch. So you switch to the master branch and do 'git merge custombranch'. What happens is all the commits are copied to the master branch, you can see them with 'git log --oneline'. If you want to cherry-pick a commit, you actually want to copy the changes of one commit to your master branch (or whatever branch you are). So you get a new commit based on the 'changes' of your custombranch which is a different hash!
I'll add some images to get a better understanding, as there is a saying "a picture says more than thousand words".
git diff
To show what files have changed, 'git diff' shows the content of the changes, for example:
git diff
this will show the difference between the last commit and the added changes that are NOT added in the staging index
To show the changes in the staging index, do this:
git diff --cached
If you want to show both of the changes, meaning the changes in your working directory, do this:
git diff HEAD
To show the difference between two commits:
git diff HEAD^ HEAD
Note that the HEAD's could also be the sha's of the commits.
Subscribe to:
Posts (Atom)
-
To use Vim as an editor for C/C++ (and other programming languages as well), we need to extend Vim with some handy plugins. Vim is a power...
-
How to get intellisense like (omnicompletion) feature on Vim for standard C libraries! If you're a Vim user and also code C sources i...
-
I wanted my RaspberryPi to autoconnect through wifi on a spcified Access Point (AP). To do this, first I copied /etc/wpa_supplicant/wpa_su...