Wednesday, August 17, 2011

C++ Practice

After searching for a while, I found that this is the best place for information on converting an int to a string in C.

Thursday, August 11, 2011

Practice Problems

I am always looking for fun and interesting problems to practice my programming and/or math.  The problem is they are hard to find on the internet in my opinion.  Here is a list that will continue to grow as I find more. 

1.  Project Euler - I love this page!  The problems scale, so as you learn about and solve the problems, they tend to get harder as you go.  A great way to practice any programming language and learn a little math in the process. 

2.  Coding Bat - Actually written for Java or Python.  Geared towards beginners, if you are interested in learning either of those languages. 

3.  Six Revisions - Their own comprehensive list of links to problems.

4.  TopCoder - These problems are more geared towards intermediate and advanced level programmers.  A very active community and tons of practice problems here for C++, C#, Python, and Java mostly. 

5.  Ruby Quiz - Another large list of problems, but without much activity in their community.  Still a great resource for problems to be solved. 

Ruby Tutorials

Over the last few weeks I have found quite a few places that have been helpful in learning about Ruby, I wanted to make a comprehensive list here for any that come after.  Digging through Google can be tedious sometimes. 

Ruby Essentials

Mr. Neighborly's Humble Little Ruby book

Tutorials Point

Watir Tutorial: Logging into EnterpriseOne

Here is a great little example to do so that we can log into EnterpriseOne and thereafter get our testing groove on.  Here's the code, and thereafter I will explain what is going on. 

  1. require 'rubygems'
  2. require 'watir'
  3. b =
  4. b.goto("")
  5. b.text_field(:name => "User").set "myUserID"
  6. b.text_field(:name => "Password").set "myPassword"
  7. b.button(:type => "submit").click
  8. b.wait_until {b.form(:action => "/jde/E1Menu_FastPath.mafService?e1.state=maximized&e1.mode=view&e1.namespace=&e1.service=E1Menu_FastPath&RENDER_MAFLET=E1Menu").exist?}

Lines 1 through 3 are described elsewhere

4.  Tell the browser object to go to your EnterpriseOne login page. 

5.  Set the 'UserID' field to your user name.

6.  Set the 'Password' field to your password.

7.  Click the submit button.

8.  This will wait until the Fastpath button is visible to Watir, it is great for ensuring that enough has loaded for your script to continue and execute the next operation successfully. 

Ruby Tutorial: IDEs

Personally I am a fan of NetBeans.  It was the easiest to get working with Ruby and Watir for myself.  It will run on Eclipse, and even Visual Studio, among other programs I am sure.  The most basic way to write scripts is to do so in the console, but that is tedious. 

As for NetBeans, the newest version 7.0.something will not work with Ruby, so be warned!  You have to go download version 6.9.1.  From there go to the Tools menu bar and then to plug-ins, from there you can find Ruby and install it.  Any extra gems that you are interested in using, you will have to install either manually or through the console using the "gem install xxx" and then 'require' it from within your script. 

As for Visual Studio, there is a flavor of the language called 'IronRuby' that is being developed to play nicely with C# and thereby Visual Studio.  I tinkered with it a little bit trying to see if I could get decent database connectivity but was unable to.  I'm not an expert, so I wouldn't call it an impossibility but IronRuby is certainly something to look at if you are interested in that sort of thing. 

Project Euler #4 in Ruby

Project Euler #4

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.  Find the largest palindrome made from the product of two 3-digit numbers.

Another great example here! 

  1. success = 0
  2. for i in (100..999)
  3.   for j in (100..999)
  4.     k = i * j
  5.     if (k.to_s == k.to_s.reverse && k > success)
  6.       success = k
  7.     end
  8.   end
  9. end
  10. puts success

