Beefy Boxes and Bandwidth Generously Provided by pair Networks RobOMonk
Do you know where your variables are?
 
PerlMonks  

Cool Uses for Perl

( #1044=superdoc: print w/ replies, xml ) Need Help??

This section is the place to post your general code offerings.

CUFP's
A Sweet Little Esolang Implementation
1 direct reply — Read more / Contribute
by corenth
on Mar 24, 2013 at 19:23
    Some time ago, I tried my hand at an Esoteric Programming Language, Iris.

    To commemorate the birth of my first yungin' on the 22nd of March 2013, I've built Amelia. It's amazing what a little positive motivation can bring about. (She's already a little monkey!)

    What follows is the implementation followed by a fibonacci program written in Amelia.

wxPerl LED Dot Matrix Display Panel
2 direct replies — Read more / Contribute
by jmlynesjr
on Mar 14, 2013 at 16:15

    This code simulates an old fashioned 5x7 LED Dot Matrix Display Panel. This is a reimplementation of a C++ wxWidgets program by Christian Gr�fe (info@mcs-soft.de).

    The demo app displays 7 panels to demonstrate all the options supported: 7 Color pallets, Upper/Lower case & special characters, Scrolling, Inverse video, etc. The demo uses about 35% of the CPU on my old ThinkPad and has a fair amount of flicker, it's "blit"ing a whole lot of individual LEDs. Maybe it will update smoother on a more modern PC. A single panel display should look pretty good.

    The modules are: LedPanelApp.pl, LedPanelDisplay.pm, LedPanelMatrix.pm, LedPanelColourTbl.pm, & LedPanelCtbl.pm.

    Need a stock ticker or retro display? Give it a try.

    James

    There's never enough time to do it right, but always enough time to do it over...

Perl replacement for choice.com
4 direct replies — Read more / Contribute
by onelander
on Mar 01, 2013 at 23:48

    After running into the incompatibility of the choice.com program on Windows 64bit, I wondered if I could write a Perl replacement. I believe I have done it. I wanted to share what I created as this site has provided me so much help.

improve hexdump output
No replies — Read more | Post response
by daxim
on Feb 28, 2013 at 10:53
    hexdump only shows ASCII characters in the visualisation column, and substitutes everything else with a period. That's lame, but nothing that the following filter from my ~/.bashrc couldn't fix:
    # Turn   1220  4c 29 e5 41 89 ff 49 89  f6 48 c1 fd 03 49 89 d5  L).A..I. .H...I..
    # into   1220  4c 29 e5 41 89 ff 49 89  f6 48 c1 fd 03 49 89 d5  L)åA�ÿI�öHÁý␃I�Õ
    # requires http://catb.org/~esr/hexdump/
    hex () {
        hexdump $@ | perl -C -ne'
            $_ = substr $_, 0, 56;  # without right-hand side columns
            print $_;
            @F = split;             # split on space
            shift @F;               # drop address column
            for (@F) {
                $h = hex;
                if ($h < 32) {
                    print chr($h+0x2400);   # control character symbols
                } elsif (127 == $h) {
                    print chr 0x2421;       # delete symbol
                } elsif (0x80 <= $h and $h <= 0x9f) {
                    print chr 0xFFFD;       # undefined in iso-latin-1
                } elsif (0xa0 == $h) {
                    print chr 0x2420;       # non-breaking space as space symbol
                } else {
                    print chr $h;           # just the character as is
                };
            };
            print qq(\n);
        '
    }
    
