Categories
Programming

Array sorting

First an explanation about big O notation. If you have f(x) = 6x4 − 2x3 + 5. Then to simplify the equation, as x approaches infinity, the only number that seems to matter is x4 as all other parts of the equation become more and more insignificant as x grows.

This means we can say f(x) is almost equal to  x4 or f(x) = O(x4).

 In sorting, For typical sorting algorithms good behavior is mathcal{O}left( n log nright) and bad behavior is mathcal{O}left( n^2 right). The ideal is Ideal behavior for a sort is mathcal{O}left( n right), but since comparison is needed in programming algorithms, we have to settle for at least O(n log n).

 Popular sorting algoriths:

  • Bubble sort: Starts at the beginning of the data set, compares the first two elements and swaps (if neccesary) the lowest element first. Repeats the same comparison until the end of the list, and then starts again in element 2. Highly unefficient. A 100 elements array will need about 1ooo comparison tasks.  Bubble sort average case and worst case are both O(n²). Here’s an example:

    function myBubbleSort(arrayName,length) {
    for (var i=0; i<(length-1); i++){ for (var j=i+1; j
  • Insertion sort: Efficient in small lists, but expensive, because it creates a new array to accomodate all elements of the unsorted array there in order as the insertion happens.
  • Shell sort: one of the fastest algorithms to sort data, but very unefficient in large data sets. It arrange the data sequence in a two dimensional array, and then in the vertical columns of the array it uses intersion sort to the columns. The you decrease the number of columns and do it again.
  • Merge sort. Divides the data set into lists of two elements (1 and 2, 3 and 4, etc), sort the lists, and then create new lists of 4 with the resulting lists, sort them again and create lists of 8, etc, until all list is sorted. Scales well with large lists because its worse case scenario is O(n log n).
  • Heap sort. It puts the data set in a data structure called heap, which is a binary tree where the smallest (or largest) element is the root, and childen of each node are also smaller than their parent. When a node is removed, the heap updates itself again to reflect that rule.  Heaps run on O(n log n).
  •  Quicksort: Based on a mid number, partition the list and moves all elements lower than the number to one side of the list and the elements bigger than that number to the other part. Then recursively repeats the same algorithm until finish. One of the fastest sorting algorithms, but depends on choosing the right pivoting point as the median, if so we get O(n log n) performance, if not we may get closer to O(n²), yet we need to O(n) operation to determine the median, so that also adds up to the execution time.
Categories
Programming

MVC architecture

It is a design pattern that helps separate business logic from input and presentation, making it easier to maintain each one of those components independenly from each other.

Model: it is the representation of data according to the application’s function or domain. It includes data access but it is not exclusively the retrieval or records.

View: renders the model so it can interact with users. It is the UI. It can have several manifestations for a given Model.

Controller: receives input and coordinates actions between the Model and the View. In the case of web servers translates HTTP requests into calls to backend and ultimately HTML pages.

Categories
JavaScript

Ajax

XMLHttpRequest object: is a browser object that allows you to communicate to the server. To create one of these objects you use the following JavaScript code:

var newXHR = new XMLHttpRequest(); // Doesn’t work in IE 6 though

In order to send a GET request using the object above, you do something like:

newXHR.open(‘GET’, ‘shop.php?productID=34’);

To indicate the callback function that will process the request received back from the server:

newXHR.onreadystatechange = myCallbackFunction;

Up to this point, everything has been setup, now to send the data to the server you use:

newXHR.send(null);

If you want to send additional parameters, instead of null you specify:

newXHR.send('q=javascript');

The XHR object receives up to three pieces of information back from the server:

  • status: like 404, 500, 200, etc
  • responseText property: it is part of the XHR object, and stores the server response, could be HTML, plain text, or a JSON object
  • responseXML property: also part of the XHR object. Loaded if the server responds with XML
Categories
JavaScript

popup windows created with JavaScript

var winProps = ‘width=400,height=300,location=yes’;
var newWin = open(‘about.html’,’aWin’,winProps);

newWin.close();

  • height dictates the height of the window, in pixels. You can’t specify percentage values or any other measurement besides pixels. If you don’t specify a height, the Web browser matches the height of the current window.
  • width specifies the width of the window. As with height, you can only use pixels, and if you leave this property out, the Web browser matches the width of the current window.
  • left is the position, in pixels, from the left edge of the monitor.
  • top is the position, in pixels, from the top edge of the monitor.
  • resizable specifies whether a visitor can resize the window by dragging.
  • scrollbars appear at the right and bottom edges of a browser window whenever a page is larger than the window itself. To completely hide the scrollbar, set this property to no. You can’t control which scrollbar is hidden (it’s either both or neither).
  • status controls the appearance of the status bar at the bottom of the window. Firefox and Internet Explorer normally don’t let you hide the status bar, so it’s always visible in those browsers.
  • toolbar sets the visibility of the toolbar containing the navigation buttons, bookmark button, and other controls available to the particular browser. On Safari, the toolbar and location settings are the same: turning on either one displays both the toolbar buttons and the location field.
  • location specifies whether the location field is visible. Also known as the address bar, this field displays the pages URL and lets visitors go to another page by typing a new URL. Opera, IE 7, and Firefox don’t let you hide a page’s location entirely. If you don’t turn on the location property, then the page’s URL appears up in the title bar. This feature is supposed to stop nefarious uses of JavaScript like opening a new window and sending you off to another site that looks like the site you just left. Also, Safari displays the toolbars as well as the location field with this property turned on.
  • menubar applies to browsers that have a menu at the top of their windows (for example, the common File and Edit menus that appear on most programs). This setting applies only to Windows browsers—Macs have the menu at the top of the screen, not the individual window. And it doesn’t apply to IE 7, which doesn’t normally display a menu bar.
Categories
JavaScript

JavaScript global and local variables

Any variable that is initialized inside a function using the var keyword will have a local scope. If a variable is initialized inside a function without var, it will have a global scope. A local variable can have the same name as a global variable.

Categories
JavaScript

JQuery: selecting elements from the DOM

  • You can select by id: var my_element = $(‘#element_id_here’);
  • You can also select a group of tags: var linksList = $(‘a’);
  • To select elements by class name (and then hide them in this case): $(‘.submenu’).hide();
  • Filter the elements you choose by the preceding ids or tags: $(‘#navBar a’) This will select the a tags that are inside the #navBar id. As a matter of fact, you can follow the CSS syntax to select elements this way. Other variations of this are:
    • $(‘body > p’) – Chooses the p tags that are children of body
    • $(‘h2 + div’) – Chooses the very next adjacent children right after the h2 tag
    • $(‘img[alt]’) – Attribute selecting images (in this case only if they have the alt attribute on them)
    • $(‘input[type=text]’) – Selecting all attributes that have are type=text
    • $(‘a[href^=mailto:]’) & $(‘a[href$=.pdf]’) – Attribute selection using regular expressions
  • Jquery filters: these are used to selectively choose further from a given group of selected items, based on certain criteria:
    • $(‘tr:even’) – From all the list of tr’s, it will only select the ‘even’ elements, you can also use tr:odd as a variation
    • $(‘a:not(.navButton)’); – Select elements that don’t match the criteria inside the not(), in this case select a tags that are not of class navButton
    • $(‘li:has(a)’) – Finds elements that contain another element, in this case, find all the li that contain an ‘a’ tag
    • $(‘a:contains(Click Me!)’) – Find elements that contain a specific piece of text, in this case, find ‘a’ tags that contain the “Click Me!” text inside
    • $(‘div:hidden’).show(); – Find elements that are currently hidden (and in this case show them). This does not find elements with ‘visibility’ property, only takes in account the ‘display’ property. “:visible” will be the opposite of this.
  • Caution about elements picked by Jquery selectors: the normal methods used in JavaScript won’t work, you will have to use the JQuery equivalents. For example:
    • $(‘#banner’).innerHTML = ‘New text’; // won’t work
    • $(‘#banner’).HTML(‘New text’); // Propietary Jquery to say innerHTML, this will work
  • A note about looping through a set of elements selected through Jquery: the loop is already built-in, you don’t have to specify it. For instance:
    • $(‘#slideshow img’).hide(); – The groups of images selected can be hidden without having to loop through them one at a time
  • Chaining functions to an element, you can do this in JQuery, as long as the chain of functions are also JQuery functions as well:
    • $(‘#popUp’).width(300).height(300).text(‘Hi!’).fadeIn(1000);
Categories
JavaScript

JavaScript select an element from a page (or a group of elements)

myelement  = document.getElementById(‘header’);

Where ‘header’ is the id of the tag we are selecting

You can also select a group of elements with:

var pageLinks = document.getElementsByTagName('a');
That will give you an array by the way.
Categories
PHP

PHP abstract classes

Basically, abstract classes define methods but don’t have any functionality inside of them, and can’t be instantiated directly. They are just blueprints for classes that extend them, inheriting their methods (and being forced to define them). Abstract classes can’t be instantiated, just extended.

Categories
PHP

PHP static methods

A static class in PHP acts pretty much the same way as static variables, it is loaded into the “static” space, where every time it is spawned or instantiated, it is the same object already built before.

Static variables inside classes can’t be addressed with the $this identifier:

class SomeClass {
   public static $counter = 0;
   function __construct() {
        self::$counter++; // Notice how we say self::$counter instead of $this->counter
   }
}
Creating a static method inside a class:
class SomeClass {
   public static function do() {
        // Code.
   }
}
So now, to call the method, we need to do the following:
SomeClass::do(); // $obj->do(); // NO!
Constants are like static variables, except that their values is final and can't be changed:
class SomeClass {
   const PI = 3.14;
}
To call the value:

$obj::PI; // $obj->PI // !No

 
Advantages / reasons for using static classes:

  1. Available anywhere from your script, without the need to instanciate an object or store it into a global variable.
  2. It can save you performance time, not instanciating objects just to access their static methods, functionality or variables.
Categories
PHP

PHP using the class scope resolution operator ::

Since it is possible methods will have the same name or signature accross multiple classes, the way to specify which class the method you are calling belongs to is:

ClassName::method_name();

Variations of this are:

  • parent::method_name(); // Calling the class parent method
  • self::method_name(); // Same as $this->method_name();

In PHP4, you could call any method using this syntaxis, in PHP5, since now we have visibility attributes, you can only call static functions with it.

So the syntaxis above is used to call overriden parent methods, instead of the current class ones, for instance: $base = parent::getSummaryLine(); to call the parent getSummaryLine() method, not the overriden version of it in this object.