Showing posts with label code I wrote. Show all posts
Showing posts with label code I wrote. Show all posts

Friday, 11 September 2015

A log about writing a logger

So, I finally completed the first cut of my logger, and initially it was a LOT larger than the version in the repository, but after 'test driving', I found that (sadly) all my fancy ideas were just too fancy.

So, it's a pretty small 'opus', and just proves the rule that the shorter a piece of software is, the longer it takes to write.

I found that the ability to define new logging macros, set levels and display options, cherry pick levels to show and defining an output function on the fly really is more than enough for everything that is needed.

Other fails include that my idea to use 'ts -i "%.s"' from moreutils for adhoc profiling didn't really work properly for some reason that I cannot work out why.

If I try to use it with a macro that sets a few printout markers inside a function, all I get is that the expected function printf output stops totally whilst it does it's thing, then I get the total time taken put out on the top line, and everything that I expected to arrive 'peu-a-peu' comes in one go as it's finished doing the time wasting loop test, and it looks suspiciously like it's simply measuring the time it takes for writing to stdout via printf, and that some weird blockage is happening to the stdout output.

Oh well.  Looks like I just have to write something else to have that service :-D




Sunday, 23 August 2015

A logger for Corinthia

I managed to get the first cut written, and I got use the logmessage scribe.  Took 5 minutes to write the log message, woo!  Profit! :-))

Of course I found a couple of minor bugs in the logmessage scribe, mostly because I had to use GNU diff instead of git diff, but, I could not be happier.


Translation: if you're happy and you know it just say 'meow'!

Tuesday, 18 August 2015

Tree keeping made easy

If you want snazzy tree views for your project of your local drive files and the remote master repository that you can traverse with a browser, just modify this script and set up a cronjob to keep your trees updated.

How does it look?

Download the file itself, load it into your browser and have fun traversing the tree of the Corinthia GitHub repository. (blogger.com and google.drive won't let me paste the file without crippling the links, fair enough, it's 168 directories (and thus links) and usually people who do this kind of thing would probably be up to no good[1]).  If you just want to see it without working links, it's here.




I think it's nice to have a tree overview --- a picture is worth a 1000 words (as they say).

[1] sadly, saving the document also ninja-edits the original.  So, don't waste your time with pasting lots of links into Google Docs :(

Sunday, 5 July 2015

Introducing Logmessage Scribe

This is my first python project.

It turns patches into logmessage templates, ready for you to produce a great logmessage.

The source (along with a proper introduction about the project) is parked on Bitbucket and the webapp is hosted on Google Appengine

Enjoy!



Wednesday, 27 May 2015

Put some colour in your C code

I like colours.

Colours make things easier to spot, especially if you have to look at a few metres of test output bumpf --- looking for something blue or pink is much quicker.

So, I made myself a little color.h file that lives in /usr/include/ where it is available anywhere I need some colour in my code.

You will probably notice the colour names --- I took the liberty of renaming 'green' to 'moss', 'bold green' to just 'green' and 'magenta' to 'purple' and so on.  It's less to type, more descriptive, and, also functions as a small cheat map to understand the weird names the fashionistas in your life use to describe colour shades.

You can find the source for color.h here, note that the test code is present in the file in a comment, ready to be copied into a *.c file.

Enjoy!

                                                 

Monday, 25 May 2015

A fake switch

This post is about a trick from the Dalvik VM Internals video, which was mentioned in the Coursera Android course that is currently running. (maybe the next million years will be more exciting?)
                                         
The claim was that this is the one case where goto isn't evil around minute 33:31 and that it performs better than switch.  Well, does it?  And if so, by how much?

This was the example:

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#define DISPATCH()  \
    { goto *op_table[*((s)++) - 'a']; }

static void interp_old(const char* s)
{ 
   static void *op_table[] = { 
   &&op_a, &&op_b, &&op_c, &&op_d, &&op_e };
   DISPATCH();
   op_a: printf("Hell"); DISPATCH();
   op_b: printf("o "); DISPATCH();
   op_c: printf("wo"); DISPATCH();
   op_d: printf("rld!\n"); DISPATCH();
   op_e: return;
}
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            
Switch is pretty switched on, so let's see how this compares!

The code that does the comparison can be found here.  Results(on my ancient 32 bit Dell):

With gcc -g:
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 
Using default value of 100000.  Usage: ./dispatch #
Sample size = 100000 chars * 100000 iterations. 
Dispatch method:                         0.002152 
Dispatch shuffled method:                0.002144
Goto switch method:                      0.002641
Goto switch method 2:                    0.002351
For loop Switch method:                  0.002667
For loop Switch shuffled method:         0.002660 
Recursive switch method:                 0.010798
Recursive shuffled Switch method:        0.006913
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

