Monday, April 16, 2012

Modifying Bluetooth Chat

I started out trying to pull the android bluetooth chat application from the developer website....BAD IDEA. I spent quite a bit of time commenting this out, adding a toast here and a if then there. That one is built for a different sdk version than I'm using, so my recommendation would be to pull it from the examples folder in the sdk download.

Well I finally grabbed the bluetooth chat application from the sdk examples folder (when you download from google). After about 5 minutes I tried loading the default app on my phone and touchpad, it worked just fine. I then changed ONE LINE of code and my arduino can talk to my android devices with bluetooth. What line say you? This one:

In the BluetoothChatService.java
From
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");

To
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");


That's it that's all it took. Apparently that UUID from what I've been able to gather is for the bluetooth serial interface, so that's all I needed.

Here is video proof of the application in action.





http://youtu.be/Zof0IYUU71Q

Good luck and let me know if you have any questions.

Monday, April 9, 2012

Ada Withs

Eclipse has a really nice feature which allows through a keyboard shortcut the ability to update the imports required for your code.

I liked that, but didn't know of anything that did the same thing for Ada source code.

I have began creating a script which does this, and you can use programs to run it, (perhaps port it to a plugin for a program).

I called it Ada-Withs (I know it sounds pretty boring)

It's not complete, but right now the script will pull out all packages used in the program.

If you want to give it a try go for it. If you want to mess with it, pull and let me know if you have any improvements.

The link above does go to it but here is the full url as well:
https://github.com/onaclov2000/Ada-Withs

Wednesday, April 4, 2012

One Language to Rule Them All

Do I think that there is one language that is best? No. I can say that with a high degree of confidence. Each language has it's own idiosyncrasies. If the first language that was created was the best, we wouldn't be using anything else. But we all know that there are issues with each language, and each language was often created to make an aspect of another language easier/better.

Last week I recommended not attempting to solve a particular problem with python. The solution was already partially coded up in perl and it just didn't make sense to re-solve the problem (simple data parsing) all over again. It got me to thinking, was this the right suggestion? I think the final result of the script should have been in perl, however learning to do it in python was a good idea. It would improve their toolbox.

I realized I should encourage writing things in a variety of languages. Why? So you know which tool to use. I came to realize that parsing data was easy to do in perl 90% of the time. If I knew python better I would probably feel the same way about python. The issue isn't about python vs perl vs java vs c++ vs c#, the issue is knowing what to use when.

I know that if I want to make a simple fast to build gui application I can use Visual Basic. Joe Blow will use Java, and Jim Bo will use Perl. Are any of them wrong? No, what you use, depends on your tools available. If you know how to do the same thing in 5 different languages, you'll start using a default for one set of problems, another for another, and mixing them if necessary.

I can solve the same problem in every single language, but the issue is, which is easier to do it with? Do some research, if you find that dragging and dropping a button onto a form is easier then writing the back end required to create you idea. DO IT! There is nothing more encouraging then building something and actually seeing it working, then spending tons of time building something and never seeing it come to fruition.

Good Luck.

Monday, March 12, 2012

New Apps

New Apps Released!
Well it was a busy couple of weeks, I have released 2 apps on the market in the last few weeks.  Pizza Area, and I Am Here.

Pizza Area
This calculates the square inches of a pizza for you (really works for any size circle with a diameter), Also if you have a price it'll calculate the price per square inch, as well as the estimated cost at that rate for the pizza size smaller and larger that the app contains. Give it a try and let me know if you have any suggestions, and as always a positive rating on the appstore would be appreciated.


I Am Here
This app will allow you to select a friend from your contacts (or type the number in) and when you hit the icon it'll send a message. This app is very similar to another one on the Apple Market, I was a little disappointed I hadn't released this sooner, my buddy civissmith had come up with the idea originally,  and I was just way to slow to implement. Well give it a try either way, I think mine has a little more spunk then the Apple Market version.

