Friday, February 22, 2013

Partition and Splat in Quick Sort

The Ruby Array has a partition method that takes a block and returns an array of elements for which the block evaluates to true, and a second array of elements for which the block evaluates to false.

This method can be used in a quick sort, which involves selecting one element to be a pivot and putting all other elements into either a "less than" array or "greater than" array and sorting each other those the same way.

This is a recursive sort, which means it calls itself.

def quick_sort number_array
  return number_array unless number_array.size > 1
  
  pivot, *the_rest = number_array
  
  less, more = the_rest.partition { |number| number < pivot }
  
  quick_sort(less) + [pivot] + quick_sort(more)
end

this_array = [22,66,4,44,5,7,6,8,77,33,8,99,6]


puts "unsorted: #{this_array.inspect}"

puts "sorted: #{quick_sort(this_array).inspect}"

Also interesting is the splat operator (the asterisk), which enables the new variable to take more than one parameter.  When an array is assigned to multiple variables, the splat operator allows an item to take enough elements to make the assignment work.  Above it is assigning one element to be the pivot and the rest to be partitioned.

When defining a method, the splat operator can be used with one of the parameters, enabling it to accept multiple parameters as an array.  Although it can be anywhere in the parameter list, using splat on the final parameter is preferred because extra parameters will all go into the array instead of changing how other parameters are assigned.

As used above, elements are used arbitrarily so the order doesn't matter as long as the_rest gets all but the element assigned to pivot.  I guess you could think of the left side of the assignment as the method definition's parameter list and the right as a call to that method.

Friday, September 14, 2012

Fixed vs. Growth Mindset

You are, indeed, stretchable....


Sunday, July 17, 2011

Learning Git

Scott Chacon: Getting GitImage by fraserspeirs via FlickrTo learn a challenging topic, first find someone who knows both the topic and how to teach.  For git, Scott Chacon is one of those guys.  Scott is a Rails developer working for github, THE place to host your open source git repository.  Here's Scott:

I recommend trying everything discussed yourself as the video progresses, stopping when you need more time or need to google what you don't understand.
Enhanced by Zemanta

Friday, July 8, 2011

Become a Learning Machine

BinaryImage by Xerones via FlickrIf you find your education lacking, its now easier than ever to learn your way out of it. Universities all over the world put their lectures online. You can find one that teaches the topic of interest in a way that works for you.

And if you don't understand something, you can STOP the lecture and google it until you do. Replay the few seconds of video to make sure you heard it right. Do whatever it takes. You're in control.

Become a learning machine. Then no one can stop you.

Case in point. I lack a computer science background and get stumped when asked about basic software engineering concepts like sorting algorithms.  And I'm a software engineering. Or at least I play one on TV. :-)

So I finally decided to do something about it. I've found several courses on the topic. Here's a great one from Australia:

http://www.youtube.com/watch?v=RpRRUQFbePU

All the world's knowledge is being made accessible to you. Seize the opportunity!
Enhanced by Zemanta

JavaScript Semicolon Insertion

Code reviewImage by richardmasoner via FlickrHere's a good discussion of when a Javascript developer should use semicolons.

Basically, semicolons are statement separators and there are situations where a line break won't be interpreted as the end of a statement.

Many Javascript developers put them at the end of every line, but this is unnecessary.  Its better to actually understand the cases where a line break won't end a statement.

If you use a minification tool that doesn't interpret line breaks correctly, bugs could be introduced.  But if you use semicolons only where you need to, a bad tool will probably break most things right away. And that will be obvious.  Use semicolons ALMOST everywhere and then you won't discover the problems until you test specific lines that don't have them.
Enhanced by Zemanta

Saturday, April 17, 2010

Color Tools That Will Make Your Web Shine

Creative Arts Matthew Boulton CollegeImage by jisc_infonet via Flickr

Haven't checked all of them out yet, but it looks like a very useful list of color tools.

I'm creating a new resume tool and looking for something that will let me find a professional color scheme.
Reblog this post [with Zemanta]

Wednesday, February 24, 2010

Intuit Ruby with Ruby Koans

SAN FRANCISCO - SEPTEMBER 25:  A zen garden cr...Image by Getty Images via Daylife

The ruby koans plugin promises to "walk you along the path to enlightenment" in your quest to understand the finer points of ruby.

A koan is a Zen Buddhist concept meaning "a story, dialogue, question, or statement; the meaning of which cannot be understood by rational thinking, yet it may be accessible by intuition."

Koans encourage test driven development by presenting you with tests of ruby code and challenges you to make the tests run successfully by fixing the code. Presumably, once you have acquired the intuition targeted, your test will run.

Ruby can be challenging but has a lot of power and flexibility. And some day, maybe even scalability :-)

Tuesday, January 13, 2009

Showing and Hiding Divs in Facebook FBML

By the way, Facebook provides a simple way to open and close divs on a page. Its fairly limited though. I couldn't figure out how to use it in response to selecting an option from a dropdown list.