What happens here is very straightforward, because he is asking for two, three-digit numbers multiplied together, it immediately tells us the constraints of our two for loops, and thereby the maximum possible value we could have:  999x999 or 998001.  What we need to do then is just compare the value we get from multiplying them together, and then the reverse of that, thereby checking to see if it is palindromic.  It's super easy in Ruby as well, you just have to convert both to strings using the '.to_s' operator and then the '.reverse' on one of them.  In line 5 the first conditional 'k.to_s == k.to_s.reverse' checks to see if it is palindromic and the second if it is greater than the last palindrome that we found, because there will be many.  If it is, the line 6 states that we save it. 

This code runs in just over a second for me, satisfying the 1 minute guideline set forth by the project Euler team. 

Project Euler #3 in Ruby

Project Euler #3

The prime factors of 13195 are 5, 7, 13 and 29.  What is the largest prime factor of the number 600851475143?

 Here is my solution in Ruby:

  1. def lPrimeFactor(n)
  2.   i = 2
  3.   largest = 0
  4.   while (i <= n)
  5.     if (n % i == 0)
  6.       while (n % i == 0 )
  7.         n = n / i
  8.         largest = i
  9.         i += 1
  10.       end
  11.     end
  12.     i += 1
  13.   end
  14.   return largest
  15. end
  16. puts lPrimeFactor(600851475143)

This is a great example for defining methods (or functions if you are a 'C' guy or gal).  You will notice in line 1 the 'def lPrimeFactor(n)'.  'def' is the keyword for 'define', as in 'define function'.  Whenever you define a function you also have to end that definition, as you will notice in line 15.  The declaration of our function here to find the largest prime factor is written in camel-case, while the standard is to write it in all lower-case.  You may write it however you like, if you use NetBeans though it might get grumpy at you. 

In explanation of the code I have written here, all it does is check to see if 'i' is a factor of n, if so it will divide it and then continue to do so until it is not (like in the case of 8, it would divide by 2, three times), and then continues on to the next number working its way up until i is smaller than n, keeping track of the factors and returning the last one it divides successfully. Pretty straightforward. 

Project Euler #2 in Ruby

Project Euler #2

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Here is my solution:

  1. one = 1
  2. two = 1
  3. sum = 0
  4. while (two <= 4_000_000)
  5.   temp = one
  6.   one = two
  7.   two = one + temp
  8.   if (two % 2 == 0)
  9.     sum += two
  10.   end
  11. end
  12. puts sum

