Strategy and Tactics
I often hear the two words in the same sentence, but never actually took the time to find out what the two mean.
From the general usage you could say that tactics is something short term and based on particular cases and actions with them.
On the other hand a strategy faces types of problems and the general guidelines how to deal with them.
I found a very nice definition of the two at: http://www.molossia.org/milacademy/strategy.html
Military strategy and tactics are essential to the conduct of warfare. Broadly stated, strategy is the planning, coordination, and general direction of military operations to meet overall political and military objectives. Tactics implement strategy by short-term decisions on the movement of troops and employment of weapons on the field of battle.
The great military theorist Carl von Clausewitz put it another way: “Tactics is the art of using troops in battle; strategy is the art of using battles to win the war.” Strategy and tactics, however, have been viewed differently in almost every era of history. The change in the meaning of these terms over time has been basically one of scope as the nature of war and society has changed and as technology has changed. Strategy, for example, literally means “the art of the general” (from the Greek strategos) and originally signified the purely military planning of a campaign. Thus until the 17th and 18th centuries strategy included to varying degrees such problems as fortification, maneuver, and supply. In the 19th and 20th centuries, however, with the rise of mass ideologies, vast conscript armies, global alliances, and rapid technological change, military strategy became difficult to distinguish from national policy or “grand strategy,” that is, the proper planning and utilization of the entire resources of a society–military, technological, economic, and political. The change in the scope and meaning of tactics over time has been largely due to enormous changes in technology. Tactics have always been difficult–and have become increasingly difficult–to distinguish in reality from strategy because the two are so interdependent. (Indeed, in the 20th century, tactics have been termed operational strategy.) Strategy is limited by what tactics are possible; given the size, training, and morale of forces, type and number of weapons available, terrain, weather, and quality and location of enemy forces, the tactics to be used are dependent on strategic considerations.
An application of this to a business environment can be seen at: http://www.thinkingmanagers.com/management/strategy-tactics.php
KDE Shutdown, Logout, Restart
Inspired by this post.
It is interesting how simple specialised devices cope with their functions much better than a all-in-one PC. Sometimes, I wish to fall asleep with some music on. But how annoying it becomes, when you have to get up in the middle of the night to turn off your PC, which has been playing something all this time. Digital radios have mastered the trick decades ago. Of course there is a way to make a PC do it.
Running linux, I thought that it should be fairly straightforward to shut it down after say half an hour automatically.
Something like shutdown (below) will kill the X. The KDE then will just exit without saving the session. Next time you log on, you will see some session from a distant past. If you do this often, it gets really annoying. Also this requires superuser privileges on some distributions.
/sbin/shutdown -h now "Power button pressed" # or halt
Then how to make KDE quit without calling any dialogs (I am sound asleep by this time and I can’t afford to wake up and press ‘OK’)? There is a way.
dcop ksmserver ksmserver logout 0 2 2
The three numbers are explained below (see source):
First parameter: confirm
Obey the user’s confirmation setting: -1
Don’t confirm, shutdown without asking: 0
Always confirm, ask even if the user turned it off: 1
Second parameter: type
Select previous action or the default if it’s the first time: -1
Only log out: 0
Log out and reboot the machine: 1
Log out and halt the machine: 2
Third parameter: mode
Select previous mode or the default if it’s the first time: -1
Schedule a shutdown (halt or reboot) for the time all active sessions have
exited: 0
Shut down, if no sessions are active. Otherwise do nothing: 1
Force shutdown. Kill any possibly active sessions: 2
Pop up a dialog asking the user what to do if sessions are still active: 3
MP3 Tags to Unicode
If you have some old mp3 files, where the tag information is not in english and years ago you have used an encoding your current music player does not understand? The answer is easy - covert to Unicode. First I tried doing it manually, and it works if you have less than 10 tracks. Let’s just say I had more…
I have tried several approaches (all on linux): id3iconv-0.2.1, EasyTag, etc.
It is possible I was missing something, but I could accomplish my task and change the encoding. id3iconv-0.2.1 just removed foreign characters, so that no recovery would have helped (good I had a backup).
And then I found a set of python tools: python-mutagen-1.11.
It was enough to one script (below) and all my tracks had Unicode tags:
mid3iconv -e CP1251 *.mp3
You have to specify the incoming encoding, mine was CP1251 (Windows - Cyrillic).
After trying lots of these tools, I was kind of skeptic about this one as well. If you run it in verbose dry run mode, it will say what it would normally just do. This way you can get full confidence that you specified the initial encoding correctly and that the tool will work at all without changing anything.
mid3iconv -e CP1251 -p -d *.mp3
Gnuplot PDF Terminal
When producing plots of data by gnuplot one can specify many different output formats:
set terminal png set output 'plot.png' plot ...
The output file ‘plot.png’ will contain the image. By replacing ‘png’ by some other format, like ‘gif’ one can change the output format.
Often when producing PDF documents with LaTeX one would like to use images in PDF format for better quality. However due to licensing problems usual installations of gnuplot don’t support PDF output format. One could recompile gnuplot and include the feature manually. But this seems like a lot of hassle especially if you want to produce just one image.
However there is a work around:
set terminal postscript enhanced color set output '| ps2pdf - plot.pdf' plot ......
Here we are directing the PS stream into ps2pdf (the ‘-’ sign in the command states to read the PS file from stdin).
Sometimes the PDF files produced have an extra white border, but there are ways to fight with it. I see this as an easy solution to a small problem. Of course if you want many top quality PDF images, you should recompile gnuplot with PDF support.
Inspired by this post .
JUnit Testing Under Maven2
JUnit testing provides an easy to use flexible framework to write unit tests for Java code. Maven incorporates this functionality as part of it’s software life cycle. JUnit plug-in under maven2 is called Surefire.
> mvn test
Putting the above on the command line will compile the test code and run it.This is really convenient when testing someones code or if you are willing to test everything.
Single Test
However if you are the developer and are working on one specific feature tested in one test case you can run:
> mvn -Dtest=MyTestCase test
This will compile all the tests, but will run only the specified one.
Multiple Selected Tests
Sometimes you want to run just a selected set of tests. For example 2 out of 50:
> mvn -Dtest=MyTestCase,MyOtherTestCase test
This will compile all the tests, but will run only the specified two tests.
Wild Cards
You can use ‘*’ in the anywhere in the name of the class. However be careful if you have inner classes as for example My* will match MyTestCase and MyTestCase$1, which is the inner class you have used in the code, but it is not really a test and therefore the build will fail. Link to Documentation .
Cleaning
However what happens if you have discovered a bug or for some other reason edited the functional code (the one you are testing)? You will be surprised, but maven will not pick it up and will continue the old version of the compiled code. To make it compile the entire sub-project you should first clean it.
> mvn clean -Dtest=MyTestCase test
This will clean your target/ directory and therefore get rid of the old compilations. Then it will recompile the whole project along with the testing code, but still run only MyTestCase.
Abstract Tests
Before Maven 2.0.8 test cases starting with a word Abstract were not considered to be real tests. Abstract Tests are usually used if you have some testing code, which is common for 2 test cases. Then you would write an Abstract*Test class and extend it by the 2 test cases. The inheritance allows you to have the code in one place, but Abstract tests are not really test cases, so they should not be run. This changed with the new version. Excludes property contains the patterns of names, which should be excluded from testing. With its help you can remove the Abstract tests again if your project relies on it.In your pom.xml you should add:
<build>
<plugins>
<!-- Added test excludes for Abstract -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/Abstract*</exclude>
</excludes>
</configuration>
</plugin>
<!-- ....... other configuration ....... -->
</plugins>
</build>
Land of Narcissi, Tranquility and Sea
As it often happens in England the weather had decided to be indecisive right from the morning: some clouds, some wind and some sun. Us, humans were left with our theories whether it would rain or it would shine. BBC Weather had no real idea on this matter as they have changed the forecast throughout the previous week from shiny sunlight to gloomy raining and back.
This Sunday we have planned to visit the Isle of Wight, in particular Alum Bay on its west coast. Not too ambitious - we wanted to enjoy ourselves, not record a new personal high score on the amount of places visited in a day.
Alum Bay is famous because it was involved into an experiment of Guglielmo Marconi. It just happened to be the place, from where he transmitted a first radio signal to an hotel some away 20 miles.
This of course had a huge impact on the world as well all use wireless communications all the time now. However alone it is not a good enough reason to get a ferry and get a 2 hour bus ride. If you were to read about the history of wireless networks and come across the experiment of Guglielmo Marconi you would inevitably see a photograph of Alum Bay - a tall steep cliff meeting the sea. For people like me that picture is a good enough reason to travel.
The island itself is very beautiful and green. As a matter of fact green is the dominating colour on the island, no wonder that buses and other objects on the road would go green where possible. And on the thick green carpet of grass one would often spot hares running wild and free. Although nice, hares are not as surprising as the selection of flowers on this island. Every pitch of grass however small would contain at least a few yellow narcissus (lent lily). They blossom just at this time, so all the numerous pathes of grass on the island would have a yellow highlight to them. Sometimes there would be more narcissi than grass itself.
But the hares, the pretty houses with curved rooftops, narcissi and other wonders of this island matter only before one sets eye on the Alum Bay and the sea. Once you step on the cliff or come down to the beach you enter a completely different world - time stops, sounds are different, light is different. Everything is not the same. You feel that the thoughts and troubles you had before you entered this world are completely irrelevant and you somehow forget about them really quickly. One thing you can see and comprehend is the sea, the wind and the sun. Luckily we did not have to comprehend the rain as well - it was nice and sunny during our visit to the foreign world of Alum Bay.
I don’t know how long we have stayed there, but the day just passed by without us noticing, I guess time really does run different there. But it is a small price to pay for the view of the freedom and power of the sea and the magnificence of the cliff.
Maven Variables in Java context
Maven is a very convenient and powerful tool for managing large projects, their builds, testing, deployment, versions, etc. It is so great, that sometimes it would be nice to have access to Maven variables from Java or other source language.
For example when writing a test case with JUnit I would like to use some data in an XML file. The file is distributed with the project as part of testing routines.
However getting hold of it’s location in Java is not easy.
- One could use the current working directory and assume that it is always the project root (where the pom.xml file is located), but that is really really not flexible although really simple when there is just one project to build.
- One could try fiddling with the Class Loader and possibly find the location of a specific class and then from that deduce the location of the test file. Very tedious and somewhat not elegant.
- One could try getting hold of one of Mavens variable values. For example ${basedir} contains the project root. This would be flexible and quite general as the code will be run through Maven all the time anyway.
So let’s look at option 3 more closely. Maven variables can be used in the maven scripts. If you are writing Maven plugins there are ways of getting these values. But if you are running a separate application, which is not part of Maven - there is no easy solution.
One way is to use the filtering capabilities of Maven.
For example, one could have a myproject.properties file somewhere in the project, where you would specify some configuration options.
// src/test/resources/myproject.properties
// .............
project.root=${basedir}
// .............
Now we have to let Maven know that it should help us and nicely provide the values we are after.
<!-- pom.xml -->
<project>
<build>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
</build>
</project>
The testResources directive with the filtering turned on will ask Maven to go through all files in src/test/resources and replace the Maven variables within then with the values. After it has done that it will put the files on the classpath of your application so you can get hold of them really easy.If one were to replace testResources with resources it would affect the application execution rather than just the testing.In Java all you have to do is load the properties file and there you go:
java.util.Properties props = new java.util.Properties();
// Get hold of the path to the properties file
// (Maven will make sure it's on the class path)
java.net.URL url = Config.class.getClassLoader().getResource("sql.properties");
// Load the file
props.load(url.openStream());
// Accessing values
porps.getProperty( "project.root" ); // This will return the value of the ${basedir}
That is it, we are done. Now that we have the project root, it is trivial to reference any file within the source tree with no dependence on the class layout or the current directory.
Valencia
Getting there
Valencia is on the middle of east coast of Spain. There are plenty of cheap airlines flying to Valencia from the UK. That is one of the reasons, why we chose the location. The choice was between Gerona (quite close to Barcelona) and Valencia. Most people would probably go for Gerona - Barcelona is a very beautiful large city with loads of places a tourist might visit. Personally I have not been there, but I have heard quite excited opinions about it from people I am willing to trust.
Because of a hunch, sheer chance or some other reason (no one can remember now) we have chosen Valencia as our destination. I think we were lucky. The destination was decided long before we actually started buying the tickets and booking the hotels. Actually, it was really close for us to stay at home and compete in pretending that we enjoy the January Southampton weather for that weekend. That’s why we were lucky - we managed to get back to the thought of going to Valencia before it was too late. I am so glad we did - Valencia is one of the most beautiful cities I have ever seen throughout my travels.
We landed in Valencia on a nice Airbus from Gatwick supplied by EasyJet - despite being a low price airline, they have done a good job (didn’t really like budget airlines before this). During the 3 days that we have spent in the wonderful city of the sun we stayed at a wonderful hotel Nova Victoria. It claims to be a 4 star hotel, I am no expert, but it was nice, clean and quiet - those are all the things I need in a hotel.
Valencian transport
The page Valencia @ Wikipedia will tell you that the population of Valencia is just under a million people and that it is the capital of an autonomous region with the same name. For visitors this should say that there is a separate language in Valencia, different from Castilian (main Spanish dialect).
Despite its size Valencia has a well developed metro system with 4 lines underground and 2 more tram lines connecting directly with the underground. The nicest thing is that 2 metro lines go up to the airport, which makes getting to the city really easy and quick. Going around the city in a metro is not really convenient as they follow the main streams of passengers, who live in Valencia or its suburbs and want to get to the center. We ony took the metro to the airport and the beach.
My companions might disagree with me, but I find that if one wishes to visit the city center and have a look around the place in general it is quite enough to use ones own feet. Our hotel was right in the center of the city, so we could reach any point withing 30 minutes on foot. And trust me, if you are in Valencia, you don’t want to miss out anything that you might meet on your way. This city is perfect to wander around and admire - taking random turns always proves to reveal something new and magnificent.
Experience of the city
Valencia is not spoiled by constant attention from tourists. When we wandered around we found many places, where people spoke Spanish only. Which made us learn some of it and brought a smile to everyone around us while we were at it. They were not mean about it though - usually the people of Valencia were genuinely trying to help us express ourselves. And would smile at our attempts - guess it was funny. Mostly we could understand each other with some time spent on rearranging the cultural differences.
It is quite interesting to see what people can do given this little information about our wishes. Usually it was enough to express an approximate direction or area of what you would like (for example a paella - common dish in valencia) and they would not bother you about all the fine detail they would usually ask people - would just go away and do something sensible.
Although we have seen only the center of the city, I am quite positive that this is the most beautiful city I have ever seen. My companions probably had something to do with this impression - we had a hell of a good time, but even so - the city is magnificent.
The combination of old city’s streets and a modern city’s drive is incredible. Yes, there is a commercial center and all the high and ugly buildings are there as well, but they are well overpowered by the amount of old and beautiful architecture.
The largest impression, at least for me, was sun and 20C in January plus a magnificent idea of the city to create a park in a former riverbed. The green snake of trees, bushes, benches, flowers and fountains splits the city into 2. The parts are connected with bridges, both new and old, which makes it even more special.
This makes it incredible easy to go through the city just by following the riverbed - you are in the middle of town, yet you can walk to miles between tress (given that you go along the path of the river). Fountains in Valencia are a completely special story of their own.
The people of Valencia use the riverbed park as a place for jogging and cycling, so it is always full of people, even at night. Which is great and makes you feel safe there even at midnight - nights are really warm, so everyone wants to go outside and either jog or just walk, cycle or enjoy the moonlight. And this time everyone includes you.
This was my first visit to Spain and I doubt that all cities in the country are like that, but even if so, it is definitely worth visiting Valencia - no doubts about it.
Food
One of my companions was very persuasive about trying out several Spanish dishes:
Paella - a dish of rice and meat usually served at lunch time (about 3pm local time). Comes in a variety of ingredients and tastes. We had several attempts to get one - the most successful was in a place so far away from the tourist world, that we had serious trouble communicating, but we got a paella and some fish out of them, both superb.
Horchata - a white colour drink made from almond nuts, great in hot weather.
Churos - stripes of pastry deep fried and sprinkled with sugar. Usually served with thick version of hot chocolate. Really depends on the place, where you get them. But if it is the right one, they are delicious.
Bocadillo- sandwiches with the strangest of ingredients, we had a tortilla (omelet) one - delicious. The guy serving it looked so hot that the feminine side of our company could not stop talking about him for the rest of the vacation.
Sea in January
The beach in Valencia is a classical sandy Mediterranean beach with low waves and plenty of wind from land. Because it was January there were not many people there, so searching for food proved to be a problem. Took us some time to find a place serving food. It was a kebab place, so we were quite reluctant to go there first - a kebab is always a kebab, but we could not find anything better, so had to settle for that.
While we were searching for a place to eat we came across a school festival. Kids and their teachers were dressed up in costumes according to a theme special to each class going through the streets with music and dances.
The sea itself was really peaceful and somehow brought the sensation of the whole city together - peaceful and calm, yet understanding that time goes on. Sometimes rushing, sometimes slowing down, but never standing. I know that I will enjoy coming back to Valencia.
Date and Shell Find in Ruby
I was writing a small script to do backups on my local machine. Before this I was doing backups manually. To make this easier I came up with a naming scheme, with a dream to automate this.
Today the dream came true.
The scheme is really simple: Distinct_name_for_a_resource-DATE[-comment].(tar.gz|7z)
DATE is of format YYYYMMDDHHSS - no separators.
Sorting is really easy.
That’s the background. The tool finds if there have been any modified files in the directory being backed up and backs up the whole thing if so (no incremental backups). I wanted to use find as the tool for searching. Imagine my surprise when I could not find the key to give find a date for comparison.
There are keys of type -mtime and -mmin, which are relative to current time and specify an offset in days and minutes respectively. But I wanted a date.
It is possible of course to use -newer flag, which takes a filename and finds all, which are newer than that. It is possible to create a file with a specific date with
`touch -d DATE filename` output = `find PATH -newer filename` if (output.size > 0) # you found something end
However, there is a better solution. It is not really convinient when using from command line - it involves some computation. In this particular case, I use find inside a script, therefore it is perfectly appropriate.Reinventing the wheel is not an option - takes too much time to write and run. It would be relatively easy to write a ruby-based traversal with this single test. If not for the fact that I love to backup large quantities of files and really hate waiting. So let’s use find - it is implemented in C with lots of optimisations - should work faster than some ruby code comparing ruby date objects. It is quite easy:
tnow = Time.now
last_archive =~ /(#{prefix}-)([0-9]{12})([-.].*)/
puts "Found last backup: #{last_archive}"
time = get_time_from_string($2) # converts the 12 char string to Time obj
# Convert to minutes
minutes = ((tnow - time) / 60.0).floor
# Search
out = `find #{path} -mmin -#{minutes}`
archive_it = out.size > 0
puts "Files were modified" if archive_it
And that is it, no rocket science. Note, that one needs to use ‘-#{minutes}’ to tell find to use <= operator rather than just == without the ‘-’.Why not use DateTime if we need both the date and the time? Apparently the performance of DateTime is much worse than Time, and they have the same functionality.
PHP mysqli Prepared Statements
Recently I had a close look at the mysqli prepared statements. Why use prepared statements in php if you can easily concatenate a statement string and then execute it?
There are several reasons:
- Performance is an interesting issue, for example an article http://dealnews.com/developers/php-mysql.html states that prepared statements make a difference.
- From the programming point of view though one gets character escaping written by someone who went through the trouble to do it properly and it is guaranteed to hapen each time.
- From the style perspective - most your SQL statements are created once and are generally in one place, therefore it is easy to make changes if your schema has been changed.
Let’s start from the beggining. mysqli is an extended version of the well known mysql library. Why is that a good thing? Well most functions are called the same and therefore porting from one to the other will not be as difficult - one does not need to change the approach, just make sure that everything works and the names of functions have a ‘mysqli’ instead of ‘mysql’.