Become a fan of Slashdot on Facebook

 



Forgot your password?
typodupeerror
×
PC Games (Games)

Journal qohen's Journal: LINKDUMP: Interview Prep (LAMP)

To save some time and to keep Google from having to pay loads of nickels to Mozilla as I look up various topics for interview-prep:

OOP
http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming
(GoF pattern examples: Adapter/Wrapper and Strategy patterns).

From: http://en.wikipedia.org/wiki/Object-oriented

Polymorphism allows the programmer to treat derived class members just like their parent class' members. More precisely, Polymorphism in object-oriented programming is the ability of objects belonging to different data types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior.

From: http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming

In simple terms, polymorphism is the ability of one type, A, to appear as and be used like another type, B. In strongly typed languages, this usually means that type A somehow derives from type B, or type A implements an interface that represents type B.

In non-strongly typed languages (dynamically typed languages) types are implicitly polymorphic to the extent they have similar features (fields, methods, operators). In fact, this is one of the principal benefits (and pitfalls) of dynamic typing.

Operator Overloading the numerical operators +,-,/,* allow polymorphic treatment of the various numerical types Integer, UnSigned Integer, Float, Decimal, etc; each of which have different ranges, bit patterns, and representations. Another common example is the use of the "+" operator which allows similar or polymorphic treatment of numbers (addition), strings (concatenation), and lists (attachment). This is a lesser used feature of polymorphism.

The primary usage of polymorphism in industry (object-oriented programming theory) is the ability of objects belonging to different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior. The programmer (and the program) does not have to know the exact type of the object in advance, and so the exact behavior is determined at run time (this is called late binding or dynamic binding).

The different objects involved only need to present a compatible interface to the clients (the calling routines). That is, there must be public or internal methods, fields, events, and properties with the same name and the same parameter sets in all the Superclasses, Subclasses, and potentially Interfaces. In principle, the object types may be unrelated, but since they share a common interface, they are often implemented as Subclasses of the same Superclass. Though it is not required, it is understood that the different methods will also produce similar results (for example, returning values of the same type).

BTW, OOP interfaces are protocols:
http://en.wikipedia.org/wiki/Interface_(object-oriented_programming)

Design Patterns

One line descriptions of GoF:
http://social.msdn.microsoft.com/forums/en-US/architecturegeneral/thread/af062e83-3e61-45d4-aeaa-d30b4366c6a2/

http://en.wikipedia.org/wiki/Design_patterns
http://en.wikipedia.org/wiki/Design_pattern_(computer_science)
http://en.wikipedia.org/wiki/Creational_pattern
http://en.wikipedia.org/wiki/Structural_pattern
http://en.wikipedia.org/wiki/Behavioral_pattern
http://mahemoff.com/paper/software/learningGoFPatterns/ -- a better order for learning GoF patterns vs. the book's.
http://sourcemaking.com/design-patterns/

http://en.wikipedia.org/wiki/Architectural_pattern_(computer_science)
http://en.wikipedia.org/wiki/Model-View-Controller

PHP OOP
http://us3.php.net/manual/en/language.oop5.php
Reality check: make sure you can define all of the basics in sound-bites, e.g.
* class
* abstract
* extends
* interface
* implements
* method
* static
-- $this vs. self
-- see also: late static-binding, as of 5.3
-- example of self in GoF pattern: http://en.wikipedia.org/wiki/Singleton_pattern#PHP_5
* OOP-related functions
* Magic Methods (e.g. construct/destruct, toString, sleep, wakeup, etc.)

PHP Design Patterns
http://www.google.com/search?q=design+patterns+in+PHP
http://www.ibm.com/developerworks/library/os-php-designptrns/
http://www.ibm.com/developerworks/opensource/library/os-php-designpatterns/
http://www.fluffycat.com/PHP-Design-Patterns/
http://www.tonymarston.net/php-mysql/model-view-controller.html
http://www.getinstance.com/ (Matt Zandstra's blog)
http://www.hurricanesoftwares.com/ten-php-design-patterns/
http://phppatterns.com/
http://www.phpwact.org/
http://sourcemaking.com/design-patterns/php -- new to me, has implementations in PHP and other langs. too.
PHP Design Pattern: Front Controller
http://www.phppatterns.com/docs/design/the_front_controller_and_php -- survey of sorts
http://www.onlamp.com/pub/a/php/2004/07/08/front_controller.html

PHP Design Pattern: MVC
http://www.phpwact.org/pattern/model_view_controller
http://blog.astrumfutura.com/archives/353-An-Example-Zend-Framework-Blog-Application-Part-2-The-MVC-Application-Architecture.html

PHP
Cheat Sheets:
http://www.scottklarr.com/topic/100/php-cheat-sheets/ -- a bunch of them here
http://www.scottklarr.com/media/cheatsheets/php/11.jpg -- Smarty cheat sheet