But if you want to open or close a div whenever a particular link is clicked, all you need do is add a "clicktoshow" or "clicktoshow" attribute to the anchor tag for a ink.

This code presents the "link_only" div initially. Clicking the link it creates will hide this div and present the "link_and_about" div.

<div id="link_only">
<a href="#" clicktohide="link_only" clicktoshow="link_and_about">What is this?</a></div>
<div id="link_and_about" style="display: none;">
About text
<a href="#" clicktohide="link_and_about" clicktoshow="link_only">Ok</a></div>

The value for these attributes can be a single div id or a list of them separated by commas.

There's also a "clicktotoggle" attribute you can use for a link that will always be available.

It would be nice if you could call a javascript method from a form element that could open and close the same divs. Haven't found an easy way to do this myself, but this post has some code that could be called to simulate a click.

This code won't work as is on Facebook though, as the createEvent method is undefined. FBJS does have some event listener functionality; perhaps this code be used to make that happen. Of course, this complexity is probably more trouble than what I did above.


Reblog this post [with Zemanta]

Javascript for Facebook

Facebook, Inc.Image via WikipediaJust spent some time with Facebook's Javascript replacement, FBJS. Its a must if your Facebook app has complex things to do.

FBJS rewrites all of your method and variable names so your code is confined to a sandbox and cannot mess with any of Facebook's code.

This renaming confines your code to a document called "aXXXXX.document", where "XXXXX" has to be your Facebook app's numeric id. So if you have this code:

document.getElementById('choice2_info')

Facebook changes it to this:

a19756161464_document.getElementById('choice2_info')

You can see this if you look at the source for the page finally presented by Facebook.

You'll also see that the id attributes for HTML elements are also changed in the page source. The original attribute may have been:

id="choice1_option_id"

but is actually rendered as:

id="app19756161464_choice1_option_id"

When using making use of methods and id, your code should use the originals, not the replacements. The FBJS version of getElementById will add the appropriate prefix to whatever you pass it, so it will look for an element with the id "app19756161464_app19756161464_choice1_option_id" if you prepend the id first.

FBJS also requires that you use different method names than you would if you are writing straight Javascript. For example, instead of using ".target" to look at or change an element's target, you use ".getTarget" or ".setTarget".

You can see a list of the methods affected here. There is much more on FBJS on that page and I highly recommend reading and understanding the material there before beginning a project.

If you do anything complex, you'll probably want to use a tool like Firebug to set breakpoints and watch the values of key expressions. I had a lot of trouble with the newest version, but version 1.2.2 worked fine.


Reblog this post [with Zemanta]

Wednesday, December 3, 2008

Capitalism in the Workplace

Plot of S&P Composite Real Price Index, Earnin...Image via WikipediaA bit more on the compensation end of what I spoke of.

I would love to see people derive a large part of their compensation from revenue from the projects they've worked on. Employees could be given a percentage of the project's profits (shares) in exchange for not getting part of their salary.

If a project fails, employees would lose money too.

But what if employees could buy and sell those shares of the project's future revenue (or some amount of money earned by success) in an internal market? A stock price for all your projects would give you a pretty good idea of what employees working on the project really think.

What could be more valuable? Believe me, employees will not be blowing sunshine you know where when their own money is at stake.

I'd also make it so everybody could select what projects to work on and could leave them if they decided another project would be more profitable. By having some skin in the game and being able to act in their own interests, employees would be helping make decisions about where the company can most profitably deploy its capital.

Can't get on a project? Maybe you need some skills development or a course in manners. The company can offer a coach that gets his extra compensation only when you're on projects that succeed.

Still can't get someone to pick you for your team? Well maybe your base compensation starts declining gradually until you change that situation or decide another easier company is right for you.

I think such an approach would make everyone in the organization tune in to what really matters. High value opportunities, revenue-rich markets, eliminating effort wherever it doesn't create value. And everyone would be selling themselves, selling others on opportunities and selling to the world.
Reblog this post [with Zemanta]

How About Really Going Capitalist?

Adam Smith (1723-1790) {{he|דיוקנו של אדם סמית}}Image via Wikipedia

Why is capitalism more productive than centralized economic systems? Perhaps its because people have incentives to make decisions that benefit the system as a whole.

Most companies make their decisions from the top down, making them more like the Soviet Union than a free market economy. But could they make a change?

I would like to see companies be more like startups internally. Employees know an enormous amount about the markets, technology and other employees that goes unleveraged when decisions are made from the top down.

I'd like to see people rewarded for the risks they take and for making decisions when their own compensation is at stake in the projects on which they work.

An important strength of capitalism is its decentralization of decision making, with commensurate risks and rewards. But traditionally companies are run from the top down, which makes slower to react and much more inaccurate when they do.

Startups do a much better job at taking risks and responding to the market. But there are advantages to scale that they cannot benefit from at the same time. But a large company could combine both with the right philosophy and information systems.

Interestingly, part of the appeal of scale comes from the tax code. Transactions between companies are taxed, but transactions between employees in a company are not, so the tax burden is lower per transaction. But often the loss of effectiveness more than swamps the advantages in size.