With gcc -O3:

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Using default value of 100000.  Usage: ./dispatch #
Sample size = 100000 chars * 100000 iterations.
Dispatch method:                         0.001083
Dispatch shuffled method:                0.001108
Goto switch method:                      0.001338
Goto switch method 2:                    0.001381
For loop Switch method:                  0.001465
For loop Switch shuffled method:         0.001385
Recursive switch method:                 0.001437
Recursive shuffled Switch method:        0.001385
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

So, there is a small difference, but it's really not that big a deal, unless you really are pressed for time and space.

The ever useful gcc manual has an entry about fun with local labels which will tell you more. Still, building this by hand is tedious, even if emacs is your best friend.  

What if you have a huge array of a struct that maps variable A to variable B and also has an optional function pointer F?  What you need is a 'fake_switch' generator, here is my version.  It should be easily adjustable for your taste. 

Goto it ;-)

Ps.: For extra fun, try this C to Assembler translator.  I really like the hover feature they built, but another thing that would be useful is showing the size of the generated code.
                                                                                                                                                                                    

Sunday, 10 May 2015

Programming is fun (when stuff compiles)

Went to a BBQ.  Seemed to be a training session for competitive eating :-)

Came home, got my project's blueprint working.  Got emacs to smoke'n'choke with an M-x indent-region -- no idea what it did there, but it needed 20 minutes to indent gbg_test.h.  Impressive.


This music definitely helped things along :-)

Saturday, 7 March 2015

A little perl alias for git log messages

To get a nice log message for your git diff patch which makes it easy for a reviewer to check your stuff, try this little perl proggy:

alias gitdifflogmesg="perl -ne 'BEGIN {print \"[[[\";} /^\\+\\+\\+ b\\/(\\S+)/ && print \"\\n\\n* \$1\";  /^@\@.*[ *]([^ ]+)\(/ && print \"\\n  (\$1).\"; END { print \"\\n\\n]]]\\n\";}'"

Put this into your .bashrc (as one line), and, grab a patch you made with git diff, and use the alias like so:

cat your.patch | gitdifflogmesg

The output is something like this:

* path/to/modifed-file1.c
   (some_function_a).
   (some_function_b).

* path/to/modifed-file2.c
   (some_function_c).
   (some_function_d).

Now all you need to do is some accounting -- a good 50 char intro line and say what you did with all those functions and your log message is ready for sharing.  Of course not all log messages need this level of scrutiny, but, this goes a long way towards helping your reviewers and also, to help yourself to produce a great patch (or mailing list post).

Note that this does not pick up everything --- new #includes and new functions for example.  Then again, whilst that one liner is kinda cute, this service should really be offered by git itself.  But whilst git doesn't have this feature, this goes a long way towards making log messages easy ;-)

I am not a perl wizard though, I just read the book 'Perl One-Liners: 130 Programs That Get Things Done' -- even if you only read the first 3 chapters, you gain a handy little skill, plus, it's just fun to fiddle with.

Wednesday, 4 March 2015

Corinthia

I am proud to announce that I've been made a full committer and PPMC member of the Apache Incubator project Corinthia.

I'll be coding in C and Javascript, and I'll be looking to help with the editor and whatever else needs attention :-)






Sunday, 12 October 2014

Solving a Non-Problem

If you solve Euler Project problem 26, you will be able to see my 'solution' in the forum for that problem on page 9, as user Gabriela.

It's terrible.  Taarrrribbble.   First I didn't research the math, thinking: Oh, that is _easy_!  Then one simple hack led to another quick hack (with a bit of faerydust sprinkled) and let's just say I got the correct solution the first time I checked, because I lucked out, not because I wrote a good algorithm.

Valgrind was happy with it.  I'm not.  After posting the code, I realised that *somehow* I crammed nearly 1000 chars into a string I malloc(500)'ed.

The question is:  Why did it work?  The next question is: would it work on another computer?  And most important of all: should it have worked in the first place?  Plus, other than eye balling the code and seeing the obvious problem, is there a way to check?

True, you could say that it's not a bug as such, because it does what I intended, but... the issue that I have, is if that isn't picked up with a nice helpful (and popular!) SIGSEV, what else is as dodgy and wrong?

Adding -fstack-protector-all didn't help to find a indication of an error either.

After some surfing, I found that dmesg (and readelf -s) is my friend, and, lo and behold:

(...)
[12556151.546186] project2-exe[18950]: segfault at 7fff5a18ae00 ip 00007fd452916744 sp 00007fffaddf9338 error 4 in libc-2.19.so[7fd45288d000+1bb000]                                                                       
[12564217.667780] traps: project2-exe[19250] general protection ip:7f94a50ad7cd sp:7fff01927b90 error:0 in libc-2.19.so[7f94a5072000+1bb000]
(...)         

Luckily I knew where the problem was, or so I thought.  But, alas, this was a previous SIGSEV which I had fixed[1] and there was nothing that readelf had to tell me.  After some more coffee, I finally had the bright idea that perhaps those allocations were just not used, and I checked the man pages for strndup() and strstr() and... yep, that was the non-problem.


[1] One good reason to use the emacs shell instead of M-x compile:  search upwards is trivial and you find out some things that otherwise would have confuzzled you for yonks.

Wednesday, 13 August 2014

Sometimes, to fake is better than to make

#! /bin/bash                                                         
# Compile a test file without those noisy -Wunused* flags, but       
# everything else that may be useful.                                
# 
# Usage: compileCTest <name of your file  without the '.c'>  
       
# give the executable an easy to spot and mass-delete friendly name
executable="$1-exe"

# remove the old executable if it exists                             
if [ -e $executable ]
then                                                                 
    rm $executable;                                                  
fi                                                                                                            
echo ""
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo ""

# all flags from -Wall and -Wextra minus the -Wunused flags
runGCC='gcc -g -std=c99 -Waddress -Warray-bounds -Wchar-subscripts -Wenum-compare -Wimplicit-int -Wimplicit-function-declaration -Wformat -Wmain -Wmaybe-uninitialized -Wmissing-braces -Wnonnull -Wparentheses -Wpointer-sign -Wreturn-type -Wsequence-point -Wsign-compare -Wstrict-aliasing -Wstrict-overflow=1 -Wswitch -Wtrigraphs -Wuninitialized -Wunknown-pragmas -Wvolatile-register-var -Wclobbered -Wempty-body -Wignored-qualifiers -Wmissing-field-initializers -Wmissing-parameter-type -Wold-style-declaration -Woverride-init -Wsign-compare -Wtype-limits -Wuninitialized $1.c -o $1-exe -lm -lgmp'

eval $runGCC                                                         

# check that compile resulted in executable and if so, run it  
if [ -e $executable ]                 
then                                                                 
# add a couple of dividing lines to make this easier to read 
echo "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=";
./$executable;
echo "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=";
fi         

Saturday, 21 June 2014

It Seemed Like a Good Idea at the Time

My latest idea for the svn --diff-cmd can be seen here.


Let's hope it does better than this guys' great idea!

Tuesday, 17 June 2014

SVN --invoke-diff-cmd branch shipped

So what happened that took the time?

1. I forgot *everything* (and had to re-re-re-read the manuals)

2. My main laptop died (RIP frogburg, it croaked it's last) and so I had to build everything back from scratch on my remaining machine.  I also have a new desktop that I had so far avoided to set up, which I did at the same time.

3.  Because the trunk had changed quite a bit, my feeble attempts to merge initially produced a veritable mess that added to the general confusion.  It didn't help that this was my first merge that required actual work, nor did it help that I had a complete new install and for a few days didn't realise that kdiff3 wasn't installed, and thought that my code was broken (which it was, but not in this place) and so, I of course kept looking in the illuminated place for the door keys.

4. Somewhere in the new trunk code, a miracle happens.   That is, it picks up the actual command line input en passant 3 functions deep whilst it reads the config file, and I had to break out gdb to search the haystack.

5.  Every time I get stuck (or bored) I read a page of the TCP/IP book.  I read a lot of TCP/IP book.

Anyway, here is the new branch, this time as a patch.

Thursday, 29 May 2014

A script for Exaile: bedtime-story.sh

As much as I like Exaile, it sadly lacks the option of turning a recording off after n minutes.

But, who needs a feature for the Exaile GUI when a script will suffice?

So, set your story up to play in the GUI, then use this:

bedtime-story.sh:

# turn the screen off
xset dpms force off

sleep $@ > /dev/null 2>&1

if [ $? = 1 ]
then
    # turn the screen on
    xset dpms force on
    echo "Fade out Exaile playback after a defined time, using the computer's volume control."
    echo ""
    echo "Usage: bedtime-story NUMBER[smh]..."
    echo ""
    echo "Each argument is a number followed by a unit."
    echo "The units are: s (seconds), m (minutes), h (hours)"
    echo "Example: bedtime-story 20m 10s"
    echo "The screen will be turned off, move the mouse or press a key to turn it back on."
fi

# grab current spot and volume, then gently fade and pause
c=$(exaile --current-position)
v=$(pactl list | grep Volume | cut -d ":" -f 3 | cut -d "%" -f 1 |\
 sed -n '1p' | sed -e 's/^[ \t]*//' -e 's/[ \t]*$//')
for((i=$v;i>=0;i--)) do
    sleep 1s
    pactl set-sink-volume 0 ${i}%
done
exaile --play-pause

# return volume to former setting
pactl set-sink-volume 0 ${v}%
echo "The current track was faded out beginning at $c."

Now I can go to sleep in style, whilst listening to the Internet's longest history podcasts. (in parts).

Friday, 23 May 2014

Fail to Plan --- Plan to Fail

'Fail to Plan -- Plan to Fail' is an itinerary planner to help you organise days when you have lots of little chores, or, it you want to see how long a process you have planned actually takes (Pi*thumb^procrastination).  It's quite useful for getting an idea of where your day goes.

The 'Help' drop down on the top far right has a tutorial to help you get started.

Some things to know about this little tool:

1) I didn't add a timer because I didn't want a nagplication.  Also, if you're in the garden, you won't hear your computer beep.