That's all for now, I have so many projects in the works at all time, I just have to finish a few so I can write about them.

Thursday, February 16, 2012

GraphViz

I decided to start playing around with GraphViz, here are a few of my notes:
To call a file use the following command (works for me).

dot .gv | dot -Tpng >.png
This generates a png file.

Next up what the .gv file contains:

digraph G {Hello->World; World->Earth; World->Mars; World->Jupiter}

It looks like if you call it a digraph, and give it each of the start/finish points, it'll graph them for you.

I'll be back with more as I discover more.

Friday, February 10, 2012

TrueCrypt

I was having problems getting truecrypt to work on my ubuntu machine. Once I downloaded it and unzipped it there was no extension and for some reason my machine didn't know what to do with it. I simply renamed it with a .sh at the end and re-ran the file, everything worked as advertised at that point.
I.E. FROM: truecrypt-7.1a-setup-x86
      TO: truecrypt-7.1a-setup-x86.sh


Good Luck

Tuesday, January 10, 2012

Android Like SQL Statement, sqllite sql software

While using sqllite sql software for android, I was runing into problems. I was able to do exact matches, but for some reason I couldn't get LIKE matches to work. I was hunting around like crazy trying to figure out how to write a LIKE statement in Android. I had a working example of '=' and figured it would be pretty simple to use the LIKE command. After many variations I just couldn't figure it out. I almost posted to stackoverflow but decided to read the information on the "rawQuery" parameters of the database methods.

After doing a little reading it turns out that if you enter in a ? in your query it pulls the selection arguments and stuffs them in where that ? is. My first example didn't exactly make it clear that ? was replaced with the arguments, so now that I knew that it led me to my next train of thought.

As silly as this might sound my original query that pulled exact matches in used this:
cursor = db.query(DBHelper.TABLE, null, DBHelper.C_TEXT + " =?", whereArgs, null, null,null);

I finally tried this:
cursor = db.query(DBHelper.TABLE, null, DBHelper.C_TEXT + " LIKE ?", whereArgs, null, null,null);

Guess what? The whereArgs get stuffed in the ? position.

As much as I could have sworn I tried this, apparently I tried various iterations. Be sure if you're going to  use this, make sure you have "column" space "LIKE" space "?" and then your arguments as the next parameter. If you notice that the first example I was using had no space between the front, between the = and ? as well as behind, this is part of what tripped me up, LIKE is a word so you have to be sure to separate them using the right spaces.

If you're not sure what a column is take a look at W3 Schools SQL Like Tutorial. It doesn't explain the ? and how that works with respect to android. But after reading to this point you should be able to use the LIKE command in android.

I hope this helps others, so long and short of it, I can now query my db with a like operator, and it works.

Note* whereArgs contains only one element which contains % on either side in my case (%string%). Perhaps in the future I'll poke around at the options when I have more then one string in that field.

Monday, October 17, 2011

Music Glove Part 1

Well after much heartburn (and once again being burned by pull down resistors). I have managed to make some progress.

I now have half of my Music Glove prototype complete. This is the hardware side. I paired a bluetooth module from sparkfun (something that does uart). With an arduino to handle the button presses. I can now receive an A and a B from my button presses on my phone using the BlueTerm application.

Once I am able to handle receiving the bluetooth data on the phone side, I will better package the whole assembly.

Here is a shot of the circuit:




Here is the code which does all the work:

/*
  What you will need to do is wire up your bluetooth module hooking the RX and TX up to the arduino, then

 */

// A is IO 2
int A = 2;              // Switch connected to digital pin 2
int AState = 0;              // Switch connected to digital pin 2
int AStatePrev = 0;              // Switch connected to digital pin 2
// B is IO 3
int B = 3;              // Switch connected to digital pin 3
int BState = 0;              // Switch connected to digital pin 3
int BStatePrev = 0;              // Switch connected to digital pin 3


int buttonState = 0;


