Monday, May 13, 2013

Making RequireJS and AngularJS Play Together

If you have to make AngularJS and RequireJS play together, here's how to do it.

1. Make Angular wait until you're ready.

  • Remove the ng-app from your HTML. This way, Angular won't run before Require has gathered dependencies.
  • In your main JavaScript file for Require, start Angular manually:
require([], function(){
  
  //... snip ...

  //start angular after dependencies are gathered
  //I'm using document here, but it should be whatever element 
  //you'd put the ng-app on normally
  angular.bootstrap(document, ["moduleWithControllers"]); 
});

2. Put your RequireJS stuff into an Angular module

  • This lets you stay Angular-y from inside Angular code!
  • This should also be in the main .js file for your Require stuff, before running bootstrap()
require(['someDependency'], function(someDependency){
  
  angular.module('requireStuff')
    .factory('someDependency', function(){
      //make this require object or whatever available to angular
      return someDependency;
    });

  //from section #1
  angular.bootstrap(document, ["moduleWithControllers"]); 
});

Then from the Angular code:
angular.module('moduleWithControllers', ['requireStuff'])
  .controller('MyCtrl', function($scope, someDependency){
    //do something with someDependency
  });

3. Get Angular libraries into your Require modules (Optional)

  • This lets you access libraries provided by Angular from outside of Angular code.
  • Warning: These won't be available until after Angular runs the first time, after all Require dependencies are gathered
define([], function(){
  var result = {
    $http: null,
    $q: null
  };

  angular.module('requireLibStuff')
    .service('randomService', function($q, $http){
      result.$http = $http;
      result.$q = $q;
    });

  return result;
});
Then you just need to reference the service from your angular code:
angular.module('main', ['requireLibStuff'])
  .controller('MyCtrl', function(randomService){
    //randomService won't be used, it's only referenced here 
    //to make Angular run the code above
  });

Update

I forgot to mention something for step #3 above: most Angular-provided libraries only work if called within Angular code. For example, the $q.defer() object will only notify its listeners if resolve/reject are called from within the regular Angular $apply and the like.

Wednesday, January 9, 2013

Check All Bookmarklet

Here's a bookmarklet for checking or un-checking all check boxes on a web page. It will flip the first check box, then set all the others accordingly.

check!

Here are a couple checkboxes, just to try it:
Here's the code, de-minified:
(function(){
 //all inputs on the page
 var cbs=document.getElementsByTagName('input'); 
 //the value for the checked (true of false)
 var cv;
 //the current checkbox
 var cb;
 
 for(var i in cbs){
  cb=cbs[i];
  if(cb.type=='checkbox'){
   if(cv==null)
    cv = !(cb.checked);
   
   cb.checked=cv;
  }
 }
 
 void(0); //prevent the bookmarklet from switching pages
})() //call the anonymous function


To get this bookmarklet, just drag it to your bookmarks toolbar or your bookmarks area. Click it whenever you want to use it.

Arduino - HSV to RGB

I got an Arduino for Christmas, along with a cool starter pack that contains all kinds of cool switches, LEDs, wires, etc. My favorite component to play with so far is the RGB LED. It has red, green, and blue LEDs inside of one unit, so you can use it to fake any color.

I started with making it just show random colors, but then thought I could do better. The code below chooses a random Saturation and Hue, then turns the brightness all the way up, all the way down, and then starts over again.

//these have to be attached to PWM pins
int REDPin = 6;
int GREENPin = 5;
int BLUEPin = 3;


int vIncrement = 5;

unsigned int h = 0, s = 0, v = 0; //hsv
unsigned int r, g, b, hh, c, x, m;


void setup()
{
  pinMode(REDPin, OUTPUT);
  pinMode(GREENPin, OUTPUT);
  pinMode(BLUEPin, OUTPUT);
  randomSeed(analogRead(0));
  Serial.begin(9600);
}