2) The 'now' button recalculates your day's plan to start 'now', if things take longer than planned.   I also find it useful to move a task to the end that I decide to do later.

3) Visually it's a bit of a jumble initially, but once you have practice (and worked through the tutorial)  it's actually not as bad as it looks.  I will try to fix this in later iterations.

4) The curry recipe is quite good -- it only looks that huge because I broke the process down into individual steps, it's actually not that difficult to cook ;-)

5)  I wrote this in raw javascript because it's hosted on Blogger for now, so, the drop down menus have been hand coded (I know... :) and... look accordingly.   I will try to move it to a saner space, where I have handy tools like JQuery available.

6) I'm no javascript/html champion, this started out as a little hack for fun and grew into something bigger than I estimated.  Advice/bug reports/collaborators are very welcome, mail me please. I have some more plans for this toy, for example, I'd like to be able to insert groups of tasks -- say, if you want to do the laundry, that consists of the tasks washing, hanging, drying & folding --- being able to drop those tasks in as a group would save a lot of typing.

7) Cookies in HTML 4 are limited in size, so don't go crazy with too many entries/files :-D

Enjoy!

Saturday, 16 November 2013

--invoke-diff3-cmd branch ready for review




Finally the feature --invoke-diff3-cmd for Subversion is ready -- 23 files in 8 directories, 86 code snippets for a total 782 lines of code, 53 log message components plus a BRANCH-README file.

Sunday, 10 November 2013

Making sure I stay lucky



After nearly losing all my work yesterday, I've made this little script to run in the Emacs compile buffer before the make command.  This runs svn diff every time I compile and puts the result into a separate directory.

#!/bin/sh
CURRENT_DIR=`pwd` 
DATE_MARKER=$(date +%Y%m%d%T) 
SECURITY_PATCH_DIR=/home/g/security_patches/ 
WHAT=`echo "${CURRENT_DIR##*/}"`
EXT=.patch
SECURITY_DIFF=${SECURITY_PATCH_DIR}${WHAT}${DATE_MARKER}${EXT}
SVN=/home/g/InstalledSVN1.9/subversion
$SVN diff > $SECURITY_DIFF 

Sunday, 27 October 2013

New invoke-diff-cmd feature: --svn-cfg-file

Wrote this feature yesterday, all in one go.

Had the idea whilst pondering what to do with the --invoke-diff3-cmd interactive user dialogue.

Maybe the new agate necklace magic really works?  Heh.

Thursday, 24 October 2013

How to use svn diff to create a list of visitable files with line numbers in the Emacs compile buffer


Here is how to use the svn diff output within the emacs compile buffer to generate a handy list of files with line numbers that you can click on to visit every bit of code you've changed:

M-x compile

svn diff |\
perl -ne '/Index: (.*)$/ && ($name = $1);\
/^@@.*\+(\d+),/ && print "./$name:$1:diff\n";'  


Tuesday, 22 October 2013

The svn diff Project: First part done, review passed!

The --invoke-diff-cmd part of the svn diff project has been completed (bar one possible improvement).

The BRANCH-README file explains it all.

Of course, there has to be a fitting video for this post:



Now for the second part --- the invoke-diff3-cmd section!