A piggy bank of commands, fixes, succinct reviews, some mini articles and technical opinions from a (mostly) Perl developer.

Jump to

Quick reference

Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

401 vs 403 HTTP codes

Explanation:

401 'Unauthorized' should actually be 401 'Unauthenticated'
It should be used for missing or bad authentication.

403 'Forbidden' is the server telling you, "I know who you are, and you don't have permission to access this resource".

(source)

The best way to embed code snippets in your blogger posts

Use gist.github.com

That is all.

Its very easy, its hosted by Github.
I like git.

Many different ways to resolve an IP to a hostname in Perl

Some different ways to look up hostnames.

Notes:

  • getnameinfo() gets a hostname and a service name, so it's not exactly the same as gethostbyaddr()
  • although the docs imply you need to enter a port, that's just to get the local service name. If you set it as undef then you can ignore any service

# 1, old deprecated way

use Socket; # gethostbyaddr, inet_aton, AF_INET

sub ip_address_to_host {
    my ( $self, $ip_address ) = @_;
    my ($hostname) = gethostbyaddr(
        inet_aton($ip_address),
        AF_INET,
    );
    return $hostname;
}

# 2, newer better way

use Socket qw(AF_INET inet_pton getnameinfo sockaddr_in);

sub ip_address_to_host {

     my ( $self, $ip_address ) = @_;

    my $port = undef;
    my $socket_address = sockaddr_in($port, inet_pton(AF_INET, $ip_address));

    my $flags = 0;
    my $xflags = 0;
    my ($error, $hostname, $servicename) = getnameinfo($socket_address, $flags, $xflags);

    return $hostname;
}

# 3, best way - that only uses DNS and not /etc/hosts first

use Net::DNS;

sub ip_address_to_host {

     my ( $self, $ip_address ) = @_;

    my $res = Net::DNS::Resolver->new;
    my $target_ip = join('.', reverse split(/\./, $ip_address)).".in-addr.arpa";
    my $query = $res->query("$target_ip", "PTR") // return;
    my $answer = ($query->answer)[0] // return;
    my $hostname = $answer->rdatastr;

    return $hostname;
}

# 4, the code golf way (no validation) - by Mark B

 perl -le 'use Net::DNS::Resolver; print ((Net::DNS::Resolver->new()->query("10.232.32.158","PTR")->answer)[0]->ptrdname);'


Make it easy to review your code

tldr; It's difficult to arrange for a whole team of developers to follow and participate in code reviews, but if you use dedicated code review software then it's easy.

Of course you want a wide audience reading your code - in order to improve the quality of the code being produced by your team. You don't have anything to hide, do you? ;-)

Problem: Say you're not the "designated reviewer", and you want to see your team mates' code before it's merged to trunk, perhaps the following things have to happen:
    - Configure your email filters to pick out reviews from the hundreds of other update emails
    - Check out the code in your environment
    - Wait some time for the checkout to complete
    - Run a diff command to see the changes
    - Hope that your team is using version control tools which make it easy/possible to see only the commits they made, without mixing them up with all the code that was pulled from trunk/master along the way
    - Read the code
    - Copy and paste the lines of code you want to comment on (for context) into a message to the developer. As it's often easier and faster to use email, instant chat or a face to face meeting than adding comments to a bug tracking system, the rest of the team isn't part of the conversation and is denied the chance to learn about technique, see how to conform to house policy, etc.
    - Write the comments
    - The developer reads the comments and may or not make changes, you don't always know, and the rest of the team certainly doesn't know.
    - In a team where developers are expected to designate a single person to review each feature, attempting to give feedback on someone else's code out of turn could be seen as interfering and a distraction.

Solution: A better arrangement could be:
    - Use a code review tool: ReviewBoard, Stash or something similar
    - Click on a URL in the review notification email
    -  Read the code
    - Click on the line you want to comment on
    - Write the comments. The whole team gets notification emails of comments, so they can effortlessly follow along with conversations about the code.
    - The developer replies to the comments publicly, everyone is now aware of what technical decisions were made and why
    - Everyone is expected to review all code - it's not distracting because it becomes part of the general work of the team to ensure high code quality.

Code works on one environment but not another

What can differ between environments? Check the following:

* Your code (obviously)
* Versions of other dependent packages - both in-house and third-party
* Versions of other installed in-house modules
* Versions of other Perl CPAN modules
* Processes which didn't die when you restarted the app
* Data in the database
* Number of rows in tables, i.e. is some limit being hit?
* Schema of the database
* Browser cache
* Server side web cache
* Files on disk, e.g. cached print documents

