Tuesday, August 16, 2011

Folder Permissions

I've been having problems with folder permissions on ubuntu, oddly enough, trying chmod 777 on stuff wasn't really working well, basically I just did gksu nautilus then I modeled the "permissions" tab to the same as a folder I wanted permissions to be the same as. Apply to all files/folders within and viola it worked.

Hope that helps others.

Originally found the command from http://ubuntuforums.org/showthread.php?t=1086624 although I have heard of it before, just haven't used it much.

Tuesday, August 9, 2011

Boxee Update DEB

I was hoping to download boxee for my recently updated media server.

Turns out that boxee has some issues with the package downloadable from here:
http://www.boxee.tv/make#content

The original site I built the script to mimic is located in the source code.

The file which did the job for me can be found here:
Boxee Deb Fix


Good luck!

Friday, July 29, 2011

getc/getchar why doesn't it wait?

So getc is basically the same as getchar but to get the same effect
getc(stdin) = getchar basically.
From the above link:
Returns the character currently pointed by the internal file position indicator of the specified stream. The internal file position indicator is then advanced by one character to point to the next character.

What this means is that this is not a "wait for input" type operation, it literally will grab the next character from the stdin stream unless you find a way to prevent it,


Example function from code to be used:

char getMathSymbol()
{
while (getchar() == '\n') // use this or getchar will not wait for input.
{
// temp varaible
char userSymbol;
cout << "please enter yoru math symbol" << endl;
// need getchar to get a character from the console
      userSymbol = getchar();
      
//cout << "getchar done" << endl; // debug code
// return your symbol
return userSymbol;
}
}

For Example you entered in the following:


Enter your first number
1
Enter your second number
2
please enter yoru math symbol
+
3


Lets look at this again, with all (hidden) characters visible
Enter your first number\n
1\n
Enter your second number\n
2\n
please enter yoru math symbol\n
+\n
3



When you hit getMathSymbol
you are at this point:
Enter your first number\n
1\n
Enter your second number\n
2\n
please enter yoru math symbol\n

When you get the char, the \n is grabbed (which is why the "while loop works").

So what I suspect happens is that we hit that \n and since it's a valid character (not end of line or end of file) we grab the character and exit the function. (when the while loop is gone).

What happens if we read the last character to increment to the next char (which is EOF or EOL)?

char getMathSymbol()
{
//while (getchar() == '\n') // use this or getchar will not wait for input.
{
// temp varaible
char userSymbol;
cout << "please enter yoru math symbol" << endl;
// need getchar to get a character from the console
           userSymbol = getchar();
           userSymbol = getchar();
      
//cout << "getchar done" << endl; // debug code
// return your symbol
return userSymbol;
}
}

After compiling, it looks like it works, so what happens is that if there is a valid character the getchar returns immediately, if the next char isn't valid, then it waits until a valid char occurs.

Make sense?

Thursday, July 28, 2011

Forward Declaration vs Function Prototyping, What's the difference?

Valid Conditions
The following will be how we can get a successful compile.

This would be using Function Prototyping:

### BEGINNING OF FILE###
... // declarations of whatever you want

void INSERT_STRING (char b);

int main()
{
  INSERT_STRING("A");
}


void INSERT_STRING(char b)
{
  // Where INSERT STRING is literally implemented.
}
#### END OF FILE ####



This would be Forward Declaration.

### BEGINNING OF FILE###
... // declarations of whatever you want

void INSERT_STRING(char b)
{
// Where INSERT STRING is literally implemented.
}

int main()
{
INSERT_STRING("A");
}
#### END OF FILE ####

Now what this last one means, is that if you wish to use INSERT_STRING, it must be fully implemented above the calling function (in this case main).



### BEGINNING OF FILE###
... // declarations of whatever you want

void INSERT_STRING (char b);
void USE_INSERT_STRING();
int main()
{
USE_INSERT_STRING();
}

void USE_INSERT_STRING()
{
INSERT_STRING("b");
}
void INSERT_STRING(char b)
{
// Where INSERT STRING is literally implemented.
}
#### END OF FILE ####