Personal perldoc webserver
3 direct replies — Read more / Contribute
by Tanktalus
on Feb 27, 2013 at 19:49

    Most of the time I want to read the doc for a module, I either bring up konqueror where I have a shortcut "mod:" that sends me to "https://metacpan.org/module/\{@}", or I have to run "perldoc" on the module in my console because either I need the specific version of the module I'm using, and that's not always the latest, or, more likely, I need the doc to a module in our own repository (i.e., our code).

    Having given up on that, I whipped together the following. Now I can go to "http://localhost:8877/Module::Name" and get the perldoc in HTML form in my browser for this particular level. As a bonus, the links (L<...>) between modules works as well, which didn't quite happen for free.

    TODO list includes being able to dynamically switch between multiple installed perls for the @INC that I'll be using, as well as multiple code streams (getting the doc for My::Foo in the current release, the previous release, etc.), probably by allowing some sort of version identifier in the URL (http://localhost:8877/v3/My::Foo), and getting the perldoc -f flag :)

    In the hopes it gives someone else a starting point...

    # App::PerldocServer use autopackage; use strict; use warnings FATAL => 'all'; use 5.16.2; use EV; use AnyEvent::HTTPD; use File::Basename qw(basename dirname); use Pod::Simple::HTML; use URI::Escape qw(uri_unescape); sub new { bless {} } sub run { my $self = shift; my $httpd = AnyEvent::HTTPD->new( port => 8877 ); $httpd->reg_cb( '' => sub { my ($httpd, $req) = @_; my $path = $req->url()->path(); my $m = uri_unescape(basename($path)); $httpd->stop_request(); my $f = $self->find_module($m); my $html; if ($f) { local $Pod::Simple::HTML::Perldoc_URL_Prefi +x = ('http://localhost:8877' . dirname($path) . '/') =~ s[/+$][/]r; my $p = Pod::Simple::HTML->new(); $p->output_string(\$html); $p->parse_file($f); } else { $html = "<html><body><h1>Unknown module: $m +</h1></body></html>"; } $req->respond( { content => [ 'text/html', $html ] } ); }, ); EV::loop; } sub find_module { my $self = shift; my $m = shift; my @paths; push @paths, File::Spec->catdir($ENV{CC_ROOT},'lib'), if $ENV{CC_ROOT}; push @paths, @INC; $m =~ s[::][/]g; for my $p (@paths) { for my $e (qw(pod pm)) { my $fullpath = "$p/$m.$e"; return $fullpath if -r $fullpath; } } return undef; } 1;
    And the main script is my as-always-so-short:
    #!/usr/bin/perl use rlib '../lib'; use App::PerldocServer; my $app = App::PerldocServer->new(); exit $app->run();

    Update: removed reference to parent class - I don't think it's needed here.

Find an IP within a live nework
1 direct reply — Read more / Contribute
by blue_cowdawg
on Feb 27, 2013 at 14:00

    I whipped this up today to solve a problem that I deal with all the time. We have hundreds if not thousands of IP addresses on our network along with a very dynamic data center. What I mean by dynamic is hosts are always being added and with others being removed.

    So the system guys come to me all the time and ask me for one or more IP addresses on a given network. My group manages DNS and IP addresses (as opposed to the network team for some reason) and for some reason they like to come to me in particular for those requests.

    The normal process calls for combing through the DNS zone files and looking for a hole in the address range that isn't being used. Enough of that.. computers work for me not the other way around!

    Here's what I came up with:

    #!/usr/bin/perl -w $|=1; use strict; use Net::Ping; use Net::Netmask; use Net::DNS; use Getopt::Long; my @blocks=(); my $outfile=""; my $dns = Net::DNS::Resolver -> new; my $res = GetOptions("net=s",\@blocks, "out=s",\$outfile ); $outfile="candidates.txt" unless $outfile; @blocks=split(",",join(",",@blocks)); foreach my $i(0..$#blocks){ unless ($blocks[$i] =~ m@^\d+\.\d+\.\d+\.\d+/\d+$@){ $blocks[$i] = $blocks[$i] . "/24"; } } open FOUT,sprintf("> %s",$outfile) or die "$outfile: $!"; my $p = Net::Ping->new(); foreach my $block(@blocks){ my $net = Net::Netmask->new($block); foreach my $ip($net->enumerate()){ next if $ip =~ m@\.0$@; next if $dns->search($ip); printf "%s\r",$ip; unless ($p->ping($ip,1)){ printf FOUT "%s\n",$ip; } } }
    Now there is great room for improvement in this script, but I'll leave it to the gentle reader as an intellectual excersize.


    Peter L. Berghold -- Unix Professional
    Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg
ffmpeg console progress bar
2 direct replies — Read more / Contribute
by strredwolf
on Feb 18, 2013 at 12:01

    If you're in the furry fandom, more often than not you heard of the videos of a certain Big Blue Fox by the name of BBF TV HD. They're by a German video editor who works at RTL, and of when he and the Eurofurance crew visits a furry convention. It's a great way to get an idea of what a con is, or if you missed it, what happened.

    I pulled most of the videos from his site, and every so often I tweak the encode settings to mencoder to do it... except mencoder doesn't do bframes right. I switched over to ffmpeg (not avconvert from the rogue libav gang; the original ffmpeg)... which doesn't have a nice status line.

    Thankfully ffmpeg hit 1.0 and got a -progress option, which gives a nice status readout. Too bad my build outputs to a file, md5 code, or a pipe.. aka an opened file descriptor. Forget named pipes, it'll recreate 'em as a file.

    After some hacking around... I have this! The settings in the ffmpeg command match that for a 2nd Gen AppleTV, but I also have info for the 3rd Gen/iPhone 5/iPad 4. I name this version atv-enc.pl. It takes two arguments: atv-enc.pl input output

    EDIT: Whoops, a few bugs crept in with the bar. Fixed, and enhanced a bit.

    Information doesn't want to be free. It wants to be feline.