void setup()                    // run once, when the sketch starts
{
  Serial.begin(115200);           // set up Serial library at 115200 bps
  pinMode(A, INPUT);    // sets the digital pin as input to read switch
  pinMode(B, INPUT);    // sets the digital pin as input to read switch
}


void loop()                     // run over and over again
{
  AStatePrev = digitalRead(A);              // Switch connected to digital pin 2
  BStatePrev = digitalRead(B);              // Switch connected to digital pin 3
  delay(60);
  BState = digitalRead(B);              // Switch connected to digital pin 3
  AState = digitalRead(A);              // Switch connected to digital pin 2

  // Handle button "2" presses 
  if (BStatePrev==BState)
  {
    if (BState == HIGH)
    {
      Serial.println("B");
      delay(60);
    }
  }
  // Handle button "1" presses
  if (AStatePrev==AState)
  {
    if (AState == HIGH)
    {
      Serial.println("A");
      delay(60);
    }
  }

}

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 tasks, iterators, infinite 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!

Bankers algorithm

The Algorithm
The bankers algorithm seems to be a pretty simple algorithm, essentially what you do is have some defined amount of resources, and then you kick off a bunch of threads, now if there are resources left, the thread can run and do it's thing, but if there are no resources, the thread must wait.

Deadlock
The key here we need to ensure is that there is no possibility of a deadlock. A deadlock occurs when two processes are waiting on each other to run. This can happen if we lock the mutex to try to see if we have resources, and then we don't let it go if the resource doesn't exist. For example the following situation would produce a deadlock.
1. thread 1 locks the mutex, gets the last resource, and unlocks the mutex.
2. thread 2 locks the mutex, no more resources exist so, thread 2 waits for resources, (not unlocking the mutex).
3. thread 1 is finished doing it's work, and needs to return the resources. It trys to get the mutex, it's blocked until thread 2 is done, but thread 2 won't give up the lock until thread 1 is finished.

This can be avoided by forcing thread 2 to lock the mutex, check for resources, unlock mutex, then check again if needed by doing it all over again. Now when thread 2 locks the mutex, and thread 1 tries to lock it, thread 2 releases it shortly later, and then thread 1 gets it, finally the next time thread 2 comes to lock the mutex, it now has resources and can run. See? Deadlock resolved!

Additional Thoughts
Reading up on the bankers algorithm on wikipedia, it defines that each thread should declare how many system resources it will eventually need, and if the number of resources it needs is more then the system has remaining it must wait until the resources are available, since my implementation only requests one resource at a time, I didn't see the need to declare how many it would use. But my understanding of this is that the thread has itself a max number of instances allowed, so it has a max that it needs to check on. So essentially there are two resources each thread needs to handle, a system and a local, if it exceeds the local, this is an error condition, so it needs to be handled appropriately, if it exceeds the system, again it's an error and needs to be handled appropriately.


Bankers Algorithm Running
The fact is that I had way too many lines running to show it all, so I redirected the output, here is what is printed out.

Customers are coming..............     
Customer Created..............     
Doin Something Time Consuming..............     
Customer Created..............     
Doin Something Time Consuming..............     
Customer Created..............     
Doin Something Time Consuming..............     
Customer Created..............     
Doin Something Time Consuming..............     
Customer Created..............     
Doin Something Time Consuming..............     
Customer Created..............     
Doin Something Time Consuming..............     
Customer Created..............     
Doin Something Time Consuming..............     
Customer Created..............     
Doin Something Time Consuming..............     
Customer Created..............     
Doin Something Time Consuming..............     
Customer Created..............     
Doin Something Time Consuming..............     
Customer Created..............     
Customer Created..............     
Customer Created..............     
Customer Created..............     
Customer Created..............     
Customer Created..............     
Customer Created..............     
Customer Created..............     
Customer Created..............     
Customer Created..............     
Waiting until all customers are gone..............     
Doin Something Time Consuming..............     
Doin Something Time Consuming..............     
Doin Something Time Consuming..............     
Doin Something Time Consuming..............     
Doin Something Time Consuming..............     
Doin Something Time Consuming..............     
Doin Something Time Consuming..............     
Doin Something Time Consuming..............     
Doin Something Time Consuming..............     
Doin Something Time Consuming..............     
Time to go home..............     
I hope you enjoyed the information! Let me know if you have any questions!