This is because the function has been prototyped, when the compiler goes to use it it knows that some function exists that has such and such properties and then it won't complain.
When it finally hits that function it compiles it, I am pretty sure that later the compiler comes back to the USE_INSERT_STRING function and replaces the "pointer" (or however it knows where to go to "call" the function), with the location that INSERT_STRING finally ends up, but don't quote me on it, as I'm not 100% certain, and I don't know compilers that well. If someone can confirm I would appreciate it.




Error Conditions
The following will contain some examples of how we can fail to compile.

Post Declaration with No Prototype

### BEGINNING OF FILE###
... // declarations of whatever you want

int main()
{
INSERT_STRING("A");
}

void INSERT_STRING(char b)
{
// Where INSERT STRING is literally implemented.
}
#### END OF FILE ####


Gotcha
This time it is by another function then main. You might have thought you were safe, but this should fail as well.

### BEGINNING OF FILE###
... // declarations of whatever you want

void USE_INSERT_STRING()
{
  INSERT_STRING("b)");
}

void INSERT_STRING(char b)
{
  // Where INSERT STRING is literally implemented.
}

int main()
{
USE_INSERT_STRING();
}
#### END OF FILE ####

The above fails because again the compiler is trying to use the function INSERT_STRING in USE_INSERT_STRING, and since it's not been "forward declared" (declared before it's used), it fails.

Saturday, July 16, 2011

Building an Echo Server using Bluetooth and Blueterm

I recently picked up the Bluetooth moduleRN-42 This was a cheap low cost way to integrate Bluetooth into an upcoming project. First up was getting the pieces soldered. Thanks to Walter over at Walter's Epic Blog he hooked me up with a great soldering job.
He soldered up the power, ground, tx and rx lines, as well as the required SPI lines in case I need to program the device.
I got the itch a little bit ago and started doing some research on building an Android App to communicate with this thing (with the eventual plan to hook it up to a microcontroller). I found BlueTerm this program connects to a Bluetooth Device and sends UART data across.
I started thinking to myself I wonder how I can echo the data back without having to build the UART up for my microcontroller. I asked the question over at electronics.stackexchange, and of course being the impatient type I just jumped in and hooked the rx to the tx lines.
As you can probably guess from the little jumper above, those are the RX and TX lines. It worked, I type something and bam it echoes it back. I'll be posting more as I build this project up so stay tuned.

Sunday, July 10, 2011

AsyncTasking

I was attempting to place my calculations from eecon into an AsyncTask.  I initially thought I would make a common task, calling it from both my find factor activity, and my find interest activity. I had to deal with the whole mess of figuring out which one was being called, and whatnot. Then I ran across the problem of getting the data back from the task. I initially tried using the getstatus function that async provides, as well as the get function, this returns the result. Seems great right? WRONG! get is blocking, this means that when I kick off the async task, it doesn't just kick off and run and when it's done let the UI know it's done, I FROZE the UI. This is bad.  Now if my calculation is time consuming then we have a chance at a force close. I wanted to try to pass the data back to the UI components so hopefully I wouldn't have to cause the main thread to wait. I wasn't sure how to do this, but after reading about the AsyncTask more, I realized that the onPostExecute was supposed to update the calling UI thread. Finally I realized (after a little reading) you can place the AsyncTask class in as a subclass, this allows it to have access to the parent's elements. 

No more blocking and no more force closes from this calculation.

Good luck and Good night.

Saturday, July 2, 2011

Admob in Android

This link is great for just throwing a quick ad in with admob into your app.

http://code.google.com/mobile/ads/docs/android/fundamentals.html

followed by the following:

http://code.google.com/mobile/ads/docs/android/banner_xml.html

Basically you add the "publish code" jar to your app, then insert a few lines into your manifest. Then you place the banner into your app where you want.

The one piece that tricked me is that if you simply try to add the sample xml unit to your project you need to make sure that in the main layout (the one that declares the "android" namespace), you need to add the following:

xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"

Monday, April 4, 2011

Job At Google

Well I finally did it, I applied at Google, I don't know if I'll ever feel ready with the epicness this company has brought to every household. If not, I won't discourage, I'll keep working, if anything I'll create a business that Google will want to buy, so I'm not too worried, if it doesn't happen now, it will someday, but then again someday I might be ready for my own business and will be able to R & D on my own merits.

