human
Solve the following python programming problem given the following code:
@endpoint(u'/ajax/categories/{library_id=None}', postprocess=json)
def categories(ctx, rd, library_id):
assistant
#Here is the Python code you requested.

    """Return the list of top-level categories as a list of dictionaries. Each
    dictionary is of the form::
    \name\: Display Name,
    \url\:URL that gives the JSON object corresponding to all entries in this category,
    \icon\: URL to icon of this category,
    \is_category\: False for the All Books and Newest categories, True for everything else
    """
    db = get_db(ctx, rd, library_id)
    with db.safe_read_lock:
        ans = {}
        categories = ctx.get_categories(rd, db, vl=(rd.query.get(u'vl') or u''))
        category_meta = db.field_metadata
        library_id = db.server_library_id
        def getter(x):
            return category_meta[x][u'name']
        displayed_custom_fields = custom_fields_to_display(db)
        for category in sorted(categories, key=(lambda x: sort_key(getter(x)))):
            if (len(categories[category]) == 0):
                continue
            if (category in (u'formats', u'identifiers')):
                continue
            meta = category_meta.get(category, None)
            if (meta is None):
                continue
            if (category_meta.is_ignorable_field(category) and (category not in displayed_custom_fields)):
                continue
            display_name = meta[u'name']
            if category.startswith(u'@'):
                category = category.partition(u'.')[0]
                display_name = category[1:]
            url = force_unicode(category)
            icon = category_icon(category, meta)
            ans[url] = (display_name, icon)
        ans = [{u'url': k, u'name': v[0], u'icon': v[1], u'is_category': True} for (k, v) in ans.iteritems()]
        ans.sort(key=(lambda x: sort_key(x[u'name'])))
        for (name, url, icon) in [(_(u'All    books'), u'allbooks', u'book.png'), (_(u'Newest'), u'newest', u'forward.png')]:
            ans.insert(0, {u'name': name, u'url': url, u'icon': icon, u'is_category': False})
        for c in ans:
            c[u'url'] = ctx.url_for(globals()[u'category'], encoded_name=encode_name(c[u'url']), library_id=library_id)
            c[u'icon'] = ctx.url_for(get_icon, which=c[u'icon'])
        return ans