Debugging

Exception Handling
http://en.wikipedia.org/wiki/Exception_handling_syntax#PHP

Buffer Control
http://us2.php.net/manual/en/book.outcontrol.php

Database Access
http://us.php.net/pdo
http://www.phpclasses.org/blog/post/82-PHP-ObjectRelational-Mapping-ORM-or-ROM.html

Sessions
http://us2.php.net/manual/en/book.session.php

Why not in a file: this would make them localized to a single machine.
Why not in the DB: disk-bound, so slow and:

- Almost always larger than 250 bytes, and almost always smaller than 5 kilobytes.
- Read from datastore for every logged in (and often logged out) user for every dynamic page load.
- Written to the datastore for every dynamic page load.
- Eventually reaped from the database after N minutes of inactivity.

Ok well that sucks I guess. Every time a user loads a page we read a blob row from mysql, then write a blob row back. This is a lot slower than row without blobs.

(From: http://dormando.livejournal.com/495593.html )

Why not in memcached:

- Set a memcached expire time for the max inactivity for a session. Say 30 minutes...
- Read from memcached.
- Write to memcached.
- A miss from memcached means the user is logged out.

Voila! ZERO reads or writes to the database, fantastic! Fast. Except I really don't like the tradeoffs here. This is one example where I believe the experience of both your users and your operations team is cheapened. Users now get logged out when anything goes wrong with memcached! Operations has to dance on eggshells. Or needles. Painful.

- Evictions are serious business. Even if you disable them (-M), out of memory errors means no one can log into your site.
- Upgrading memcached, OS kernel, hardware, etc, now means kicking everyone off your site.
- Adding/removing memcached servers kicks people off your site. Even with consistent hashing, while the miss rate is low it's not going to be zero.

Hybrid memcached solution:
The memcached/mysql hybrid really isn't that bad at all. You can get rid of over 90% of the database reads, a lot of the writes, and leave your users logged in during rolling upgrades of memcached.

(Also: http://kevin.vanzonneveld.net/techblog/article/enhance_php_session_management/)

First, recap the components involved: The page session handler itself, and some batch job which reaps dead sessions. For small websites (like a vbulletin forum) these batch jobs are often run during page loads. For larger sites they will be crons and so forth. This batch job can also be used to save data about sessions for later analysis.

The pattern is simple. For reads fetch from memcached first, database second. For writes write to memcached, unless you haven't synced the session to the database in the last N seconds. So if a user is clicking around they will only write to the database once every 120 seconds, and write to memcached every time.

Now modify the batch job. Crawl all expired sessions, and check memcached for the latest data. If session is not really expired don't expire it then, if it is use the latest possible data from memcached. Write back to the database. Easy.

You take the tradeoff of sessions being mildly lossy for recent information, but you gain reliability back in your system. Reads against the database should be almost nonexistent, and write load should drop significantly, but not as much as reads.

Security
http://funkatron.com/inspekt/user_docs/
http://www.pixelated-dreams.com/uploads/misc/cheatsheets/FilteringAndEscapingCheatSheet.pdf

strip_tags()
preg_replace()
str_replace()
stripslashes()
urldecode()
rawurlencode()

Memcached
http://us3.php.net/memcache

https://launchpad.net/memcached-udfs Memcached + MySQL using UDFs
http://www.phpjack.com/content/improving-php-sessions

Interview Questions
http://www.google.com/search?q=php+interview+questions

Misc PHP Junk
* @ suppresses error msgs from function calls
* require vs. include -- require fatals you out; include doesn't
* echo vs. print -- print returns return-code, echo doesn't
* split vs. explode: split can use a regexp
* mysql_pconnect vs. mysql_connect => persistent vs. regular DB connection
Discussion about when to use and when not (pconnect will have people backed up
on your website, not necessarily a real advantage to using it if DB is on same server as Apache, table locks won't be released and temp tables won't go away w/pconnect, etc.):
http://www.php.net/function.mysql-pconnect
And, more neatly (but without positive reasons to use pconnect):
http://www.softwareprojects.com/resources/programming/t-nginx-+-php-mysql_pconnect--database-errors-too-m-1751.html

* Remember == vs. === -- one of the cheatsheet links above has the comparison-operator cheatsheet.

BTW--it's not just === is identity; turns out, the following is also so:

http://sharag.wordpress.com/2008/06/11/php-interview-questions-part-6-asked-in-yahoo-interview/

if (strpos(ï½abcï½, ï½aï½) == true) { // this does not get hit, since ï½aï½ is in the 0 index position, it returns false.
}
if (strpos(ï½abcï½, ï½aï½) === true) { // this does get hit as the === ensures this is treated as non-boolean.
}

Database / SQL
http://en.wikipedia.org/wiki/Database_normalization
http://en.wikipedia.org/wiki/Sql
http://en.wikipedia.org/wiki/Join_(SQL)

From: http://articles.techrepublic.com.com/5100-10878_11-5142674.html

Left outer

The left outer join retrieves records from both tables, retrieving all the records from the one side of the relationshipï½that's the left tableï½and any records from the right table (or many table) where the primary/foreign key values match. If there are no matching values in the primary/foreign key columns, the join still retrieves all the records from the one side. Consequently, the resulting recordset often appears to have incomplete records.

SELECT Customers.CustomerID, Customers.CompanyName, Orders.OrderID
FROM Customers LEFT JOIN Orders
    ON Customers.CustomerID = Orders.CustomerID
ORDER BY OrderID

FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID

Is the same as the old Oracle way:

WHERE Customers.CustomerID = Orders.CustomerID(+)

UPDATE with join:
From http://dev.mysql.com/doc/refman/5.0/en/update.html

UPDATE items,month SET items.price=month.price
WHERE items.id=month.id;

And, in the comments to that page:

Posted by Babu Ramesh on January 12 2004 11:33pm

Update column in a table whose values are not found in another table.

UPDATE TABLE_1 LEFT JOIN TABLE_2 ON TABLE_1.COLUMN_1= TABLE_2.COLUMN_2
SET TABLE_1.COLUMN = EXPR WHERE TABLE_2.COLUMN2 IS NULL

An outerjoin is performed based on the equijoin condition.
Records not matching the equijoin from table2 are marked with null.

This facilitates to update table1 column with expression whose corresponding value from table2 is returned as NULL

http://en.wikipedia.org/wiki/Correlated_subquery

A correlated sub-query is a term used for specific types of queries in SQL in computer databases. It is a sub-query (a query nested inside another query) that uses values from the outer query in its WHERE clause. The sub-query is evaluated once for each row processed by the outer query.

SELECT empnum, name
FROM employee as e1
WHERE salary > (SELECT avg(salary)
      FROM employee
      WHERE department = e1.department);

In the above nested query the inner query has to be executed for every employee as the department will change for every row. Hence the average salary will also change.

Link to Karwin's SQL Anti-Patterns Talk notes

MySQL Syntax
http://php.about.com/od/mysqlcommands/g/Limit_sql.htm

Table creation, with foreign keys, etc.:

-- MODULE_PREFERENCE_OPTIONS
CREATE TABLE IF NOT EXISTS `MODULE_PREFERENCE_OPTIONS` (
          id int NOT NULL auto_increment,
          module_id int,
          preference_id int,
          preference_value varchar(40)
          PRIMARY KEY (`id`),
          FOREIGN KEY (module_id) REFERENCES modules(id),
          FOREIGN KEY (preferences_id) REFERENCES preferences(id),
) ENGINE=InnoDB;

Stored Procedures

From: http://www.brainbell.com/tutorials/MySQL/Using_Stored_Procedures.htm

CALL productpricing(@pricelow,
                                        @pricehigh,
                                        @priceaverage);

CREATE PROCEDURE productpricing()
BEGIN
      SELECT Avg(prod_price) AS priceaverage
      FROM products;
END;

More complex example from the same place:

-- Name: ordertotal
-- Parameters: onumber = order number
-- taxable = 0 if not taxable, 1 if taxable
-- ototal = order total variable

CREATE PROCEDURE ordertotal(
      IN onumber INT,
      IN taxable BOOLEAN,
      OUT ototal DECIMAL(8,2)
) COMMENT 'Obtain order total, optionally adding tax'
BEGIN

      -- Declare variable for total
      DECLARE total DECIMAL(8,2);
      -- Declare tax percentage
      DECLARE taxrate INT DEFAULT 6;

      -- Get the order total
      SELECT Sum(item_price*quantity)
      FROM orderitems
      WHERE order_num = onumber
      INTO total;

      -- Is this taxable?
      IF taxable THEN
            -- Yes, so add taxrate to the total
            SELECT total+(total/100*taxrate) INTO total;
      END IF;

      -- And finally, save to out variable
      SELECT total INTO ototal;

END;

http://www.shinguz.ch/MySQL/mysql_mv.html -- more complex examples (for setting up materialized views, despite MySQL not having them)

Create Trigger:

CREATE TRIGGER `tgr_name` AFTER UPDATE ON `addresses` FOR EACH ROW begin
update products set countryName new.countryName where products.shippingAddressId old.id;
end;

MySQL Utilities
mysqladmin: http://dev.mysql.com/doc/refman/5.1/en/mysqladmin.html
mysqldump: http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html
Remember that you can have extended inserts, drop table statements, etc.
mysqldumpslow: http://dev.mysql.com/doc/refman/5.1/en/mysqldumpslow.html
http://osde-info.vox.com/library/post/mysql-slow-query-log-and-mysqldumpslow.html
mysql load
mysqlcheck

MySQL Scaling / Performance
Slow Query Log documentation

From a comment to the above (with my comments to the right)

[mysqld]
log-slow-queries = slow.log "long_query_time" seconds
log-queries-not-using-indexes

Nati Shalom's bullet-point summary of various scaling-out MySQL strategies including replication and sharding--including pros/cons--as well as in-memory
Good-look blog post on Shards
Percona's blog (mysqlperformanceblog.com) post on high-performance click-analysis that discusses a variety of techniques, e.g. aggregating data (e.g. by date), using indexes well, etc. -- worthwhile (as is the blog in general).

mySQL Query Optimization
32 Tips to Speed Up Your Queries

MySQL Interview Questions
http://www.techinterviews.com/29-mysql-interview-questions

Apache
http://www.google.com/search?q=apache+cheat+sheet
http://www.petefreitag.com/cheatsheets/apache/

Linux
Cheatsheets
http://www.cheat-sheets.org/#Linux -- a bunch
http://homepage.powerup.com.au/~squadron/linux_manual.pdf -- has some overview-type stuff
http://www.pixelbeat.org/cmdline.html -- Common sysadmin-y type cmds

Perl

Punctuation
http://perldoc.perl.org/perlvar.html

"Diamond operator" @ARGV (i.e. read command-line params to a command)
$_ Current line
@_ Parameter array in a subroutine
$0 Program name

$! Error number (useful only after failure)
$@ Eval error (i.e. error returned by eval() )
$? Status returned by last pipe close, backtick (`` ) cmd or system()

$` returns everything before the matched string.
$& returns the entire matched string
$' returns everything after the matched string.
$+ returns whatever the last bracket match matched.
NOTE: these have a speed penalty, though it's one-time only

$/ input record separator -- local $/ for slurping (instead of undef $/)
$\ output record separator for the print operator.

Style
http://perldoc.perl.org/perlstyle.html
http://mxr.mozilla.org/mozilla/source/webtools/bugzilla/contrib/recode.pl -- not the best, but worth a look, for how to use POD, etc.

Idioms
http://dave.org.uk/perlwhirl/idiomatic.pdf -- good run through lots of stuff
http://world.std.com/~swmcd/steven/perl/idiom.html
http://refcards.com/docs/vromansj/perl-best-practices/refguide.pdf -- Damien Conway's list of Perl Best Practices on a refcard

Regular Expressions
http://www.perl.com/doc/manual/html/pod/perlre.html

Exception-handling
http://en.wikipedia.org/wiki/Exception_handling_syntax#Perl
http://www.perl.com/pub/a/2002/11/14/exception.html

Creating Modules, Module Mechanics, etc.
http://www.perlmonks.org/?node_id=431702
http://world.std.com/~swmcd/steven/perl/module_mechanics.html
http://en.wikipedia.org/wiki/Perl_module

References
http://perl.plover.com/FAQs/references.html

Data Structures
http://perldoc.perl.org/perldsc.html (Perl Data Structures Cookbook--part of perldoc)
http://perl.plover.com/BTree/article.html (MJD: article + code)

DBI (Database access)
http://search.cpan.org/dist/DBI/DBI.pm
http://www.perlmonks.org/?node_id=706404 -- a useful example (read the comment, too).
http://www.perl.com/pub/a/1999/10/DBI.html
http://search.cpan.org/~msergeant/DBD-SQLite-1.14/lib/DBD/SQLite.pm

OOP (Old)
http://perldoc.perl.org/perlboot.html
http://perl.plover.com/yak/oop/ -- topics MJD covers in his OOP Perl class--make sure you know them.

OOP (Moose)
http://www.iinteractive.com/moose/PPW-2008/moose.xul
http://www.stonehenge.com/merlyn/LinuxMag/col94.html
http://www.stonehenge.com/merlyn/LinuxMag/col95.html

Version Control

SVN
http://www.addedbytes.com/cheat-sheets/download/subversion-cheat-sheet-v1.pdf

Git

Web Formatting

XHTML

CSS

Misc
http://www.nntp.perl.org/group/perl.jobs/2008/12/msg8897.html -- a job-listing from a guy who doesn't pay a lot, but it could be useful for staying in shape, etc. -- his outfit essentially wrote BugZilla and does customizations for it.
This is what he wants in the way of sample-code (stuff like: use strict, OOP, Moose, POD, etc.)
http://avatraxiom.livejournal.com/95669.html

Algorithms, Computer Science, etc.
Quick list of Big-Oh notation for various data-structures

"Money is the root of all money." -- the moving finger

Working...