void loop()
{
  v = v + vIncrement;

  if (v <= 0){
    h = random(0, 360);
    hh = h / 60;
    s = random(0, 255);
  }
  
  if (v <= 0 || v >= 255)    // reverse the direction of the fading
  {
    if (v > 0x10000) //handle overflow - unsigned int
      v = 0;
    vIncrement = -vIncrement;
    v = constrain(v, 0, 255);
  }
  
  c = (v * s) / 256;
  x = (c * (60 - abs(h % 120 - 60))) / 60;
  m = v - c; // 44
  
  switch(hh){
    case 0:
      r = c + m;
      g = x + m;
      b = m;
      break;
    case 1:
      r = x + m;
      g = c + m;
      b = m;
      break;
    case 2:
      r = m;
      g = c + m;
      b = x + m;
      break;
    case 3:
      r = m;
      g = x + m;
      b = c + m;
      break;
    case 4:
      r = x + m;
      g = m;
      b = c + m;
      break;
    case 5:
      r = c + m;
      g = m;
      b = x + m;
      break;
    default:
      r=g=b=m;
  }
  
  
  r = constrain(r, 0, 255);
  g = constrain(g, 0, 255);
  b = constrain(b, 0, 255);
  analogWrite(REDPin, r);
  analogWrite(GREENPin, g);
  analogWrite(BLUEPin, b);

  delay(20);  // wait for 20 milliseconds to see the dimming effect
}

There are lots of algorithms out there for converting HSV to RGB, but I didn't like all the converting between float and int. This one does it only using unsigned ints (my Arduino uses 16-bit numbers, so I needed them unsigned to prevent overflow). It was based on the Wikipedia HSV page.

(For this algorithm, S, V, R, G, B are in [0, 255] and H is in [0, 360])

Tuesday, October 25, 2011

Lego Creeper

It ended up a little short, but was made from enough bricks to fill the $15 container at the Lego store.

Friday, August 20, 2010

Blog!

This is a blog entry.

Saturday, February 27, 2010

Software Design Lessons for Business People

At work recently, a client requested a huge, complicated (but really cool) feature. Because it was such a cool feature, I slightly underestimated in hopes that the client would approve it. When they found out about the estimate, the client was surprised it was so high - I think they even called it "absurd!" They thought the (huge, complicated) feature would take no more than 2 hours.

This isn't the first time something like this has happened. Most business people seem to think that the hard part of software development is thinking of how a feature should work. In other words, "I can think of how it works, so programming it must be easy!"

So, business people, here's a good way to think of software development. Imagine that you have a worker who only speaks Italian. You have a simple task that you want him to do. However, this particular worker does exactly what you tell him, only what you tell him, and all of what you tell him. So you have to come up with exact instructions, translate them into Italian, watch him try to perform the action, then alter the original instructions if things don't go the right way. How many times would you have to let him go through the procedure before you got it right? How many provisions would you have to create for unusual situations?

Now take that employee and make it a computer. That's software development! We have to translate requirements into exact instructions that the computer understands. Coming up with the requirements is important, but it's just the first step of a long process.

Thursday, August 6, 2009

Real Life! AHHHHH!!!!!!!

With graduation came the realization that I'm now doing what I will be doing for the rest of my life. And I want writing on this Blog to be a part of it. So I'm now planning to do more posts, and make them more meaningful.

This Blog started out as a school project, so I didn't really get a choice about what topics I could write about. Now I get to decide what to make this blog about. After that class was over, I scrambled to post, wanting to make this a great blog. I still didn't really have the time to think about a theme for my blog, though. I'm still thinking about that, but I have some pretty good ideas so far:
  • Life
  • General Geekiness (video games, hacks, TV, books...)
  • Advanced Geekiness (programming, Internet, Linux, software companies, math...)
  • Music
  • Random stuff that interests me

I'm aiming for a post about twice a month, with at least one of those being geeky. That's starting in August, with this post not counting!

Tuesday, March 10, 2009

HBO: Not Surprising

Big Love's ratings must be really bad. Why else would HBO be pulling such an outrageous publicity stunt?