You will notice the '_' symbol where the commas would be (or periods if you don't live in the States), for reference in keeping track of how many zeroes we have if we were writing '4,000,000' out by hand.  Coding up '4_000_000', is basically the same, the compiler will ignore the underscores.  It is just so we can keep track of how many zeroes there are. 

I wanted to illustrate something handy in this tutorial, called 'parallel assignment'.  Nothing earth shattering, but it could cut down on the number of times you have to press the enter and equals key.

Ruby allows you to assign variables to values, lined up one after the other, on a single line of code.  If you will notice we combined lines 1 through 3 above into a single line (1) below.  The same is true for lines 5 and 6 above into a single line 3 below.  Line 4 below is still on its own line as Ruby won't let you do arithmetic while doing parallel assignment. 

  1. one, two, sum = 1, 1, 0
  2. while (two <= 4_000_000)
  3.   temp, one = one, two
  4.   two = one + temp
  5.   if (two % 2 == 0)
  6.     sum += two
  7.   end
  8. end
  9. puts sum

This isn't the most clever way of solving this problem, but certainly the easiest to understand.  We simply do what the question asks for:  Add up each even term of the Fibonacci sequence below 4,000,000. 

Wednesday, August 10, 2011

Project Euler #1 in Ruby

Project Euler #1

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

The problem is fairly straightforward, and is the most correctly answered problem in the whole set.  I will be explaining a little bit of Ruby in this solution I give.

  1. x = 0
  2. sum = 0
  3. while (x < 1000)
  4.   if (x % 3 == 0 && x % 5 == 0)
  5.     sum += x
  6.   elsif (x % 3 == 0)
  7.     sum += x
  8.   elsif (x % 5 == 0)
  9.     sum += x
  10.   end
  11.   x += 1
  12. end
  13. puts sum

1.  This is the declaration of a variable in Ruby, and you will notice you do not have to declare its type.  It is inferred from what the variable is set equal to when it is declared.  Handy!  This is what is meant by being a "dynamically typed language", other programming languages like C require you to declare the variable's type at declaration and forever afterward it is of that type.  This is referred to as a "statically typed language". 

2.  See line 1.

3.  While loops in Ruby are very similar to those seen in Java or C++, the difference being we don't use brackets, instead we get a great deal of use out of 'end' statements.  You will notice that everything within the while loop is tabbed out once (at least).  If you use NetBeans, or Notepad++, or some such fancy editor, it will automatically do this and help you see where your blocks of code are located.

What you need to know for 'while' loops, is that you need the keyword 'while' then a conditional, and to close the 'while' block, you must include the 'end' keyword, just like I did on line 12. 

For more information on while loops in Ruby, you may use Tutorials Point, or the slightly more concise Techotopia wiki.

4.  This is our first look at 'if' statements.  Again, very similar to C++, even in the modifiers '&&' or '||' which are 'AND' and 'OR' respectively, in how they modify logical statements. 

In our case, line 4 says "if x modulus 3 is equal to 0 and if x modulus 5 is equal to 0 then...", and that is all there is to it!  For those new to the game, modulus is just looking for the remainder after we divide.

For example:  6 % 5 = 1, because 6/5 = 1 R 1, where 'R' stands for 'remainder', and % stands for 'modulus' or 'mod' for short.

If you would like to learn more about the modulus, or the area of modular arithmetic in mathematics, you can look here, for a quick primer on the subject.

5.  Line 5 is just what it looks like for anyone that has used C or Java, the "+=" operator takes the left hand side and simply adds to it the right hand side.  For example:

  1. x = 0   #=> 0
  2. x += 3  #=> 3
  3. x += 39 #=> 42

6.  An 'elsif' statement is just an "else" and "if" statement crammed together, and takes a conditional just like the 'if' statement in line 4.

10.  We will skip to line 10, as lines 7 through 9 are explained previously.  All there is to explain here is that when using 'if', you must also close the block with the 'end' keyword.  This is not true for an 'else' or 'elsif' as these are part of a larger 'if' block or statement.

13.  This is the last line in our code, and important if we want to know what the answer is!  "puts" stands for "put string", and all you have to do to use it is put a string after it.  Our sum happens to be of the 'Integer' class, but it has been written in such a way to know what to do when we use it in the 'puts' statement.  More on this later!

As for what we are trying to accomplish in this project Euler problem, we want to sum up all of the multiples of 3 and 5 below 1000.  Pretty straightforward.  There are a few places where one can trip up though:

1.  If you incorrectly sum up multiples of both 3 and 5.  For example, 15 is a multiple of both 3 and 5, and if you write your code incorrectly you will get a sum that is too large, because you have added twice every multiple of both 3 and 15.

2.  Another place is not noticing that the question states below 1000, not up to and including 1000.  So just be wary of that. 

If anyone has some other pitfalls to be wary of, please email me and I will be sure to include them here, for those that follow after!  Good luck all, and happy coding!

Tuesday, August 9, 2011

Ruby Tutorial: SQL Query to Console i.e. TinyTDS in Action

So a previous post talked about using TInyTDS as a means to connect to your database.  Now we actually want to make a query and use it.  The first thing I did when I got it working, was figure out how I could emulate SQL Server Management Studio and make a query and display it.  So here is my code: 

  1. sql = "SELECT * FROM Whatever"
  2. client = => "myUsername", :password => "myPassword", :dataserver => "myServer", :database => "myDatabase")
  3. result = client.execute(sql)
  4. results = result.each(:symbolize_keys => true, :as => :array, :cache_rows => true, :empty_sets => true) do |rowset| end
  6. for i in (0..result.fields.length)
  7.   printf("%14s", result.fields[i])
  8. end
  9. for j in (0...result.affected_rows)
  10.   puts ""
  11.   for i in (0...result.fields.length)
  12.     printf("%14s",results[j].at(i))
  13.   end
  14. end

