Monday, July 28, 2008

Have I appropriately professed my love for Ruby yet?

I used to play around with Ruby a lot. Here's another script, where I was downloading fedora ISOs and giving myself feedback as to the progress of the operation (yes, I was in cygwin also).


#!/usr/bin/ruby
require 'net/ftp'
require 'fileutils'
ftp=Net::FTP.new("ftp.linux.ncsu.edu")
ftp.login("anonymous", "me@email.com")
FileUtils.chdir("/cygdrive/c/downloads/fedora")
files=ftp.chdir("pub/fedora/linux/core/3/i386/iso")

def mecallback()
print 'filename: ', (File.size($fileName) * 100.0 / $fileSize), "%\n"
end

$fileName="FC3-i386-disc3.iso"
$fileSize=ftp.size($fileName)
print 'filename: ', $fileName, "\n"
ftp.getbinaryfile($fileName, $fileName, 2**20) {
print 'filename: ', (File.size($fileName) * 100.0 / $fileSize), "%\n"
}

ftp.close

Labels:

Ruby is so elegant

This is a script to log in to a server via Telnet and run a single script remotely.


require 'net/telnet.rb'

myserver.com = Net::Telnet::new("Host" => "myserver.com",
"Timeout" => 30,
"Prompt" => /[$%#] \z/n)

myserver.com.login("username", "password") { |c| print c }
myserver.com.close
myserver.com.cmd("./check_missing.sh") { |c| print c }

Labels:

Sunday, July 27, 2008

Regular expressions reference

Saturday, July 26, 2008

.htaccess redirect guide

My favorite tip:

Changed file extension?

This example is perfect if you've decided to switch to .php from .html pages. It will look for any .html page and redirect it to .php (ie http://www.example.com/yourpage.html and redirect it to http://www.example.com/yourpage.php). Now, be careful with this, it does mean any html page. I did this on one of my sites and had totally forgotten I had an iframe with .html content on some pages... I didn't notice for weeks that it was broken :S.
So learn from my mistake ;-) check, double check, then check again.

RedirectMatch 301 (.*)\.html$ http://www.example.com$1.php

Labels:

Tuesday, July 22, 2008

Rip page to new window in firefox

On the bookmark toolbar, right-click and select "New Bookmark..."

Under name, give your bookmark a fitting title, like, "Rip page."
Under location, enter the following code:
javascript:var x=window.open(document.URL, '_blank','width=800,height=600')


Or... just drag the following link to your bookmark toolbar.
Rip page.


Update on August 5, 2008:

I found the following works well for ripping a Google Docs page to a new window (former window closes as well.)
javascript:var%20x=window.open(document.URL,%20'_blank','width=800,height=600
,status=1,toolbar=1,location=1');window.close();

Rip page.

Labels:

Sunday, July 20, 2008

Optimized prime number generator

Same specs as previous system, 8 hours to find all primes to ULONG_MAX.


#include <stdio.h>
#include <malloc.h>
#include <limits.h>
#include <math.h>

struct linked_list
{
unsigned long number;
struct linked_list *next;
};

int main(int argc, char **argv)
{
unsigned long divisor, max_divisor, prime_test;
unsigned long max_prime_to_store;
struct linked_list *first=NULL, *current=NULL, *last=NULL;

first=(struct linked_list *)malloc(sizeof(struct linked_list));
first->number = 2L;
first->next = NULL;
last = first;
printf("%lu\n", 2L);

max_prime_to_store = 1L + sqrt(ULONG_MAX);

for(prime_test = 3L; prime_test < ULONG_MAX; prime_test+=2L)
{
max_divisor=1L+sqrt(prime_test);
for(current = first; current && current->number <= max_divisor; current = current->next)
{
if(prime_test % current->number == 0)
{
break;
}
}
if(!current || current->number > max_divisor)
{
if(prime_test <= max_prime_to_store)
{
last->next = (struct linked_list *)malloc(sizeof(struct linked_list));
last = last->next;
last->next = NULL;
last->number = prime_test;
}
printf("%lu\n", prime_test);
}
}
return 0;
}

Labels: ,

Friday, July 18, 2008

I miss C programming. Program to find prime numbers

Uses unsigned long long, goes up to ULONG_LONG_MAX.

Intel Core Duo 2 processor, running Cygwin on Windows XP, and compiled using gcc 3.4.4. Stops at first million results due to time. Can reasonably get to 10 million, if you're willing to wait.


#include <stdio.h>
#include <math.h>
#include <limits.h>

int main(int argc, char **argv)
{
unsigned long long divisor, max_divisor, prime_test;
int break_time = 0;

printf("%llu\n", 2LL);
for(prime_test = 3LL; prime_test < ULONG_LONG_MAX; prime_test+=2LL)
{
max_divisor=1LL+sqrt(prime_test);
for(divisor=3LL;divisor <= max_divisor; divisor+=2LL)
{
if(prime_test % divisor == 0)
{
break;
}
}
if(divisor >= max_divisor)
{
printf("%llu\n", prime_test);
}
else
{
continue;
}
break_time++;
if(break_time == 999999)
{
break;
}
}
return 0;
}

Labels: , ,

Thursday, July 10, 2008

VBScript to push files into an array based on a wildcard


Option Explicit
Dim gFSO
Dim dirListing
Dim fileName

set gFSO = CreateObject("Scripting.FileSystemObject")

dirListing = ListDir("c:\??*d*")

If UBound(dirListing) = -1 then
Wscript.Echo "No files found."
Else
For Each fileName in dirListing
WScript.Echo FileName
Next
End If

'==============================================================================
' List a directory, with the last part of the directory being the path
'==============================================================================
Function ListDir (ByVal Path)
Dim fileRegex
Dim searchFolderName
Dim searchFolder
Dim searchFolderFiles
Dim fileName
Dim fileArray
Dim file

set fileRegex = New RegExp
If gFSO.FolderExists(Path) Then ' Path is a directory, list all files in path
searchFolder = Path
fileName = ""
Else
searchFolderName = gFSO.GetParentFolderName(Path)
fileName = gFSO.GetFileName(Path)
fileRegex.Global = True
fileRegex.Pattern = "\."
fileName = fileRegex.Replace(fileName, "\.")
fileRegex.Pattern = "\?"
fileName = fileRegex.Replace(fileName, ".")
fileRegex.Pattern = "\*"
fileName = fileRegex.Replace(fileName, ".*")
End If
With fileRegex
.Pattern = fileName
.IgnoreCase = True
.Global = False
End With

ReDim fileArray(1)
Dim fileCount : fileCount = 0

Set searchFolder = gFSO.GetFolder(searchFolderName)
Set searchFolderFiles = searchFolder.Files

For Each file in searchFolderFiles
If fileRegex.Test(file.Name) Then
If fileCount > UBound(fileArray) Then
ReDim Preserve fileArray(fileCount*2)
End If
fileArray(fileCount) = file.Path
fileCount = fileCount + 1
End If
Next
ReDim Preserve fileArray(fileCount - 1)
ListDir = fileArray
End Function

Labels:

Tuesday, July 08, 2008

Tag Cloud for ftp blogger blogs

In the sidebar section for Blogger template, include:

<h2 class="sidebar-title">Labels</h2>
<p><?php include($_SERVER['DOCUMENT_ROOT']."/labels.php"); ?></p>



The following is a modified version of tag cloud source I found.

<?php

define('PREFIX', 'labels/'); // for url
define('SEARCH_DIR', '/home/username/www/labels'); // server location of labels subdirectory

define('THIS_FILE', 'labels.php'); // name of labels file (this file)

if(file_exists(SEARCH_DIR.'_cloud_include_cache.php') &&
filemtime(SEARCH_DIR.'_cloud_include_cache.php')>(time()-(60*60)))
{
echo file_get_contents(SEARCH_DIR.'_cloud_include_cache.php');
}
else
{
build_cloud();
}

/**
* build_cloud builds a tag cloud from the labels files.
* It actually uses labels file size to determine font size... which does
* not necessarily coincide with number of posts for a given label.
*
* smallest file is assigned 100% font-size. largest file - 200%
* everything else is proportional in between.
*/
function build_cloud()
{
$output = '';
$files = array();
$dir = opendir(SEARCH_DIR);
$low_end=PHP_INT_MAX;
$high_end=0;
while($file = readdir($dir))
if($file != '.' && $file != '..' && $file != THIS_FILE && $file != CACHE_FILE)
{
$files[$file] = filesize(SEARCH_DIR."/".$file);
$low_end = min($low_end, $files[$file]);
$high_end = max($high_end, $files[$file]);
}
closedir($dir);
ksort($files);
foreach($files as $name=>$size)
{
$output .= "<a style=\"". get_style($low_end, $high_end, $size) . "\"".
"href=\"".PREFIX.
htmlentities($name)."\">".
htmlentities(str_replace('.php','',$name))."</a> ";
}
echo $output;

$fp = fopen(SEARCH_DIR.'_cloud_include_cache.html','w');
fwrite($fp, $output);
fclose($fp);
}
function get_style($low_end, $high_end, $size)
{
$net = $high_end - $low_end;
$font_size = (($size - $low_end) * 100) / $net + 100;

if(!$interval) $interval++;

return "font-size: ".$font_size."%;";
}
?>

Labels: ,