(source: a decade's experience building software)

Perl code review

What is wrong with this line of code?

return !grep { $_ == $item->id } grep { $_ } @$scanned_items;

A lot of things are implicit in it.
It returns 1 (true) if the count is zero, and "" (emtpy string - false) if the count is non-zero.

I would prefer for it to be written more explicitly:

my $item_count = scalar grep { defined $_ && $_ == $item->id } @$scanned_items;
return ($item_count > 0) ? 0 : 1;

Automatically generated diagrams of Perl code


  • Use UML::Sequence to diagram your method calls - Looks cool but couldn't get the module's tests to pass.
  • Write your own code to produce a Graphviz spec file - Good choice if you want a data structure diagrammed, e.g. State transitions.
  • SchemaSpy works well for database tables.
Untried:
  • UML::Class::Simple - class diagrams, not methods?
  • Devel::Diagram - class diagrams, not methods?
  • Devel::DProfPP

Display upcoming code in Perl debugger

Type this after the debug session has started:
> @DB::typeahead=('v')
or
{{v

See also these questions and perldebug.

Misc Ruby stuff

  • Write to a file:
  • File.open(local_filename, 'w') {|f| f.write(doc) }
  • Read from a file:
  • File.open(local_filename, 'w') {|f| f.write(doc) }
  • stringify: .inspect

Basic Javascript

if( document.getElementById ){
var myReference = document.getElementById('divID');
}

Taxonomy menu for Drupal

<?php
$vid = 1; /* <---- put correct vocabulary ID here */
$terms = taxonomy_get_tree($vid);
print "<div class=\"item-list\">";
print "<ul>";
foreach ( $terms as $term ) {
$tcount = taxonomy_term_count_nodes($term->tid);
print "<li>".
l($term->name." (".$tcount.")",'taxonomy/term/'.$term->tid, array('title' => $tcount." posts in ".$term->name)).
"</li>";
} /* end foreach */
print "</ul>";
print "</div>";
?>

Code folding in vi

All you ever wanted to know about code folding in vim, including keys: http://www.linux.com/archive/articles/114138

Config settings for code folding: http://smartic.us/2009/04/06/code-folding-in-vim/

Vim documentation for folding: http://www.vim.org/htmldoc/fold.html
There are six methods to select folds:

manual manually define folds
indent more indent means a higher fold level
expr specify an expression to define folds
syntax folds defined by syntax highlighting
diff folds for unchanged text
marker folds defined by markers in the text

Key concepts:
  • To use the indent method you need to set the :tabstop correctly
  • Syntax method requires the correct syntax files to be present
Commands:
  • zc -> close fold
  • zo -> open fold

Importing a module's namespace in Perl

Ever get this error for a module you've written?

Use of inherited AUTOLOAD for non-method X() is deprecated

Put this at the top of your module:

package My::Module;

use Exporter;
our @ISA = 'Exporter';
our @EXPORT = qw(put the methods here);

And then in the main program:

use My::Module qw( the methods to import );

keywords: export import exporting

Freeing memory in C

If you allocate memory in a subroutine for a variable that you then return, you’ve got to free the variable you return:
 
char * allocstring(char * text)
{
    char * s = malloc(s, strlen(text)+1);
    strcpy(s, text);
    return s;
}
 
void main()
{
    char * s = allocstring(“Hello World”);
    free(s);
}

Comparing strings in C

In c it is not possible to directly compare two strings so a statement like if (string1==string2) is not valid. Most c libraries contain a function called the strcmp().This is used to compare two strings in the following manner.

if(strcmp(name1,name2)==0)
 puts("The names are the same");
else
 puts("The names are not the same.");

Thanks johnt

c logging

if your fprintf statements don't reach the apache error log, you may have to flush the output buffer:

fprintf(stderr, "error statement\n");
fflush(stderr);


Logging in an apache handler

ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "debug message");

Concatenate C strings, and return them from a function

Don't do this. Just use strcat() and strncpy() instead.

#include <stdlib.h>

char* concat(char*, char*);

int main (int argc, char** argv)
{
char *x = "something";
char *y = " completely different.";
  char *combined = concat(x, y);
printf("And now for %s\n", combined);
}

char* concat(char *a, char *b)
{
  char *target = malloc( strlen(a) + strlen(b) + 1 );
  strcpy(target,a);
strcat(target,b);
return target;
}

Deeply copy a perl hash

use Storable;

$bad_recipe = dclone($recipe);

Bash arithmetic/command expansion

Command expansion, I use a lot
echo something $( date +%s )

Backticks also work for command expansion
echo something `date +%s`
...but do they work any differently to $( )?

Conditionals, like an if statement, use square brackets
if [ "$end_hour" = "24" ]; then ....; fi

Arithmetic, like 1 + 2, uses this:
i=$(( i + 1 ))
let i+=1
See http://www.softpanorama.org/Scripting/Shellorama/arithmetic_expressions.shtml