CISC 3110 Lecuture 7 Notes: Review and Exception Handling

We began by discussing headers from last class.

When we make a change to a function, we need to recompile, change the header file, and recompile the program that uses the library again.

When compiling, g++ will generally clean up the object file. To avoid this, we use the -c argument (c stands for compile only). For example:

vc13:berman_moshe> g++ mySourceFile.cpp -o

This will produce mySourceFile.o.
You can redirect the output of g++ into a text file to see the entire preprocessed source. To do so:

vc13:berman_moshe> g++ -E mySourceFile.cpp > junk

Now, our entire expanded source file, with the include statements replaced, will be inside of a file called junk. By the way, -E tells g++ to preprocess the file, but not compile it. We can use another program, called wc to count the number of lines.

Another thing we can do is use the vertical bar, the pipe symbol [|], to send the output of one program, to the input of another program. We could pipe the output of g++ to wc like so:

vc13:berman_moshe> g++ -E mySource.cpp | wc

This will count the number of words in the file.

We can use a Unix program called sort in a similar fashion:

vc13:berman_moshe> ls -l | sort

You can do the same with cat.

vc13:berman_moshe> cat mySource.cpp | sort

This outputs the source file, with the lines sorted in order.

There’s also grep, which allows us to search for patterns in a file. Professor Weiss’ example:

vc13:student_weiss> g++ -E test.cpp | grep cout

This will show us all of the occurrences of cout in our file.

There is a unix command to read a file. There’s a unix command to sort a file. We can use another unix command to count duplicates. In about four or five piped commands, you get a sorted, counted, zip code file. Sweet.

A programmer is a McGyver. You want to use the tools at your disposal no matter what.

Professor Weiss is talking about recursive code. He told an amusing a story about the time he tried to make a computer blow up by writing a recursive program. Of course the mainframe was smarter than that and shut down after 30 seconds of CPU time.

Demo…

self_includer.h:1:27: #includes are nested too deeply.

Think about how to have a function call itself without running into infinite loops.

Datatypes are only there for the compiler to know things about your variable, such as size. The notion of a class does not go into a compiled program. It’s only there for the compiler. At runtime, C++ has no data types. You trust the compiler to generate the proper code. Professor Weiss gave a long description of this, but now we’re writing a min function.

We’re using basketball scores, in pairs.

We initially tried to use a ternary operators:

int min(int x, int y){
  return x>y ? y : x;
}

This won’t work if the values are equal. So, we modify it like so:

int main(int x, int y){
  if(x

We still don't have a way to handle equal values though. The correct way to handle this is with a flag. The next iteration of our function looks like this:

int min(int x, into, bool &isCorrupt){
  if(x==y){isCorrupt = isTrue; return;}
  return x>y ? y : x;
}

To use this code:

bool isCorrupt;
int result = min(team1,team2,isCorrupt);
if(isCorrupt)
  cout << "Corrupt";
else
  cout << "Loser: " << result;

There are other was of doing this as well. The function can return a bool and the lowest score will have the reference parameter. The function header looks like this:

bool min(int x, int y, bool &lowest);

This is like eating soup before the main course, or the main before the soup. Yet another way to do this is as follows:

void min(int x, int y, int &lowest, bool &isCorrupt);

There's no penalty for adding parameters, and it's not a good idea to play favorites.

CISC3110 Lecture 6 Notes: The Compilation Process and Separate Compilation

Intro:

Professor Weiss recalls the first lecture.

Welcome to CISC3110. Be prepared to work your butts off

The readings for the PAC lecture is live. Long – but live. (No long live the king jokes, please.)

There are a few ways to display contents of a file. `cat` is one of them. A religion war in programming (like family, politics, and religion) is something that you;re never going to convince someone else about. Today, we learn a new term: module. We want to take our code, and reuse it, without using those copy functions, like cat.

History:

Machine language is a binary string of 0s and 1s that operates on the machines. If you read Asimov, and Goldberg, programmers were treated like a Gd of sorts. Indeed, early programmers, Turing and Von Neumann were heavy mathematicians. Early programming was error prone and tedious process. People spent most of their time thinking about the structure of the machine. You would look at a payroll program and a navigation program, and they’d all look the same. The goal of todays modern languages is to bring our expression of the program away from the machine and closer to solving the problem. This has an additional advantage that when I run my code on another machine, the program doesn’t need to change. (In theory. Different platforms reintroduce this problem.)

Two early languages are Fortran for science programmers, and COBOL, and business programmers. Reading a COBOL program read more like reading business logic. COBOL never quite realized the dream of having business managers understanding the code.

Early programs were often similar. Code became repetitive. People would use the same code over and over again. There would be decks of “array function” card. It didn’t always work, and what if two people wanted the same deck of code at the same time. Also, a human can’t keep track of so much code without a sort of organization.

Anecdote: Professor Weiss was consulting for an ATM company, working on over a million of code. On the express bus, he had an epiphany. He says it was tempting to go back and fix the bug, but he didn’t.

Terms and Background Facts:

Library, Module: Both terms refer to the files containing reusable code.

An integer  is 4 bytes.

A double is 8 bytes

A double is more complicated than an integer, when examined in binary form, because it’s expressed as scientific notation. (The earth is 92 million miles from the sun.) Original PCs didn’t support floating point numbers.

Integers are almost a natural representation, especially for the positive numbers. Double, on the other hand was developed by IEEE who developed a representation which makes sense to show numbers which contain fractions. “Someone from Mars might recognize the binary system.” (I love how people make assertions about Martians.)

Casting tells the compiler to actually insert code to convert a variable from its original type to the new type. There is no magic.

I heard the word algorithm being used on the radio the other day. Algorithm is the sexiest word in the English language, nowadays. Everyone thinks that if they know how to spell algorithm, they’re going to become millionaires.
-Professor Weiss

Consider the following:

z = x + y;

How do we know what x and y are? We declare them.

int z;
double x,y;

The compile has to know how to generate the code. Four byte? Eight byte? Conversion operators before using the double? But – there’s another reason. Suppose I wrote z = x/y and z and y were strings. You can’t divide strings.

The only difference between magic and technology is the amount of science you know.
- Richard Feynman

The compile checks your code for legality and generates code. There are languages that don’t have declarations, and things blow up at runtime. The navigation system will go down while the plane is in the air. The screen will go blank and the pilot who has is feet up and is drinking a coffee will have to actually fly the plane and earn his money.

 

How It Works – Function :

f1();    //
f2();    //  Declarations
f3();    //

void main(){

}

int f1(int, int){
//...
}

int f2(){
//...
}

int f3(){
//...
}

When I declare function, I state the existence of a function. Definition is where I actually say what the function is.

Consider this example:

void f1(int y);

int main(){
  int x = f1(15);  //Generates an error
}

This causes an error, because f1 doesn’t return an integer. C compilers used the honor system, but this caused problems, because this allows for simple programmer error. If you don’t test a program, it crashes. At runtime, the plane crashes.

A function header is only there for the compile to be able to check your code. It’s like driving without a seatbelt. Usually, you’ll get there, but occasionally you won’t and it’s very bad when that happens.

Professor Weiss is splitting up his array file into a separate file now.

Now, when we used cout on the very first day, where did it come from? When we wrote .close(), .substr(), .length(), and .exit(), they came from libraries.

Why would people buy my software over someone else’s system? Either it’s cheaper, or it’s better. Compare a bubble sort with a priority queue sort. If I sell you code, how do I give it to you without giving you the source code?

When I compile my code, I’m not necessarily compiling an entire program. What a compiler creates is a object file. On Windows, the file ends with a “.obj”. On Unix and GNU based programs, you get a .o file. On Windows, the “.obj” is a “file extension”. On Unix, the “.o” is called a “file suffix”.

Libraries help people collaborate by letting different developers write and compile just their portion of a larger program without waiting for everyone else.

Whenever you compile a program without including the proper header, theoretically, there will be holes in your program. The compiler makes “reference” to that function. There’s a table of references in the object file. There’s also a table of definitions.

Now, I have all the object files and I want to put them together. I look through all of the files and collect the references and definitions, and see what files have what functions and which ones are just references. The program that does this is called a “linker” or “link editor”. If there’s a function in the reference table that’s not the definitions table, there’s going to be an error.

So… When I sell you my library, I’m going to send you object code, instead of source code.

People who reverse engineer are stuck with object code, not nice variable names. It’s often possible to tell what compiler and language generated the code by looking at object code – but only if you’re a nine year old with nothing better to do. When you optimize code, you mix it up. This can mess with the “patterns” that reverse-engineers expect.

When you call a function that’s in another library, the compiler needs a way to know about it, before you call it.

Linkers don’t check the number of parameters, you’ll realize Columbus’ greatest fear; you’ll fall off the end of the world. To call functions in a library correctly, you need know how to call it. For that, we write this:

#include

By the way, you can do something similar with VIM using the command [:]+[r].

Apps. School. Life. Awesome.

The title of this blog is Apps. School. Life. Tonight I’d like to sum up my past week and tack on a fourth noun there. Awesome.

Just taking a moment out to be thankful to Gd for everything that’s going on. It’s been a whirlwind of a week, and I’d like to record some of it for myself, when I look back and read my own blog as I occasionally do (yea, I’m a sick narcissist). Those posts are are always fun to read. Well, lots of stuff going through the head of this second semester freshman.

I woke up today and stared up at my bookshelf. I saw the book “Algorithms in a Nutshell”. That’s when it occurred to me: Al Gore invented the internet. That’s why solutions to computer problems are called algorithms.

Today I had my first work day at my first internship. (Okay, getting acquainted, but yea.) That’s Tuesdays, Thursdays and Fridays. Tomorrow is Friday, so I’ll be in again. That’s been working out really well. I don’t want to talk about it on the internet, so that’s all that I’m writing about it. Suffice it to say, “awesome” sums it up.

What else did I do today?  Well, I woke up before seven o’clock for the first time in a while. That was a good deal. Tomorrow, I hope to be up even earlier, but I’m not sure how practical that is, given the current time (11:35PM). Ah well. The art of waking up early is hard to master and easy to forget. It’s just one of those things that make life a work in progress. As long as it’s being worked on.

I finally got around to renewing my iOS Developer program membership. I also enrolled in the Mac Developer Program (yes, largely because I want to play with the just-announced Mountain Lion). I’d like to port some of my apps to OS X (and, unrelated to the Mac Developer Program, perhaps Android).

I started on the CISC 3110 homework – which does indeed have a due date. (Thanks to the person who pointed that out, you know who you are.) In case anyone from the class does decide to read this, it’s not difficult, but TuringsCraft can be picky about exact spelling of the answers. It’s much more lenient with code, it’ll take anything correct that compiles. Based on my experience, word based answers need to match what they want to see.

Working backwards from today, Wednesday  I released iBrooklyn, my tool for Brooklyn College students. You can get it from the iTunes App Store here. I was really pleasantly surprised to see an email that went out from the CS department to some people who I’m glad got to see it. (Thanks, Professor!) Not sure if I was supposed to see it, but several people forwarded it to me. :-D

Monday was fun. I am quite embarrassed, as a New Yorker, to admit that I got lost in Macy’s for no less than 10 minutes on Monday night. The best part was asking British tourists where the exit was and they thought it was upstairs. They were wrong. It was straight behind them. I’m an idiot. (There was some really nice NYC Subway themed swag in the basement, but I’m sure it’s bloody expensive.)

Anywho, it’s late, and tomorrow is Friday. I can’t help but think that publishing part of my brain to the internet is stupid. My grandmother wouldn’t approve. Regardless, I’m about to hit publish because it’s late, and I must be insane. Have a great weekend, and see you all next week. Awesome.

CISC 3110 Lecture 5 Notes: Data Patterns

Professor Weiss begins by showing how to clean up swap files. In short:

rm .*swp

Now, he’s explaining what meta data is, specifically, in regards to a list of numbers. The “header” is metadata. To understand metadata, consider the following joke.

Three people walk into a bar. The bartender says, “What is this, a joke?”

The joke describes jokes. That’s meta. Now we’re discussing reading patterns.

In a data file, we have “records”, which contain “fields”. (Consider a table, each row is a record, each part of distinct information in the record is called a field).

Weiss Gerald 3.45 100
Arnow David

Now we’re discussing looping through the table, to read the data.

Note: You must use getline() for strings.

Pattern: Read Data File

for(int i=0;i> s.last;
  infile >> s.first;
  ...
  ...
}

Pattern: Header Value

//header value
infile >> numItems;
if(numItems > MAX_ARR_SIZE){
  // Fatal Error, blow up.
}
//... Fill the array as usual.

The pattern of reading is generally the same, regardless of whether you’re dealing with integers or classes, etc.

Pattern: Trailer Value
An alternative to header values is a trailer value. Pretend we were reading a list of grades.

  • 85
  • 76
  • 92
  • 47
  • -1

Question: Why use a trailer over a header?
Answer: You don’t need to know how many values or objects you have.

Question: Why not use a trailer over a header?
Answer: You can’t use a certain number once it’s set aside as a trailer.

So we’re going ahead with a trailer value. Before we loop, we need to read in our first value. Don’t simply ignore the value or set it to zero. It’s too easy to accidentally count the zero into your data or otherwise misuse the data.

Being inside of a while loop is like being inside a vault. If you’re not data, you don’t get in. So, we start by reading in a value:

int num;
infile >> num;

while(num != -1){
// ...
}

Then we need to process the data. If we don’t immediately process the data, we’ll skip the first value. The proper way to do this is as follows:

int num;
infile >> num;

while(num != -1){
// ... Process the data
infile >> num;
}

Suppose we don’t want to use a trailer value. What if we want to use end of file? Well, that’s essentially a trailer, but we don’t need to put that data into the file. The advantage of the end of file is obvious, there’s no need to limit yourself to not using your trailing value.

int num;
infile >> num;

while(infile){
// ... Process the data
infile >> num;
}

If we want to take an average, simply declare a count value outside of the loop, and increment it on each iteration.

int count = 0;
int num;
infile >> num;

while(infile){
count++;
// ... Process the data
infile >> num;
}

Processing Data
Now, we’re processing data. To process data, we’re going to assume, for our purposes, that each record is complete. We’re going to use a string as our trailer value.

int count = 0;
int num;
infile >> num;

Student students[MAX_ARR_SIZE];

infile >> s.last;

while(s.last != "****"){
  count++;
  // ... Process the data
  infile >> s.first;
  infile >> s.gpa;
  //...
  infile >> s.last;
}

You can’t put anything into an array until we know that we don’t have a trailer value, and until we know that we have enough space. Let’s use our integer example for now.

const int MAX_SIZE = 10; //some value
int count = 0;
int num;
int a[MAX_SIZE];
while(infile){
  if(count >= MAX_SIZE){
    cerr << "Array is too Small";     exit(1);   }  a[count] = num;  count++;  infile >> count;

}

Now we take this back to our Student class.

const int MAX_SIZE = 10; //some value
int count = 0;
Student s;
Student students[MAX_SIZE];

String last;
infile >> last;

while(last != "****"){
  if(count >= MAX_SIZE){
    cerr << "Array is too Small";     exit(1);   }   students[count].last = last;   //infile >> student[count].first ...
}

I don’t have too many years of my life left to start thinking of [variable] names.
- Professor Gerald Weiss

VIM Tip
To make a new window, use :split.
To close your new window, use [:]+[q]

Meanwhile, back on VC13…
Superman is working with input files now, discussing the spec. (Eh, boring.)
Batman: Give me the a grand tour of the source files.
Robin: Oooh, Batman, we’ll be doing searching, looking for *two* fields.
Batman:Meh, add function adds a new donor to our file… Print function… I can do that in my sleep – backwards.

Professor Weiss says, that for sanity’s sake we always want a donations file, even if there’s no donors.

Clever code doesn’t mean good code. Clever boys get eaten in fairy tales.

When you leave your job, you don’t want the next programmer to be in clever mode to have to understand what you did. – Professor Gerald Weiss

The rest of the class was spent going over boring spec details that were kinda useless. We’ll get to

c_str()

in about three weeks. We have to use it when passing a C++ string literal to open an ifstream.

“Pointers” is a dirty word in our class until further notice. Heh. Using c_str() is arbitrary, but necessary. It’s not intuitive. One of those weird things about C++. It’s a pattern.

Introducing iBrooklyn

 Introducing iBrooklyn.

An incredible tool for Brooklyn College students.

Free, for iPhone, iPad, and iPod touch.

I started Brooklyn College in Fall 2011. My first semester, was… interesting. (The mandatory learning communities were something else.) What I found frustrating, for the first few weeks, was finding my classes. Apple released the iOS 5 preview to developers just in time for me to get the notification center that everyone now has. I was able to show my classes in there, and all was well. But I still had this idea stuck in my head. The building letters are nonintuitive in some cases. (Case in point: Whitehead Hall is A.)  There are a zillion offices scattered throughout campus.What assignments do I have? While trying to juggle all of this information, an app was born.

iBrooklyn Features:

• List your classes, showing all classes, or only classes that you have today.
• Show classes on a map of the gorgeous campus.
• See building names and letter abbreviations.
• See all buildings, or only the ones which you have class in.
• Send Feedback from within the app to have features added to my to-do list! (And there are quite a few.)

Although iBrooklyn doesn’t solve all of these problems yet, I’m really working on it. I debated releasing iBrooklyn until it had  a more diverse feature set, but I think that releasing early on will get me good feedback while the app is still fresh and malleable. Once it a program grows into a monolithic thing, it becomes a lot more difficult to implement new features. So folks, tap on that email button and send me your ideas. My dept. chair did it, and so should you!

On that note, I’d like to run by a list of thank yous.

  • First, Baruch HaShem (thank Gd) for giving me everything and anything.
  • My parents for the encouragment and occasional prodding.
  • Professor Langsam for encouragement and early feedback. I’m on it.
  • Max Savin for an early draft of the app icon. (Here’s a plug for Phism. Good luck with that!)
  • Abraham Vegh for the feedback. Your changes are already implemented for v1.1.
  • Yosef Gunsburg for your ideas. Still letting them brew in my head for while.
  • Isaac Friedman for messing around with data for me. (Still would like to get that info into a version 2 release!)
  • All the other people who I bugged about messing with the data.
  • The folks with Android for trying to convince me that Android is better than iPhone. Not a chance. I’m not quite ready to make an Android version, but I’m definitely considering it.
  • Everyone else who hasn’t been mentioned here due to causes related to neurological abeyance (thanks Google!), political or religious reasons. You know who you are.

For the moment iBrooklyn is free, but don’t count on it staying free forever. I put work into this, and I have some incredible ideas lined up. iBrooklyn runs on iPhone, iPad, and iPod touch running iOS 5.0 or greater. If you’re a student (or professor) at Brooklyn College, do yourself a favor and download iBrooklyn today.

Just a Little Reminder…

Commands in VIM are often performed with the key that is the first letter of the name of the command. It seems like I’m not the only one having trouble making this association, so made a little picture. Here’s a little list, which I’m making from memory, to help myself. It’s by no means exhaustive, but it’s a decent starting point.

[i]nsert mode – Let’s you type. This is the mode you’re in when you use Microsoft Word or Pages. You’re just inserting lots and lots of text into a canvas. To use any of the other commands in this list, hit [Esc] to exit –INSERT– mode and enter –NORMAL– mode. (Which as a classmate of mine points out, is not quite normal at all.)

Also, remember that when the computer doesn’t complain, assume it did what you told it to do. Don’t go looking for visual feedback after every, yank, put, and extract.

These are some NORMAL mode commands:

[e]nd – Move the cursor to the end of the next word

[y]ank – When your grandmother says “copy”, VIM users say yank. Tomato tomahtoe.

[{number}]+[G]o – Go to line number {number}.

e[x]tract – The granny equivalent is “cut”. Granny made cookies with vanilla cut, urm, extract. (I might have made this up, but it fit.)

[p]ut – In grannynese (Yes, I just said that!) it’s “paste”. We could call it that too.

[u]ndo – We know you didn’t mean to  put that last line 80 times, you just got caught up in not knowing how to use VIM. Here’s how to undo your foolish mistake, before granny sees how unsavvy you are.

[o]pen – Adds a blank line, moves the cursor to it, then – this is important – activates –INSERT– mode. We’re opening some space up to write new things in.

Control Mode:

When we’re in –NORMAL– mode, you hit the colon key for control mode. Colon stats with a c, so does control. For all things here, precede the key in question with [:].

[w]rite – Writes the current file to disk. If granny can use a computer, she’d call this saving. Odds are she didn’t do this often enough before her computer “crashed” last time. (We all know she downloaded a virus while trying to download an episode of a Martha Stewart cooking show or something. – Kidding, my Grandma is too cool to watch cooking shows, but she uses a computer.)

[q]uit – When you’re “ready to chuck your computer at a wall because VIM is frustrating you”, then you’re also ready to ____ . That’s right, quit.

Here’s how to save and quit in one line:

[:]+[w]+[q]