For anyone not familiar with the story, Big Love is planning on including an LDS Endowment Ceremony in their next episode. In The Church of Jesus Christ of Latter-Day Saints, this is a sacred ceremony that not everyone can attend. Only worthy members of the church can go to a Temple and be in this ceremony.

It's working. The Church didn't bite (in fact, they urged members not to respond!) But individual members have been organizing protests and boycotts.

When people mock something sacred, it doesn't make the thing less sacred - it makes the mockers less sacred. Don't watch it, but don't give them what they want either. Jesus Christ lived his life not organizing protests against the Pharisees, but teaching love. Let's follow him.

(And for anyone who's tempted to tune in, let me give you this warning: HBO also made Sex and the City. If Big Love is anything like it, it's melodramatic, boring, and has ugly actresses.)

Friday, February 27, 2009

Utah by Habit

I'm going to go out on a limb and say that most people who live in Utah are here by habit. It's funny because Utah culture (= Mormon culture, derived from Mormon doctrine) says that you're supposed to pray about big life decisions such as where to live. Most of the people who live here are here because they grew up here. Some of them even have myths about the outside world - that it will be destroyed (not backed by Mormon doctrine), or that it's exceptionally evil (out of ignorance).

Here's what I think. No, I'm going out on another limb - this is the truth. For the most part, God wants Mormons everywhere in the world right now. A Latter-Day Saint can do more good outside of the Great Utah Valley Bubble (GUVB) than inside. And if you haven't considered moving outside of Utah, you haven't adequately "studied it out in your mind."

So rest assured: wherever I end up after graduation, we'll have decided to go there after lots of thinking and lots of prayer. We're not ending up on either side of the GUVB without knowing that it's the right place.

Monday, February 9, 2009

25 Things

In honor of the Facebook "25 Things" fad, here are 25 completely random statements.

  1. The word monosyllabic should be monosyllabic! I suggest splag.
  2. Jack Handey was a genious.
  3. I like spelling things wrong (see above.)
  4. There will be no #17.
  5. They have reruns of The Critic on a channel called Reelz!
  6. I have a shirt that says "Keeping South Brunswick Clean."
  7. In OpenGL, you rotate by glRotate{df}(angle, x, y, z)
  8. In JOGL, you rotate by gl.glRotate{df}(angle, x, y, z)
  9. Wii!!!!!!
  10. Everybody shout, "What's the big idea?!??!"
  11. This song comes from the heart of my bottom. (-Brak, on Brak presents the Brak Album starring Brak)
  12. The movie The Santa Clause ruined people for spelling Santa Claus forever.
  13. It's really hard to think of 25 completely random things!
  14. I bet the movie Arachnophobia causes arachnophobia. They should do a study.
  15. People drive bad!
  16. My favorite Utah fake swears: Oh my heck, What in the Sam Hill (apparently "Sam Hell" is a term, who knew?), and of course, Good gravy.
  17. #4 is a lie.
  18. I never said any of these things had to be true.
  19. Writing good is hard.
  20. It is your birthday.
  21. eia = cos a + i sin a
  22. I couldn't figure out how to do a theta in blogger or HTML.
  23. I should be doing my homework.
  24. There will be no #17.

And the number one thing overheard at the Winter Olympics:
"Why did I come here when I could be home playing Wii????"

Saturday, November 8, 2008

Re-dispatching an Event in Flex

There's a trick to re-dispatching a custom event in Flex, and I always forget what it is. Hopefully, I'll remember to look at my own blog the next time I get stuck.

Here are the symptoms this solves: You're dispatching a custom event in one component, then catching that event in another component, only to dispatch it again. But the event never gets to the next component up, which is listening for it.

The reason it's not working is because the flex.events.Event.clone() method is being called when you call dispatchEvent() the second time. All you need to do is override it that function in your custom Event class:


public override function clone():Event{
return new MyEvent(type, mytype1, mytype2, bubbles, cancelable);
}


This fixes the problem every time, and the re-dispatched event will get to the next component. Of course, if you're doing more than two layers of dispatching to get what you want, you may want to consider a better design, but this is useful as a quick hack.

