Thursday, December 22, 2011

ams and enumerate (2nd. time round)

The enumeration problem has been nagging on me overnight and thus investigated further. The solution is simple: the enumerate package is plain incompatible with AMS (probably with anything other than standard latex).

As you can see ams changes a lot of widths including parsep, parindent and leftmargin. The enumerate package also changes leftmargin, unfortunately not relative to the one set but absolute, probably calculated from the standard. So don't use enumerate and AMS! I will define my own list environment from now on which looks better.

Amsthm, lists and enumerate.

Problem:
Amsthm has three theorem styles normal, remark and definition, of which only the normal style is set in italics normally. If you use a list within such a theorem (questionable according to some, necessary to me) then the item labels for these lists are italicized as well which doesn't look good.

The advice to correct this was to manually \textup the label in each item. This of course works normally, but i also employ enumerate. In this case i got a warning "The counter will not be printed.", which is due to the fact, that enumerate will not detect counters that are inside braces.
Solution:
\begin{enumerate}[\upshape i)]
\item...
\end{enumerate}

This finally looks good

Disjoint Unions

I had countless revelations about math and LaTeX over the last week. I don't know why this happened but i made a major step forward. Most of them are little but they add up and it shows. One of the things that I fudged together years ago was an ugly construction for disjoint unions, something along the lines suggested in a4symbol.pdf. The correct solution however is to \usepackage{MnSymbol} and use \cupdot/\bigcupdot!

Tuesday, December 20, 2011

Latex macro reference for authors

I just found this handy reference for package authors, that I didn't know so far. Try it here.

Monday, November 14, 2011

I just realized my squid was down. The /var/log/squid/squid.out was unhelpful as were all the other logs in that dir. The only thing that pointed me to right solution was
Nov 13 10:00:28 emma (squid): The basicauthenticator helpers are crashing too rapidly, need help!
Nov 13 10:00:28 emma squid[9292]: Squid Parent: child process 9359 exited with status 1
It turns out the problem was that i added a comment after the last word of the first line, documenting what i did:
auth_param basic program /usr/lib64/squid/ncsa_auth /etc/squid/squid_passwd #use apache style pwd file instead of pam
Remember: Squid is idiotic and doesn't strip comments before parsing the line.

Suicide in the morning

This morning i woke up, started my day with a bit of blog reading and five links into the day i reached this. I especially liked the 5 +1. I guess this is the paradigmatic example for the dislike/-1 debate.

Sunday, October 2, 2011

youtube proxy script/pac file

function FindProxyForURL(url, host)
{
  if (shExpMatch(url, "http://*.ytimg.com*")) { return "PROXY <server>:<port>"; }
  if (shExpMatch(url, "http://*youtube.com*")) { return "PROXY <server>:<port>"; }
  return "DIRECT";
}
I really love this one, finally GEMA can go **** themselves for not providing distribution rights!
Of course you have to actually replace the variables like tehsuck.de:8079

Friday, September 23, 2011

Priceless Python FU


__ = """
enu
 Help
   Some help
 Colors

   Red
   Green
       Light green
               1
               2
               3

       Dark green
   Blue
       Cyan
       Cobalt blue
       Diamond blue
 Version

   Verion 0.1

   Details
       D 1
       D 2
       D 3
   Test version

 Progress bar    
""".splitlines()

class _:
    def __init__(_):

        _.___ = []
        _.__ = [(-1, _.___)]

    def _(_, __):
        __________________ = _.___

        for ___ in __:
            if not ___.strip():

                continue

            ____ = ___.replace('\t', '    ')

            _____ = ____.lstrip()
            ______ = ____.strip()

            _______ = len(____)-len(_____)

            if _______ > _.__[-1][0]:

                _________________ = []
                __________________.append(_________________)
                _.__.append((_______, _________________))

                __________________ = _________________
            elif _______ <_.__[-1][0]:

                _.__.pop()
                __________________ = _.__[-1][1]

            __________________.append(______)

        return _.___[0]

print _()._(__)

Tuesday, August 2, 2011

Direct Connect Hubs for Mac