Get a specific frequency from various crystals & divisors
3 direct replies — Read more / Contribute
by roboticus
on Feb 16, 2013 at 13:29

    I'm trying to play with some RF electronics, and am thinking of experimenting with QRSS operation. I'm not a licensed amateur, so I'm planning on using the LowFER band under FCC part 15 rules for unlicensed operation. Especially as I've been interested in building another LF receiver (WWVB) for some time.

    So to get started, I need to find a suitable crystal and divisor network from what I have in my junkbox. This is the third time I've used this program, so I thought others might find it useful, as well.

    WARNING: The code is ugly and brute-force. I just wanted results, rather than something "nice". Normally, I wouldn't want to show something this ugly, but if it helps other people play with RF, it's worth it.

    To use it, you need a file (nominally "crystals.txt") that holds a list of the oscillators, crystals and/or resonators you have in your junkbox. My current list is:

    # Crystals, Oscillators & ceramic resonators. All freq in MHz # TODO: find way to specify tolerance: currently just using stated fre +quency # and can count number of zeros... # TODO: Modify to allow M or K to be decimal point to specify other fr +eq ranges # Oscillators (cans) OSC 20.0000 OSC 28.3220 OSC 42.0000 OSC 36.0000 OSC 36.00000 OSC 50.000 OSC 60.0 # Bare crystals XTAL .032768 XTAL .0384 XTAL 1.8432 XTAL 3.58 (tiny) XTAL 4.00 (tiny) XTAL 4.5 XTAL 7.3728 XTAL 6.000 XTAL 6.5536 XTAL 8.0000 XTAL 14.31818 XTAL 20.000 XTAL 27.115 XTAL 27.125 XTAL 30.000 XTAL 31 # UNKNOWNS: # BOMAF C-6 1W14T | MEW 31 PU47931-2 # A set marked 301-502 on side, top: (14,4,3,2,-1,-5,-8,-9,-11,-12,-1 +3) # Ceramic resonators RES 4.000 RES 8.000 RES 7.37 # ? "737 Cm 219" RES 10.7 RES 16.93

    Then you run the program specifying the frequency you want, and the tolerance you'll accept. It'll rip through the list and determine how to get the frequency you want. Then it reports the possibilities. Each line is formatted like:

    actualFreq (error) = startFreq / divisor "div =" factors

    For example, if I'm looking to build an oscillator for 175kHz, and am willing to accept a 500 Hz error, I'd run it like so:

    $ ./find_xtal.pl 175k k5 175,000 ( 0) = 42,000,000 / 240 div = 2^4 * 3 * 5 = 27,125,000 / 155 div = 5 * 31 174,935 ( 65) = 27,115,000 / 155 div = 5 * 31 174,927 ( 73) = 60,000,000 / 343 div = 7^3 175,141 ( 141) = 31,000,000 / 177 div = 3 * 59 174,827 ( 173) = 28,322,000 / 162 div = 2 * 3^4 174,825 ( 175) = 50,000,000 / 286 div = 2 * 11 * 13 174,757 ( 243) = 36,000,000 / 206 div = 2 * 103 174,611 ( 389) = 14,318,180 / 82 div = 2 * 41 175,409 ( 409) = 10,700,000 / 61 div = 61 175,438 ( 438) = 20,000,000 / 114 div = 2 * 3 * 19 = 30,000,000 / 171 div = 3^2 * 19 = 60,000,000 / 342 div = 2 * 3^2 * 19 = 50,000,000 / 285 div = 3 * 5 * 19 174,536 ( 464) = 16,930,000 / 97 div = 97 175,476 ( 476) = 7,370,000 / 42 div = 2 * 3 * 7

    What luck! I can hit the exact frequency I was thinking about using the 42 MHz crystal oscillator and three TTL chips from my junk box: (7490:divide by 10, 7492:divide by 12, 7476:divide by 2). That'll put me right in the middle of the LowFER band.

    (Note: I used k5 instead of 500 for tolerance, because 500 doesn't work, and I didn't want to spend the time to fix it. I'll try to update this post if I fix it or make any further improvements.)

    Anyway, I hope someone out there may find it useful. The code follows...

    Now I just need to do a little more research to find exactly what the best areas in the LowFER band are for QRSS to see if my intended 175kHz transmitter/receiver would be in a good spot.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Poll mailinator.com
1 direct reply — Read more / Contribute
by Corion
on Feb 12, 2013 at 14:16

    Recently, I've signed up for some forums, just to read their posts. As I'm not interested in having my email address sold, I used http://mailinator.com to create disposable email addresses. As I'm also lazy and didn't want to visit http://mailinator.com, I wrote the following script which generates a random email address and polls that inbox on mailinator.com, printing all HTTP links found in every mail, in the assumption that one of them is the signup/verification link mailed.

    Update: Mailinator is for Humans points out that they've cut the POP3 access and likely will cut all other "machine-only" access soon. So I won't bother porting this to consume the RSS feed. Sad that we can't have nice things.

    #!perl -w use strict; use Net::POP3; use MIME::Parser; use URI; use App::scrape 'scrape'; use Getopt::Long; use Pod::Usage; GetOptions( 's|server:s' => \my $server, 'd|domain:s' => \my $domain, 'm|mailbox:s' => \my $mailbox, 't|sleep:s' => \my $delay, ) or pod2usage(1); $server||= 'pop.mailinator.com'; $domain||= 'mailinator.com'; if( ! defined $delay) { $delay = 45; }; my @letters = ('a'..'z','0'..'9'); $mailbox ||= join '', map { $letters[ rand 0+@letters ] } 1..12; print "$mailbox\@$domain\n"; sleep $delay+rand(5); #while( 1 ) { poll(); #sleep 45+rand(5); #}; sub poll { my $connection= Net::POP3->new( $server ); if( $connection->login( $mailbox => 'xxxxxxxx' )> 0) { my $messages= $connection->list; for my $id (sort keys %$messages) { my $msg= $connection->get($id); my $mime= MIME::Parser->new(); my $raw= join '', @$msg; my $entity= $mime->parse_data( \$raw ); print $entity->head->get('subject'),"\n"; print $entity->head->get('from'),"\n"; (my $payload)= grep { $_->bodyhandle } ($entity, $entity-> +parts()); my $body= $payload->bodyhandle->as_string; if( 'text/html' eq $payload->effective_type ) { print "$_\n" for map { @$_ } scrape( $body, ['a@href'] +, { base => 'xxx' } ); } else { print "$_\n" for $body=~ m!(https?://[^\s]+)!g; }; }; }; $connection->quit; }; =head1 NAME anon-signup - poll a mailinator email address for HTTP links =cut
A few grammar checks for strings
3 direct replies — Read more / Contribute
by Lady_Aleena
on Feb 04, 2013 at 18:20

    I was digging around some old scripts in my play directory and found a script I started writing for form inputs for my site. It checks for eight little grammar problems or typographical errors, some of which I am guilty of every so often. If you can think of any more which would fit the format, please let me know.

    You can take out WORDLIST and just use join if you do not feel like installing Lingua::EN::Inflect (my favorite module). If you do not want to use the last until, just take out the returns in correct_grammar.

    I do not know how cool this is, but I think it is a bit cute.

    #!/usr/bin/perl use strict; use warnings; use Lingua::EN::Inflect qw(WORDLIST); local $\ = "\n"; print "Enter string: "; my $string = <>; chomp($string); my @conjunctions_list = qw(and but or nor); my @prepositions_list = qw( aboard about above across after against along amid among an +ti around as at before behind below beneath beside besides between beyond bu +t by concerning considering despite down during except excepting excluding following for from in inside into like minus near of off on onto opposite outside over past per plus regarding round save since than through to toward towards under underneath unlike until up upon versus via with within without ); sub correct_grammar { my ($string_to_check) = shift; my $CAPS = join('|',"A".."Z"); my $conjunctions = join('|',@conjunctions_list); my $prepositions = join('|',@prepositions_list); my @errors; push @errors, "have not used punctuation" if ($string_to_check +!~ /(?:\.|\!|\?|\,|\;)/); push @errors, "have not spaced your words out" if ($string_to_check +!~ /\s/); push @errors, "have not capitalized anything" if ($string_to_check +!~ /(?:$CAPS)/); push @errors, "have two capital letters in a row in your text" if ($ +string_to_check =~ /(?:$CAPS)(?:$CAPS)/); push @errors, "started with a conjunction" if ($string_to_check +=~ /^(?:$conjunctions) /i); push @errors, "ended with a preposition" if ($string_to_check +=~ / (?:$prepositions)(|\W)$/i); push @errors, "have a number which should be written out" if ($strin +g_to_check =~ / \d\d /); push @errors, "misspelled 'the'" if ($string_to_check +=~ / teh /i); if (scalar(@errors) > 0) { print "It appears you ".WORDLIST(@errors,{conj => 'and'}).'.'; return 0; } else { print "Good job, and thank you!"; return 1; } } until (correct_grammar($string)) { $string = <>; chomp($string); }

    Have fun with it!

    Have a cookie and a very nice day!
    Lady Aleena
wxPerl LCD Clock
No replies — Read more | Post response
by jmlynesjr
on Feb 04, 2013 at 11:41

    As suggested by ww in his response to my wxPerl Simulated 7 Segment LCD Display post, it's now available in clock form.

    The LCD, Angular Meter, and Linear Meter are all now in module format using Class::Accessor. Sure makes changes easier/quicker. There is also an additional process control example displaying 4 linear meters and 2 angular(round) meters. The updated code will be(has been) posted to github http://github.com/jmlynesjr/wxPerl-Module-Examples in a couple of days. For now, enjoy the clock code below.

    Update1: Need to add another flag to signal 12/24 hour display format. And light one of the decimal points on am/pm. Creeping elegance..:).

    Update2: Made the fix for 12/24 hour display and realised that I have polluted the LCDdisplay class with data that is only needed by the LCDClock program. I need to derive a sub-class of LDCdisplay to hold this data, It's always something...

    Update3: Derived class version done and will be the version posted to github when I can get to it.

    Update4: Alarm Clock version completed. Uses a wxMediaControl within an AudibleAlarm.pm class to play a selected MP3 file as the wakeup alarm sound.

    Update5: Latest code now posted to GitHub. A new repository was created, so the URL above was changed.

    LCDClock.pl

    LCDdisplay.pm

    James

    There's never enough time to do it right, but always enough time to do it over...

