Coding Page

From Computer Science Wiki

Jump to: navigation, search

Seems like a wiki might work to let us collect community experience in coding; the good and the bad. As of 10/24/09 this page will also include basics, like templates for MPIS files.

Contents

[edit] C

  • && for & (further exp. see Oldham)
 hiByte = word & 0xFF000000;      # ex) the intended code to extract high order byte, bitwise & intended
 hiByte = word && 0xFF000000;     # ex) perfectly legal, but hiByte is 0 or 1 -- && is logical
  • Separate Compilation in C (further exp. see Oldham) Avoid #include of .c files except possibly when using tools like lex and yacc -- generators that require it. Although you can get by more simply, here is a pretty standard approach illustrated with very small files. driver.c holds a main(), which will call function strtime() defined in utils.c. Function strtime() is declared in utils.h, which is included in both driver.c and utils.c. (Like I said, you can do it more simply, but as files grow this is pretty standard stuff.)
 CALL here                   | DECLARATION here     | DEFINITION here
 /* begin driver.c */        | /* begin utils.h */  | /* begin utils.c */
 #include<stdio.h>           | #ifndef _UTILS_H_    | #include"utils.h"
 #include"utils.h"           | #define _UTILS_H_    | char *timestr() {
 int main( void ) {          | #include<time.h>     |     time_t now;
     char *now = timestr();  | char *timestr();     |     time( &now );
     printf( "%s", now );    | #endif               |     return asctime( localtime( &now ) );
     return 0;               | /* end utils.h */    | }
 }                           |                      | /* end utils.c */
 /* end driver.c */          |                      |
Notes:
  1. Compiles like this: gcc -o demo driver.c utils.c
  2. "compilation" includes linking -- no need for any "import" statement
  3. If you want to compile utils.c without driver.c then use gcc -c utils.c to get utils.o. If you use gcc utils.c then when ld tries to link it will find no main(), which is the entry point for the code. That is a link error. To have an executable you have to have main().
  • Tokenizing a line of text in C (Further info see Joe) The strtok function (see string.h) is old, arguably poorly designed, error prone, and warned against on its own man page. However, for non-critical (academic?) purposes it is darned convenient to take apart a piece of text. Here is an example. See the man page.
 #include<stdio.h>
 #include<string.h>
 int main( int argc, char **argv ) {
     char *buffer = (char *)malloc( 128 );
     char *nxt = NULL;
     fgets( buffer, 128, stdin );
     buffer[ strlen(buffer)-1] = 0;
     printf( "buffer before: [%s]\n", buffer );
     nxt = strtok( buffer, " \t\n" );
     printf( "buffer after: [%s]\n", buffer );
     while ( nxt != NULL ) {
         printf( "[%s]\n", nxt );
         nxt = strtok( NULL, " \t\n" );
     }
 }
Here is a sample execution of the above strtok code. The first line is the input:
 Centre College          CSC demo
 buffer before: [Centre College          CSC demo]
 buffer after: [Centre]
 [Centre]
 [College]
 [CSC]
 [demo]

[edit] Java

  • If you want to include a backslash (\) in a string, you always have to escape it with another backslash because its a special character. I always end up forgetting this and it causes me problems.
  String path = "C:\\Documents and Settings\\Jackie";      //a valid Windows pathname; using single \'s would cause problems


[edit] MIPS assembler (with MARS simulator)

Note that the Patterson & Hennessey text used in CSC 221 refers to the SPIM simulator. We prefer the MARS simulator available here. SPIM and MARS can differ on occasion. Comments here should pertain to MARS.

  • Here is a template for a basic MIPS file suitable to run under MARS:
# Author ???@centre.edu
#  
#-----------------------------------------------
	.data				# begin data segement with .data	



	.text				# begin text (instructions) segment
	.globl main			# main is global (globl)

main:					# begin execution here
	

	li		$v0	10		# specify exit function
	syscall				# syscall to exit
  • If you want to allocate uninitialized space, use the .space directive. For example
 unint:      .space      4         # alocate 4 bytes (.word) uninitialized

[edit] Python

[edit] Zelle graphics.py

  • To install the Zelle module graphics.py so that you do not need it in your working folder you need to figure out where python is installed and find the site-packages folder. Put graphics.py there. XX is a place holder for the python version, e.g. Python25 for python 2.5 in spring 208.
    • In Windows that should be something like C:\pythonXX\Lib\site-packages
    • In OS X that should be your machine name/Library/Frameworks/Python.framework/Versions/Current/lib/pythonXX/site-packages

[edit] Loop and List Trap

  • When you use a for-loop to iterate through a list by value ("for item in myList"), you cannot change the list by assigning a new value to the "item" variable. If you want to change the value in the list, you have to do it by index.
  for item in myList:      #myList is not changed; item is only a value, not a pointer to the place in the list
      item = item+1
  for index in range(len(myList)):     #this does change myList
      myList[index] = myList[index]+1

[edit] More advanced

You can use the map function to change each element in a list.

  myList = map(lambda x: x+1, myList)


  #suppose you're looking for the first element of a list 
  #for which the isUnicorn function returns True
  #a very efficient way of doing this would be:
  from itertools import ifilter
  unicorns = ifilter(isUnicorn, myList)
  unicorn  = unicorns.next()

The itertools library (included with Python in version 2.3 and later) is an interesting place to poke around to find interesting things to learn.

[edit] PHP/PostgreSQL

[edit] References

  • Wikipedia article on anti-patterns – perhaps more useful as a glossary or reference work than just for reading and self-improvement, but there's some useful knowledge there
Personal tools