tags:

views:

528

answers:

12

I'm not talking about huge project but short little pieces of code you'd be willing to post. I'm just interested to see what quick little things other people come up with. For me, my favorite is this one. It is in C.

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

FILE* getFile(char* prompt, char* fileType)
{
   char* name = malloc(256*sizeof(char));
   printf("%s\t", prompt);
   scanf("%256s", name);
   FILE* file = fopen(name, fileType);
   free(name);//this solves the memory leak doesn't it?
   return (file == NULL) ? getFile(prompt, fileType) : file;
}
void encrypt(FILE* enc, FILE* key, FILE* ofs)
{
   printf("beginning file encryption\n");
   char c, k;
   while(!feof(enc))
   {            
      if(feof(key))rewind(key);
      c = getc(enc);
      k = getc(key);
      int put = (int)(c ^ k);
      putc(put, ofs);   
   }
   printf("\nencryption completed\n");
}
int main()
{
   FILE* enc = getFile("Input file to encrypt/decrypt:", "rb");
   FILE* key = getFile("Input file to use as encryption key:", "rb");
   FILE* ofs = getFile("Input location to output encrypted file:", "wb+");
   encrypt(enc, key, ofs);
   getchar();//clears buffer
   printf("press any key to exit");
   getchar();
   return 0;
}

The idea was to encrypt one file using another file in such a way that the method used for encryption could also be used for decryption.

I was hoping other people would post some of there pet code and explain what it does.

+1  A: 

I am ocasionally proud of my work, but it's usually part of a big project, not small things.

In the end, having one GREAT piece of code and lots of bad code is not as good as having some GOOD pieces of code and almost no bad code.(at least, in my opinion. It obviously depends on how great/good/bad the code is)

luiscubal
I totally agree with this but some code just stands out to me. Sometimes a snippet of code feels special. It isn't necessarily even great code, like my above code isn't that good I just feel partial towards it.
faceless1_14
+1  A: 

Any time I write a piece that works in future projects without modification I get that proud parent feeling.

Mike Robinson
+1  A: 

This is a joke i coded for Windows when i was going to school: this was to fool the professor he got a virus ;) It basically scroll the screen as a showreel. Not particularly proud of it, but it's funny to see people's reactions when you schedule it once a day (removing the dialog, of course).

.486P
locals
jumps

.Model Flat, StdCall

include windows.inc

Extrn   GetTickCount:PROC
Extrn   ExitProcess:PROC
Extrn   Sleep:PROC
Extrn   GetSystemMetrics:PROC
Extrn   MessageBoxA:PROC
Extrn   GetDC:PROC
Extrn   CreateCompatibleDC:PROC
Extrn   CreateCompatibleBitmap:PROC
Extrn   SelectObject:PROC
Extrn   BitBlt:PROC
Extrn   ReleaseDC:PROC
Extrn   DeleteDC:PROC
Extrn   DeleteObject:PROC


.data

fCapt db  'Thats-a-joke',0
fText db  'See it!', 0


dwHeight dd ?
dwWidth dd ?
dwWinDC dd ?
dwMemDC dd ?
dwBitmap dd ?
dwCount dd ?
dwTemp dd ?

.code


main:

Call MessageBoxA, 0, offset fText, offset fCapt, 0

Call GetSystemMetrics, SM_CXSCREEN
mov dwWidth, eax
Call GetSystemMetrics, SM_CYSCREEN
mov dwHeight, eax

Call GetDC, 0
mov dwWinDC, eax

Call CreateCompatibleDC, eax
mov dwMemDC, eax

Call CreateCompatibleBitmap, dwWinDC, dwWidth, dwHeight
mov dwBitmap, eax

Call SelectObject, dwMemDC, dwBitmap

Call BitBlt, dwMemDC, 0, 0, dwWidth, dwHeight, dwWinDC, 0, 0, 00CC0020h  ; SRCCOPY

mov dwCount, 0

; switch X-pixels
mywhile:
mov eax, dwWidth
sub eax, dwCount
mov dwTemp, eax

Call BitBlt, dwWinDC, 0, 0, dwTemp, dwHeight, dwMemDC, dwCount, 0, 00CC0020h
Call BitBlt, dwWinDC, dwTemp, 0, dwCount, dwHeight, dwMemDC, 0, 0, 00CC0020h

Call Sleep, 1
add dwCount, 1

mov eax, dwWidth
add eax, 1
cmp dwCount, eax
jne mywhile

Call ReleaseDC, 0, dwWinDC
Call DeleteDC, dwMemDC
Call DeleteObject, dwBitmap


jmp endprog



endprog:
 call ExitProcess,0

end main
Manuel
+2  A: 

I remember one time I wrote this ginormous pipe involving sed, awk, grep, find and xargs. It hit about 10 or 12 pipe symbols and I thought "this doesn't have a hope in hell of working", but it did. That's when I decided I'd reached Unix nirvana.

I was kind of sad when I switched my news server from tradspool to CFNS, because it made my ginormous pipe obsolete.

Paul Tomblin
+3  A: 
Dmitri Nesteruk
+6  A: 

Once I wrote a program for the Intensive Care Unit at Addenbrooke's Hospital, Cambridge, UK.
It printed out labels with patients' names and numbers to go on little blood-sample containers which were sent to labs for testing.
It wasn't amazing or anything, but I am still proud of it because it made a real (albeit small) difference in looking after people who were very ill.