The most powerful CMS developed in Perl (not spam, sounds that way)
2 direct replies — Read more / Contribute
by snoopy20
on Feb 04, 2013 at 02:52
    Fellow programmers,

    I've been a Perl advocate for ten years now, while many have transferred to PHP I stuck with it and over seven years developed a hugely powerful, vastly dynamic management system in functional perl. The seven years were spent refactoring and making the 'structure' of the software beautiful, so that it can run any website of any specification.

    It's aim is simply to be unbeatable in any category. Although it wont have the biggest feature set, it's unbelievably dynamic and can be made to do anything with reduced code plugins. It already features the best security system of any CMS (I believe this) with user-group rights, inheritance and section security. Then there's the speed (ModPerl ready) and reliability. Comes with workflow, admin and user tools. Most websites won't need anything else over what is already provided.

    My website has only basic documentation at the moment but those with a basic understanding of Perl can jump right in. You can see my own personal website as I travel the world at: andrewcharnley.com. It uses much of the functionality offered by this software.

    It's GNU and downloadable here: igaro.com

    I LOVE feedback, it makes my day to read comments and suggestions, so if you try it out please let me know what you think.

    Lastly, this is software for developers. It allows end-users to run websites but is for developers to create them. As such, do not expect a 'Windows Install' setup. You still need to know your stuff.

    Power to those that love Perl!

    Enjoy, Andrew

    ## Coding on the go, currently in India travelling the world with his Mac.

