Thursday 29 November 2012

Getting your own (IP) address and port in a javascript web app

While hacking something up using socket.io I needed to know the IP of the server, so I could connect a socket back to it. localhost was the solution at first, but I wanted to access it from other machines in my network.

I didn't want to get the local IP using node. I might want to serve the application from a server with more than one network card. I needed to have the IP fixed.

But I often develop the app while commuting, on my EEEPC. When I get home, I sync my code as I turn on my desktop computer to proceed work.

So I found myself needing to have a fixed IP over two different machines: my desktop PC, and my EEEPC. A fixed IP was clearly not an option.

I had the idea of using window.location. I used window.location.hostname to get the IP address or domain name of any server I was connected to. It was such a simple solution I was very positively surprised.

All uses of window.location:

example url: http://192.168.1.7:8080/chat?nickname=F%C3%A1bio#fragment

  • hash (#fragment)
  • host (192.168.1.7:8080)
  • hostname (192.168.1.7)
  • href (http://192.168.1.7:8080/chat?nickname=F%C3%A1bio#fragment)
  • pathname (/chat)
  • protocol (http:)
  • search (?nickname=F%C3%A1bio)

Wednesday 28 November 2012

Common Regex

I have been busy lately, hacking up stuff with socket.io

I've created a table for regular expressions to do common validations or searches.

Anyway, here is the link, I hope you enjoy it! If you think that an important regex is missing, drop me a line.

Tuesday 13 November 2012

Dividing by zero for fun and profit

It's monday, and I'm back from vacation, feeling like I'm wasting my time and inevitably falling victim to the great cycle of life, money and everything. while (42) { }. Fortunately, I have sweet, sweet sarcasm on my side.

Anyway, this post is supposed to be about dividing by zero.

In python, it's a great way to find if a certain code path deep inside your call stack is really getting called, and when. You get to write one line which results in a noisy exeption, so your pain and confusion is properly turned into a Traceback.

    class ReturnStatement(Statement):
        def __init__(self, returnee):
            1/0
            super(ReturnStatement, self).__init__(returnee, '<return>')

"Oh. This time the exception never fired. I was sure this was supposed to be executed."

That's the kind of thought you are supposed to get, or something among the lines of:

"There, the exception.. Then why is this @!$# method not working if it's being called?"

Anyway, you get a good troubleshooting test just for typing three characters and a new line. Good bargain!

Of course, in JavaScript it's useless.

Yields Infinity. That's a discussion for another point in time. Maybe. I may never be inclined again to speak of that matter. Hours and hours of agony because of a number having a completely unpredictable number. Ugh.

In compiled languages, it's mostly useless, too.

Mondays.

Wednesday 7 November 2012

Valilang

I have started a new project. Its name is valilang.

Create validation rules in a single format, meant to be used in both client and server sides.

Although I have given up my first plan of making valilang a minimal imperative programming language, the name still has the suffix "lang". I have opted to base the language syntax upon JSON, so it will be easier to learn and use.

The format is very easy to write. There are :

  • fields, which correspond to form fields, and
  • rules, which are (mostly premade) short functions taking a value argument and doing an assertion upon that value.

A valilang file will have an object with these keys:

  • fields, a list of fields.
  • fieldValidation, an object mapping field names to a list of rules applied sequentially to these fields.

Here is an example valilang file, for a form with a single field:

    {
        "fields": ["name"],
        "fieldValidation": {
            "name": [
                "required",
                "min-10",
                "max-50"
            ]
        }
    }

In the above object, we can see we have a single field name which has the following rules:

  • It's a required field
  • It takes at least ten characters (min-10)
  • and at most 50 characters (max-50).

These rules (which are actually functions) are executed sequentially, until any function returns null, in which case the validation fails.

Notice how arguments are handled. They are extracted from after the dash in each of the rule strings, provided these strings have a dash.

On the client side, you just have to include a valilang file and valilang.js.

    <script type="text/x-valilang">
        {
            "fields": ["name"],
            "fieldValidation": {
                "name": [
                    "required",
                    "min-10",
                    "max-50"
                ]
            }
        }
    </script>
    <script type="text/javascript" src="valilang.js"></script>

On the server side, you will load the valilang library for your framework or language, and ask it to validate your fields.

Of course this is all when both the client side and the server side are implemented. Remote loading of scripts is not yet supported. The server side hasn't been prepared for any language except for javascript (by requireing valilang.js in node and using its API), and there are too few validators (validation functions). Also unit testing is not done for the client or the server.

However, valilang.js is definitely compact, under 5 kb minified, and it is in a nearly usable state. Care to try it out and maybe contribute to its development? Report bugs and fork the github repository.

AAAAAAAAAA

A AAAA AAAAAA AA AAAA AAAA AAA AAAAAAAAAAAAAA.

    >>> def AAAAAAAAAA(s):
    ...     import re
    ...     return re.sub('\w', 'A', s)
    ...
    >>> AAAAAAAAAA('I want to know what Guido eats for breakfast.')
    'A AAAA AA AAAA AAAA AAAAA AAAA AAA AAAAAAAAA.'
    >>> AAAAAAAAAA("I have found a new way to encode messages. But it's irreversible.")

    "A AAAA AAAAA A AAA AAA AA AAAAAA AAAAAAAA. AAA AA'A AAAAAAAAAAAA."
    >>> AAAAAAAAAA("You have a way with words.")
    'AAA AAAA A AAA AAAA AAAAA.'
    >>>

AAAAA AA AAA AA AAAAAAAAAAAAAA AAAA.

And a thousand pointless points are given to whoever decodes this post.

Tuesday 6 November 2012

Periodic table of HTML5 elements

A very interesting and helpful link from Josh Duck:

http://joshduck.com/periodic-table.html

It contains all HTML5 elements, formatted in a table that looks much like the Periodic Table of the Elements. It is very nice and informative to look at all of them, grouped into categories.

Find out a couple of new elements, and use it as reference, since every element in the table has links to helpful documentation on MDN and the formal declaration in W3C when you click them.

The little form on top lets you count elements used in any published website. Detect divitis!

Monday 5 November 2012

Practical example of str.split's optional argument. Config file parser

Taking my little fun discovery for a ride. Used it to create a simple config file reader together with itertools.

    >>> lines = iter(open('config.cfg'))
    >>> import itertools
    >>> splitonce = lambda s:s.split('=',1)
    >>> trim = lambda s:s.rstrip('\n\r')
    >>> trimmed_lines_generator = itertools.imap(trim, lines)
    >>> split_lines_generator = itertools.imap(splitonce, trimmed_lines_generator)
    >>> settings = dict(split_lines_generator)
    >>> settings
    {'ConfigSetting3': '  Allow leading+trailing spaces!   ', 'eqsign': '=', 'ConfigItem2': 'Settle for no "=" signs!', 'Con
    figItem1': 'Configured'}
    >>>

This of course wouldn't work if I hadn't applied the optional argument to str.split, which I talked about in my previous post. It helps me split the file lines into keys and values by the equal sign, and not worry that the values might include equal signs of their own.

I am getting ahead of myself. In case you are not familiar with CFG files, here is the file I used in the above example. The settings file config.cfg:

    ConfigItem1=Configured
    ConfigItem2=Settle for no "=" signs!
    eqsign==
    ConfigSetting3=  Allow leading+trailing spaces!

Stripped out of the interpreter into cleaner code:

    from itertools import imap

    with open('config.cfg') as fp:
        lines = iter(fp)
        def splitonce(s):
            return s.split('=', 1) # split limit
        def trim(s):
            return s.rtrim('\n\r')

        trimmed_lines_generator = imap(trim, lines)
        split_lines_generator = imap(splitonce,
            trimmed_lines_generator)

        settings = dict(split_lines_generator)

I have used itertools.imap. Using iterators and chaining them together will make larger config files use less memory than if I used list(fp) to get a list of lines. This of course is more of a concern in larger config files.

Saturday 3 November 2012

Timetable selection snippet.

I have put together a simple timetable snippet for helping keep track of time, or to do time allocation of some resource.

Check it out on jsfiddle:

This is a jQuery plugin. It works by converting a table with checkboxes inside each td into a time planner. It does this by moving the checkboxes away from their td containers into a div inserted below the table.

Here is that DIV's HTML. As you can see it has all the checkboxes from every cell.

    <div style="display: none;" class="timeplanner-checkbox-dump">
        <input type="checkbox" checked="checked" name="0-0">
        <input type="checkbox" name="1-0">
        <input type="checkbox" name="2-0">
        <input type="checkbox" che...

Then it routes the events of each td into its containee checkbox. This is done by using an annonymous function for each td. In a jQuery.each loop I declare var checkbox_here, (so it is different for every closure) and then just do $(checkbox_here)-click() in the click event handler for the td.

Python's string formatting syntax

As you are surely aware of, you can use python's % operator to do string formatting. It's part of the reasons why the language is so good at text processing.

The left operand is the format string, the right operand is a single format argument, or an iterable of format arguments. In the format string, you can use %s to insert a string, %d to insert an integer, %f for a float, etc. It's much like C's printf family of functions.

    >>> '%s %d' % ('a string', 123)
    'a string 123'

This you almost surely know. You might not know that the string can take a %r argument which calls repr on the arguments. Now that's useful!

    >>> 'a repr: %r' % ['', ""]
    "a repr: ['', '']"
    >>> 

Or that the format parameters can be in a dictionary.

    >>> '%(a_string)s %(an_int)d' % {'a_string':'a string', 'an_int': 123}
    'a string 123'
    >>> 

If the parameters were passed as a dictionary, the format string will not raise exceptions for extra parameters. So you can use locals() on your (trusted) format string, and format it easily. In a class method, self.__dict__ would also be useful.

    >>> a_number = 3
    >>> '%(a_number)d' % locals()
    '3'

String formatting parameters will also take their own parameters. The parameters are decimal characters (and an optional separation dot) between the % sign and the character indicating the type.

Here is an ugly syntax representation. Bear with me.

% [0|-][leading/trailing character count][An optional dot][Truncation](Type character)

That's all, I think. Be careful to add no spaces. The only characters allowed between % and the type indicator are [0-9\.\-]

  • First, the usual percentage sign.

  • Then, add a single zero if you want to fill the string with zeroes (you specify how many characters you would like to fill the string with in the next argument). If you want the string to have trailing spaces instead of leading spaces, add a minus sign.

  • After that, add the number of characters you want to fill the string with. You can skip this.

  • If you want to use the truncation argument (explained below), add a dot here.

  • Add the truncation argument, which is an integer.

For obvious reasons, you can't have trailing zeroes in anything.

The "Truncation" argument is used to left-truncate a string to that size, to grow (only grow) an integer string by zero-filling the left to that size, or to use that many decimal digits in a float.

Here are some examples with %s. %s doesn't let you put leading zeroes on your string. You can use str.zfill() for that.

    >>> s = '1234'
    >>> '%.1s' % s
    '1'
    >>> '%.4s' % s
    '1234'
    >>> '%.6s' % s
    '1234'
    >>> '%10s' % s
    '      1234'
    >>> '%10.2s' % s
    '        12'
    >>> '%10.4s' % s
    '      1234'
    >>> '%10.6s' % s
    '      1234'

%f examples:

    >>> f = 10.123
    >>> '%f' % f
    '10.123000'
    >>> '%.4f' % f
    '10.1230'
    >>> '%4f' % f
    '10.123000'
    >>> '%20f' % f
    '           10.123000'
    >>> '%20.2f' % f
    '               10.12'
    >>> '%020.2f' % f
    '00000000000000010.12'
    >>> 

%d can also be told to have leading zeroes or leading spaces. As mentioned above the "Truncation" part of the parameter can only make it grow. It wouldn't make sense to let it shrink, since that would shrink the number's value.

    >>> i = 10
    >>> '%d' % i
    '10'
    >>> '%.1d' % i
    '10'
    >>> '%.4d' % i
    '0010'
    >>> '%4d' % i
    '  10'
    >>> '%4.1d' % i
    '  10'
    >>> '%4.3d' % i
    ' 010'
    >>> '%4d' % i
    '  10'
    >>> '%04d' % i
    '0010'
    >>> 

As you know, in python, characters are indeed strings with len() of 1, so if you want to represent a character you just use %s. But you can also use %c. %c will raise an exception if the input string is not a character, and the extra assertion might prove a little useful. You can add leading and trailing spaces to this parameter too.

Finally, it's worth something to note that python has a newer formatting syntax. I haven't seen it used much, and don't use it either. It's not so practical as the one I described.

More information on string formating can be found in the python documentation

This has hopefully been a thorough dissection of python's string formatting syntax. Now go out and enjoy the sun!