1.  This is your SQL Statement, pretty self-explanatory.  If you need help with SQL, a great place to start is here
2.  This is where the magic happens, logging into and connecting to the database.  This was the simplest gem I could find to connect to the database, we use SQL Server (fyi). 
3.  Also very readable, if you need help with what 'execute' does, you can read about TinyTDS's syntax here.  Basically it runs the sql query. 
6-8.  This will print out the column headers from the table you just created. 
9-14.  This will print out each row, one by one. 

This post is in the process of being written

Watir Tutorial: Error Recovery

So your script is happily humming along, testing myriad little tests, and then despite all your best efforts, it hangs!  Tragedy!  Sometimes despite our best efforts, it will still crash.  But it doesn't have to be like that.  No sir.

Ruby comes with error handling and with just a few lines of code, you can get your script to recover itself when it hangs, as it sometimes will.

If you need a primer on exceptions and error handling, I recommend Alan Skorkin's post about it.  As he covers a great deal of what you need to know, we will just be talking about the Watir code you will use.

And here it is:

  1. while !(b.frame(:id => "e1menuAppIframe").text.include? "Welcome!")
  2.   autoit.Send("^!l")
  3. end
  4. retry

What this will do, is hit cancel until you are back at the welcome screen.  So by placing this in the 'rescue' portion of your error handling and the begin statement after where you would initially be seeing the welcome screen in the first place, it will work like a dream.

I understand this won't work for all cases, but for some it will, and for those that it will, it makes the testing go that much smoother!  Enjoy~

Watir Tutorial: Too fast for ya?

One of the first issues I encountered was my script running too fast for the browser's loading time.  Watir will click a button or tab out of a field, or any number of things that requires a little of time to load and would metaphorically trip on it's own feet.  OATS (Oracle Application Testing Suite), which is run in Java fixes this by waiting until the page is loaded and then 'sleeping' for a second or two and then continuing on.  It will actually time how long the user is paused when you are writing your scripts there.  Watir has a similar functionality in that you can code in:  "sleep 2", and it will pause for 2 seconds, wherever your heart desires.  This is nice as a second line of defense but definitely not as a first, in my opinion.  There are a number of things that can go wrong in a testing script that has 1000 cases, even if 99% of the time it will load within 2 seconds, you will inevitably have some outliers that may make your script choke because the server hung for too long, or whatever may happen.

Watir developers added a nice little method called "wait_until", and it does just that!  It will wait until a given condition is met, checking every half second for a maximum of sixty seconds.  The best way to use this is in conjunction with a method to look for something that will come up in the next screen, or better yet, the actual field that you will be using in the next screen.  There are a couple of places I have used these, which I will illustrate:

1.  Wait until text field exists

Going back to the Watir example, we can make a somewhat redundant improvement to the code that they have there. 

  1. require 'rubygems'
  2. require 'watir'
  3. browser =
  4. browser.goto("")
  5. browser.wait_until {browser.text_field(:name => "entry.0.single").exist?}
  6. browser.text_field(:name => "entry.0.single").set "Watir"

Again:  Probably not necessary in this situation, but it illustrates a point that the difference that we see on one run between a script that includes line 5, and one that excludes it is nil.  But running and rerunning it, or in a different script it will mean the difference between a crash and the computer waiting half a second longer for the page to finish loading. 

2.  Wait until text is included

If your next screen has no fields, or even if it does, this is a good option. 

  1. b.wait_until {b.text.include? "Real Time Account Statement"}

I use this single line of code to tell Watir to wait for a screen within one of our programs.  Is it always necessary?  No.  Sometimes it can completely autopilot, but inevitably it will choke and the script will have to be restarted, this method is very nearly fool-proof.  (I say this because I have still seen it crash, albeit with much less frequency).

