Top.Mail.Ru
? ?
entries friends calendar profile My Website
Image
Image
Image Image Image
Image
Image
Image Image Image
mrflash818, posts by tag: java - LiveJournal
Things I would like to remember and share.
Image Image Image
Image Image Image
Image
Image
Image
Image Image Image
Image
Image
Image Image Image Image Image Image
Image
Image
Image
Image Image Image
Image
Image
Image
Image
Now that I actually have created software I want to share with the world (nevermind how simple it is, I hope _somebody_ out there might find it useful besides myself!), It has triggered the desire to start updating my other little piece of the internet:

http://mrflash818.geophile.net/php/index.php

So...

I had my wife reactivate my SFTP account to our POWWEB web hosting (they are great, btw), and I was able to fetch the HTML and PHP files I had put out there... 5yrs ago.

Also re-remembered how to fire up my Debian workstation's install I did of apache v2.2.10 and PHP v5.2.7.

So...

The plan is to re-remember web development, and go through the professional motions of editing and testing files locally on my workstation, then SFTPing them to POWWEB to share with the world.

So...

The things I am going to create or update are:
1. CLANG (c-language) page.
1a. It will simply be simple HTML/PHP that has links to the source code and makefile for timediff for now

2. JAVA page
2a it will simply same as 1a, but for the trivial Java source code I made

3. resume - need to update it, it is now 2yrs out-of-date

Tags: , , , , , ,
Current Location: san gabriel, california
Current Mood: chipper chipper

Image
Image Image Image
Leave a comment
Image
Image
Image
Image Image Image
Image
Image
Image Image Image Image Image Image
Image
Image
Image
Image Image Image
Image
Image
Image
Image
Wa hoo! The calulation results from my timediff program match Open Office's calc results!

Now the only things left to add  to the program are:
1. Take an optional command line parameter to adjust the output ("-x" flags)
2. Add functionality to do the adjustment mathematics.

Next phase goals:
A. Begin to create a Debian package so that timediff is installed to either
i. /usr/local/bin or
ii. /usr/bin
(I need to do more research on which one would be the 'proper' location for a utility program like timediff.)

B. Make my program GPL'd and adjust the program source code declarations and package structure to adhere to GPL guidelines and be a Debian package.

Image

***
/*
 * Copyright (c) 2011
 *      Robert Leyva
 *
 * timediff.h
 *
 * Simple, but useful way to quickly determine the difference
 * between two A.D. dates as a command line program:
 *
 * timediff [options] date1 date2
 *
 * where
 *
 * dates are in ISO 8601 format ( http://en.wikipedia.org/wiki/ISO_8601 )
 * (basically yyyy-mm-dd)
 *
 * Leap year calculated by constraining date to after 1600AD and
 * the algorithm for the Gregorian Calendar from:
 * http://en.wikipedia.org/wiki/Leap_year of
 *
 * if year modulo 400 is 0
 *       then is_leap_year
 * else if year modulo 100 is 0
 *       then not_leap_year
 * else if year modulo 4 is 0
 *     then is_leap_year
 * else
 *     not_leap_year
 *
 *
 *
 * options
 * -------------
 * specify the units of time between system time and date1, or
 * between date1 and date2:
 *
 * -ms milliseconds
 * -s seconds
 * -m minutes
 * -h hours
 * -d days **default**
 *
 */

void usage();

typedef struct {
  int year;
  int month;
  int dayOfMonth;
} date_struct;
date_struct ISO8601dateStringConv(char*,int);

void printErrorAndExit(char *);