Here is my submission window, I was kinda excited:

Monday, March 28, 2011

Ideas

How often do you have "big ideas"? It frustrates me as I have so many ideas so frequently, and I don't have enough time to implement them all. Once school is out, I'll have some more freetime and will finally be able to hit on all the projects I've got queued right now.

Stay tuned, when May hits, there will be a lot, I might even start making more videos about the projects and build process.

Thursday, March 24, 2011

Google Market vs. Amazon Appstore

The Amazon App store looks good, and yes I do like the recommendations and whatnot just like regular old Amazon. My question for the big G is this, we had to check "unknown sources" just to get the appstore on our phones and download apps through them.

Recently there were some issues with some apps found in the Android App Market and this prompted google to remove apps from their store, as well as remove them from infected phones. Will they continue to do this with Amazon Store apps, or will it be a "too bad" because it's not something we're controlling, and you took the risk.

Will this fall on Amazon's shoulders?

Here are the emails I've sent to Amazon when I get word from them I'll update:

Since we are installing apps from the Amazon App Store, what will the process be if/when an app that has been downloaded has been found to contain a virus?

Tuesday, March 22, 2011

Batch Renaming

I have a bunch of MTS files that I get from my camcorder, and frankly I don't have any interest in sitting down and renaming each file by hand, in perl this is a pretty simple case, I decided I wanted to name them based on their creation date, then number of file in that creation date. I still would say read over this script and make sure you understand what it is doing and then go ahead and use it.

This can easily be modified to work with any kind of file, but I was only concerned about my video camera files. if you want change the <*.MTS *.m4v> to whatever file types you want!


Here is the code:
#!/usr/bin/perl
# Written by Tyson Bailey
# with date/string creation from: http://www.seto.org/mt- diary/archives/2005/11/using_perl_to_d.html
use File::stat;
use Time::localtime;
@files = <*.MTS *m4v>;
$extension = "";
foreach $file (@files)
{
    # get date/time
    $date_string = ctime(stat($file)->mtime);
    # break it up into an array.
    @date = split('\s+',$date_string);
    $i = 0;
    # figure out file extension
    if ($file =~ m/.m4v$/)
    {
        $extension = "m4v";
    }
    else
    {
        $extension = "MTS";
    }
    # Filename format MAR_05_2011_x.extension
    while (-e "@date[1]_@date[2]_@date[4]_$i.$extension")
    {
        $i++;
    }
    # just to be safe
    $base_name = quotemeta("@date[1]_@date[2]_@date[4]_");
    chomp($file);
    # if our filename already exists we really don't want to try renaming it.
    if ($file !~ m/$base_name/i)
    {
        print "Didn't Matched: $base_name\n";
        print "Renaming: " . $file . "\n";
        print "To: @date[1]_@date[2]_@date[4]_$i.$extension\n";
        rename("$file", "@date[1]_@date[2]_@date[4]_$i.$extension");
    }
    else
    {
        print "Not Renaming: $file\n";
    }
}

Big thanks to:
http://formatmysourcecode.blogspot.com/
for formatting my source code!

Wednesday, March 2, 2011

Friday, December 24, 2010

GoogleTV

Right now I am watching Youtube on a Google TV. I see some things that should very much be fixed. Frankly the video should be larger,the page itself takes up a ton of space, and the suggestions, those should be a side bar pop-in, same with comments.

Here's a quick screenshot:
and it looks almost exactly like this on the tv, and if all I was doing was websurfing, this wouldn't be a problem, but since I'm wanting to watch video on GoogleTv, I don't want to see this, I'm hoping google will come out with a youtube app that cleans this interface up.

Things like centering the video, and allowing a translucent slide in from the right with a set of suggestions for additional videos. And finally the comments should slide in from the bottom, just a small bar not distracting.

Interestingly enough. Why is it ok to have an interface like this on a regular computer, but when we get to hand held device, or something small, we want a cleaner and simpler interface, the question is, is this how interfaces should look on computers? I mean google got it right when they designed a really simple and clean interface for searching. Google taught us that screen real estate is valuable and as a company they wanted to make sure it was worth it. When it comes to TV, the same holds true.