a few facts

  • Date: 1990
  • Language: Borland Turbo C
  • Hardware: Early PC clone and Epson dot-matrix printer
  • Number of installations: 2
  • Number of users: about ~20
AJ
+1  A: 

I once wrote a Mandelbrot set "browser" in QBASIC. It used the mouse to let the user select a quadrant of the image to zoom in on. No images were cached; it was all rendered on-demand. I was working on adding a "zoom out" feature to it when other tasks caused me to put it on hold.

The program was slow as heck (on my 400 MHz laptop running NT 4.0), but it worked and looked nice! The code has likely since been lost to the ether, I'm afraid.

Brian
+2  A: 
RoadWarrior
Well, it's certainly not completely random, but that's rather the point, isn't it? It is, on the other hand, completely clever. :)
Adam Bellaire
A: 

Jon Skeet once wrote a program that would reboot the world in one sitting while petting his pet piranha with the other hand. And that was just before dinner. Luckily the piranha bit him and he mistyped and the code never compiled.

Later the piranha died of electronic poisoning (Only Jon Skeet knows what that is).

Cyril Gupta
+1  A: 

I wrote like six years ago a bash script that took all my MP3's decoded them into wav, normalized them, encoded them back to MP3 with a 128 bitrate (yeah, MP3 players had like 64MBs of memory back then) and downloaded/asked author, title and all that stuff, showing a pretty fancy SCP like progress bars. Now I wonder where that little guy is at :(

Ubersoldat
A: 

My first time ever playing with Perl was writing a small utility that extracted records from an Excel file and used them to build a PL/SQL script. It saved me a ton of time as it replaced manually updating each record in the schema. Funny thing is that it was my first time ever touching Perl and I loved it. Sadly, I never touched since then (it's on my to-do list though). Here's the code:

#!/usr/bin/perl
 use strict;
 use Win32::OLE qw(in with);
 $Win32::OLE::Warn = 3;
 # get already active Excel application or open new
 my $Excel = Win32::OLE->GetActiveObject('Excel.Application')
 || Win32::OLE->new('Excel.Application', 'Quit'); 
 # open Excel file
 my $Book = $Excel->Workbooks->Open("c:/patients.xls"); 
 my $Sheet = $Book->Worksheets(1);
 my $sql_string = "BEGIN";
 my $count = 0;
 my $rowNum = 2;
 while ($Sheet->Cells($rowNum, 1)->Value ne ''){
my $convert_string = 'convert_crf_version(\'osmgr\', \'patient\', \'form\', 0, \'versions\');';
# skip empty cells
next unless defined $Sheet->Cells($rowNum,1)->{'Value'};
my $patient_os_id = $Sheet->Cells($rowNum, 1)->{'Value'};
my $form = $Sheet->Cells($rowNum, 2)->{'Value'};
$form =~ s/^\s+//;
$form =~ s/\s+$//;
my $procstep_id = get_procstep_id($form);
printf "\nFor patient $patient_os_id, Form is $form and procstep_id is $procstep_id\n";
my $version_name = $Sheet->Cells($rowNum, 3)->{'Value'};
my $version = get_version($version_name); 
$convert_string =~ s/patient/$patient_os_id/;
$convert_string =~ s/form/$procstep_id/;
$convert_string =~ s/versions/$version/;
$sql_string = $sql_string . "\n" . "--" . $patient_os_id . "\n" . $convert_string;
$count++;
$rowNum++;
 }
 $sql_string = $sql_string . "\nEND;" . "\n\/";
 open FILE, ">", "convert_patients.plsql" or die "Can't open or create the file      convert_patients.plsql: $!\n";
 print FILE $sql_string; 
 printf "Conversion successful and resulting file is: convert_patients.plsql.";
 printf "\n$count patient records converted.";
 close FILE;
 # close the excel file;
 $Book->Close;

 ############################################################
 # Method: get_procstep_id #
 # Objective: returns the procstep_id that corresponds to the form name #
 # Arguments: $form: form name to get the procstep_id for #
 # Returns: the procstep_id that corresponds to the form name #
 #############################################################

 sub get_procstep_id {
my $form = shift;
my $procstep_id;
if ($form eq 'Baseline'){
 $procstep_id = '2767';
}elsif ($form eq 'Index Procedure'){
 $procstep_id = '2768';
}elsif ($form eq 'Discharge'){
 $procstep_id = '2769';
}elsif ($form eq '30 Day Follow-Up'){
 $procstep_id = '2770';
}
return $procstep_id;
 }

 ############################################################
 # Method: get_version #
 # Objective: returns the version 'label' that corresponds to the version name #
 # Arguments: $version_name: version name to get the version 'label' for #
 # Returns: the version label that corresponds to the version name #
 #############################################################

 sub get_version {
my $version_name = shift;
my $version;
if ($version_name eq '1'){
 $version = '1b';
}elsif ($version_name eq '2'){
 $version = '2a';
}
return $version;
 }

It's obvious a Perl newbie wrote it but it's code I'm proud of :)

Zabbala
+1  A: 

Snake game on my first month in a programming course. :D I was refreshing the screen every second but I didn't know about timers or thread sleeping so I wrote an empty "for" loop to do the waiting. Of course this code was cpu bound.

Later I ran it in on a much more powerful computer. I could barely see the snake move. :(

10 ms after the start of the game, you would lose. So think fast.

Your first mistakes are the one you laugh the more about... if you've learned from them. ;)

Silence
ha that sounds like a fun game of snake right there. Snake is actually rather challenging at least it feels like it would be. Thats pretty impressive.
faceless1_14