Squarepusher - A Tool To Convert Images To Audio For Oscilloscope X/Y Mode Displays
4 direct replies — Read more / Contribute
by bpoag
on Feb 01, 2013 at 12:01
    I have a side hobby that involves resurrecting ancient electronics, and retrofitting them for modern purposes. One such tinkering project was to make an old early 60's oscilloscope and turn it into a device for displaying bitmap images.

    To do this, I needed something that would convert a bitmapped image into audio. The resulting audio can then be played back with the Left and Right audio channels hooked up to the Horizontal and Vertical inputs on the oscilloscope.

    Given the constraints of the hardware (an always-on single beam of electrons being redirected and shot against the backend of phosphor tube) this poses a bit of a challenge. First of all, youre constrained to 48 KHz of bandwidth, the upper limit of what most audio cards are capable of. Secondly, there's a limit to how quickly the oscilloscope can move the beam around. It's very easy to tell the oscilloscope to draw something too intricate, which results in terrible image flicker. Comprimises must be made to ensure that the image is both legible and as close to devoid of flicker as possible.

    Simply put, Squarepusher takes a 1-bit PBM image, and converts it into a 48KHz 2-channel (stereo) .WAV audio file. Why 1-bit? Because oscilloscopes are naturally monochrome display devices, read: no color. Secondly, the brightness of any given spot on the phosphor is a function of how long the beam stays in that location. There simply isn't enough time to modulate the beam at the microsecond level to emulate different greyscale values. You're effectively constrained to a small resolution (256x256) and the equivalent of 1-bit depth... a pixel is either on, or off. PBM happens to be a good format for such purposes, since ASCII PBM is nothing but a file of zeroes and ones. As a side note, to convert an image to 1-bit PBM, you can use pnmtools, GIMP, or Photoshop. The resulting image must be 256x256, and only 256x256.

    Why 256x256? Think of it like this. There's an upper limit to the number of points you can continually re-plot on an oscilloscope display before it becomes insanely flickery. There simply isn't enough time. At 256x256 resolution, in a worst case scenario, all 65536 pixels will need to be plotted, but it will usually be less. Even when the pixel count is far less than 65536, you'll still see noticable flicker..So, even at 256x256, that's already kind of above the functional threshold of the hardware. 256x256 just happens to be the best comprimise between image resolution and the draw speed of the beam. In theory, my code can be modded to do much higher resolutions, but you're going to need a wicked fast oscilloscope that might require violating every known law of physics to make it happen. :) I suppose you could change the resolution to 512x128, and it would look just as good, but, I figure most people would prefer having a nice square to work within, versus a rectangle. 256x256 is the best comprimise between image resolution the need to move the beam quickly. You're not likely to ever see a script such as this operate at any larger resolution.

    Squarepusher can render an image using any one of three different modes; "Standard", "turbo", and "plow".

    In Standard mode, the beam is directed across the display in a fashion similar to how you're reading this text; from left to right, and repositioning to a zero location once the end of a line is reached. This makes for a nice drawing, but some time is wasted in the horizontal sync (the time required to move the beam back to begin painting the next line.)

    In Turbo mode, Squarepusher will only bother drawing an outline of the image you provided, skipping any region that contails a solid-filled area of pixels. This helps reduce flicker at the cost of image clarity, but it can also produce some interesting effects.

    In Plow mode, Squarepusher will paint the image on the phosphor boustrophedonically. In English, like a farmer with an ox plows a field. The first scanline will be drawn left-to-right, and the following will be drawn right-to-left, in order to minimize the amount of time wasted respositioning the beam for the next pixel.

    Each mode takes three values. Frames, Lossyness, and Skip.

    Frames: Squarepusher will render multiple frames, which you will probably want to do most of the time. Multiple frames are also a must-have for images that require some persistence-of-vision trickery to look good. More on that in a moment.

    Lossyness: Often times, it simply takes too long for the beam to paint every single pixel of an image. The results will look terribly flickery. To get around this, we can specify a "lossyness" value. With this value, the painting algorithm can be instructed to randomly jump ahead, painting only a portion of the pixels on a given scanline. This is fine, provided you are rendering multiple frames, because eventually, the entire scanline will be painted, and thus the entire image. Specifying a lossyness value of "10", will tell the algorithm to randomly jump anywhere from 1 to 10 pixels ahead, checking to see if that pixel needs to be drawn, jumping another 1-10 pixels ahead, seeing if that pixel needs to be drawn, and so on. The net result will be a legible image via persistence-of-vision that seems a little bit glittery or grainy, but complete, and mostly flicker-free. Again, comprimise is the name of the game--We only have 48 KHz to work with, compared to something like NTSC television, which has something in the neighborhood of 4 MHz.

    Skip: Additional time can be saved by specifying a skip value. This value dictates the painting algorithm to skip a number of scanlines, sort of like the horizontal equivalent of the lossyness value. For example, specifying a skip value of 5 will tell the painting algorithm to paint a scanline, randomly skip ahead 1-5 scanlines, and continue painting. Used in conjunction with the lossyness value, the best possible combination of image clarity and refresh rate can be obtained.

    Squarepusher dumps its output to stdout, so, be sure to redirect it into a file. You'll see the command template, usage, and example usage below.

    Watch the video of this script beating the crap out of a 52 year old oscilloscope here. (Edit: Updated 2/2/13)

    #!/usr/bin/perl ## ## Squarepusher v0.1 written by Bowie J. Poag, 1/29/13 <bpoag@comcast. +net> ## ## Squarepusher converts a 1-bit 256x256 PBM image to a WAV audio bits +tream ## suitable for playing on an XY-mode oscilloscope display. ## ## Usage: ./squarepusher.pl <mode> <#frames> <lossyness> <skip> <filen +ame> ## Example: ./squarepusher.pl turbo 50 20 3 foo.pbm ## English: Using turbo mode, spit out 50 frames with a lossyness valu +e of 20, ## rendering every 3rd line of the image foo.pbm. ## ## Valid mode names are standard, turbo, and plow. ## ## Standard: Straightforward left-to-right traversal of the image, Thi +s will ## render the image on the screen in a sawtooth sort of fashion, like +one might ## read words a sentence in a paragraph. ## ## Turbo: This method attempts to optimize beam time by only rendering + the outline ## of a filled area, rather than the area itself. Useful if you have a + high-detail ## image that flickers a lot, and doesn't need precise detail. ## ## Plow: Like "Standard", but boustrophedonic traversal. The picture i +s drawn ## on the screen in a zig-zag fashion, alternating left-to-right and r +ight-to- ## left. This saves time in that the beam does not need to return to a + zero position ## to render the next scanline. ## ## Image conversion is beyond the scope of this script. If you want to + use some ## other image format with this script, you'll need to first convert i +t using ## netpbm tools, GIMP, Photoshop, or some other image processing tool +capable ## of exporting 1-bit images to ASCII PBM $mode=$ARGV[0]; $frames=$ARGV[1]; $lossy=$ARGV[2]; $skip=$ARGV[3]; @bitmap=`cat $ARGV[4]`; ## This is a 48 KHz 2-channel (stereo) 8-bit WAV file header. ## Normally, we would want to have correct subchunk values, but, ## i'm a lazy bastard, so we're just going to tell whatever's ## going to play this audio sample that it's 0xFFFFFFFF bytes ## in size, and have them deal with the underrun. ## ## I do this because I'd rather be waterboarded than have to ## deal with a file format that uses mixed big- and little-endian ## data. ## $header="\x52\x49\x46\x46\xFF\xFF\xFF\xFF\x57\x41\x56\x45\x66\x6D\x74\ +x20\x10\x00\x00\x00\x01\x00\x02\x00\x80\xBB\x00\x00\x00\x77\x01\x00\x +02\x00\x08\x00\x64\x61\x74\x61\xFF\xFF\xFF\xFF"; if ($lossy==1) { $frames=1; } if ($lossy<=0 || $lossy >=255) { $lossy=1; } # Strip the header information off.. shift(@bitmap); shift(@bitmap); shift(@bitmap); # A little cleanup.. foreach $item (@bitmap) { chomp($item); $total.=$item; } @image=split(//,"$total"); # The weird conditional block below is a hack. # It's basically a quick convolve filter, that will # produce a vector outline of any solid white area. # this saves beam traversal time, and significantly # reduces image flicker on images with a large ratio # of white to black pixels. # # In English, it will take any solid white shape, # and draw it as simply the outline of that shape. # # If you don't want to use this optimization, just # comment out the whole if statement. for ($q=0;$q<$frames;$q++) { if ($mode=~/turbo/) { for($x=0;$x<(256*256);$x+=rand($lossy)) { if(($image[$x]=="0" && $image[$x+1]!="0") || ($image[$x]=="1" && $image[$x+1]!="1") || ($image[$x]=="0" && $image[$x+257]!="0") || ($image[$x]=="1" && $image[$x+257]!="1")) { $col=$x%256; $row=int($x/256); if ($x<(256*256)-256) # Don't try to optimize the last line. { if ($row<256 && $col<256 && $row%((rand($skip))+1)==0) { $sample.=chr($row); $sample.=chr($col); } } } } } if ($mode=~/standard/) { for($x=0;$x<(256*256);$x+=rand($lossy)) { if ($image[$x]=="0") { $col=$x%256; $row=int($x/256); if ($row<256 && $col<256 && $row%((rand($skip))+1)==0) { $sample.=chr($row); $sample.=chr($col); } } } } if ($mode=~/plow/) #Boustrophedontastic! :) { for ($x=(256*256);$x>0;$x-=256) { $thisRow=int($x/256); if ($thisRow%2==0) { for ($c=0;$c<256;$c+=rand($lossy)) { if ($image[$x+$c]=="0") { $col=$c; $row=$thisRow; if ($row<256 && $col<256 && $row%((rand($skip))+1)==0) { $sample.=chr($row); $sample.=chr($col); } } } } if ($thisRow%2==1) { for ($c=256;$c>0;$c-=rand($lossy)) { if ($image[$x+$c]=="0") { $col=$c; $row=$thisRow; if ($row<256 && $col<256 && $row%((rand($skip))+1)==0) { $sample.=chr($row); $sample.=chr($col); } } } } } } } # We now have a rather large scalar who's contents are identical to an + 8-bit two-channel WAV audio stream, suitable for framing.. # $dump=$header.$sample; print $dump;