On second thought why do websites even have search bars anymore? I mean why not push it back on the browsers to simply allow a search function that searches whatever is on the current domains content. If I can find a way to create apps for GoogleTv I think any media sites should be the first targeted, either that or create a "tv." version much like mobile contents. This comes back to the whole idea of content vs formatting separation. Why not just put a bunch of websites together and say "heading" and "video" and then the device that get's it can format it how it likes....wouldn't that be sweet? Well I hope you've managed to follow the off the wall insanity that my posts seem to like to follow. If you have Google TV, what do you like, or not like about it?

Wednesday, December 8, 2010

SPI vs UART vs I2C vs Four Event Protocol

I had to write a paper for my Computer Organization and Architecture course. Its due this evening but if you want to take an early look I've shared it on google docs. I plan to make a few grammatical edits, if you have any additional suggestions or comments I'm all ears.
Here's the link:
Communication Protocols

Monday, November 15, 2010

Coroutines

Today we talked a little about coroutines, at first glance based on the slides it seemed like they were saying that the coroutines would start at the beginning and end when they return, this was a little confusing as they seemed to be identical to procedures.

Turns out we were misunderstanding the picture.

From Wikipedia:
In computer science, coroutines are program components that generalize subroutines to allow multiple entry points for suspending and resuming execution at certain locations. Coroutines are well-suited for implementing more familiar program components such as cooperative tasksiteratorsinfinite lists and pipes.


So what is a Coroutine? Well think of it this way, suppose we have a few programs running in threads, and we have an operating system. Do you think the operating system calls each of these threads to do some work, and when it has to pause and stop to go do something it just starts what it was doing all over again? We wouldn't ever get anything accomplished in computing if that was the case. This is where coroutines come into play, since we can return to the last context that was running we can just keep on running. For example, suppose we have a thread that runs a REALLY LONG for loop, the OS does a context switch and pushes the current status onto the stack. Another thread does some work then returns (or perhaps another thread needs servicing). Upon return all the data that was in use from the function is popped from the stack and back in use again. 


Now the book describes the process in a little more detail, but basically what's happening is that the next address is being pushed to the stack, then the operating system goes off and does some stuff, and pops the address off back into the program counter, and the function keeps running as if nothing happened (to it, the change was transparent).


I hope that helped ya out, let me know if you have any questions.

Friday, November 5, 2010

Circuit Analysis II Lecture 13

****THE BELOW IS INCOMPLETE, but I'm releasing it in case anyone can get some value out of what was written.****
Disclaimer: This series of posts is to serve as notes for myself as well as any others interested in the subject of Circuit Analysis II. This is the course ECE 213 at UNM.
The course will follow the book:
Electric Circuits (8th Edition)


Agenda for the day:
13.6 - AP 13.12
13.7


AP 13.12

x(t) = Acos(wt+phi) is given

Looking at the equation:
vo/ig = ((2+s)s * 10/s)/((2+s)+10/s)

working the algebra through to simplify you get:
10*(2+s/(s2 + 2s + 10))

This is our H(s), so using that H(s) we sub it into our steady state equation:


yss(t) = A|H(jw)|cos(wt+phi+theta)

Now we want to find H(jw) so remember that s = jw so we can just grab w and sub j and w in for s in the H(s) equation, that will look like this:
10(2+j4)/((j4)2 + 2*j4 + 10)

a little manipulation we get:
20+j40/(-16 + 8j + 10)

next we combine and multiply by the conjugate:
(20+j40)/(-6 + 8j) * (-6-8j)/(-6-8j)

finally we get:
2-j4

Converting to polar we get:
4.47e-j63.43


Finally substituting back in our equation we get:
10*201/2cos(4t-63.43°)

Exercise 13.72
we have a resistor of 50 ohms and two inductors whose values are 2F and 8F in series.
vi is attached between the resistor and the 8F inductor. the vo is located across the 8F inductor.

Converting to the S domain and using voltage division we get:
vo = vi/(50+2s+8s) * 8s

Solving it out for vo/vi we get:
.8s/(s+5)

