Dec 27 2009

Heredocs and Nowdocs in PHP

A here document (also called a here-document, a heredoc, a here-string or a here-script) is a way of specifying a string literal in command line shells including all the Unix shells (sh, csh, ksh, Bash and zsh) and the Windows PowerShell and in programming or scripting languages such as Perl, PHP, Python and Ruby. It preserves the line breaks and other whitespace (including indentation) in the text. Some languages allow variable substitution and command substitution inside the string.

The general syntax is << followed by a delimiting identifier, followed, starting on the next line, by the text to be quoted, and then closed by the same identifier on its own line. Under the Unix shells, here documents are generally used as a way of providing input to commands.

from Wikipedia

Example Heredoc Syntax

<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

/* More complex example, with variables. */
class foo
{
var $foo;
var $bar;

function foo()
{
$this->foo = ’Foo’;
$this->bar = array(‘Bar1′, ’Bar2′, ’Bar3′);
}
}

$foo = new foo();
$name = ’MyName’;

echo <<<EOT
My name is ”$name”. I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital ’A': \x41
EOT;
?>

NowDocs

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML <![CDATA[ ]]> construct, in that it declares a block of text which is not for parsing.

A nowdoc is identified with the same <<< seqeuence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<’EOT’. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.

<?php
$str = <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;

/* More complex example, with variables. */
class foo
{
public $foo;
public $bar;

function foo()
{
$this->foo = ’Foo’;
$this->bar = array(‘Bar1′, ’Bar2′, ’Bar3′);
}
}

$foo = new foo();
$name = ’MyName’;

echo <<<’EOT’
My name is ”$name”. I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital ’A': \x41
EOT;
?>

from PHP.net


Dec 26 2009

The PHP Object Expands in PHP5

Starting with PHP 5, the object model was rewritten to allow for better performance and more features. This was a major change from PHP 4. PHP 5 has a full object model.

Among the features in PHP 5 are the inclusions of visibility, abstract and final classes and methods, additional magic methods, interfaces, cloning and typehinting.

PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. See Objects and References

from php manual


Dec 25 2009

Good Practices in PHP

Here are a few tips for those of you who’d like to write good code in PHP:

Set up a Development Server

Set up a development server or sandbox. Don’t write, test, or develop code on a production server. If you are a *nix user, you probably already have a LAMP environment on your own computer. If you are a Windows user, try XAMPP or WAMPSERVER (personal favorite). If you are on mac, try MAMP.

As you develop your PHP, you will need to be learning about the environment which it runs in, and the settings that will affect your code and/or application. This is a journey, so don’t expect to master it all at once. You will get into things like virtual hosts, .htaccess files, rewrite rules, and file permissions.

Turn on Error Reporting

At least, on your development server. On your production site, turn off displaying errors, but have them sent to a file. Check this file periodically as it will show you what unexpected things are happening in your code.

Do’s and Don’t’s

Don’t use short codes. They take longer to type, but PHP will be moving away from them in future versions. Also, the <? syntax can be mistaken for XML. Examples of short codes include <? instead of <?php, and also the syntax <?= $var ?> which is the easy way of writing <?php echo $var; ?>

Do use comments and document your code.

Don’t use a closing ?> at the end of your PHP files. Just leave it off – it is not required and it keeps you from accidentally having white space under your closing ?> so that headers, sessions, and cookies don’t get messed up.

Do use the latest version of PHP possible for developing applications. Right now the most common version / latest stable version of PHP is 5.2.8. While 5.3.x is out, there were some major changes many hosting companies and server admins have not completely adapted to, yet. Some of these deal with symlinks / softlinks / junctions and how the code is parsed. So, always try and use the latest commonly-adopted version.

Do use a versioning software of some sort (SVN, CVS, or GIT)


Nov 26 2009

gmail compose resize for chrome (extension / addon / add-on)

Bigger Gmail Compose Box

screenshot0

Details:

Have you ever wanted a larger compose box for gMail? especially when using g-mail to reply to a conversation?

I give them credit, most times when composing a new message or using it in full-screen mode, it does well. But if you’re like me, about 80% of your conversations are replies. And that is, after all, what is great about g-mail, right? The awesome threading capabilities.

So why doesn’t g-mail support a resizeable compose box? You are stuck with a fixed size, of about 260 px, even in the Chrome browser!!! A browser that is know to let you resize text boxes by default!

Well, I don’t know the answers to these questions, but they are frustrating, so I’ve written an extension for Chrome (or Chromium) which allows you to specify how big you want that box to be, and then it automatically resizes it (it make take a few seconds after you hit reply to fully grow).

Download the extension here:

Bigger Gmail Compose Box

It has an options page, which you can access by going to settings (wrench icon) and then extensions. I have also added in auto-update for this extension. I’m really quite pleased with it and wanted to share.

Let me know what you think.

Having trouble? Didn’t know that Chrome allows extensions? You probably need to upgrade to the latest version. This is tested and working for the 4.x versions, so get the latest chrome now, and after downloading, you need to enable extensions.