Reblog this post [with Zemanta]

Saturday, November 29, 2008

Ideas are the Bomb

Arizona Passive Rain Water Collection System (...Image by cogdogblog via FlickrI'm currently working on a provisional patent application for this idea I have, which will make life significantly better for older people.

I'm also reading a book on the topic called Patent Pending in 24 Hours. A good resource, but its taking way more than 24 hours!
Reblog this post [with Zemanta]

Tuesday, November 11, 2008

Modelizer

Journey to the Heart, a poem (89800031)Image by Shutterhack via FlickrI wrote a little Rails app called Modelizer back when I was first learning about Rails model associations.

Modelizer looks at the databases that your other Rails are using and identifies possible associations based on the naming conventions Rails uses for database table and column names.

Modelizer creates an ActiveRecord object that connects to the selected application's database using the credentials in each app's database.yml.

What should normally go in the model for an MVC app was pretty hard to pin down for this app, so most of what should be in the model is stuck in the controller. The model isn't specific to one schema, but actually would have to use databases instead of tables and hadn't really wrapped my head around how to do that. Basically, ActiveRecord handles tables, not entire databases and this app treats all of your schemas as the model.

This also uses AJAX when you drill down into tables and the possible associations for each.
Reblog this post [with Zemanta]

Friday, November 7, 2008

Using REST for a Facebook Application

Image representing Facebook as depicted in Cru...Image via CrunchBaseIf you're into Ruby on Rails, you've probably heard a lot about REST. It supposedly simplifies your life, but in many situations, things actually get more complicated.

Building Facebook apps is one of these situations. I've been using the Facebooker Rails plugin that helps you interact with the Facebook API.

Facebooker gives all requests from Facebook an "fbml" format. You need to add this line to your config/initializers/mime_types.rb file:

Mime::Type.register 'text/html', :fbml

You need to handle this format when you call respond_to:

def index
@facts = @topic.facts

respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @facts }
format.fbml end
end

The meaning of RESTful requests depends on which method or HTTP verb is used.

When GET is used and the path is "/topics/4/facts", the request is routed to the controller's "index" action. In this example, all the facts for topic 4 will be returned. But if POST is used, the request is routed to the "create" action, which will ry to add a new fact to topic 4 (these are nested resources).

But all Facebook requests are made with GET, so your code or your plugin needs to look at a request parameter called fb_sig_request_method to see which method was used initially.

One problem I had was deleting something RESTfully from a Facebook canvas page.

Normally, clicking a RESTful delete link created by Rails causes Javascript to run that creates the confirmation popup and a form that passes the authenticity_token variable required for deleting something.

But Facebook doesn't allow you to execute javascript so you can't rely upon the javascript normally created by the link_to tag to create the form when the page is loaded.

You can't create the form in HTML and then use FBJS to submit it either; Facebook rewrites your forms, dropping the name attribute. So you can't call the form when you click a link.

In the end I had to settle for confirming the deletion on a page of its own. And a less than desirable button had to be used instead of a link because Facebook links can't submit a form. So I'm still not happy with the outcome.
Reblog this post [with Zemanta]

Tuesday, November 4, 2008

Facebook Plugins

Facebook, Inc.Image via WikipediaThere are two Facebook plugins for Ruby on Rails. Both help you deal with the Facebook API.

RFacebook was the first Facebook plugin introduced and is basically a wrapper around the Facebook API enabling you to call it through plugin methods whose names map to the corresponding call in the API. If the API changes, the plugin supports that. You can use Facebook docs to figure out what to do and you can get data in XML or JSON.

RFacebook was intended to be quick and dirty and the author even stated early on that developers should eventually move to Facebook. But many people stuck with it.

Facebooker does things "the Rails Way", and gives you methods that follow Rails conventions. Data is delivered in arrays and hashes Ruby developers are used to working with. In addition, there are classes that help you with publishing to feeds and sending notifications.

With Facebooker, being able to deal with ruby objects saves development time. But you aren't always aware of whats happening under the covers. Sometimes a call to Facebook is initiated when you don't expect and that costs you time. Its an even bigger deal on Rails because your Mongrel can't service any other requests while its waiting for Facebook to respond.

The support for Facebooker has been questionable at times also, since the original auther Chad Fowler left the project. Code has been checked with typos, the entire project was simply moved to github without sufficient notification (even the Facebook app for the plugin pointed to an unusable SVN version for weeks) and some of code was baffling to use. The template registration stuff, for example, took me some major digging through the code to figure out what to do and it didn't even work.

Of course, some of these issues are due to Facebook changing so frequently, but at least with RFacebook, you're rely upon Facebook documentation rather than on the ability of Rails developers to code against each version of the API. Either way its still a moving target sometimes.

Facebooker does give you some help with REST, but even that took me quite a while to figure out how to use that successfully. I do use Facebooker for my grokLokker Facebook app and its stable enough for what I'm doing. But I doubt I'd use it if I had t to due over.
Reblog this post [with Zemanta]