Now we'll sub in 75/s for vi

so we'll get:
75*.8s/s(s+5)

Finishing the algebra we get:
60/(s+5)

Now we want to use the convolution integral on this one:

Circuit Analysis II Lecture 16

****THE BELOW IS INCOMPLETE, but I'm releasing it in case anyone can get some value out of what was written.****
Disclaimer: This series of posts is to serve as notes for myself as well as any others interested in the subject of Circuit Analysis II. This is the course ECE 213 at UNM.
The course will follow the book:
Electric Circuits (8th Edition)


<Concepts:
1. High/Low Pass Filters can be RC or RL circuits depending on what element you are using for vo

a. For RC the Low Pass filter is on the Capacitor.
b. For RL the Low Pass filter is on the Resistor.
c. a/s+b is low pass
s/s+b is high pass

2. Band Pass/Reject Filters are RLC circuits
a. Ks/(as2 + bs + c)

3. The cutoff frequency is A/(2)1/2

4. Q = (L/CR2)1/2

5. wo = 1/(LC)2

To recap:
If there is a quadratic equation on the bottom, it's likely it's a bandpass.
If it's not and there is an s on the top then it's a highpass filter and if not then it's a lowpass.
Don't forget if given in HZ convert to rads/sec via equation w = 2piF

>Examples:
1. Ap 14.1 page 577
2pi * 8000 = 1/10,000c
c = 1/(80000*2*pi)
c = 1.98*10-9
c = 1.98nF

2. Given a 1-10Khz band, C=1uF what are R and L
1/LC = wc1 * wc2
LC = 1/wc1 * wc2
L = 1/C*wc1 * wc2
Solving we get 2.53mH
From there we use the equation R/L = wc2 - wc1
Remembering 2piF = w,
R = 2pi*L*(9000)
R = 143.06 ohms

3. 14.20 page 602
Given c = 20nF, Q = 5, wc = 20kHz
(20000*2*pi)2 * 20*10-9 = 1/L
L = 3.17mH
5 = (3.17*10-3/20*10-9*R2)2
25 * 20*10 = L/R2
R = (1.25/394784176044)1/2
R = (3.166*10-12)1/2


ECE 340 Test Review

****THE BELOW IS INCOMPLETE, but I'm releasing it in case anyone can get some value out of what was written.****

So I have been looking at the explanations for the first problem, and right away I believe looking at the problem and analyzing it will go a long way in this case.

1.
a) Looking at the first part of problem 1, we see that it says "What is the probablility that both engines fail during the marine mission". 
Let's break the first question up into parts, Reading Both implies that we are looking for an intersection. From the introduction to the question we know that given one engine failing (the first engine) the second one fails with a probability of .1, Thus the probability of A given B is going to be .1, and we know that B is .0001, now we can say that P(ANB) = P(A|B) * P(B). Which equates to .0001 * .1

b) Breaking down "suppose the second engine fails during the mission what is the probability that the first also failed".
We can extract that we are looking for the case where P(B|A) we are looking for B given A in this case, we also know that the probability of that is = to P(ANB) / P(A) we are looking for the case where there is an intersection over the probability of just the second. This can equate to (.0001 * .1)/(.0003)

c) Looking at "What is the probability that at least ONE of the engines fail" we can extract we are looking for the UNION of the two, Because of that we know P(AUB) = P(A) + P(B) - P(ANB) we know each of the elements here, so the solution is .0003 + .0001 - (.0001 * .1)

d) Breaking the sentence "What is the probability that the first engine fails, and the second engine doesn't fail during the mission" we can extract that given A we are looking for the probability of A sans B, so that would be P(A) - P(ANB) this equates to .0003 - (.0001*.1).

2a. A group of 30 people shake hands with everyone else once,
Looking closely at this we are looking that person 30 shakes hands with 29 people, person 29 shakes hands with 28 people(can't shake 30's hand again), and so forth, so the total number of shakes that occur would be the summation of 30 .. 1 , since we can't really make an easy estimate on this one, then subtract the appropriate number of hand shakes this comes out to n(n-1)/2 or 435. Realistically if you think about it the last person can't shake hands with anyone else so I think the final result should be 434