static int days_in_month[2][13] = {
    {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
};

date_struct min(date_struct,date_struct);
date_struct max(date_struct,date_struct);
int isLeftDateSmaller(date_struct,date_struct);
long daysBetween(date_struct, date_struct);
date_struct addOneDay(date_struct,int);
int isLeapYear(int year);

const char* PROGRAM_NAME = "timediff";


***
/*
 * Copyright (c) 2011
 *      Robert Leyva
 *
 * timediff.c
 *
 * Simple, but useful way to quickly determine the difference
 * between two A.D. dates as a command line program.
 *
 * Tracks leap year using Gregorian Calendar.
 *
 * timediff [options] date1 date2
 *
 * where
 *
 * dates are in ISO 8601 format ( http://en.wikipedia.org/wiki/ISO_8601 )
 * (basically yyyy-mm-dd)
 *
 * options
 * -------------
 * specify the units of time between system time and date1, or
 * between date1 and date2:
 *
 * -ms milliseconds
 * -s seconds
 * -m minutes
 * -h hours
 * -d days **default**
 *
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "timediff.h"


int main(int argc, char* argv[]) {
  // The program needs to be invoked as timediff yyyy-mm-dd yyyy-mm-dd
  if(argc != 3) usage();

  //1. fetch 1st date
  //2. fetch 2nd date
  //3. determine the difference, adjust for February when it is a leap year
  //4. return the difference in value defaulted or
  //   specified by modifier

  //Determine the lenth of a valid date string, including the required string termination character
  const int VALID_DATE_STRING_LENGTH = strlen("yyyy-mm-dd ");

  date_struct ds1, ds2;
  ds1 = ISO8601dateStringConv(argv[1],VALID_DATE_STRING_LENGTH);
  ds2 = ISO8601dateStringConv(argv[2],VALID_DATE_STRING_LENGTH);

  long result;
  result = daysBetween(ds1,ds2);
  printf("%ld",result);

  return 0;
}
// ***   end of main   ***
void printErrorAndExit(char * message) {
  fprintf(stderr, message);
  exit(1);
}
date_struct min(date_struct date1, date_struct date2) {
  if(date1.year < date2.year) return date1;
  if(date2.year < date1.year) return date2;

  if(date1.month < date2.month) return date1;
  if(date2.month < date1.month) return date2;

  if(date1.dayOfMonth < date2.dayOfMonth) return date1;
  if(date2.dayOfMonth < date1.dayOfMonth) return date2;

  return date2;
}
date_struct max(date_struct date1, date_struct date2) {
  if(date1.year > date2.year) return date1;
  if(date2.year > date1.year) return date2;

  if(date1.month > date2.month) return date1;
  if(date2.month > date1.month) return date2;

  if(date1.dayOfMonth > date2.dayOfMonth) return date1;
  if(date2.dayOfMonth > date1.dayOfMonth) return date2;

  return date2;
}
int isLeftDateSmaller(date_struct date1, date_struct date2) {
  if(date1.year < date2.year) return 1;
  if(date2.year < date1.year) return 0;

  if(date1.month < date2.month) return 1;
  if(date2.month < date1.month) return 0;

  if(date1.dayOfMonth < date2.dayOfMonth) return 1;
  if(date2.dayOfMonth > date2.dayOfMonth) return 0;

  return 0;
}
int isLeapYear(int year) {
  int value;
  value = year;

  //if year modulo 400 is 0
  //   then is_leap_year
  value = year % 400;
  if(value == 0) return 1;

  //else if year modulo 100 is 0
  //   then not_leap_year
  value = year % 100;
  if(value == 0) return 0;

  //else if year modulo 4 is 0
  //   then is_leap_year
  value = year % 4;
  if(value == 0) return 1;

  //else
  //   not_leap_year
  return 0;
}
date_struct addOneDay(date_struct ds, int isLeapYear){
  int daysInMonth;

  ds.dayOfMonth++;

  //If the month is February test for leap year and adjust daysInMonth
  if(ds.month == 2) {
    daysInMonth = days_in_month[isLeapYear][ds.month];
  } else {
    daysInMonth = days_in_month[0][ds.month];
  }

  if(ds.dayOfMonth > daysInMonth) {
    ds.month++;
    ds.dayOfMonth = 1;
    if(ds.month > 12) {
      ds.year += 1;
      ds.month = 1;
    }
  }
  return ds;
}
long daysBetween(date_struct date1, date_struct date2){
  long result = 0l;
  date_struct minDate = min(date1, date2);
  date_struct maxDate = max(date1, date2);

  date_struct countingDate;
  countingDate.year = minDate.year;
  countingDate.month = minDate.month;
  countingDate.dayOfMonth = minDate.dayOfMonth;

  int leapYear = isLeapYear(countingDate.year);
  int countingYear = countingDate.year;

  while(isLeftDateSmaller(countingDate,maxDate)) {
    countingDate = addOneDay(countingDate,leapYear);
    //if the year changes while counting, check to see if
    //it is a new year
    if(countingYear != countingDate.year) {
      countingYear = countingDate.year;
      leapYear = isLeapYear(countingDate.year);
    }

    result++;
  }

  return result;
}

date_struct ISO8601dateStringConv(char* dateString, int VALID_DATE_STRING_LENGTH) {
  char STRING_DATE_DELIMITERS[] = {'-','/'};
  date_struct result;
  char ds[VALID_DATE_STRING_LENGTH];
  char * pDs;
  int i;
  int MIN_YEAR = 1800;
  char ERROR_MSG_MISSING_PART[] = "Value must be yyyy-m[m]-d[d]\n";
  char ERROR_MSG_BAD_VALUE[] = "Invalid value for year, month, or date\n";

  strncpy(ds, dateString,VALID_DATE_STRING_LENGTH);
  if (VALID_DATE_STRING_LENGTH > 0)
    ds[VALID_DATE_STRING_LENGTH - 1]= '\0';

  // get the year
  pDs = strtok(ds,STRING_DATE_DELIMITERS);
  if(pDs == NULL) printErrorAndExit(ERROR_MSG_MISSING_PART);
  i = atoi(pDs);
  if(i == NULL || i < 1 || i < MIN_YEAR) printErrorAndExit(ERROR_MSG_BAD_VALUE);
  result.year = i;

  // get the month
  pDs = strtok(NULL,STRING_DATE_DELIMITERS);
  if(pDs == NULL) printErrorAndExit(ERROR_MSG_MISSING_PART);
  i = atoi(pDs);
  if(i == NULL || i < 1) printErrorAndExit(ERROR_MSG_BAD_VALUE);
  result.month = i;

  // get the day of month
  pDs = strtok(NULL,STRING_DATE_DELIMITERS);
  if(pDs == NULL) printErrorAndExit(ERROR_MSG_MISSING_PART);
  i = atoi(pDs);
  if(i == NULL || i < 1) printErrorAndExit(ERROR_MSG_BAD_VALUE);
  result.dayOfMonth = i;

  return result;
}

/*
 * Tell the user how to invoke the program
 */
void usage() {
  printf("%s [options] date1 date2 \n",PROGRAM_NAME);
  printf("\n");
  printf("where \n");
  printf("\n");
  printf("dates are in ISO 8601 format and are after 1800 A.D. \n");
  printf("(http://en.wikipedia.org/wiki/ISO_8601) \n");
  printf("(basically yyyy-mm-dd) \n");
  printf("\n");
  printf("options \n");
  printf("------------- \n");
  printf("The units of time between date1 and date2: \n");
  printf(" -ms milliseconds \n");
  printf(" -s seconds \n");
  printf(" -m minutes \n");
  printf(" -h hours \n");
  printf(" -d days **default** \n");
  printf("\n");
  exit(1);
}


***

It feels really good to see that three values are matching:
1. my new timediff program in C
2. OpenOffice's Calc program
3. my trivial program in Java, TimeBetweenTwoDates, which uses Java's Calendar class, and BigDecimal class.


All three concur with a value of days between 9999-12-31 and 2010-01-01 of 2918286 :)