Thursday, October 28, 2010

Register Renaming

What is the purpose of Register Renaming?

The goal of register renaming is to allow blocks of instructions to be executed out of order.
Take for example the following instructions

1. divd r5, r7, r12
2. addd r6, r7, r8
3. sd r6 0(r1)
4. subd r8, r14, r12
5. muld r6, r15, r8


Looking at these you can see that  without register renaming you have to run the instructions in the sequence 1,2,3,4,5. However if you note, lines 4 and 5 don't depend on 1,2,3. The issue is that if they run before 1,2,3 they will clober the data that 1,2,3 are trying to calculate with.

If we simply rename the registers r8 and r6 in 4,5 we can remove that dependency.

This type of dependency is called a false dependency, because the only thing preventing them from running out of order is simply you are using the same registers, not the same data.

Now look at this:
1. divd r7, r5, r12

2. addd r6, r7, r8
3. sd r6 0(r1)
4. subd S, r14, r12
5. muld T, r15,S

Now the instructions 1,2,3 can occur independent of 4,5. Since there are Read after Writes (RAW), and Write after Reads (WAR) the instructions within the 1,2,3, they must occur in order.
for example, the following orders are now valid.
a. 1,4,2,3,5
b. 4,1,2,3,5
c. 1,2,4,5,3
...
The only requirement now is that 1,2,3 occur in succession, and 4,5 occur in succession for example
the following executions are invalid
a. 2,1,4,5,3
b. 3,1,4,2,5
The reason is because the instructions are data dependent on each other "in" those blocks of code.

Any questions? Just go ahead and ask.

Sunday, September 26, 2010

Threading and Mutexes

So the overall assignment this week was more or less the same as last week, make your main/parent program call a thread to do the fibbonacci work. That was easy, so easy I did it at 3am friday morning when I couldn't sleep, in about 30 minutes, it took a little bit of rework from the fork program I wrote last week, but was simple to implement.