Since I've started hacking on the brand new ncdc I found myself in need of a hub. I don't mind it being slow since it's only for testing purposes, but it should at least run and work which proved surprisingly hard.

  • Lamahub was the most promising. It is written in C, supposed to run on just about every platform under the sun and has a lama(sic) theme which i'm always up for. Sadly it doesn't work out of the box on a mac. It took me a bit of time to patch it so it finally built correctly. I then spent an hour playing with it and four clients, believing to have found an error in ncdc which turned out to be a bug in the hub. Needless to say i was annoyed and trashed it.
  • dtella was up next. The website doesn't tell you anything (well maybe it does, but it was done and the sf.net page isn't very informative), the macosx install script is borked and i quickly gave up debugging it. That would have all been ok, i just started the dtella.py from where it was but had to discard that program as well since it isn't meant for running more than one client from the same ip. How that fits with their premise is a bit of a mystery to me, what about a dorm room where two people share an external ip?
  • MPPS aka Voltron dchub aka Tiny Box dchub are apparently iterations of the same luabase hub core from what i can tell. I got some errors about missing modules and i don't feel like learning lua to debug it, so i moved on. Still, if you are Lua affine this is probably your hub.
  • Valuthub is a now extinct project (at least their berlios site doesn't exist anymore and I can't find a different one.
  • myhub is a java based (not exactly my favoured programming language mind you) hub that barfed on me when compiling. From the short time i looked over it I believe the author plain forgot to include one file that contains the missing class. Since upstream's dead I won't write it either
  • and the winner is py-dchub. It's the only one that worked straight out of the box with so far no insufficiencies I've found yet. Upstream's dead here as well from what i can tell but it's python so who cares.
So only one out of 6-8 hubs actually worked out of the box, two maybe three sort of work after some fiddling of which dtella is probably not your regular dchub.  All in all the usual sad state of affair for OSS software for the mac (well or anything that isn't completely mainstream).

Friday, May 27, 2011

On Passwords

This has been bugging me for years but it comes up again and again. So it's time for passwords - a case study:
  • Passwords are important, hardly anyone doubts that (well at least for some passwords). Still people don't act accordingly. I know a company that has a policy(wtf!) that the password for any company related account is required to always be the same as the user name. (I mean wtf?!?)
  • Passwords are sensitive.
    • Still a lot of servers do auth in plain without encryption. At any stage in between anybody with access to the wire can see them. This is scarier than you might think. For example my dorm has switches that let you read the traffic of hundreds of other people.
    • Even if that is not the case you still have to trust the other end (and that they know what they are doing). I administrate a lot of computers and the people i work with are a rather capable team. I am pretty sure i can vouch for their good will, so i would trust this end. Nevertheless we for example had our ldap passwords stored in plain text and synced them into our university backup system, since we didn't set up the server initially and never thought about.
  • Passwords are difficult to get right: This is has many aspects
    • they should be memorable. It doesn't help if you have to carry it around in a pocket to know it
    • they shouldn't be too short and lala is too short ;)
    • they should be somewhat safe You know the drill, alphanumeric, capitalization, not based on a dictionary word...  Read this and laugh. If you find the full list, you'll be surprised how sexed up thelist is. When setting up our new shell server, we ran all passwords against cracklib as an audit and over half of them fell through!
    • they shouldn't be too safe. It's a sad reality but some setups even if they allow it are plain incapable of processing certain chars/encodings whatever. I had to have my university computer account reset because they had a fuckup in their system rendering passwords with umlauts different when entered and read back. This is germany for christ's sake. How many times a week must they have had this problem?!?
    • they shouldn't all be the same. Most people use the same password over and over, if you get one you potentially have a lot of accounts (i verified this a couple of times).You'd be scared if i had actual figures proving how many people do that.
      There is a difference to be made here: I asked the most tech affine and security conscious people i know and they on average had something like 5 or 6 different personal passwords. The point is they usually have an unobvious scheme of adjusting it and incorporating part of the sites name or similar into it to make them different for each site
A lot of this gone wrong can be learned by bad example from the security "experts" at HBGary and their recent fuckup. So we have all these ideas and that's all nice in theory, but:
  1. Why, oh why does every single site have to make up another different insane requirement for passwords. Please use sane somewhat lenient minimum requirements. I propose 7 chars min, one letter, one other and possible an upper case letter.  I can understand requiring numbers or special chars, a minimum length or not all lower/upper case but why the heck would you impose a maximum length of 8 (!) chars or no caps or requiring numbers only. All these make it more predictable, less easy to remember (i still hit sites where none of my standard passwords can be adapted to be accepted) and less safe in the long run. You don't gain security you lessen it!
  2. If you insist on restricting your passwords firmly, please, please add your requirements to the login page! I have reset my password countless times on many sites only to remember it when i read the reqs when asked to set the new passwords. That would usually help me more than anything. I have turned to writing the reqs in the security question because it's easier that way.

Synctex

I recently became aware of Synctex the successor of pdfsync.
pdfsync is a technology that allows synchronization between a (la)tex file and the corresponding pdf output. It wasn't the first of its kind but certainly the best i've tried. In practice you need support by both your viewer and editor but then it's down to pressing a command or (shift/ctrl/whatever)+clicking somewhere and you are magically teleported into the other app to the spot corresponding to the one you were at on the other side. Anyone who has texed and needed to proof a doc of more than 5 pages length before will understand that this is invaluable.


For all the goodness, this had some drawbacks unfortunately: pdfsync was based on some tex primitives as opposed to being embedded into the engine, so the output under some circumstances wasn't perfect, it could change the generated rendering and it was incompatible with some popular packages (e.g. colortbl). I have never been bitten by any of these in the last 3 years but it always was a good excuse for viewers not supporting it (they are usually the end that carries the burden).
It unfortunately still has it's place as we will see shortly, so here are links to set up  forward  and backward search underMacOS + vim + skim, evince doesn't have it and never will which leaves you with xpdf and okular on linux, both of which aren't my favourites.

In comes synctex: It is the natural evolution of pdfsync done by the original author and has all the goodies without the down sides. Setting it up under Mac was even easier now that skim supports macvim as a preset :). Just choose MacVim under preferences>sync and put the following in your .vim/ftplugin/tex.vim (assuming you use the vim-latex suite)

let g:Tex_DefaultTargetFormat = 'pdf'
let g:Tex_CompileRule_pdf = 'pdflatex -synctex=1 --interaction=nonstopmode $*'
let g:Tex_ViewRule_pdf = 'Skim'
 
Look at this for all other MacOS related progs, mupdf, and evince. Okular just needs to be called with
okular --unique 'file.pdf#src:linenumber file.tex'
(That's what i think the evince people should have done instead of using dbus. Oh, well...)

Now for the bad part, lua(la)tex + evince/okular isn't working with synctex. I filed bugs with luatex, evince and okular but i don't expect a solution for this anytime soon. :( That means i am back to pdfsync for now, since i really, really like my luatex. So have fun with that!

Edit: you need to tell vim to call okular/evince with the exact same filename that lualatex produces which is ./file
In order to do that goto compiler.vim which if you installed vim-latex in your .vim is under .vim/ftplugin/latex-suite/compiler.vim otherwise probably somewhere in /usr.
Apply this patch for okular. For evince it really depends which script you use, but read the patch and do it analogously.

Tuesday, May 3, 2011

Impurity Test endlich online!

Du hörst immer du wärst verdorben, glaubst es aber nicht? Du hast schon vor langem von ihm gehört, aber nie getraut ihn zu machen? Verzweifle nicht, er ist endlich hier! In der Tradition der besten Varianten, die wir kennen, raffiniert durch endloses Durchtesten, perfektioniert durch das verderbte Wesen Vieler. Der Impurity Test ist endlich hier!

Wednesday, April 13, 2011

Interesting article and some of the comments are even more insightful than the article itself. I think i agree with Anonymous (22. August 2010), who explains the futility of the whole attempt, s/he laconically summarized it like so:
That to make the internet useless for bad people, it must also be made useless for good people. You could literally firewall the entire damned thing to where the internet passed only ICMP echo requests, and do you know what would happen then? Spammers would resort to hawking viagra via ping packets fired in morse code, hoping to reach ham radio operators looking in the general vicinities of their DSL modems' RX LEDs. (I'm *not* kidding.)
And sadly enough s/he's right.

libao and the mac

Anyone who hasn't updated libao on the mac to 1.1. yet do so now! It fixes those two really annoying bugs concerning playback stopping when hibernating,suspending or (un-)plugging an audio connector.
By the way if you don't know why open source is useful, i think i have yet to find a text that expresses my views on this better than http://www.xiph.org/about/

Tuesday, March 29, 2011

HIbernate mac from cli

I forgot to turn off my mac and left the house, so what's a guy to do? Right log in via ssh (having dyndns working is a real plus here) and hibernate it. To do this use the following snippet in a script.
#!/bin/bash
osascript << EOT
tell application "System Events"
     sleep
end
EOT

Control apple network profile from the command line

I have to change between a network with a fixed address setup and some others with dhcp quite often, so i was really glad i found out about networksetup. The following snippet switches from the static to the dhcp profile, both of which i defined earlier in the network settings.
networksetup -setnetworkserviceenabled static off
networksetup -setnetworkserviceenabled DHCP on
This is a real time and sanity saver!

Thursday, March 3, 2011

New zsh Prompt

Spring's coming and it's time for a change. I have always liked the idea of colours in the prompt to make you aware of what kind of platform you are working on.  Stumbling upon this post inspired me and now here is my version for the zsh:

function cnprompt {
  set -A colours red green yellow blue magenta cyan #black white
  local col=${colours[$(hostname | cksum | cut -c2-6) % 6]}
  [[ -n "$SSH_CLIENT" ]] && local sig="%#%#" || local sig="%#"
  # i am thick at times; i need more warnings :P
  PS1="%B%(!.%F{red}root@.)%F{$col}%m%f%(?.. %??)%(1j. %j&.):%b %2~%B%(!.%F{red}.%F{yellow})$sig%f%b"
} 
Quick rundown:
  • first line sets up an array with the colours that make sense
  • second line computes an index into the colours array and sets col accordingly 
  • I check for whether I am on a local machine or logged in via ssh and double up the last sign
  • The main line sets a bold, coloured hostname preceded by a red root@. Then i print the exit code of the last command followed by number of backgrounded processes if any, both of which are a lot more helpful than i first thought. The whole thing ends with the last two dirs in pwd and the var set up in line 3
As for the formula, i ran

for host in list; do $((1+$(echo $host | cksum| cut -c1-2) % 6)); done 
to find the number combination that would cause the least overlap and gave the colours I preferred to the hosts I use most. I also tried using md5 instead or in addition to cksum but the spectrum it created seemed narrower.

Wednesday, February 16, 2011

Explode (Part One)

I have always been a fan of PHP's explode (quite opposed to a lot of other parts of that language) which made me want to recreate it in C. Thinking about the problem i came with a non-equivalent function that i liked better which i thought i should share.  It takes a string and a separator on which to split the string up on.  The function returns an array of strings that can (and has to be freed) with a single free. This is achieved by reorganizing the array in front of the resulting strings as one continous piece.
When thinking about it I decided to factor out multiple occurrences of the separator instead of inserting Null Strings, which may or may not be desired. One could improve this in several ways like several possible separator chars, a separator of more than one char, a limiting argument,...  of course, none of which i need right now. I am planning to write up a couple of other possible implementations over the course of time and discuss their respective merits and benchmark them.

char **explode(const char * source, char sep){
  int i =0, j =0;
  const char * runner=NULL, *oldrunner=NULL;
  int length = strlen(source)+1;
  int rlength=0;
  char ** resArr = NULL;
  char * finalArr = NULL;

  if (!(*source)){
    return NULL;
  }
  if (! (resArr = malloc(sizeof(char *) * length)) )
    return NULL;
  memset(resArr,'\0', length*sizeof(char*));

  runner = oldrunner = source;

  while (*runner){
    if (*runner == sep){
      if ( (length = runner - oldrunner) ){
        rlength+=length+1;
        resArr[i++] = (char *) oldrunner;
      }
      oldrunner = runner+1;
    }
    runner++;
  }
  resArr[i++] = (char *) oldrunner;
  rlength += runner - oldrunner+1;

  /* this part would be optional if i malloc'ed and strcpy'ed
   * above but that way the user only needs to free once*/
  if  ( !(finalArr = realloc(resArr, sizeof(char *)*(i+1) + rlength)) ){
    free (resArr);
    return NULL;
  }
  resArr = (char **) finalArr;
  finalArr = (char *) (resArr + ((i+1)*sizeof(char *)));
  j = i;

  for (i=0; i
    /* this of course only works because they are contigous */
    length = resArr[i+1] - resArr[i]-1;
    strncpy( finalArr, resArr[i], length);
    finalArr[length] = '\0';
    resArr[i] = finalArr;
    finalArr += length+1;
  }
  strcpy(finalArr, resArr[j-1]);
  resArr[j-1] = finalArr;
  return resArr;
}

Tuesday, February 15, 2011

Shine a little light

It stood there all alone in the dark. Freezing cold as it was I could not help but emphasize with the poor thing. Of course it was a rather daunting atmosphere; a new moon had just begun its course and the stars were rather dim, the air was cold, the wind was stiff. So there it stood trying to hold its ground alone in the darkness. First I wasn't sure what the flickering light meant but then I came closer. The bulb was starting to show it's age, long hours of service had made it weary and it was gathering the last bit of life in it in a futile attempt to fulfill its duty. It was close to dying but still mustered the strength to try everything and perform honourably during its last fight.

Compassion filled me and I was trying to remember when i had last seen as much grandeur in my own life, let alone on myself. I was moved and wanted to help, but what could a simple person like me do? Still I moved on seeing I was not worthy staying in its presence about it.

To my surprise it was still fighting the next time I came to this place two days later and I could all but stop and wonder. It's pride and endurance were beyond my mental grasp i must say. I wished it well, moved on thinking about it for a very long time.

The next time i got there it was replaced by a younger recruit so it must have died in the meantime, but i am sure it was with honour. I thus vowed to pay my respects to it by trying to take it as an example and I encourage everybody to do the same!

Tuesday, February 8, 2011

Setting the MacOSX volume really low

I just realized it took me insanely long to figure this out and never put it up here in case someone else had the same problem. I have this theory after using original Apple earphones once that they use a preresistor that is just way to big and once you plug something decent in then you just go deaf even on the lowest level of the volume slider.

I then quickly found out about option-shift- but that only gets you down to 2.5% of the volume which is still quite loud in a quiet place. The lowest i have found out how to get to is 1% (and even that is too loud in the library sometimes) and this is how you do it:

#!/bin/sh
osascript -e "set Volume 0.01"

Wednesday, February 2, 2011

ipv4 exhaustion

As you are hopefully aware IPv4 is on its way out and we reached a major milestone yesterday. Up until monday IANA had seven /8 subnets(that's a a bit under 17 million adresses each) left. On Tuesday APNIC requested another two, which let the number drop to the treshold agreed upon in advance on which the remaining five subnets will be distributed, one to each of the RIR's(Regional Internet Registries). That means yesterday every RIR got one last /8 Block, APNIC got three and that's it. Every IPv4 address that willl be requested once these blocks have been used up will have to come from some previous allotment.

How long will this last on the RIR level?

First you have to look at the rate with which the addresses were given out until now. As you can see the rate was about 10 /8's per year, of which only a neglegible amount was used by AFRINIC(Africa) and LACNIC(South America) (overestimate with 10%). On average RIPE(Europe) and ARIN(North America) use about equal amounts and together about as much as APNIC(Asia and Pacific) does. So that means APNIC, RIPE and ARIN will need about 4.5, 2.25 and 2.25 /8 networks over the course of next year if demand stays exactly the same.

Given that the good is becoming rarer this is unlikely as consumers will probably start hoarding. So given this increase in demand and estimating RIPE and ARIN to have a spare of about 1 /8 left over that would mean APNIC will be the first RIR to run out for good until September at the latest, shortly followed by RIPE and ARIN. LACNIC will likely run out early 2012 and AFRINIC probably will last longest given their low local demand.

What happens then?

Most likely it will be an ugly patchwork of a routing mess and a rather small bazaar for the unused parts of previous allocation that were simply to big for the organization getting them to be used up sensibly. I don't think this will scale to very small subnets since this will put too much demand on the routing infrastructure, so this market is a lot smaller than a lot of people estimate right now, although it will surely be amusing.

Apart from that there will be a rush to get IPv6 out to the public which will fail in a lot of entertaining ways and i am certain will be blamed on the short time frame that this had to be done in (a ludicrous claim that will be uttered for sure). A minor number of people will sit in the dark and wonder why a few websites won't work but overall won't notice anything wrong.

What does it mean?

PARTY! The dog days are over. Well at least to some degree I hope. I am really looking forward to what will hopefully be a global shared address space with hopefully less routing issues, NATing, masquerading and all that other fun stuff. I am sure someone will come up with some unbelievable abomination to ruin the fun but let's enjoy utopia while it lasts

If now my dorm and my work place (a scientific institution) would consider running ipv6 I'll be overjoyed.

Monday, January 17, 2011

getting Skype to work on opensuse as a user

Skype is still only provided as a 32 bit binary and that is rather upsetting, because opensuse doesn't ship libXv as a 32 bit build by default. So if it fails because of that install xorg-x11-libXv-32bit (and any other stuff it wants).

If however you aren't root, then you are a little on your own. I got it working with the following
  1. Grab a 32 bit libXv from somwehere, e.g. here
  2. Unpack it. In my case like this: rpm2cpio xorg-x11-libXv-32bit-7.5-1.8.x86_64.rpm | cpio -idmv
  3. Now push that libXv.so.1 some place sensible (I recommend ~/.local/lib)
  4. Export LD_LIBRARY_PATH="$HOME/.local/lib/" or appropriate
  5. Start skype from within the reach of that export e.g. the same shell
Steps 4 and 5 have to be redone every time, so you might as well make a script out of it
All of this can be automated of course and is just a pointer for poor souls like me that take longer than 10 minutes to figure this out.

Thursday, January 13, 2011

Tex Font Catalogue

This is a most excellent find:

http://www.tug.dk/FontCatalogue/

Saturday, January 8, 2011

Latex Wrapperclass

When you define a new class in latex you most unlikely want to start from scratch. This is of course not a problem, you can easily inherit another documentclass. Problems tend to start if you also need to react on an option of the class as well. The example shows the easiest way i know of:

\NeedsTeXFormat{LaTeX2e} 
\ProvidesClass{myartcl}[2010/01/06 This is so 2010!]
\RequirePackage[unknownkeysallowed]{keyval} 
%set up the function for finding doublesided as an argument 
\define@key{keygroup}{doublesided}[true]{% 
  % Do whatever you need to here 
  \PackageWarning{myartcl}{Found doublesided #1}% 
} 
% and we pass it on to the keyval parsing algo 
\DeclareOption*{% 
  \edef\act{\noexpand\setkeys{keygroup}{\CurrentOption}}\act% 
  \PassOptionsToClass{\CurrentOption}{article}% 
} 
\ProcessOptions\relax 
\LoadClass{article} 

Saturday, January 1, 2011

Optional Arguments in Latex Functions, Style and Class Files

I just wrote my first own latex package and as usual i was rather aiming for the stars than KISS.
The last big issue was finding out how to have optional package arguments that take a value (think geometry's left).

First: 
How to have functions with more than one optional argument or named optional arguments: Turns out not to be too complicated in the end. First you need the package keyval which enables you to parse key=value style arguments and then you need to understand how it works (the doc is aweful imho). Set up your parsing functions with something like

\define@key{keygroup}{keyname}{\dostuff{#1}}

this defines an option keyname that takes an argument, that has to be provided if the key is used.
Example: 
\define@key{keygroup}{color}{\domorestuff{#1}}

You can also define an optional argument that has an optional value that gets used when none is provided with the following syntax

\define@key{keygroup}{keyname}[default]{\dostuff{#1}}

 This lets you for example define a length type argument like follows:

\define@key{head}{width}[\textwidth]{\def\@bannerwidth{#1}}

This would set \@bannerwidth to 5cm for width=5cm and to the width of the text otherwise.
 Now to parse an optionstring you need to pass it to \setkeys like this:

\setkeys{keygroup}{optstring}

So now in order to have a command with more than one optional argument (beware syntax is different though!)

\newcommand{\printbanner}[2][]{
    \setkeys{keygroup}{#1} 
    ....
}
and call it like so: 

\printbanner[width=18cm,color = red]{Other Arg}
 
Second:
I think keyval was written with functions in mind but that shan't stop us from abusing it for package options. Declare all your options that don't need keyval syntax first (it's easier than going through keyval). Afterwards set up the catchall handler with 

\DeclareOption*{\edef\@act{\noexpand\setkeys{keygroup}{\CurrentOption}}\@act}

The reason you need this is so you can delay the expansion of the arguments. This should be enough so you can 

\includepackage[width=18cm]{package}

Further Notes:
If you want a switch case like option have a look at the package ifthen.
A complete, minimal, working example is available here.