Image

Tags: , , , , , , , , ,
Current Location: san gabriel, california
Current Mood: happy happy

Image
Image Image Image
Leave a comment
Image
Image
Image
Image
Image Image Image
Image
Image
Image Image Image Image Image Image
Image
Image
Image
Image Image Image
Image
Image
Image
Image
According to the utility electrical meter, this morning the house is at 4496 kwh.
***
Looking back at my own LJ posts, the earliest one with the new meter on the house was 2010-01-20, where I posted it read 159kwh (http://mrflash818.livejournal.com/83167.html)

2010-10-01 - 2010-01-20 = X days (2010-10-06 according to quick and dirty spreadsheet math, X should be 254, which means the average also should be 17kwh/day.

>> 2010-10-17 EDIT, after using BigDecimal and spending hours, as documented below, getting Debian Lenny Stable to be able to actually compile Java using Eclipse and Sun's/Oracle's JDK I have indeed computed 254 is the right answer [...falling to floor... THUD] ) <<

4496kwh - 159kwh = 4337 kwh

4337 kwh / X days = kwh average use per day during that time period.
***
To determine X, I'll use java. Fired up eclipse v3.2 in Debian lenny stable, ...and received error messages! oh no!
"robert@pip:~$ eclipse
searching for compatible vm...
  testing /usr/lib/jvm/java-6-openjdk...not found
  testing /usr/lib/jvm/java-gcj...found
/usr/lib/jvm/java-gcj/bin/java: symbol lookup error: /home/robert/.eclipse/org.eclipse.platform_3.2.0/configuration/org.eclipse.osgi/bundles/149/1/.cp/libswt-mozilla-gtk-3236.so: undefined symbol: _ZN4nsID5ParseEPKc"

Okay, then did a quick google search on the phrase "libswt-mozilla-gtk-3236.so: undefined symbol"

Which led me to http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=511713
"install
  xulrunner-dev 

and eclipse 3.2.2-6.1 should start under lenny."
So I then did robert@pip:~$ sudo aptitude install xulrunner-dev

Now eclipse v3.2 fires up fine in my Debian Lenny stable workstation.
***
When trying to run or debug my java program in eclipse v3.2.2-6.1
"Exception in thread "main" java.lang.NoClassDefFoundError:
   at gnu.java.lang.MainThread.run(libgcj.so.90)
Caused by: java.lang.ClassNotFoundException:  not found in gnu.gcj.runtime.SystemClassLoader{urls=[file:/home/robert/projects/java/daysBetweenDates/DateArithmetic/], parent=gnu.gcj.runtime.ExtensionClassLoader{urls=[], parent=null}}
   at java.net.URLClassLoader.findClass(libgcj.so.90)
   at gnu.gcj.runtime.SystemClassLoader.findClass(libgcj.so.90)
   at java.lang.ClassLoader.loadClass(libgcj.so.90)
   at java.lang.ClassLoader.loadClass(libgcj.so.90)
   at gnu.java.lang.MainThread.run(libgcj.so.90)"

Searching on google again:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=275656

Okay, so seems I need to get the Java JDK, fine:
http://wiki.debian.org/Java
robert@pip:~$ sudo aptitude install default-jre

robert@pip:~$ java --version
java version "1.5.0"
gij (GNU libgcj) version 4.3.2

Copyright (C) 2007 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Shutdown and restarted Eclipse, rebuilt, and tried again... still failed.
***
Installing the default-jre did not work, so now will go install the actual Java from Sun/Oracle that is still via Debian packages:

http://wiki.debian.org/Java/Sun
robert@pip:~$ sudo aptitude install sun-java6-jdk
Couldn't find any package whose name or description matched "sun-java6-jdk"  (grr!)

***
Adjusting aptitude sources list to include searches in non-free
added a line to /etc/apt/sources.list

robert@pip:/etc/apt$ sudo view sources.list
edited the existing lines to append 'non-free' at the end:
deb http://ftp.debian.org/debian/ lenny main non-free
deb-src http://ftp.debian.org/debian/ lenny main non-free

next did
robert@pip:~$ sudo aptitude update
...so aptitude now also has the list of packages available in non-free

and finally
robert@pip:~$ sudo aptitude install sun-java6-jre
robert@pip:~$ sudo aptitude install sun-java6-jdk

Sun's java installed into: robert@pip:/usr/lib/jvm/java-6-sun-1.6.0.20$

robert@pip:/usr/lib/jvm/java-6-sun/bin$ ./javac -version
javac 1.6.0_20

***
2010-10-17
Now just need to tell eclipse where the sun java goodies are.
Project-->Properties-->Java Build Path--> set the "Standard VM" to be set to /usr/lib/jvm/java-6-sun-1.6.0.20

***
Now back to the original goal, use java to calculate the number of days between 2010-10-01 and 2010-01-20:

First I just used long and double, but was not happy with the final result's rounding error after just 4 division operations, so switched to BigDecimal.

***
Here is the source code:
DatesBetweenTwoDates.java
--------------------------------------------
package org.rxl.DateArithmetic;

import java.lang.String;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;

public class DaysBetweenTwoDates {

    /**
     * Takes a String in the form of yyyy-mm-dd Returns Date set to yyyy-mm-dd
     * with time of 00:00:00
     *
     * @param dateString
     * @return Date
     */
    static Date parseDateString(String dateString) {       
        int year = 0;
        int month = 0;
        int dayOfMonth = 0;
        String item = null;
        Date result = null;

        StringTokenizer st = new StringTokenizer(dateString, "-");
        item = st.nextToken();
        year = Integer.parseInt(item);

        item = st.nextToken();
        month = Integer.parseInt(item);

        item = st.nextToken();
        dayOfMonth = Integer.parseInt(item);

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        // January is MONTH value of 0
        cal.set(Calendar.MONTH, month-1);
        cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        result = cal.getTime();
       
        return result;
    }

    public static String printDate(Date date) {
        String result = "";
       
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
       
        result += cal.get(Calendar.YEAR);
        result += "-";
        result += cal.get(Calendar.MONTH) + 1;
        result += "-";
        result += cal.get(Calendar.DAY_OF_MONTH);
       
        return result;
    }
   
    public static void usage() {
    }
   
    /**
     * @param args
     */
    public static void main(String[] args) {
        if (args.length != 2) {
            usage();
            System.exit(0);
        }
        Date date1 = null;
        Date date2 = null;

        date1 = parseDateString(args[0]);
        date2 = parseDateString(args[1]);
       
        long lminDate = Math.min(date1.getTime(), date2.getTime());
        long lmaxDate = Math.max(date1.getTime(), date2.getTime());
        long lresult = lmaxDate - lminDate;
       
        System.out.println("The difference between " + printDate(date1) + " and " + printDate(date2) + " is: ");
       
        System.out.println("milliseconds: " + lresult);
        //double dresult = lresult;
        int SCALE = 1;
        BigDecimal bdResult = new BigDecimal(lresult);
       
        //dresult = dresult / (double) 1000.0;
        bdResult = bdResult.divide(new BigDecimal(1000),SCALE,RoundingMode.HALF_UP);
        System.out.println("seconds: " + bdResult);
       
        //dresult = dresult / (double) 60.0;
        bdResult = bdResult.divide(new BigDecimal(60),SCALE,RoundingMode.HALF_UP);
        System.out.println("minutes: " + bdResult);
       
        //dresult = dresult / (double) 60.0;
        bdResult = bdResult.divide(new BigDecimal(60),SCALE,RoundingMode.HALF_UP);
        System.out.println("hours: " + bdResult);
       
        //dresult = dresult /  (double) 24.0;
        bdResult = bdResult.divide(new BigDecimal(24),SCALE,RoundingMode.HALF_UP);
        System.out.println("days: " + bdResult);
       
    }   
   
}
***
Here is the result:
The difference between 2010-10-1 and 2010-1-20 is:
milliseconds: 21942000000
seconds: 21942000.0
minutes: 365700.0
hours: 6095.0
days: 254.0
***

Tags: , , , , , , , ,
Current Mood: mellow mellow

Image
Image Image Image
Leave a comment
Image
Image
Image
Image Image Image
Image
Image
Image Image Image Image Image Image
Image
Image
Image
Image Image Image
Image
Image
Image
Image


import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.lang.Character;

public class WrapTextAfterCharacter {
 public WrapTextAfterCharacter(File inputFile, Character c, File outputFile) {
  formatText(inputFile, c, outputFile);
 }

 public void formatText(File inputFile, Character c, File outputFile) {
  //
  // Reads the input file
  // Loads a String Buffer
  // Remove carriage returns from the input
  // Once Character c is encountered
  // Outputs the contents of the StringBuffer and Character c and a
  // carriage return
  //
  FileInputStream fileInputStream = null;
  BufferedInputStream bufferedInputStream = null;
  BufferedWriter bufferedWriter = null;

  try {
   fileInputStream = new FileInputStream(inputFile);
   bufferedInputStream = new BufferedInputStream(fileInputStream);

   char dataCharacter = 0;
   int i;
   char filterCharacter = System.getProperty("line.separator").charAt(
     0);
   char filterCharacter2 = '\n';
   bufferedWriter = new BufferedWriter(new FileWriter(outputFile));

   while ((i = bufferedInputStream.read()) > 0) {
    dataCharacter = (char) i;
    if (dataCharacter == filterCharacter
      || dataCharacter == filterCharacter2)
     continue;
    bufferedWriter.append(dataCharacter);
    if (dataCharacter == c.charValue())
     bufferedWriter.newLine();
   }
   bufferedWriter.flush();
   bufferedWriter.close();
   bufferedInputStream.close();
   fileInputStream.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static void explain() {
  System.out.println("WrapTextAfterCharacter "
    + "<input filename> <text character> " + "<output filename>");
 }

 public static void validateArgs(String[] args) {
  if (args.length != 3) {
   explain();
   System.out.println();
   System.exit(0);
  }
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  validateArgs(args);

  File inputFile = null;
  Character c = null;
  File outputFile = null;

  inputFile = new File(args[0]);

  String characterString = args[1];
  c = characterString.charAt(0);

  outputFile = new File(args[2]);

  WrapTextAfterCharacter wrapTextAfterCharacter = new WrapTextAfterCharacter(
    inputFile, c, outputFile);

 }

}
 


Tags:
Current Location: san gabriel, california
Current Mood: mellow mellow

Image
Image Image Image
Leave a comment
Image
Image
Image
Image
Image Image Image
Image
Image
Image Image Image Image Image Image
Image
Image
Image
Image Image Image
Image
Image
Image
Image
Decided to download the source code for the latest stable versions of apache (v2.2.10), clamav (v0.94.2), php (v5.2.7), and postgres (v8.3.5) to my Debian Etch workstation.

Its been a while since I have indulged my inner geek, and exercised my skills as a programmer. So, going to install the necessary compilers and tools, and get them all installed and running. Here I am with my wife and I having an account on powweb.com for our http://geophile.net domain, and I haven't done a thing with it, and we have had it for years.

Current website development idea:
Figure out how to host torrents from our site, then upload my favorite web shows, such as Armin Van Buuren's State of Trance, and DJ Tiesto's Club Life.

Current project development idea:
Create an intraweb web site using the above that would allow 834 projects to be collaborative on the companies intranet, so as to minimize email traffic.

Clamav - well, that has nothing to do with a web project directly, but it feels better to have a current and running anti-virus program for scanning attachments.

I had previously downloaded and installed the eclipse package, but that is also there sitting unused. Downloaded most current version of the HttpClient java libraries. Next java goal will be getting inspired for a project.

Tags: , , , , , , ,
Current Location: san gabriel, california
Current Music: DJ Tiesto - Club Life 086

Image
Image Image Image
Leave a comment
Image
Image
Image
Image
Image Image
Image