How to create ISO Date String

It is a more and more common task that we need to have a date or maybe date with time as String.

There are two reasonable ways to do this:
* We may want the date formatted in the users Locale, whatever that is.
* We want to use a generic date format, that is for a broader audience or for usage in data exchange formats, log files etc.

The first issue is interesting, because it is not always trivial to teach the software to get the right locale and to use it properly… The mechanisms are there and they are often used correctly, but more often this is just working fine for the locale that the software developers where asked to support.

So now the question is, how do we get the ISO-date of today in different environments.

Linux/Unix-Shell (bash, tcsh, …)

date "+%F"

TeX/LaTeX


\def\dayiso{\ifcase\day \or
01\or 02\or 03\or 04\or 05\or 06\or 07\or 08\or 09\or 10\or% 1..10
11\or 12\or 13\or 14\or 15\or 16\or 17\or 18\or 19\or 20\or% 11..20
21\or 22\or 23\or 24\or 25\or 26\or 27\or 28\or 29\or 30\or% 21..30
31\fi}
\def\monthiso{\ifcase\month \or
01\or 02\or 03\or 04\or 05\or 06\or 07\or 08\or 09\or 10\or 11\or 12\fi}
\def\dateiso{\def\today{\number\year-\monthiso-\dayiso}}
\def\todayiso{\number\year-\monthiso-\dayiso}

This can go into a file isodate.sty which can then be included by \include or \input Then using \todayiso in your TeX document will use the current date. To be more precise, it is the date when TeX or LaTeX is called to process the file. This is what I use for my paper letters.

LaTeX

(From Fritz Zaucker, see his comment below):

\usepackage{isodate} % load package
\isodate % switch to ISO format
\today % print date according to current format

Oracle


SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD') FROM DUAL;

On Oracle Docs this function is documented.
It can be chosen as a default using ALTER SESSION for the whole session. Or in SQL-developer it can be configured. Then it is ok to just call

SELECT SYSDATE FROM DUAL;

Btw. Oracle allows to add numbers to dates. These are days. Use fractions of a day to add hours or minutes.

PostreSQL

(From Fritz Zaucker, see his comment):

select current_date;
—> 2016-01-08


select now();
—> 2016-01-08 14:37:55.701079+01

Emacs

In Emacs I like to have the current Date immediately:

(defun insert-current-date ()
"inserts the current date"
(interactive)
(insert
(let ((x (current-time-string)))
(concat (substring x 20 24)
"-"
(cdr (assoc (substring x 4 7)
cmode-month-alist))
"-"
(let ((y (substring x 8 9)))
(if (string= y " ") "0" y))
(substring x 9 10)))))
(global-set-key [S-f5] 'insert-current-date)

Pressing Shift-F5 will put the current date into the cursor position, mostly as if it had been typed.

Emacs (better Variant)

(From Thomas, see his comment below):

(defun insert-current-date ()
"Insert current date."
(interactive)
(insert (format-time-string "%Y-%m-%d")))

Perl

In the Perl programming language we can use a command line call

perl -e 'use POSIX qw/strftime/;print strftime("%F", localtime()), "\n"'

or to use it in larger programms

use POSIX qw/strftime/;
my $isodate_of_today = strftime("%F", localtime());

I am not sure, if this works on MS-Windows as well, but Linux-, Unix- and MacOS-X-users should see this working.

If someone has tried it on Windows, I will be interested to hear about it…
Maybe I will try it out myself…

Perl 5 (second suggestion)

(From Fritz Zaucker, see his comment below):

perl -e 'use DateTime; use 5.10.0; say DateTime->now->strftime(„%F“);‘

Perl 6

(From Fritz Zaucker, see his comment below):

say Date.today;

or

Date.today.say;

Ruby

This is even more elegant than Perl:

ruby -e 'puts Time.new.strftime("%F")'

will do it on the command line.
Or if you like to use it in your Ruby program, just use

d = Time.new
s = d.strftime("%F")

Btw. like in Oracle SQL it is possible add numbers to this. In case of Ruby, you are adding seconds.

It is slightly confusing that Ruby has two different types, Date and Time. Not quite as confusing as Java, but still…
Time is ok for this purpose.

C on Linux / Posix / Unix


#include
#include
#include

main(int argc, char **argv) {

char s[12];
time_t seconds_since_1970 = time(NULL);
struct tm local;
struct tm gmt;
localtime_r(&seconds_since_1970, &local);
gmtime_r(&seconds_since_1970, &gmt);
size_t l1 = strftime(s, 11, "%Y-%m-%d", &local);
printf("local:\t%s\n", s);
size_t l2 = strftime(s, 11, "%Y-%m-%d", &gmt);
printf("gmt:\t%s\n", s);
exit(0);
}

This speeks for itself..
But if you like to know: time() gets the seconds since 1970 as some kind of integer.
localtime_r or gmtime_r convert it into a structur, that has seconds, minutes etc as separate fields.
stftime formats it. Depending on your C it is also possible to use %F.

Scala


import java.util.Date
import java.text.SimpleDateFormat
...
val s : String = new SimpleDateFormat("YYYY-MM-dd").format(new Date())

This uses the ugly Java-7-libraries. We want to go to Java 8 or use Joda time and a wrapper for Scala.

Java 7


import java.util.Date
import java.text.SimpleDateFormat

...
String s = new SimpleDateFormat("YYYY-MM-dd").format(new Date());

Please observe that SimpleDateFormat is not thread safe. So do one of the following:
* initialize it each time with new
* make sure you run only single threaded, forever
* use EJB and have the format as instance variable in a stateless session bean
* protect it with synchronized
* protect it with locks
* make it a thread local variable

In Java 8 or Java 7 with Joda time this is better. And the toString()-method should have ISO8601 as default, but off course including the time part.

Summary

This is quite easy to achieve in many environments.
I could provide more, but maybe I leave this to you in the comments section.
What could be interesting:
* better ways for the ones that I have provided
* other databases
* other editors (vim, sublime, eclipse, idea,…)
* Office packages (Libreoffice and MS-Office)
* C#
* F#
* Clojure
* C on MS-Windows
* Perl and Ruby on MS-Windows
* Java 8
* Scala using better libraries than the Java-7-library for this
* Java using better libraries than the Java-7-library for this
* C++
* PHP
* Python
* Cobol
* JavaScript
* …
If you provide a reasonable solution I will make it part of the article with a reference…
See also Date Formats

Share Button

2016 — Happy New Year

(C) see link

Happy New Year! — Šťastný nový rok! — Laimīgu Jauno gadu! — Godt Nyttår! — Среќна нова година! — Bonne année! — Καλή Χρονια! — Sala we ya nû pîroz be! — Laimingų naujųjų metų! — Nav varsh ki subhkamna! — Een gelukkig nieuwjaar! — Frohes neues Jahr! — Ath bhliain faoi mhaise! — Selamat tahun baru! — Честита нова година! — สวัสดีปีใหม่ — Sretna nova godina! — Cung chúc tân xuân! — 新年好 — عام سعيد — Yeni yılınız kutlu olsun! — Un an nou fericit! — Hääd uut aastat! — السنة الجديدة المبتهجة — Щасливого нового року! — Shnorhavor nor tari! — Próspero ano novo! — Весёлого нового года! — Subho nababarsho! — Feliĉan novan jaron! — Felice Anno Nuovo! — 새해 복 많이 받으세요 — Onnellista uutta vuotta! — Gleðilegt nýtt ár! — Boldog új évet! — Feliz año nuevo! — Lokkich nijjier! — С новым годом! — Sugeng warsa enggal! — Gott nytt år! — Laimīgu jauno gadu! — うれしい新しい年 — Feliz ano novo! — Bun di bun an! — Срећна нова година! — Naya barsa ko hardik shuvakamana! — FELIX SIT ANNUS NOVUS! — سال نو مبارک — Srechno novo leto! — Szczęśliwego nowego roku! — Gelukkig nieuwjaar! — Godt nytår! — ¡Próspero año nuevo! — Akemashite omedetô! — Gott nýggjár!

I like to have a program again that created the text above:
#!/usr/bin/ruby
# encoding: utf-8
# coding: utf-8
texts = [ 'Akemashite omedetô!', 'Ath bhliain faoi mhaise!', 'Boldog új évet!', 'Bonne année!', 'Bun di bun an!', 'Cung chúc tân xuân!', 'Een gelukkig nieuwjaar!', 'FELIX SIT ANNUS NOVUS!', 'Felice Anno Nuovo!', 'Feliz ano novo!', 'Feliz año nuevo!', 'Feliĉan novan jaron!', 'Frohes neues Jahr!', 'Gelukkig nieuwjaar!', 'Gleðilegt nýtt ár!', 'Godt Nyttår!', 'Godt nytår!', 'Gott nytt år!', 'Gott nýggjár!', 'Happy New Year!', 'Hääd uut aastat!', 'Laimingų naujųjų metų!', 'Laimīgu Jauno gadu!', 'Laimīgu jauno gadu!', 'Lokkich nijjier!', 'Nav varsh ki subhkamna!', 'Naya barsa ko hardik shuvakamana!', 'Onnellista uutta vuotta!', 'Próspero ano novo!', 'Sala we ya nû pîroz be!', 'Selamat tahun baru!', 'Shnorhavor nor tari!', 'Srechno novo leto!', 'Sretna nova godina!', 'Subho nababarsho!', 'Sugeng warsa enggal!', 'Szczęśliwego nowego roku!', 'Un an nou fericit!', 'Yeni yılınız kutlu olsun!', '¡Próspero año nuevo!', 'Šťastný nový rok!', 'Καλή Χρονια!', 'Весёлого нового года!', 'С новым годом!', 'Срећна нова година!', 'Среќна нова година!', 'Честита нова година!', 'Щасливого нового року!', 'السنة الجديدة المبتهجة', 'سال نو مبارک', 'عام سعيد', 'สวัสดีปีใหม่', 'うれしい新しい年', '新年好', '새해 복 많이 받으세요' ]
texts.shuffle!()
str = texts.join(' — ')
puts(str)

Share Button

Scala Exchange 2015

It was possible to arrange a visit of Scala Exchange 2015 in London, short #ScalaX.

I visited the following events:

Christmas 2015

weihnachtsbaum-20151222_170639-scaled

Crăciun fericit − Natale hilare − ميلاد مجيد − God Jul! − Vesele bozicne praznike − Buon Natale − Mutlu Noeller − Честита Коледа − Glædelig Jul − Vesele Vianoce − Bon nadal − Merry Christmas − Срећан Божић − Gleðileg jól − Su Šventom Kalėdom − Bella Festas daz Nadal − Kellemes Karácsonyi Ünnepeket − С Рождеством − Gledhilig jól − Sretan božić − 즐거운 성탄, 성탄 축하 − Joyeux Noël − З Рiздвом Христовим − Fröhliche Weihnachten − Selamat Hari Natal − 圣诞快乐 − Häid jõule − καλά Χριστούγεννα − Feliĉan Kristnaskon − Priecîgus Ziemassvçtkus − クリスマスおめでとう ; メリークリスマス − Hyvää Joulua − Zalig Kerstfeest − Feliz Navidad − Prettige Kerstdagen − क्रिसमस मंगलमय हो − Gëzuar Krishtlindjet − Wesołych Świąt Bożego Narodzenia − Feliz Natal − Nollaig Shona Dhuit! − کريسمس مبارک − God Jul − Veselé Vánoce
Since this is an IT Blog, I let my program wish you whatever you will find below for me. IT guys should be lazy. 🙂
For these kind of tasks I still like Perl…

#!/usr/bin/perl
use utf8;
binmode STDOUT, ':utf8';
my $SEP = ' − ';
my @texts = ( 'Bella Festas daz Nadal', 'Bon nadal', 'Buon Natale', 'Crăciun fericit',
   'Feliz Natal', 'Feliz Navidad', 'Feliĉan Kristnaskon', 'Fröhliche Weihnachten',
   'Gledhilig jól', 'Gleðileg jól', 'Glædelig Jul', 'God Jul!', 'God Jul', 'Gëzuar Krishtlindjet',
   'Hyvää Joulua', 'Häid jõule', 'Joyeux Noël', 'Kellemes Karácsonyi Ünnepeket',
   'Merry Christmas', 'Mutlu Noeller', 'Natale hilare', 'Nollaig Shona Dhuit!',
   'Prettige Kerstdagen', 'Priecîgus Ziemassvçtkus', 'Selamat Hari Natal', 'Sretan božić',
   'Su Šventom Kalėdom', 'Vesele Vianoce', 'Vesele bozicne praznike', 'Veselé Vánoce',
   'Wesołych Świąt Bożego Narodzenia', 'Zalig Kerstfeest', 'καλά Χριστούγεννα',
   'З Рiздвом Христовим', 'С Рождеством', 'Срећан Божић', 'Честита Коледа',
   'ميلاد مجيد', 'کريسمس مبارک', 'क्रिसमस मंगलमय हो',
'クリスマスおめでとう ; メリークリスマス', '圣诞快乐',
'즐거운 성탄, 성탄 축하' );
my $n = @texts;
my $idx = rand($n);
for ($i = 0; $i < $n; $i++) {
    $idx = ($idx + 17) % $n;
    if ($i > 0) {
        print $SEP;
    }
    print $texts[$idx];
}
print "\n";

Share Button

What do +, – and * with Integer do?

When using integers in C, Java or Scala, we often use what is called int.

It is presented to us as the default.

And it is extremely fast.

Ruby uses by default arbitrary length integers.

But what do +, – and * mean?

We can rebuild them, in Ruby, kind of artificially restrict the integers to what we have in other programming langauges as int:


MODULUS = 0x100000000;
LIMIT   =  0x80000000;

def normalize(x)
  r = x % MODULUS;
  if (r < -LIMIT) then     return r + MODULUS;   elsif (r >= LIMIT) 
    return r - MODULUS;
  else
    return r;
  end
end

def intPlus(x, y)
  normalize(x+y);
end

def intMinus(x, y)
  normalize(x-y);
end

def intTimes(x, y)
  normalize(x*y);
end

x = 0x7fffffff;
y = intPlus(x, x);
z = intPlus(x, x);
puts("x=#{x} y=#{y} z=#{z}");

What is the outcome?

Exactly what you get when doing 32-Bit-Ints in C, Java, Scala or C#:

x=2147483647 y=-2 z=-2

int is always calculated modulo a power of two, usually 2^{32}. That is the
x % MODULUS in normalize(). The Rest of the function is just for normalizing the result to the range -2^{31} \ldots 2^{31}-1.

So we silently get this kind of result when an overflow situation occurs, without any notice.
The overflow is not trivial to discover, but it can be done.
For addition I have described how to do it.

See also Overflow of Integer Types, an earlier post about these issues…

I gave a talk that included this content adapted for Scala at Scala Exchange 2015.

Share Button

Devoxx 2015

This year I have had the pleasure to visit the Devoxx-Conference in Antwerp in Belgium.

I have visited the following talks:

There is a lot to write about this and I will get back to specific interesting topics in the future…

My previous visits in 2012, 2013 (part 1), 2013 (part 2), and 2014 have their own blog articles.

Share Button

Creating Unique Numbers

Many software systems rely on some kind of unique numbers. Uniqueness is always a question in what universe this uniqueness is required. We do see the different kinds of universes in the case of the IP-addresses. In theory they are world wide unique. In practice we have mechanisms in place like NAT, that use certain dedicated IP-ranges for an intranet and map them to publicly available addresses for internet traffic outside the intranet. So we already have two kinds of universes… This is typical.

A common case are database IDs, that are often used as primary keys in databases. I do challenge this by the question, if there is a natural key already available in the data, which might make this db internal id unnecessary, but more often than not DB tables do have these ID columns as primary keys. They have to be unique within the DB table. Which can mean across several servers, because somewhat distributed databases are common.

Other examples are message ids of emails. They may be quite long, a short line of text is acceptable and they should be world wide unique. Combining the fully qualified publicly accessible hostname and a time stamp and a counter is usually good enough. They look like this 5AE.630049D.2EA050907@gmx.net or 5AE.630049D.2EA050907@ms-93424.gmx.net, where the part after the „@“ stands for the mail server and the part in front is a unique id for the message created by the mail server and looking slightly different depending on its software.

Often the length is not arbitrary and the UUIDs are a good compromise for this. They have 128 bits, some of which are used to specify the type of UUID. One type combines a hostname and timestamp like the message ids. But since in some contexts the generation of the UUID should not reveal the hostname and the time, some implementations prefer random UUIDs. It can very well be argued that with good random numbers duplicates of such random UUIDs are less likely than events that would bother us much more than having a duplicate. For randomly generated UUIDs six bits are used up for expressing the version and the fact that it is a random UUID, leaving 122 bits, which is a total of 2^{122} = 5316911983139663491615228241121378304 \approx 5.317\cdot 10^{36} different possible values. Generating billions of UUIDs for many years leaves the risk of creating duplicates acceptably low.

But the issue of the quality of the random generator and the issue of potential duplicates remain something that needs attention. So it is worth to consider the path of using the host and timestamp. Now the host can not be identified by an IP address or fully qualified domain and host name, because these tend to be either too long or not unique enough. The MAC address used to be a good possibility. But I would not be so sure about this any more. Most server systems are virtualized these days and the MAC address is configured by software, so duplicates can occur accidentally or deliberately. Using a time stamp by itself can be a problem too because sooner or later it will happen that two IDs are generated at the same time, within the given granularity. Machines have several processors, run several processes and several threads within each process.

So achieving the goal of a real globally unique UUID value remains a difficult question. Following a more local uniqueness within an application or application landscape might be more reasonable. The number of servers may be large and may vary, but it should be possible to assign numbers to virtual or real servers. In case there are multiple different processes on the same (virtual) machine to assign numbers to these as well. This can be used as a replacement for the host part of the UUID. If it does not use up all the bits, these can be filled up with random numbers.

Timestamps can be obtained easily and relatively reliably for a granularity of msec (Milliseconds). The UUID timestamp allows up to a granularity of 100 nsec, which is 10’000 sub divisions of the msec. A thread safe counter that may reset during program start or with its overflow can be used to count and its positive remainder modulo 10’000 can be used instead of the 100 nsec part in conjunction with the msec.

Often a uniqueness within an application or application landscape can be achieved by using some kind of unique counter. The best choice is often the sequence of a database, which is good in this task and well tested. It is not too hard to create such a functionality. Handling of multiple processes and threads needs to be addressed. For persistence, it can be an improvement to reserve blocks of 100 or 1000 numbers and persist less often. This will result in skipping some numbers when restarting, but otherwise work out well. The same idea can also be applied for a distributed unique number generator, where each instances gets ranges from some master generator and gets new ranges, when they are used up.

Such unique numbers or identifiers are needed quite often. It is usually best to use something that works reliably, like the DB sequence. But it can be developed with adequate care, if there is a need. Testing and especially automated testing is off course very important, but only sufficient if the whole implementation is conceptionally sound and robust.

Share Button

Changing of Keyboard Mappings with xmodmap

Deutsch

Introduction

When running a Linux system in its graphical mode, keyboard mappings can be changed by using xmodmap.
Each key on the keyboard has a „keycode“ which can be found out by looking at the output of
xmodmap -pke > current-keyboard
or by running
xev
for trying out the keys.

I am using a modified German keyboard, but off course the ideas can be adapted to any setup.

Given setting as a Basis

You can start with any keyboard, for example with the German keyboard with no dead keys, which is often useful as a starting point. I prefer to modify it a little bit. This allows me to support more languages like Swedish, Norwegian, Danish, Dutch, Spanish and Esperanto. Russian is an issue that I will address in another article. On the other hand it is a good idea to have secondary positions for some symbols that are on keys that might be missing on some physical layouts, like „<", "|" and ">“ on the German keyboard, whose key is just not present in the American keyboard. The third idea is to have two Altgr-keys, because many important symbols are just accessible in conjunction with Altgr and thus easier if there are two Altgr-keys like there are two Shift-keys.

Special characters for Esperanto

For Esperanto (Esperanto explained in Esperanto) the latin alphabet with its 26 letters is needed, even though some of them are never used. And on top of that the following letters are needed as well:
ĉ Ĉ ĝ Ĝ ĵ Ĵ ĥ Ĥ ŝ Ŝ ŭ Ŭ
Unfortunately they have not reused the letters commonly used in Slavic languages and present on many international setups:
č Č ž Ž š Š
but Unicode covers it all and as long as the keyboard does not need to support Slavic or Baltic or Sami languages simultaneously with Esperanto, things should be fine.

A reasonable approach is tu put these symbols on Altgr-C, Altgr-G, Altgr-J, Altgr-H, Altgr-S and Altgr-U.

This can be achieved easily:
Create a file
.xmodmap-ori
by

xmodmap -pke > .xmodmap-ori

.
And a script $HOME/bin/orikb:

#!/bin/sh
xmodmap $HOME/.xmodmap-ori

Look up where the letters S, G, H J C and U are positioned on the keyboard in the xmodmap-ori-file.
Now create a file
.xmodmap-esperanto
using the following command

egrep 'keycode *[0-9]+ *= *[SsGgCcJjHhUu] ' < .xmodmap-ori

and edit it. Leave the part keycode = intact and change it to something like this:

keycode 39 = s S s S scircumflex Scircumflex
keycode 42 = g G g G gcircumflex Gcircumflex
keycode 43 = h H h H hcircumflex Hcircumflex
keycode 44 = j J j J jcircumflex Jcircumflex
keycode 54 = c C c C ccircumflex Ccircumflex
keycode 30 = u U u U ubreve Ubreve

The numbers between "keycode" and "=" could be different on your machine, but the rest should be like that.

Now create two scripts
$HOME/bin/eokb

#!/bin/sh
xmodmap $HOME/.xmodmap-esperanto

and
$HOME/bin/orikb

#!/bin/sh
xmodmap $HOME/.xmodmap-ori

.

Do not forgot to do the

chmod +x $HOME/bin/eokb $HOME/bin/orikb

for your scripts... 🙂

Now you can use eokb for enabling the Esperanto keys and orikb to return to your original setting.
The Esperanto keys will be accessible by using Altgr and the Latin letter they are derived from.

Other language specific characters

In a similar way you can have other characters
å and Å on the A,
ë and Ë on the E
ï and Ï on the I
ø and Ø on the O
æ and Æ on the Ä
ÿ and Ÿ on the Y
ñ and Ñ on the N
< on the , > on the .
| on the -

This allows to write a lot of languages. See what works for you...

Remaining Issues

For Russian I have bought a physical Cyrillic keyboard and I am using it with the setup that is printed on the keys. I might write about this another time.

Generally I like to have two Altgr keys and I can very well live without a windows key. I might write about this another time as well.

Btw. this article has been written for Linux, but it works perfectly well with any other Unix-like system, as long as X11 is used, just think of Aix, HPUX, BSD, Solaris and likewise systems. But Linux is by far the most common unix like desktop system these days.

Here is another approach:
xkbmap

Share Button

Tastaturbelegung mit xmodmap ändern (Linux/X11)

English

Einleitung

Wenn ein Linuxsystem im grafischen Modus läuft, kann man die Tastaturbelegung mittels xmodmap ändern.
Jede Taste hat einen sogenannten „keycode“, den man leicht ermitteln kann, indem man sich die jetzige Belegung mittels
xmodmap -pke > current-keyboard
ausgeben lässt oder mit
xev
die Tasten ausprobiert. Ich benutze gerne eine deutsche Tastatur und tue das unabhängig davon, was auf den Tasten so aufgedruckt ist. In der Schweiz ist leider eine andere Belegung üblich, die minimale Abweichungen aufweist. Angeblich (inoffiziell) um die Schweizer Tastaturhersteller zu schützen, weil man vergass, dass asiatische Hersteller diese Hürde mühelos überspringen können. Ageblich (offiziell) um einen Kompromiss für die verschiedenen Sprachregionen der Schweiz zu schaffen und die Unterschiede minimal zu halten. Die Schweizer Tastatur ist aber unpraktisch, weil das „ß“ und die großen Umlaute fehlen.

Vorgegebene Einstellung als Basis

Nun kann man unter Linux eine Deutsche Tastatur mit „no dead keys“ wählen, was normalerweise sinnvoll ist. Oder sagen wir eine sinnvolle Ausgangsbasis. Ich finde es aber praktisch, diese noch etwas zu modifizieren. Einerseits können so mehr Sprachen unterstützt werden, wobei für mich die skandinavischen Sprachen, Spanisch, Russisch und Esperanto im Moment am interessantesten sind. Andererseits finde ich es praktisch, die Zeichen, die auf Tasten liegen, die bei manchen physikalischen Layouts fehlen, z.B. die drei Zeichen „<", "|", ">„, noch zusätzlich woanders hin zu legen, damit man sie auch dann noch hat. Drittens finde ich es schön, wenn man zwei Altgr-Tasten hat, weil viele wichtige Zeichen nur über Altgr erreichbar sind und sich besser greifen lassen, wenn es ein rechtes und linkes Altgr gibt.

Zeichen für Esperanto

Für Esperanto (Esperanto auf Esperanto erklärt) braucht man das übliche lateinische Alphabet mit 26 Buchstaben, wovon einige allerdings nicht verwendet werden, und die folgenden zusätzlichen Buchstaben:
ĉ Ĉ ĝ Ĝ ĵ Ĵ ĥ Ĥ ŝ Ŝ ŭ Ŭ
Leider hat man sich nicht an die in einigen slawischen Sprachen verwendeten zusätzliche Buchstaben
č Č ž Ž š Š
gehalten, aber solange man nicht außerdem slawische oder baltische Sprachen mit lateinischer Schrift parallel verwendet, ist das kein Problem.

Die sinnvollste Lösung scheint mir, die jeweiligen Zeichen auf Altgr-C, Altgr-G, Altgr-J, Altgr-H, Altgr-S und Altgr-U zu legen.

Das lässt sich recht einfach erreichen:
Man legt eine Datei
.xmodmap-ori
mittels

xmodmap -pke > .xmodmap-ori

an.
Und ein Skript $HOME/bin/orikb:

#!/bin/sh
xmodmap $HOME/.xmodmap-ori

Man legt danach eine Datei
.xmodmap-esperanto
an, in die man die folgenden Zeilen einträgt:

keycode 39 = s S s S scircumflex Scircumflex
keycode 42 = g G g G gcircumflex Gcircumflex
keycode 43 = h H h H hcircumflex Hcircumflex
keycode 44 = j J j J jcircumflex Jcircumflex
keycode 54 = c C c C ccircumflex Ccircumflex
keycode 30 = u U u U ubreve Ubreve

Und ein script in
$HOME/bin/eokb

#!/bin/sh
xmodmap $HOME/.xmodmap-esperanto

Natürlich chmod +x für die Skripte nicht vergessen… 🙂

Nun kann man mittels eokb die Esperanto-Zeichen auf die Tastatur bekommen und mittels orikb den Originalzustand wiederherstellen.

Andere sprachspezifische Sonderzeichen

Auf ähnliche Weise lassen sich natürlich auch andere Zeichen auf die Tastatur bringen. Ich habe z.B. noch
å und Å auf dem A,
ë und Ë auf dem E
ï und Ï auf dem I
ø und Ø auf dem O
æ und Æ auf dem Ä
ÿ und Ÿ auf dem Y
ñ und Ñ auf dem N
< auf dem , > auf dem .
| auf dem –

Damit lassen sich die skandinavischen Sprachen, Spanisch und Esperanto schreiben.
Manchen Tastaturen fehlt die Taste <>| links neben dem Y zugunsten einer größeren Shift-Taste. Deshalb habe ich mir <>| zusätzlich noch auf Altgr-, , Altgr-. und Altgr– gelegt.

Ausblick für weitere Artikel zum Thema

Für Russisch habe ich mir eine kyrillische Tastatur gekauft und benutze die Belegung wie sie aufgedruckt ist.

Generell stört es mich, dass man so häufige Zeichen wie []{}\ nicht so gut erreichen kann und so habe ich jeweils Altgr rechts und links verfügbar gemacht…

Share Button

Java: Using Enums for Singletons

This singleton pattern is not really a big deal, but overused because it gives us the coolness of knowing about design patters without learning too much stuff for that… It does have its uses in some programming languages, while more or less implicit or obsolete in others, depending on the point of view.

I have already discussed the generalization of the singleton.
Actually it can be seen that the enum of Java and of languages who do something like Java’s enum in a similar way can be used as a way to build a singleton by just limiting it to one instance. Having been skeptical about this as an abuse of enums that might confuse people who read this I would now suggest to embrace this as a possible and useful way to write singletons and to be familiar with it when reading other people’s code or even to use it when writing code.

The enum way to write a singleton is the most elegant way in Java, because it uses least boiler plate code and includes some benefits that are usually ignored, especially when it comes to serialization that has to be addressed in singletons quite often, but is quite often ignored, resulting in multiple instances of the „singleton“ to float around…

So here we go:


enum Singleton  {
    INSTANCE;

    private long count;

    private Singleton() {
        count = 0;
    }

    public synchronized long nextValue() {
        return count++;
    }
}

Remarks:

  • For real programs it would be important to check if long is sufficient or BigInteger is needed.
  • For real programs using an AtomicLong could be a better way than using synchronized.

Some links:

Share Button