2b.
Since the elements of the "even" set contains 6 elements {3152, 3512, 5312, 5132, 1352, 1532} and the entire sample space contains 4 varieties of that (one for each number) then the total elements are 24, this will give the solution 6/24, which is 1/4. I didn't bother to calculate the number of elements in the sample space for various reasons. BUT I did have the solution correct in that I said it was 6/(cardinality) of the sample space, which is in fact the correct answer.

3.
Since we are trying to figure out what the probability of two students having the same birthday, we can say that the solution would be (365*364*363...335) divided by all the likely scenarios of 365, which is 365^30.
so the solution is 1- (365! /335! ) / 365^30

4. 
a. { (1,1), (1,2)...(1,6).....(6,6)}

b. Since we are looking at all the EVENTS (I read outcomes on the test....durr) we can have 2^36 different variations (since there are 36 outcomes)

c.  the event that the max of the two numbers is 2 would be {(1,2), (2,1), (2,2)} the probability of this is E^#/Ohmega^# or 3/36

d. The event containing the minimum of the two numbers being 2 is {(2,2),(2,3), (2,4), (2,5),(2,6)...(3,2)} this is 4*2 + 1, 9 outcomes,the P of this is 9/36

e. IFF P(E1NE2) = P(E1) * P(E2) then it's independent. since the intersection is (2,2) and the probability of (2,2) is 1/36, P(E1) = 3/36 and P(E2) = 9/36 so 1/36 != (3/36 * 9/36) thus they are independent.

f. Given E2, we can expect that the probability of getting E1 is the intersection of the two / cardinality of E2 so the solution is (1/36)/(3/36) = 1/3

5.
a. Decoding this we are looking for a zero to be received, this means we are looking for the intersection of the Event that a zero was received with the event that a 1 was transmitted and received as a 0 and the event that 0 was transmitted and received as a 0.  This gives P(0RN1T) + P(0RN0T) = P(0R), we also know that P(0R|1T)*P(1T) = P(0RN1T), and the same goes for the other one, so we now can say that P(0R) = P(0R|1T)*P(1T) + P(0R|0T)*P(0T) which plugging in the numbers we get P(0R) = .6*.001 + .4*(1-.01) = .3966

b. Decoding what is the probability that a 1 transmitted given a 1 was received.
We are looking for the event where a 1 was transmitted given a 1 was received this gives P(1T|1R) this can be equated to P(1TN1R)P(1T)/P(1R)which is saying that we are looking at the probability of the intersection occuring times the probability a 1 was transmitted, divided by the fact that a 1 was received. Since we know the probability that a 0 was transmitted given a 1 was received, we can say that the "opposite" would be 1-P(0T|1R) also since we solved above the event that a 0 was received we should be able to plug that in too which nets us: 1-P(0T|1R)*P(1T) /  1-P(0R) these come out to (.99 * .6 ) /.3966  is approxmiately 1.5.

c. Since .6 of the bits will have .001 chance of error, and .4 of the bits have .01 chance of an error, we are looking for the intersection of the error since a bit transmitted as a 1 can't be "converted" to a 1, we can say the sets are disjoint, and simply add the probabilities together, so .4*.01 + .6*.001

6.
Given that P(A|B) is independent we can say P(A|B) = P(ANB)/P(B) since they're given as independent, we can say that P(ANB) = P(A) * P(B) replacing that in the equation we can say that P(A|B) = P(A) Since the P(B)'s cancel out. the same will hold for P(B|A) which will equal P(B)

7.
a. Trying to decode this question we're looking for the case where a 1 was sent, this means that the majority must have ruled in our favor, so we would have to do N choose K for 4,5,6,7 and multiply appropriately (p^k)*(1-p^n-k) this would give us the solution

b.
The probability of a number being a heads (using the above sample space) we can assume that the probabilities will be the summation of the N choose K for 1,3,5,7, solving for that, I can only assume that for all cases where the # is even, is 1-P(odd).

Insert Graph here:






8. 
i. As defined in your lectures a random variable is a mapping of the elements to the real number set. thus the answer is b)

