Limit String Length in Printf in C

I can’t believe how many times I forget this trick! so I am writing it down so I won’t forget it!

Normally when you use printf function with “%s” formatting to print a string (char *) you rely on C convention of terminating a string with a NULL character (i.e. value 0).

So if you want to print small part of longer string, you copy the part you need to a new buffer and terminate it will NULL.

A better way is to use printf format for string i.e. “%s” with a precision which indicates how many characters will be used:

char *s = "Hi my name is Rayed, nice to meet you!";
printf("Hello, %.5s!\n", s+14);

If the length is not known in advance you can provide it as an argument to printf too:

char *s = "Hi my name is Rayed, nice to meet you!";
printf("Hello, %.*s!\n", 5, s+14);

Notice the “%.*s” and the extra “5” argument.

Django: How to pass an url as parameter of include

In Django web applications I usually have a single template file for navigation or bread crumb that I include from other template files, it is easy and straight forward to pass parameter to the included template file, some thing like:

{% include "nav.html" with title="title" object=my_object %}

But it would be a little tricker to send a URL as a parameter, i.e. you can’t write it:

{# WRONG DOESN'T WORK #}
{% include "nav.html" with title="title" link={% url 'book_edit'%} %}

But luckily Django have a decent and elegant solution, you can use “url” template function with “as” parameter, which will not display but will store it in a variable that you can use later in the include function:

{% url 'some-url-name' arg arg2 as my_link %}
{% include "nav.html" with title="title" link=my_link %}

In fact you don’t need to send my_link as it going to be visible on the included file anyway, so this will work as expected:

{% url 'some-url-name' arg arg2 as my_link %}
{% include "nav.html" with title="title" %}

Django CRUD Parent/Child Edition

I’ve written before about implementing CRUD operations on a single table in Django, and the post was very popular on my blog and I hope many people learned something from it.

The next logical step is to write a CRUD application with Parent/Child relationship, the application is bit more verbose but it follow the same simple logic used in the first post.

In fact I didn’t write a single application, I wrote five stand alone applications that shows different ways to implement CRUD operations:

  • books_simple: Single table CRUD operations.
  • books_pc_formset: Parent/Child CRUD operation using Django formsets, which means editing the children in the sample form as the parent.
  • books_pc_formset2: similar to previous app but uses a foreign key in the children.
  • books_pc_multiview: Parent/Child CRUD operation using multiple one view for the parent and another seperate view for the children.
  • books_pc_multiview2: similar to previous app but uses a foreign key in the children.

You can find the code here:
https://github.com/rayed/django-crud-parent-child

Hope you find it useful, and please let me know if it needs any improvements.

اقتراحات لتفعيل خدمة لاسلكي الهواة

كتبت رسالة الى معالي الدكتور محمد السويل وزير الاتصالات باقتراحات لتفعيل خدمة لاسلكي الهواة او ما يعرف بـ “Amature Radio” او “Ham Radio” ردا على طلبه للعموم باقتراحات لتطوير خدمة الاتصالات في المملكة:
https://twitter.com/MIsuwaiel/status/580704446520291328
وفي ما يلي نصها، للتاريخ وكذلك كمرجع لي.


السلام عليكم ورحمة الله،

معالي الدكتور محمد السويل اكتب لكم بمقترحات لتشجيع خدمة لاسلكي الهواة في المملكة العربية السعودية.

قبل قرابة السنتين احببت ان اتعلم تقنيات اللاسلكي ولاسلكي الهواة لاكتشف عدة عوائق لاستخدام الخدمة في المملكة.

لكن قبل ان اخوض في العوائق، ساذكر بعض من فوائد لاسلكي الهواة التي قطعا لا تخفاكم:

  • نظام اتصالات كامل بدون بنية تحتية، ضروري جدا عند الازمات.
  • نظام اتصالات كحل وحيد في المناطق النائية.
  • حل لانقاذ الارواح في حال الضياع في المناطق المعزولة مثل الصحاري.
  • مقدمة ممتازة لانظمة الاتصالات اللاسلكية بشكل عام.
  • مقدمة ممتازة لهندسة الالكترونية.

العوائق الحالية واقتراحات حلها:

  • عدم وجود اي جمعية رسمية للاسلكي الهواة في المملكة، مما يحمل الهيئة عاتق الخدمة بشكل كامل (المقترح ان شاء جمعية رسمية وتكليفها ببعض المهام).
  • صعوبة الحصول على اجهزة الراديو، نظرا لاشتراط الحصول على ترخيص. (المقترح: السماح ببيع وشراء الجهاز واستخدامه للاستقبال بدون تصريح، ويلزم التصريح عند استخدامه للارسال فقط).
  • صعوبة الحصول على الترخيص:
    • معلومات محدودة جدا في موقع الهيئة (المقترح: زيادة المعلومات والتفصيل فيها).
    • عدم وجود مواد تعليمية وارشادية (المقترح: تكليف الجمعية ببناء دليل للخدمة، او ترجمة دليل من لغات اخرى).
    • مواعيد اختبارات قليلة، بمواعد غير واضحة.
  • رسوم كثيرة ومرتفعة:

    • رسوم عالية للاختبار (٣٠٠ ريال)
    • رسوم سنوية للرخصة (١٠٠ ريال)
    • رسوم سنوية لاستخدام الترددات (١٥٠ ريال)
    • المصدر: لائحة خدمة لاسلكي الهواة (ص. ١٠)
    • (المقترح: تخفيض رسوم الاختبار والغاء الرسوم السنوية)

مقارنة الرسوم مع دول اخرى:
Screen Shot 2015-08-30 at 11.22.14 AM

المصدر:
https://www.reddit.com/r/amateurradio/comments/31q39i/amateur_radio_fees_in_your_country/

ارجوا ان تلقى هذه الاقتراحات الاستحسان والقبول.

مع تحياتي،
رائد بن عبدالله الراشد

My first public Python Package “pyagentx”

I’ve just published my first public Python package “pyagentx”, the package will help you build “AgentX” agents to extend a master SNMP agent.

Let’s assume that you want to monitor your custom application from your Network Managment System (NMS), but the NMS only speak SNMP, this package allows you to extend the master SNMP agent to include your custom application metrics.

Project page on Github

Package page on Python Package Index

AgentX on Wikipedia

RFC 2741: Agent Extensibility (AgentX) Protocol

Django Image and File Field Caveats

Everytime I work with Image or File fields in Django I forget some tiny detail that waste 10-20 minutes until I remember what was I missing, I always say I will remeber it next time but I never do! so I made a list of common errors I keep doing while working with Image/File fields:

For complete working project: https://github.com/rayed/dj-imagefield-example

Setting MEDIA_URL and MEDIA_ROOT

Make sure you set proper values for MEDIA_URL and MEDIA_ROOT in your settings.py, e.g. I use the following structure:

my_new_site/
    apps/
       apps/
          settings.py
       gallery/
       blog/
    www/
       media/
       static/
    requirements.txt


I would put the following settings (for both MEDIA and STATIC files):

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '..','www','static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, '..','www','media')

Make sure uploaded files are accessible in development server

Serving uploaded files (media) is the job of the web server and not Django, but to ease the development process I usually make Django serve it in debug mode.

This is done by adding the following at the end of your main urls.py:

from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

HTML forms changes

Make sure you have enctype=”multipart/form-data” in your form tag, i.e.:

<form method="post" enctype="multipart/form-data">


Instead of:

<form method="post">

Don’t forget request.FILES

I always forget to include “request.FILES” in my ModelForms, and I always get “This field is required” error message!

def author_create(request, template_name='author/form.html'):
    form = ImageForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.save()
        return redirect('author:home')
    return render(request, template_name, {'form':form})    

ImageField requires Imaging library

If you want to use Django built in ImageField you have to install Pillow Imaging library! FileField doesn’t needed it though.

View the image

Just a reminder that you can access the image URL in your template like so:

<img src="{{ author.image.url }}"  />