Perl Script To Detect Data Mover Failure In EMC NAS Arrays.
No replies — Read more | Post response
by perl514
on Jan 31, 2013 at 08:37

    Hi,

    Given below is a perl script that logs into EMC NAS Celerra Arrays and runs a command to check the DM status and emails the output.

    All thanks to the suggestions put forth by topher, keszler, Athanasius and two anonymous monks who helped me here (Seeking guidance for more idiomatic way of (re)writing this script.) that I was able to write a much better script and in the process learnt some new stuff. Thank you for all your suggestions. I have tried to incorporate them in here. If anyone else has further suggestions to make this better, please let me know.

    DWIM Perl Version 5.14.2 was used for this. Would also like to thank the DWIM Perl Creators. This has a lot of modules pre installed.

    Here's how the script works. There are 3 files required.Its better to have the files in the same directory. You'll need to put the script in Windows Scheduler so that it runs at regular intervals as you define.

    1) The file with the IPs of the NAS Arrays (given below).

    ############################################################### # #Lines beginning with "#" will be ignored by the script. # #This file contains the NAS IPs. # #Please use tab or space to seperate the name and IP of #the NAS Array +s. # ########################################################### NASBOX1 127.0.0.1 NASBOX2 127.0.0.2 NASBOX3 127.0.0.3 NASBOX4 127.0.0.4

    2) The file that the Config::Tiny module will read from. Its named as "nasconfig" (Given below). This file will have the various parameters like the name of the smtp mail server, the location of the nas ip text file, e-mail addresses etc etc. You'll need to populate the fields accordingly except the "nas_command" parameter.

    [params] smtp_server_name = mail.server.com nas_array_list ="location/of/nas_array_ip_list.txt" mail_from = your.name@email.com mail_to = some.name@email.com username = usrname password = passwd nas_command =/nas/sbin/getreason mail_text = "location/of/dmcheck.txt"

    3) The script file itself. And given below is the script

    And here is the output (Copy pasted from the mail)

    ###################################################################### +##################################################################### +############### Script nasmon.pl on mgmthost auto run at Thu Jan 31 05:53:19 2013 [mgm +thost Time] ###################################################################### +##################################################################### +############### ------------------------------------------------------------- Data Mover Check For NASBOX1 (127.0.0.1) ------------------------------------------------------------- DM is OK: 5 - slot_2 contacted DM is OK: 5 - slot_3 contacted DM is OK: 5 - slot_4 contacted DM is OK: 5 - slot_5 contacted ------------------------------------------------------------- Data Mover Check For NASBOX2 (127.0.0.2) ------------------------------------------------------------- DM is OK: 5 - slot_2 contacted DM is OK: 5 - slot_3 contacted DM is OK: 5 - slot_4 contacted DM is OK: 5 - slot_5 contacted ------------------------------------------------------------- Data Mover Check For NASBOX3 (127.0.0.3) ------------------------------------------------------------- DM is OK: 5 - slot_2 contacted DM is OK: 5 - slot_3 contacted DM is OK: 5 - slot_4 contacted DM is OK: 5 - slot_5 contacted ------------------------------------------------------------- Data Mover Check For NASBOX4 (127.0.0.4) ------------------------------------------------------------- DM is OK: 5 - slot_2 contacted DM is OK: 5 - slot_3 contacted DM is OK: 5 - slot_4 contacted DM is OK: 5 - slot_5 contacted

    I haven't got access to a test NAS Array to test how the message looks if there is a fault on the data mover, but I should be getting access to a test box pretty soon and will give the updates here.

    Perlpetually Indebted To PerlMonks

    use Learning::Perl; use Beginning::Perl::Ovid; print "Awesome Books";

wxPerl Process Control Example
No replies — Read more | Post response
by jmlynesjr
on Jan 30, 2013 at 18:41

    What do you do with a Simulated Linear Panel Meter? You modify it into a module and build a simulated process control screen around it.

    Need a break from "Select From...."? Give this a try.

    Left mouse click to select/deselect a meter. Right mouse click to change a meter's limit

    Many thanks to Mark Dootson for many excellent comments, not all of which are implemented yet in this example. All blame is mine.

    James

    There's never enough time to do it right, but always enough time to do it over...


Add your CUFP
Title:
CUFP:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":


  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others examining the Monastery: (8)
    As of 2013-05-19 09:01 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      The best material for plates (tableware) is:









      Results (397 votes), past polls