ii. As defined in the book/lectures p(F1uF2) is = P(F1) + P(F2) ONLY if the intersection is a null set, thus the solution is b)

iii. I immediately recognized the equation to determine independence (c), BUT I didn't think there would be more then one, and didn't really look, obviously P(F1UF2) = P(F1) + P(F2) - P(F1NF2) I didn't look closely but you can "swap" P(F1NF2) with P(F1UF2) (using simple math), I'm blind and didn't see this on the test, so the actual solution is f, C and E

iv. I spoke with you in this class, since I didn't know if F=G I couldn't determine if the probability of F was equal to that of G, from the sounds of things we SHOULD have assumed F = G which means the probability is P(G) <= P(F), this gives the solution b, BUT assuming that F = G, then isn't the P(F) = P(G) and it's not "less then" since they're literally equal to each other?


Tuesday, November 2, 2010

Page Replacement Algorithms

There are many page replacement algorithms, this week we were asked to implement the fifo and lru page replacement algorithms. But, first a little primer.

FIFO Page Replacement
The fifo page replacement algorithm is essentially a queue setup that pushes the first items into the list out first when the list is full, so for example, if you have the numbers 1,2,3 and they are put into the array in that order, when the 4th number comes along your 1 gets pushed out, and you are left with 2,3,4. That simple!

The FIFO page replacement algorithm was pretty simple to implement, all I had to do was create an array that was the size of my frames, then I simply setup a "current pointer" to that array head initially, and a pointer to the tail and head of the array. When we found a frame we didn't do anything. When we didn't find a frame, we simply assigned the data to the current pointer then moved the pointer down the array, when we reached the bottom, we simply moved the pointer to the top and repeat, also we increment our page fault counter. Something interesting to note, supposing we have the next element in the array that matches so we don't have a page count increment, well the next go around, and that one will still get written over. Since this element wasn't recently written, it doesn't get to keep it's status as "new", and still can be written over in the next iteration. This seems a little less then efficient, however perhaps changing it a small bit so that it skips over to the next element would be beneficial.

LRU Page Replacement
The Least Recently Used algorithm basically makes an association for each array with a clock. The book suggests this is easy to implement using a doubly linked list, the other option is counters.

The LRU page replacement algorithm in theory was pretty easy too, and really looking back on it, it really was. I simply decided to make a second "timing" array that matched up with the frame array. This way whenever we did a frame check, we refreshed the matching frame's time, and if the frame wasn't there, we put the new one into the frame array, and then updated our clock. Really I was able to keep a lot of my code from the fifo page replacement and reuse it, as a lot of it was simply "setup" and structure stuff that I could easily reuse.

Caveats
This sounds really simple, but I did have a few problems along the way one of the main problems I ran into was operator precedence. This occurs when you have + and * in a equation, or a ( or something like that, the compiler/processor has to know what to evaluate first, if for example you try to increment a pointer that is routed through an address, like so *ptr, and you attempt to increment *ptr++, you are actually incrementing your address, effectively losing the pointer to your pointer. This is simply fixed by (*ptr)++; since the ( has higher precedence then ++. Another issue I ran into was that using the function clock() just didn't want to cooperate, clock ran just way too fast, so I had to put wait's in there so that it would adjust the clock even minutely so that when we assigned it to the arrays we didn't use the same time on numerous ones. That makes it hard to find the oldest one if they are all matching times.

Good luck and let me know if you have any problems!

Saturday, October 30, 2010

Virtual Memory

So we were asked to devise a way to figure out which page a particular physical address was in, as well as it's offset.

Turns out this is a really simple problem, in this case each page is 4kb, which really means 4096 bytes, so simply take the address, divide by that 4096 bytes, and that tells you which page it's in. From there you subtract the number of bytes of the previous pages (4096 * n)  from the address and you get the offset.

So the nice thing about virtual memory, is that you basically always know your address will reside within a 4096 byte address. This can make more static stuff easier to handle, rather then trying to guess which physical address you are, then figure out some kind of offset.

Here is the program I wrote in action.


Well I hope you enjoyed, I know it was a bit short, but the problem was really easy to see a solution, if you're having problems understanding how to find a page and offset, please let me know and I'll do my best to help!