This morning I was thinking about mutex's.  I know that you use a mutex as a semaphore of sorts in that when you've locked it other processes needing to use it (or really use some variable you're about to modify) won't be able to.

So what I did was lock it in the child thread, then when the sibling thread attempts to lock it, it can't, and then forces it to wait until it's unlocked once the child unlocks then the sibling can print the elements of the shared memory.

Remember to include pthreads, you simply have to #include
then to compile it would be gcc -pthread -o filename.o

Good luck!

Here are a few screen shots of the results.
Fibonacci Threaded

Fibonacci with Mutexes

Tuesday, September 21, 2010

Books I would like to read 9/21/2010

Here is a list of the books I would like to sit down and spend some time reading front to back.

Let me know if you have one on your list that I would like.
Pthreads Programming: A POSIX Standard for Better Multiprocessing (O'Reilly Nutshell)
I've poked through this a bit, my buddy Phil lent me the book, and I would really like to get through it, maybe I'll knock a few chapters down this weekend if I don't have too much homework.

C Programming Language (2nd Edition) (K and R C, the definitive guide)
I borrowed this from the library at work, but only got a little into it, unfortunately work and school come first.

Mastering Regular Expressions
I borrowed this one from work, and got through the first 3 or 4 chapters, but then it started getting into the greedy etc matching and I kinda slacked off, I would like to finish this book as what I've learned from it so far has been INVALUABLE.

Linux Device Drivers, 3rd Edition
I have the second edition of this book, and it's a great book, but it only covers up to the Kernel version 2.4, the 3rd edition however covers up to 2.6 so that's great news. There is a free version of the book here: Linux Device Drivers 3rd Edition *Free

I'll give you my next list. If you've read these books give me your opinion, or maybe suggest a better one in place of the ones I've selected.

Saturday, September 18, 2010

Operating Systems -- A shared memory project

Well I decided to start hacking away at my homework for my operating systems class, in the course of about 3 hours, I managed to finish the project and make breakfast....All in all I would say it was a productive morning.

I am not going to share my source code, for reasons I'm debating about writing a post about, to make a long story short, is it ethical to post about your homework? I do think that sharing knowledge in this day and age is what will enable us (humanity) to become smarter as a whole (I think), however there is a line, explaining about shared memory for example and how it works, with examples is valid, literally posting my code up for people to simply copy and paste into their HW not so awesome.

Lets get into it, as part of the assignment we were asked to record our observations and the likes.

First off, the first problem wasn't really all that hard, initially I started to do it recursively, but decided not to, as I was just not thinking right this morning, and writing a simple for loop to do this was WAY easier.

Lets get into the meat of the project, the two main goals were forking and shared memory, the forking was relatively easy, simply creating a variable to hold your pid and then checking whether it's 0 or some other number tells you whether you are the parent or not. Then simply doing something different based on whether you are a parent or not (or if there was a pid error) was all that was required.

Shared memory was a little trickier, and I think I finally get it. Here is the deal, first we create a numerical identifier for the shared memory. Now we can begin to fork, and in the child process we create an attachment to the memory in each child process, THEN in the parent we do the same (This way we KNOW we aren't using the shared variable, it's actually memory, because we're using two different variables and I didn't assign them as pointers).

Now when you're done in the children we just detach from the processes.

In the parent we will detach then deallocate the memory. I was thinking about it, and I decided in my mind that if i deallocate that memory, then still try to point to it with my variable, I should get a segfault, guess what... I did, so that's how my program ends, with a seg fault, but it's on purpose, and I actually know why, and it just plain makes sense. Heres the output of each of the parts of my program.


Part 1
Fibbonacci with only forking
Part 2
Fibbonacci 2 with shared memory

Thursday, September 16, 2010

Kernel Modules

My ECE 437 class was assigned the monumental task of writing a filesystem driver for the linux kernel. I did a LOT of reading and finally started writing a few things, but realized I needed to be able to simply compile a kernel module just to see how to do it so I started following along with the kernel module how to here Kernel Module Tutorial

When I ran into the problem where when I called make, I would see the following error:
make[2]: *** No rule to make target `kernel/bounds.c', needed by `kernel/bounds.

I chased around the interwebs for a bit. I found out that it looks like $(PWD) wasn't returning the present directory, so I updated it to shell pwd per this site: Labjack Forums

Here is my makefile (note that in front of commands are TABS, if you replace them with spaces your makefile won't work, you've been warned)

#!/usr/bin/make -f

obj-m += hello_world.o

KERNELDIR=/lib/modules/$(shell uname -r)/build

all:
make -C $(KERNELDIR) M=$(shell pwd) modules

clean:
make -C $(KERNELDIR) M=$(shell pwd) clean




And finally here is my hello world (keep in mind it's pulled from the above tutorial)


/*  
 *  hello_world.c - The simplest kernel module.
 */
#include /* Needed by all modules */
#include /* Needed for KERN_INFO */

int init_module(void)
{
printk("<1>Hello world 1.\n");

/* 
* A non 0 return means init_module failed; module can't be loaded. 
*/
return 0;
}

void cleanup_module(void)
{
printk(KERN_ALERT "Goodbye world 1.\n");
}



Check it out. and give it a try. hopefully it works for you!

calling make all at the command line should compile it all,

and then a simple sudo insmod hello_world.ko

check out if your module was loaded via lsmod, look for it.

Now check your /var/log/messages file for your alert!

Finally do a sudo rmmod hello_world.ko to remove it from the kernel.

Thank you Caleb for the help various commands and the makefile!