DirectorySoftwareBlog Details for "Free Code,Example Code"

Free Code,Example Code

Free Code,Example Code
The FreeCode FreeCode blog is the largest collection of free Internet related source code. Free programs are available in the following languages, Java, Javascript, Ajax and Perl...
Articles: 1, 2

Articles

Secure File Copy in Java
2007-05-30 11:53:00
This example is from the book _Java in a Nutshell_ by David Flanagan. import java.io.*; public class File Copy { public static void copy(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer;
More About: Secure , Cure
JavaScript StringBuffer like java StringBuffer object
2007-05-30 11:08:00
function String Buff er() { this.buffer = []; } StringBuffer.prototype.append = function(string) { this.buffer.push(string); return this; } StringBuffer.prototype.toString = function() { return this.buffer.join(""); } Usage: var s = new StringBuffer(); s.append("Hello, ").append(" World!"); alert(s.toString());
More About: Java , Javascript , Object
Check whether a Perl module is installed
2007-05-26 16:04:00
The Perl code print all installed modules. #!/usr/bin/perl # check_modules.pl use strict; use ExtUtils::Installed; my $inst= ExtUtils::Installed->new(); my @modules = $inst->modules(); foreach(@modules) { my $ver = $inst->version($_) || "???"; printf("%-14s -v %s ", $_, $ver); } exit 0;
More About: Check , Module
Check whether a process is running or not
2007-05-26 16:04:00
The example Perl code demonstrate checking whether a process is running or not. #!/usr/bin/perl -w #$file: watchProcess .pl - watch whether a proccess is running. use strict; use POSIX; my $pid = shift; die "usage: watchProccess pid " unless defined $pid; my $times =0; do{ sleep(5); $times++; print "loop: $times "; }until kill(SIGCHLD,$pid)==0; print "proccess $pid is end. ";
More About: Running , Check
A simple java web calendar
2007-05-25 17:34:00
import java.util.Calendar ; import java.util.Date; import java.util.Locale; /** * A simple java web calendar * */ public class CalendarBuilder { protected String weeks[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; protected String shortWeeks[] = { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; protected String cnWeeks[] = { "日", "一", "二"
More About: Java , Simple , Lend
A Perl Daemon Example Script
2007-05-20 17:05:00
#!/usr/bin/perl -w#$file: daemon.pl - a daemon example script use strict;# become daemonmy $pid = fork();print $pid," ";if($pid) { #end parent process print "#parent process"; exit(0);}else { print "#child process";}# set new process groupsetpgrp;# setsid ? only Cwhile(1) { sleep(30); open ("TEST",">>/tmp/test.log"); my ($sec,$min,$hour,$mday,$mon,$year,$wday,$ yday,$isdst)=localtime(time); $year+=1900;$mon++; print TEST ("Now is $year-$mon-$mday $hour:$min:$sec. "); close (TEST);}
More About: Perl , Script , Example , Exam , Daemon
Using a Non-Capturing Group in a Regular Expression
2007-05-18 06:35:00
By default, a group captures text (see Capturing Text in a Group in a Regular Expression). In some cases, a group is needed but there is no need to capture the text. A non-capturing group should be used to improve performance. A non-capturing group starts with (?:. String inputStr = "abbabcd"; String patternStr = "(a(?:b*))+(c*)"; // (?:b*) is a non-capturing group // Compile and use regular expression Pattern pattern = Pattern.compile(patternStr); Matcher matcher = pattern.matcher(inputStr); boolean matchFound = matcher.find(); if (matchFound) { // Get all groups for this match for (int i=0; i String groupStr = matcher.group(i); } // group 0: abbabc // group 1: ab // group 2: c }
More About: Sing , Sion , Xpress
Capturing Text in a Group in a Regular Expression
2007-05-18 06:32:00
A group is a pair of parentheses used to group subpatterns. For example, h(a|i)t matches hat or hit. A group also captures the matching text within the parentheses. For example, input: abbc pattern: a(b*)ccauses the substring bb to be captured by the group (b*). A pattern can have more than one group and the groups can be nested. For example, pattern: (a(b*))+(c*)contains three groups: group 1: (a(b*)) group 2: (b*) group 3: (c*)The groups are numbered from left to right, outside to inside. There is an implicit group 0, which contains the entire match. Here is an example of what is captured in groups. Notice that group 1 was applied twice, once to the input abb and then to the input ab. Only the most recent match is captured. Note that when using * on a group and the group matches zero times, the group will not be cleared. In particular, it will hold the most recently captured text. For example, input: aba pattern: (a(b)*)+ group 0: aba group 1:...
More About: Text , Regular , Sion , Xpress , Group
A Perl Tool To Check HTTP Proxies
2007-05-16 09:19:00
Proxy Check er: only support to check http proxies.#!/usr/bin/perl -w #$file:proxy_check.pl - a simple tool to check http proxyuse strict;use LWP::UserAgent;my $proxy_list = "/root/proxy_list.txt";my $test_url = "http://www.mysite.com/";print "starting... ";open(FD,"$proxy_list") || die "can't open file $!";while() { chomp($_); my $proxy = $_; my $ua = LWP::UserAgent->new; $ua->timeout(20); $ua->proxy(['http'],$proxy); my $response = $ua->get($test_url); if ($response->is_success) { print "(Yes) $proxy "; }}proxy_list.txt:http://200.69.106.161:80 http://200.208.228.52:3128http://202.143. 133.194:8080http://201.54.163.158:6588htt p://201.56.115.242:8080
More About: Perl , Tool , Proxies , Http
Perl Telnet Program
2007-05-16 09:03:00
A perl program code to telnet to a machine.#!/usr/bin/perl -w# telnet.pl - a program to telnet to a machine# and do some stuffuse strict;use Net::Telnet ;my $host = shift || 'server.telent.com';my $user = shift || $ENV{USER};die "no user!" unless $user;my($pass, $command);print 'Enter password: ';system 'stty -echo';chop($pass = );system 'stty echo';print " ";my $tn = new Net::Telnet(Host => $host) or die "connect failed: $!";$tn->login($user, $pass) or die "login failed: $!";print 'Hostname: ';print $tn->cmd('/bin/hostname'), " ";my @who = $tn->cmd('/usr/bin/who');print "Here's who: ", @who, " ";print " What is your command: ";chop($command = );print $tn->cmd($command), " ";$tn->close or die "close fail: $!";
More About: Perl , Program , Gram
Regular Expression Search Program Example code
2007-05-16 08:45:00
This example demonstrates how to use a regular expression to find matches in a string. import java.util.regex.*; public class BasicMatch { public static void main(String[] args) { // Compile regular expression String patternStr = "b"; Pattern pattern = Pattern.compile(patternStr); // Determine if pattern exists in input CharSequence inputStr = "a b c b"; Matcher matcher = pattern.matcher(inputStr); boolean matchFound = matcher.find(); // true // Get matching string String match = matcher.group(); // b // Get indices of matching string int start = matcher.start(); // 2 int end = matcher.end(); // 3 // the end is index of the last matching character + 1 // Find the next occurrence matchFound = matcher.find(); // true } }
More About: Search , Code , Regular , Example , Program
javascript clock
2007-05-10 14:32:00
This script displays the current time in your browser. You can choose the 12-hours format or the 24-hours format. <html><head><title>Java script clock</title><head><style type="text/css"> form,label { font-family:arial, sans-serif, helvetica, "times new roman"; font-size:10pt; /* increase or decrease the value to change the size of the font */ } h1 { font-family:arial, sans-serif, helvetica, "times new roman"; }</style> <script type="text/javascript"> <!-- hide the code from old browsers that do not support javascript /* Original: daniusr You are welcomed to modify this script to your needs. This script retrieves the time from the internal system clock, so it is up to you to make sure the time is accurate or correct. */ function clock() { var today = new Date(); var hours = today.getHours(); var minutes = today.getMinutes(); var seconds =...
More About: Clock , Javascript , Lock
Adding Undo and Redo to a Text Component
2007-05-09 16:25:00
The Swing toolkit contains an undo manager that can be added to a Document object to provide undo and redo capabilty. This example adds undo capability to a JText Area component. The example binds the undo action to control-Z and the redo action to control-Y. JTextComponent textcomp = new JTextArea(); final UndoManager undo = new UndoManager(); Document doc = textcomp.getDocument(); // Listen for undo and redo events doc.addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent evt) { undo.addEdit(evt.getEdit()); } }); // Create an undo action and add it to the text component textcomp.getActionMap().put("Undo", new AbstractAction("Undo") { public void actionPerformed(ActionEvent evt) { try { if (undo.canUndo()) { undo.undo(); } } catch (CannotUndoException e) { ...
A Parsing CSV File Routine
2007-05-08 09:28:00
If any of you already know, parsing a CSV file is a pain in the !@#*! However, some people love to export their data via this format. So, I had a little time on my hands and wanted to share this bit of code with you. It is by no means "clean" and in pure OO format, but it gives you an idea of the pain of parsing this type of file/format.//*************************** ***********// Name: A Parsi ng CSV File Routine// Description:If any of you already know, parsing a CSV file is a pain in the !@#*! However, some people love to export their data via this format. So, I had a little time on my hands and wanted to share this bit of code with you. It is by no means "clean" and in pure OO format, but it gives you an idea of the pain of parsing this type of file/format.// By: Steven Jacobs////// Inputs:None//// Returns:None////Assumes:None////Side Effects:None//This code is copyrighted and has limited warranties.//Please see http://www.Planet-Source-Code.com/xq/ASP/ txtCodeId.4666/lngWId.2/qx/vb...
More About: Sing
Remove leading and trailing white space from a string
2007-05-08 09:14:00
This is a routine task best done with two regexp's when using perl.my $string = ' Mary had a little lamb. ';$string =~ s/^s+//; #remove leading spaces$string =~ s/s+$//; #remove trailing spacesprint $string;
More About: Space , White , Move , Rail , Pace
How to make a Splash Screen
2007-05-08 08:52:00
Theres no doubting that using Java Swing is time consuming on load times. So heres a demo splash screen to keep your users captivated.You will need two classes for this examplei.e. Splash .java and SplashWindow.java(remember line: 8 change this to match your splash image)just change the class name to match your entry class and bobs your uncle.Splash.javaimport java.awt.Frame;import java.awt.Toolkit;import java.net.URL;public class Splash { public static void main(String[] args) { Frame splashFrame = null; URL imageURL = Splash.class.getResource("img.png"); if (imageURL != null) { splashFrame = SplashWindow.splash( Toolkit.getDefaultToolkit().createImage(i mageURL) ); } else { System.err.println("Splash image not found"); } try { // Change the class name to match your entry class Class.forName("MainApp").getMethod("main" , new Class[] {String[].class}).invoke(null, new Object[] {args}); } catch (Throwable e) { e.printStackTrace(); System.err.flush(); System....
More About: Screen , Make , Lash , Cree
Sending a Cookie to an HTTP Server
2007-05-08 07:23:00
try {// Create a URLConnection object for a URLURL url = new URL("http://hostname:80");URLConnection conn = url.openConnection();// Set the cookie value to sendconn.setRequestProperty("Cook ie", "name1=value1; name2=value2");// Send the request to the serverconn.connect();} catch (MalformedURLException e) {} catch (IOException e) {}
More About: Server , Ending , Http
Parsing Character-Separated Data with a Regular Expression
2007-05-06 04:45:00
A line from a flat-file is typically formatted using a separator character to separate the fields. If the separator is simply a comma, tab, or single character, the StringTokenizer class can be used to parse the line into fields. If the separator is more complex (e.g., a space after a comma), a regular expression is needed. String.split() conveniently parses a line using a regular expression to specify the separator.String.split() returns only the nondelimiter strings. To obtain the delimiter strings, see Parsing a String into Tokens Using a Regular Expression.Note: The StringTokenizer does not conveniently handle empty fields properly. For example, given the line a,,b, rather than return three fields (the second being empty), the StringTokenizer returns two fields, discarding the empty field. String.split() properly handles empty fields.// Parse a comma-separated stringString inputStr = "a,,b";String patternStr = ",";String[] fields = inputStr.split(patternStr);// ["a", "", "b"]// ...
More About: Data , Character , Para , Sing
Parsing a String into Tokens Using a Regular Expression
2007-05-06 04:43:00
This example implements a tokenizer that uses regular expressions. The use of this tokenizer is similar to the String Tokenizer class in that you use it like an iterator to extract the tokens. CharSequence inputStr = "a 1 2 b c 3 4"; String patternStr = "[a-z]"; // Set to false if only the tokens that match the pattern are to be returned. // If true, the text between matching tokens are also returned. boolean returnDelims = true; // Create the tokenizer Iterator tokenizer = new RETokenizer(inputStr, patternStr, returnDelims); // Get the tokens (and delimiters) for (; tokenizer.hasNext(); ) { String tokenOrDelim = (String)tokenizer.next(); } // "", "a", " 1 2 ", "b", " ", "c" class RETokenizer implements Iterator { // Holds the original input to search for tokens private CharSequence input; // Used to find tokens private Matcher matcher; // If true, the String between tokens are retu...
More About: Regular , Sing , Sion , Xpress
JMailer is a java mail client like phpmailer
2007-05-04 10:32:00
package peace.org.mail;import java.io.File;import java.util.ArrayList;import java.util.Date;import java.util.Hashtable;import java.util.Iterator;import java.util.Properties;import java.util.Set;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.Address;import javax.mail.Authenticator;import javax.mail.Multipart;import javax.mail.PasswordAuthentication;import javax.mail.Session;import javax.mail.Transport;import javax.mail.Message.RecipientType;import javax.mail.internet.AddressException;impo rt javax.mail.internet.InternetAddress;impor t javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;/** * a java mail client is like phpmailer * author:freecode-freecode.blogspot.com */public class JMail er { // ///////////////////////////////////////// ////// // PUBLIC VARIABLES // ///////////////////////////////////////// ////// /** * Email priority (1 = High, 3 = Normal, 5 = low). */ public int ...
More About: Java , Mailer , Like , Client
How To Send E-Mail By JavaMail API
2007-05-02 16:50:00
This example demonstrates the simplest program that will send a textual E-mail message to a single recipient.import java.io.*;import javax.mail.*;import javax.mail.internet.*;import javax.activation.*;public class Send Mail {public static void send(String smtpHost, int smtpPort,String from, String to,String subject, String content)throws AddressException, MessagingException {// Create a mail sessionjava.util.Properties props = new java.util.Properties();props.put("mail.sm tp.host", smtpHost);props.put("mail.smtp.port", ""+smtpPort);Session session = Session.getDefaultInstance(props, null);// Construct the messageMessage msg = new MimeMessage(session);msg.setFrom(new InternetAddress(from));msg.setRecipient(M essage.RecipientType.TO, new InternetAddress(to));msg.setSubject(subje ct);msg.setText(content);// Send the messageTransport.send(msg);}public static void main(String[] args) throws Exception {// Send a test messageSendMail sender = new SendMail();sender.send("hostname", 25, "luotuo....
More About: E-Mail
More articles from this author:
1, 2
111751 blogs in the directory.
Statistics resets every week.


Contact | About
© Blog Toplist 2012 - Supported by Web Catalog - SEO by FeWorks
eXTReMe Tracker