Monday, October 20, 2008

Don't be a Robot!

I am sick of American politics. Watching the past few debates has reminded me more of two preprogrammed robots than anything. Rather than seeing how their ideas bounce off of each other, they just keep saying the same things over and over again.

We already know how you stand on economic policies! We know what you think about foreign policy! What we want to know is why you think that way. We want to see that you've thought out your stance, not just that you have one! We already know that!

Conversely, here's what my ideal candidate would say:
I acknowledge both that there are benefits to both raising taxes on the upper class, and lowering taxes for everyone. There needs to be a balance between helping the poor and helping the economy. That balance is (insert a thought-out economic policy here). The balance lies there because (insert reasoning why the line is there)

The point here is that Democrats and Republicans both have good ideas, and I have never heard a candidate attempt to take the best of both! (And of course, those two parties don't have a monopoly on good ideas) Robots can be programmed to defend any policy. A human will think about those policies, apply reason, and come up with something better!

Thursday, October 16, 2008

Flex Builder in Linux!

I was excited to learn today that Adobe is working on a version of the Flex Builder Eclipse plugin for Linux. It's available now in alpha. It doesn't do some of the design layout stuff yet, but it does do code completion and syntax highlighting. (Besides, only people who hate source code use the design layout tool!)

One word of caution: the plugin currently only works with Eclipse 3.3.x! Ubuntu gave me Eclipse 3.2.2, which didn't work with it, so I tried the latest release, 3.4.1. That one doesn't work either! You need 3.3.x.

Anyway, here's the download page. You get much longer than the standard 60-day evaluation period. Enjoy!

Saturday, July 26, 2008

Democrats are Cool

After a lifetime of compulsive TV watching, I've learned some interesting things about politics.

Democrats are cool. Their policies are socially acceptable. They represent the downtrodden, work-class people.

Republicans are socially backward. The only reason they're not as smart as Democrats is because either:
  1. They're Southern, and don't know how to read, or
  2. They can read, but the only things they read are Christian.
Whether an individual Republican is to be mocked or pitied depends on their belligerence. Ann Coulter, for example, is extremely outspoken, and should be mocked as harshly as possible. Poor, religious people are to be pitied until they start talking about Christianity, at which point they become belligerent.

I'm not making an argument for either side here. I'm simply stating the message of the Viacom Propaganda Machine.

Saturday, June 28, 2008

Long Time Coming

OK, so I've been lazy. This is my first post in 5 months. I was going to school, but I don't really have an excuse for the last 2 months of summer vacation.

Anyway, here's some funny stuff I found in the last 5 months:

Funny Adwords - Some actual Adwords that people have seen. Pretty funny.

Demetri Martin - Findings



And here are some more Demetri Martin videos. He's funny.


Mandelbrot Set video



Ha. Clever.

I don't know if I actually have an audience, but if so - look for more posts soon!

Thursday, January 10, 2008

My Top 5 Firefox Add-ons

One of the great things about Firefox is all the cool add-ons available. If there's anything you don't like about Firefox, there is an add-on to change it. And I have the same add-ons for my Linux machine as I do for my Windows machine, so it's pretty good that way too. It's always a pain to have to switch between different tools that do the same things.

So, without further ado, here are my favorite Firefox add-ons:

  1. PDF Download
    This one allows more flexibility about what FF does with PDFs. Instead of just opening it in-browser, it allow you to download it, open it in a new window, or view it as HTML.
  2. IE View Lite
    Firefox is great, but not all sites were programmed with the idea that anyone will access them without IE. On Windows systems, this allows you to quickly view the current page in IE.
  3. Resizeable Textarea
    This gives you the Safari-like functionality of being able to resize large text fields.
  4. Server Spy
    Lets you know in a little section at the bottom of the FF window what kind of server a site is using. It's interesting information. Always fun to see the broken sites running IIS and say, "Oh, well there's your problem!"
  5. Web Developer
    By far my favorite FF add-on. This gives you a little toolbar with more web development tools than you would ever need. It gives css and javascript tools, shows you divs, classes and ids, style information for a given element, and lots more.
So enjoy these, and make the move to FF if you haven't already!

Thursday, December 13, 2007

Ethical Roads

Ethics don't exist without opposition. Luckily, the world is full of opposition. People can either hold to their ethics or give in.

If they hold to their ethics, they should be prepared to fight, be unpopular, and feel like a loser. Bosses don't like to be told, "No." Friends don't enjoy being corrected. Of course, this won't always happen to the ethical, but they should be prepared for it, as it's likely.

If people give in and take the easy road when an ethical roadblock appears, their ethics will change. Ethics that aren't held are not ethics at all. Stated differently, when people give in to something against their personal code of ethics, that code of ethics is decreased.

Choose the hard or easy road, and be prepared for the consequences.

Tuesday, December 11, 2007

Go Forth

Forth is an interesting little programming language. First of all, it's stack based, so to do 4 + 5, you would actually need to type 4 5 +. Next, it's a compile-as-you-go language. Defining new "words" for your program is literally extending the compiler. And finally, its grammar is nothing more than a string of defined words.

Forth is used for embedded systems (in fact, according to forth.com, it's used today), and has been used in the past for arcade games.

Tuesday, November 13, 2007

PHP CGI Weirdity

I don't know why anyone would ever want to programmatically call the CGI version of PHP, but there's a slight weirdness you'll have to deal with. If you call it with just the normal CGI environment variables, PHP will complain that it was compiled with "--enable-force-cgi-redirect," and that it needs some extra stuff.

Here's that stuff:
1. REDIRECT_STATUS. I just set this to 200, and it seemed to work. Pretty sure that refers to the HTTP status, but I really haven't researched it at all.
2. PATH_TRANSLATED. This is just the location on disk of the php script to run.

Setting these two seemed to work, but (just for kicks) I also set REDIRECT_URL = SCRIPT_URL = REDIRECT_SCRIPT_URL = the URL (minus the server name, ie "/dir/script.php".)

Monday, November 12, 2007

Fun With PERL

I'm pretty proud of myself right now, because I just used PERL to do something cool. In my 360 class (CS 360 - Internet Programming) we're building a web server, and I keep finding new mistakes of mine to fix. It's going well, but there seems to be some kind of limit in Linux to the number of semaphores I'm allowed to create. So when my program dies a few times (without removing the semaphores it created), it won't create semaphores on restart. Up till now, I've been restarting the computer when this happened.

Did some investigating, and I found out that there's a nice little utility, ipcs, that prints out all the IPC (interprocess communication) stuff - message queues, shared memory, and (of course) semaphores. There's another nice little utility, ipcrm, that removes IPC stuff.

I could go through and remove all my semaphores every time, OR I could use my newfound PERL knowledge to make the computer do it for me. Being a geek, I found the second option way cooler.

Anyway, here's my code. Enjoy! (Note that I don't guarantee it on anything. Also, note that it deletes ALL semaphores under your user. So don't run this if anything else you're running is using semaphores. Finally, use this at your own risk!)


#!/usr/bin/perl

open(IPCS, "ipcs|") || die("Couldn't run ipcs.\n");

$startedSems = 0;
while (<IPCS>){
if ($startedSems){
if ($_ =~ /------ Message Queues --------/){
$startedSems = 0;
}
else{
($currkey, $currid, $usr) = split /\s+/;
if ($currid != "" && $usr eq "yourUserNameHere"){
$cmd = "ipcrm -s " . $currid . "|";
open (IPCRM, $cmd);
while (<IPCRM>){
print;
}
close(IPCRM);
print "Removed sem id=$currid\n";
}
}
}
else{
if ($_ =~ /------ Semaphore Arrays --------/){
$startedSems = 1;
}
}
}
close(IPCS);


Oh yeah, two more things. Change yourUserNameHere to your user name. And last of all, either chmod a+x the file to make it executable, or perl it.