Alternatively, if you want a one-click extension install, I suggest using Chromium (which is the development version of Chrome) because it has a lot more power and features and extensions are enabled by default.

See my posts on Downloading the latest Chromium and Chromium is not Chrome.

Also, for other great extensions, check out Chrome Extensions.




Sep 1 2009

Review: X10 Home Automation with Arduino

This is a re-post of  this blog posting since it appears to be a 404.
—-
My current project revolves around using the Arduino and the X10 home automation protocol and hardware. The gist of what I am doing with this project is using the Parallax RFID (found here) tag to identify me and then use X10 protocol/hardware (Part# 1134B from SmartHomes via Amazon) to automate my home. Below is the wiring diagram.
X10_wire

In this example, I control 1 device (on X10 circuit A, device 1). I initally turn the device off. When the RFID tag I am looking for is read, I turn the lights on. Next time that tag is read, I turn the lights off. I acknowledge various changes by providing feedback to the user via blinking LEDs and serial comms to the PC. I use the free SSH/telnet client PuTTY, found here.

Now, for the code…

——————————————–
#include x10.h
#include x10constants.h

// RFID reader variables
#define TAG_LEN 12
char tag[12] = {‘0′, ‘F’, ‘0′, ‘3′, ‘0′, ‘3′, ‘7′, ‘1′, ‘8′, ‘5′};
char code[12];
int bytesread = 0;
int ledPin = 13; // Connect LED to pin 13
int rfidPin = 2; // RFID enable pin connected to digital pin 2
int val=0;

// X10 Control unit variables
int zcPin = 9;
int dataPin = 8;
int repeat = 1;
boolean LightsOn = false;

// Declare and instance of an X10 control module
x10 myHouse = x10(zcPin, dataPin); // 9 is 0xing pin; 8 is data pin

void setup()
{

// Begin serial comms with the PC
Serial.begin(2400); // RFID reader SOUT pin connected to Serial RX pin at 2400bps

// X10 Module
myHouse.write(A, ALL_UNITS_OFF, repeat);
pinMode(zcPin,INPUT);
pinMode(dataPin,OUTPUT);

// RFID
pinMode(rfidPin,OUTPUT); // Set digital pin 2 as OUTPUT to connect it to the RFID /ENABLE pin
pinMode(ledPin,OUTPUT); // Set ledPin to output
digitalWrite(rfidPin, LOW); // Activate the RFID reader

blink(); // All variables are set, notify user ready to operate
Serial.println(“Setup complete, all lights OFF.”);
}

void loop()
{

if(Serial.available() > 0)
{ // if data available from reader

if((val = Serial.read()) == 10)
{ // check for header
bytesread = 0;

while(bytesread<10)
{ // read 10 digit code

if( Serial.available() > 0)
{
val = Serial.read();

if((val == 10)||(val == 13))
{ // if header or stop bytes before the 10 digit reading
break; // stop reading
}

code[bytesread] = val; // add the digit

bytesread++; // ready to read next digit
}
}

if(bytesread >= 10)
{ // if 10 digit read is complete
Serial.flush(); // clear “ghost” readings of the same RFID

if(strcmp(code, tag) == 0) // Does the tag read match the one we are looking for
{
Serial.print(“Tag matches: “); // Yes
Serial.println(code);

if (LightsOn == false) // If lights are off, turn them on.
{
blink();
myHouse.write(A, UNIT_1, repeat);
myHouse.write(A, ON, repeat);
LightsOn = true;
Serial.println(“Lights ON.”);
}

else // Lights are on, so turn them off
{
blink();
myHouse.write(A, UNIT_1, repeat);
myHouse.write(A, OFF, repeat);
LightsOn = false;
Serial.println(“Lights OFF.”);
}

digitalWrite(rfidPin, HIGH); // Pause the reader after a read cycle to reduce multiple
delay(3000); // readings from the same tag.
Serial.flush();
digitalWrite(rfidPin, LOW);
}

else // Tag read is not the one we’re looking for.
{
Serial.print(code);
Serial.println(” does not match”);
digitalWrite(rfidPin, HIGH); // Flush accidental multiple readings
delay(3000);
Serial.flush();
digitalWrite(rfidPin, LOW);
}
}

bytesread = 0; // clear system and prepare for next cycle
delay(500); // wait for a second
}
}
}

/***************************
* Function: blink
* Blink the LED to ack actions
****************************/
void blink()

{
digitalWrite(13,HIGH);
delay(1000);
digitalWrite(13,LOW);
}


Aug 28 2009

Solved: Photoshop CS4 won’t let me paste my screen shot (print screen)

This is an update to this issue:

Photoshop fails to paste my print screen from the clipboard. I’ve tested pasting in mspaint and it works fine. I’ve also tried creating a new document from clipboard but that won’t work either. What’s wrong and how do I fix it?

This is documented in stackoverflow, but the case has been closed and I wanted to give an update for Photoshop CS4

You can add a registry dword called “AlwaysImportClipboard” with a value of “1″ at this location: [HKEY_CURRENT_USER\Software\Adobe\Photoshop\11.0]

Remember, version 10.0 is CS3, 11.0 is CS4

Or, you can download these registry files which accomplish the same thing:

For Photoshop CS3 (fix print screen cs3 . reg)

For Photoshop CS4 (fix print screen cs4 . reg)

Update: Hey, sometimes photoshop has a hiccup and it just won’t let you paste. Something with the clipboard gets screwy. Just restart photoshop when that happens. Even this registry fix won’t solve that bug.

Photoshop actually has to “import” the clipboard to its own format – you may notice it actually doing this when you cursor changes to an hour glass (or “busy” or “busy background”) when you switch to photoshop after copying an image to the clipboard from another application. Sometimes there will be a slight delay while this import is happening before you can use / paste the image.

Also Note: You may need to go to Image->mode->RGB or CMYK  if it is set on “indexed color,” especially after opening something that has indexing enabled (like a .gif) before you can paste. Also, if you only have a background layer and it is set as “background” try either creating a new layer and pasting into that or holding “alt” (option on mac) and double clicking the background layer in the layers panel to convert it to a layer (or right click it and convert it to a layer)

Hopefully one of these things will help you paste your image.


Aug 25 2009

winrar right click archive “date” option on context menu

WinRAR has always been great. However, I find myself constantly renaming archives after using the right-click “add to archive” context menu item. I find myself prepending the files with the date created. I love streamlining things, so I decided to write WinRAR tech support a message. They prompty replied and informed me about some some things I didn’t realize were available!

Basically, you can create “profiles” for the archives you create.

Here are the steps RarLabs sent me:

- press “Add” button to open archiving dialog;

- enable “Generate archive name by mask” option on “Backup” page of
archiving dialog;

- select an appropriate mask for this option, insert + in the beginning
of mask to place it in the beginning of archive name;

- return to “General” page, press “Profiles…”, select “Save current
settings to a new profile”;

- specify a profile name and set “Add to context menu” option.
Also you may set “Immediate execution” option if you do not want to
see the archiving dialog every time after selecting this profile.

After that you shall see your new profile in context menu.

Note: The requires WinRar 3.8 or newer


Aug 22 2009

Linux / Unix: Change to a softlink’s absolute path (directory)

If you have quick links from your home directory to other places on your server, you might find this command useful:

cd -P `pwd`

It’s the Change Directory (cd) command with the -P flag (evaluates true base path from softlinks), followed by a apostrophe (same key as ~) and the pwd (print working directory) command, followed by another apostrophe

You could even create an alias to do this for you!


Aug 16 2009

Enabling Linked Tables in phpMyAdmin

This is what I was running when I got this to work:

  • WAMP Server 2.0
  • Apache 2.0.63
  • PHP 5.2.8
  • MySQL 5.1.36

Step 1: Edit and run create_tables.sql

This sql file is included with phpMyAdmin, in a wamp installation it can be found at: C:\wamp\apps\phpmyadmin3.2.0.1\scripts\create_tables.sql

There are two sections at the top which are usually commented out – one to create a phpmyadmin database, and one to create a phpmyadmin user. I usually just create the database myself and I prefer to use the following command in the next step to create the user. So, after creating the database, I usually just run the file as it originally came.

Step 2: Create a control user (controluser):

You’re on your own if you used the script above to create your control user, and you probably know what you’re doing. If you don’t, however, I recommend these mysql commands:

CREATE USER 'phpmyadmin'@'localhost' IDENTIFIED BY 'pmapass';
GRANT SELECT, INSERT, UPDATE, DELETE ON phpmyadmin.* TO 'phpmyadmin'@'localhost';

Step 3: Edit config.inc.php:

Add these lines to your config.inc.php file and then you should be good to go!


$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
$cfg['Servers'][$i]['relation'] = 'pma_relation';
$cfg['Servers'][$i]['table_info'] = 'pma_table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma_column_info';
$cfg['Servers'][$i]['history'] = 'pma_history';
$cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';

$cfg['Servers'][$i]['controluser'] = 'phpmyadmin';
$cfg['Servers'][$i]['controlpass'] = 'pmapass';

Troubleshooting:

If you’re getting the message “The additional features for working with linked tables have been deactivated. To find out why click here.” or something similar, it probably means you don’t have the pmadb, controluser, and/or controlpass set up correctly to corresponding users in the database.

If you’re getting a message saying  ”not OK [ Documentation ]” but the first line ($cfg['Servers'][$i]['pmadb']) says OK, you either need to adjust the table names, or overcome something more complex. For me, after I switched to Apache 2.0 from 2.2 it started working.

ps: After installing, I was getting this to work fine with firefox 3.5, however, it was a no-go on google chrome.

Good luck.

Also see:


Aug 16 2009

nVidia profile (keyboard) shortcuts

If you have recent nVidia software, you can enable the nView desktop manager, and then access the nView Desktop manager’s HotKeys tab.

There you will find an option to assign a keyboard shortcut to a profile.

nvidea keyboard shortcut profile

I’ve also been trying to figure out a way to adjust the brightness and contrast with a quick, command line or shortcut method. Here’s as far as I’ve gotten.