Python - 2d Array's don't work.

22. February 2012 20:25

 

If you have been working with python you will notice that 2d array's just don't work. This might come as a surprise since almost every other modern programming language supports 2d array's. What might even come as a bigger surprise is that pythin doesn't support array's at all in its language. It uses lists to support this functionality. It might look like an array but it is actually a list.

 

This can be showen with the following. Note the error about the list.

 

 

arr = []
arr[0] = 1


Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

 

 

So once you stop thinking about trying to create and array in pythin (which is easy since they don't exist) and start thinking about creating a list of items things become much easyier to understand why your 2d arrays of arr = [][] just doesnt work. As you have just attempts to create 2 lists and set a variable with them.

 

So to create a single array list is easy and we can do so using the following code.

 

>>> arr = range(0,5)
>>> print arr
[0, 1, 2, 3, 4]

>>> arr[0] = 1
>>> print arr
[1, 1, 2, 3, 4]

 

 

I actually find this really ugly. Since we just created a list of incrementing number and the array still needs to be set to zero. So to create a real array preset to zero you need to use the following.

 

 

>>> arr = []
>>> for i in range(0, 5):
...  arr.append(0)
...
>>> print arr
[0, 0, 0, 0, 0]

 

 

So moving onto the 2d array and you do exactly the same thing. Except you create a list and put it in the list item. Like this

 

 

>>> arr = []
>>> for i in range(0, 5):
...  x = []
...  for j in range(0, 5):
...   x.append(0)
...  arr.append(x)
...
>>> print arr
[
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]

 

Now you can read / write to the items by using an array like syntax or arr[0][0] .. arr[4][4].

 

There is another alternative support to using 2d arrays in python by using a single list and then calulating the offsets. However for the particular problem I was trying to solve it really didn't help since python doesn't appear to support proper for loops either!

 

I guess thats what you get with python!

E-mail Kick it! DZone it! del.icio.us Permalink


C - get home dir location in linux

20. February 2012 08:00

 

This is a short example of how to get the home directory location in linux in a C program. There is really a few choices here and depending on what your requirements are you might want to use one or other methods. The first method can be changed by the user. The second method cannot. However if the first method fails you should drop faill back on the other method.

 

The simple method is to pull the enviroment variable "HOME"

 

The slightly more complex method is to read it from the system user database.

 

 

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>


int main(int argc, char **argv) {


        char *homedir = getenv("HOME");

        if (homedir != NULL) {
                printf("Home dir in enviroment");
                printf("%s\n", homedir);
        }

        uid_t uid = getuid();
        struct passwd *pw = getpwuid(uid);

        if (pw == NULL) {
                printf("Failed\n");
                exit(EXIT_FAILURE);
        }

        printf("%s\n", pw->pw_dir);

        return 0;
}

 

E-mail Kick it! DZone it! del.icio.us Permalink


C - ip address validation

17. February 2012 08:00

 

A short example to show how to check and ip address is actually an ip address in C. I have seen a number of time that people provide solution using reg'ex and various other methods to attempt to do this. However there is a standard function that will test for you.

 

The function is called inet_pton will be able to tell you if a string is acutally an ip address or not. Typically the function also has another use which is to convert an ip address into its network byte ordered integer format.

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <arpa/inet.h>

int main(int argc, char **argv) {
    unsigned long ip = 0;

    if (argc < 2) {
        printf("Usage: %s <ipv4>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    if (0 == inet_pton(AF_INET, argv[1], &ip)) {
        printf("Failed\n");
        exit(EXIT_FAILURE);
    }

    printf("IP: %ld\n", ip);
    return 0;
}

E-mail Kick it! DZone it! del.icio.us Permalink


C - Get current ip address of an interface

15. February 2012 08:00

 

This is a short example to retrive an ip address from an interface in linux. It is typically used to be able to bind a port to a specific address on a machine.

 

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

#include <arpa/inet.h>
#include <net/if.h>

#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>

int main(int argc, char **argv) {
    int sock = socket(PF_INET, SOCK_DGRAM, 0);
    struct ifreq req;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <interfacename>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    if (sock < 0) {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    memset(&req, 0, sizeof(req));
    strncpy(req.ifr_name, argv[1], IF_NAMESIZE - 1);

    if (ioctl(sock, SIOCGIFADDR, &req) < 0) {
        perror("ioctl");
        exit(EXIT_FAILURE);
    }

    printf("%s\n", inet_ntoa(((struct sockaddr_in *)&req.ifr_addr)->sin_addr));


    close(sock);

    exit(EXIT_SUCCESS);
    return 0;
}

 

E-mail Kick it! DZone it! del.icio.us Permalink


Read / Write a pid for a file in linux

13. February 2012 08:00

 

This is a short example to show you how to read and write a process id to a file in linux.

 

First the write.

 

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

int main(int argc, char **argv) {
    pid_t pid = getpid();

    if (argc < 2) {
        printf("Usage: %s <filename>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    FILE *fp = fopen(argv[1], "w");
    if (!fp) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }

    fprintf(fp, "%d\n", pid);

    fclose(fp);

    return EXIT_SUCCESS;
}

 

 

Then the read

 

 

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

int main(int argc, char **argv) {
    pid_t pid = 0;

    if (argc < 2) {
        printf("Usage: %s <filename>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    FILE *fp = fopen(argv[1], "r");
    if (!fp) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }

    if (fscanf(fp, "%d\n", &pid) == 1) {
        printf("PID: %d\n", pid);
    } else {
        printf("Failed to Read PID\n");
    }

    fclose(fp);

    return EXIT_SUCCESS;
}

 

E-mail Kick it! DZone it! del.icio.us Permalink