The example code is pretty self-explanatory, in that the first part is always the same, what is within the brackets is your conditional of either the '.include?' or '.exist?' flavors as you need.  Don't forget that within the brackets and in your include or exist statement you may have to tell it that the thing it is looking for is within a frame somewhere.  Like in our case with EnterpriseOne, you may need to specify where the specific object is so that Watir can find it. For example: 

  1. b.frame(:id => "e1menuAppIframe").text.include? "Welcome!"

I use this include statement to look for the "Welcome!" message after logging into EnterpriseOne. 

Ruby Tutorial: Julian to Gregorian method

There are plenty of these on the internet, but I have been using it in my testing procedures and so I thought it might be useful to someone who wants to use it.

It may be retrieved from here.

  1. def jul2gre(n)
  2.   y = 0
  3.   m = 0
  4.   d = 0
  5.   begin
  6.     if !(n.is_a?(Integer))
  7.       raise Exception::exception("Wrong input for jul2gre, an integer must be used")
  8.     end
  9.     case n.to_s.length
  10.     when 6
  11.       temp = n.to_s[0..2]
  12.       y = n2year(temp.to_i)
  13.       temp2 = n.to_s[3..5]
  14.       m = days2mon(temp2.to_i,y)
  15.       d = days2day(temp2.to_i,y)
  16.     when 5
  17.       temp = n.to_s[0..1]
  18.       y = n2year(temp.to_i)
  19.       temp2 = n.to_s[2..4]
  20.       m = days2mon(temp2.to_i,y)
  21.       d = days2day(temp2.to_i,y)
  22.     when 4
  23.       temp = n.to_s[0]
  24.       y = n2year(temp.to_i)
  25.       temp2 = n.to_s[1..3]
  26.       m = days2mon(temp2.to_i,y)
  27.       d = days2day(temp2.to_i,y)
  28.     when 3
  29.       y = 1900
  30.       temp2 = n.to_s[0..2]
  31.       m = days2mon(temp2.to_i,y)
  32.       d = days2day(temp2.to_i,y)
  33.     when 2
  34.       y = 1900
  35.       temp2 = n.to_s[0..1]
  36.       m = days2mon(temp2.to_i,y)
  37.       d = days2day(temp2.to_i,y)
  38.     when 1
  39.       y = 1900
  40.       temp2 = n.to_s[0]
  41.       m = days2mon(temp2.to_i,y)
  42.       d = days2day(temp2.to_i,y)
  43.     else
  44.       raise Exception::exception("Wrong number of digits in the jul2gre function, #{n.to_s.length} digits used")
  45.     end
  46.   end
  47.   if (d > 31 || d < 1)
  48.     raise Exception::exception("Final date is out of bounds in the day value, #{d} claimed")
  49.   elsif (m > 12 || m < 1)
  50.     raise Exception::exception("Final date is out of bounds in the month value, #{m} claimed")
  51.   elsif (y < 1900 || y > 2100)
  52.     raise Exception::exception("Final date is out of bounds in the year value, #{y} claimed")
  53.   else
  54.     return "#{m}/#{d}/#{y}"
  55.   end
  56. end
  57. def n2year(n)
  58.   return 1900 + n
  59. end
  60. def days2mon(n,y)
  61.   ly = isLeapYear(y)
  62.   if (ly)
  63.     if n <= 31          #January
  64.       return 1
  65.     elsif n - 31 <= 29  #February
  66.       return 2
  67.     elsif n - 60 <= 31  #March
  68.       return 3
  69.     elsif n - 91 <= 30  #April
  70.       return 4
  71.     elsif n - 121 <= 31 #May
  72.       return 5
  73.     elsif n - 152 <= 30 #June
  74.       return 6
  75.     elsif n - 182 <= 31 #July
  76.       return 7
  77.     elsif n - 213 <= 31 #August
  78.       return 8
  79.     elsif n - 244 <= 30 #September
  80.       return 9
  81.     elsif n - 274 <= 31 #October
  82.       return 10
  83.     elsif n - 305 <= 30 #November
  84.       return 11
  85.     elsif n - 335 <= 31 #December
  86.       return 12
  87.     else
  88.       raise Exception::exception("Number of days out of bounds for the given year, #{n} days claimed where 366 possible")
  89.     end
  90.   else
  91.     if n <= 31          #January
  92.       return 1
  93.     elsif n - 31 <= 28  #February
  94.       return 2
  95.     elsif n - 59 <= 31  #March
  96.       return 3
  97.     elsif n - 90 <= 30  #April
  98.       return 4
  99.     elsif n - 120 <= 31 #May
  100.       return 5
  101.     elsif n - 151 <= 30 #June
  102.       return 6
  103.     elsif n - 181 <= 31 #July
  104.       return 7
  105.     elsif n - 212 <= 31 #August
  106.       return 8
  107.     elsif n - 243 <= 30 #September
  108.       return 9
  109.     elsif n - 273 <= 31 #October
  110.       return 10
  111.     elsif n - 304 <= 30 #November
  112.       return 11
  113.     elsif n - 334 <= 31 #December
  114.       return 12
  115.     else
  116.       raise Exception::exception("Number of days out of bounds for the given year, #{n} days claimed where 365 possible")
  117.     end
  118.   end
  119. end
  120. def days2day(n,y)
  121.   ly = isLeapYear(y)
  122.   if (ly)
  123.     if n <= 31          #January
  124.       return n
  125.     elsif n - 31 <= 29  #February
  126.       return n - 31
  127.     elsif n - 60 <= 31  #March
  128.       return n - 60
  129.     elsif n - 91 <= 30  #April
  130.       return n - 91
  131.     elsif n - 121 <= 31 #May
  132.       return n - 121
  133.     elsif n - 152 <= 30 #June
  134.       return n - 152
  135.     elsif n - 182 <= 31 #July
  136.       return n - 182
  137.     elsif n - 213 <= 31 #August
  138.       return n - 213
  139.     elsif n - 244 <= 30 #September
  140.       return n - 244
  141.     elsif n - 274 <= 31 #October
  142.       return n - 274
  143.     elsif n - 305 <= 30 #November
  144.       return n - 305
  145.     elsif n - 335 <= 31 #December
  146.       return n - 335
  147.     else
  148.       raise Exception::exception("Number of days out of bounds for the given year, #{n} days claimed where 366 possible")
  149.     end
  150.   else
  151.     if n <= 31          #January
  152.       return n
  153.     elsif n - 31 <= 28  #February
  154.       return n - 31
  155.     elsif n - 59 <= 31  #March
  156.       return n - 59
  157.     elsif n - 90 <= 30  #April
  158.       return n - 90
  159.     elsif n - 120 <= 31 #May
  160.       return n - 120
  161.     elsif n - 151 <= 30 #June
  162.       return n - 151
  163.     elsif n - 181 <= 31 #July
  164.       return n - 181
  165.     elsif n - 212 <= 31 #August
  166.       return n - 212
  167.     elsif n - 243 <= 30 #September
  168.       return n - 243
  169.     elsif n - 273 <= 31 #October
  170.       return n - 273
  171.     elsif n - 304 <= 30 #November
  172.       return n - 304
  173.     elsif n - 334 <= 31 #December
  174.       return n - 334
  175.     else
  176.       raise Exception::exception("Number of days out of bounds for the given year, #{n} days claimed where 365 possible")
  177.     end
  178.   end
  179. end
  180. def isLeapYear(y)
  181.   if (y % 4 == 0)
  182.     if (y % 400 == 0)
  183.       return true
  184.     else
  185.       return false
  186.     end
  187.   else
  188.     return false
  189.   end
  190. end