Tag Archive


3D 3dprinting android ant BigData bitcoin Browsers C/C++ cryptocurrency CSS dd ddrescue dogecoin DOS editors find Games Git hadoop html html5 Java Linux litecoin node perl Postgres Programming Python scripting Shell SQL Swing TOTK Utilities utilization vi Video Web Web Design Wifi Windows Wordpress XML Zelda

SQL: Get a list of dates

So I didn’t have a table of dates set up, but I needed to get a list of dates going
back a certain number of days. I was looking at programming up a date function but
decided that a little SQL could do just what I wanted. I used the following query
to generate my list:

select (current_date-21) +s.a as date from generate_series(0,21) as s(A);

This returned a list of dates:

2012-06-01
2012-06-02
2012-06-03
2012-06-04
2012-06-05
2012-06-06
2012-06-07
2012-06-08
2012-06-09
2012-06-10
2012-06-11
2012-06-12
2012-06-13
2012-06-14
2012-06-15
2012-06-16
2012-06-17
2012-06-18
2012-06-19
2012-06-20
2012-06-21
2012-06-22

This dealt with end of month issues and end of year issues without having to generate a ton
of code to do the same thing.

C: Check if string is a number

I was recently testing some basic input and wrote this code to test if the input was a number or not.

#include 

int main()
{
  char name[10];

  scanf("%s",&name);
  if (checkifNumber(name))
  {
     printf("Is a numbern"); 
  }
  else
  {
     printf("Invalid numbern");
  }
}

int checkifNumber(char *inp)
{
  int i=0;
  int isanumber = 1;

  while(inp[i] != '' && i < 10)
  {
    if (inp[i] >= '0' && inp[i] <= '9')
    {
    }
    else
    {
      isanumber =0;
    }
    i++;
  }
  return isanumber;
}

One thing that could be improved is to potentially use a global variable to define the length of the
input string as it is used in two different places in the program and could potentially lead to an
array overrun/underrun.

JAVA: XMLGregorianCalendar Dates

I was updating some plugins for a project and came to a query for an e-mail program I was writing, I had to send out recently introduced defects to their respective owners and insure that they would only get the defects from the a given offset. It turned out that my API had a XMLGregorianCalendar argument. So I went out to look for a way to offset the date object so I could retrieve the correct information.

I used the following to convert my date:

package com.etechtips;

import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class UpdateDate {

	public static void main(String[] args) {
		XMLGregorianCalendar xgcstart;
		GregorianCalendar gc;
		int daycount = 0;
		if (args.length != 1)
		{
			System.out.println("Need to specify offset");
			System.exit(1);
		}
		
		daycount = Integer.parseInt(args[0]);
		
		// This will get the current date based on System time of an object
		gc = new GregorianCalendar();
		System.out.println("CURRENT:" + gc.toString());

		// This will offset the date by daycount days
		gc.add(Calendar.DATE, daycount);
		System.out.println("OFFSET: "+ gc.toString());
		
		try
		{
			// Now the XMLGregorianCalendar object has an 
                        instance that is based on the time set in the gc object
			xgcstart = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
		}
		catch(DatatypeConfigurationException dce)
		{
			dce.printStackTrace();
			System.exit(1);
		}
		
		// Code omitted 	
	}
}

Output:

CURRENT:java.util.GregorianCalendar[time=1321793315934,areFieldsSet=true,areAllFieldsSet=true,
lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Chicago",offset=-21600000,
dstSavings=3600000,useDaylight=true,transitions=235,
lastRule=java.util.SimpleTimeZone[id=America/Chicago,offset=-21600000,dstSavings=3600000,
useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,
startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,
endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2011,MONTH=10,
WEEK_OF_YEAR=48,WEEK_OF_MONTH=4,DAY_OF_MONTH=20,DAY_OF_YEAR=324,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=3,
AM_PM=0,HOUR=6,HOUR_OF_DAY=6,MINUTE=48,SECOND=35,MILLISECOND=934,ZONE_OFFSET=-21600000,
DST_OFFSET=0]
OFFSET: java.util.GregorianCalendar[time=1321706915934,areFieldsSet=true,areAllFieldsSet=true,
lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Chicago",offset=-21600000,
dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/Chicago,
offset=-21600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,
startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,
endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,
YEAR=2011,MONTH=10,WEEK_OF_YEAR=47,WEEK_OF_MONTH=3,DAY_OF_MONTH=19,DAY_OF_YEAR=323,
DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=6,HOUR_OF_DAY=6,MINUTE=48,SECOND=35,
MILLISECOND=934,ZONE_OFFSET=-21600000,DST_OFFSET=0]

The printouts above show the current date and the new date based on the offset. I made the day of the month bold in the printouts to show what the offset has updated the date. You could put a much larger offset than 1 and Calendar object will take care of updating the day of week, week of year and more. You will not need to deal with checking for leap year or dealing with updating all the month and years, this is all taken care of for you.

Perl: CPAN installing modules

Sometimes it is necessary to install other modules into the Perl environment. Luckily there is a great repository of modules known as CPAN (The Comprehensive Perl Archive Network). This lets you install modules to help with encryption, XML,YAML, and many other things. There are a few ways to install a package and here are the ones that I use the most.

Using the CPAN shell:

perl -MCPAN -e shell

This will open a command prompt that will let you search for CPAN modules with:

i /PACKAGENAME/

or install a new module:

install /DateTime/

The nice thing about installing with CPAN is that it will look for the dependencies and suggest installing them before the module you requested.

NOTE:This can take some time and your dependencies could have dependencies.

The other method I use is to skip the CPAN prompt and just directly execute the install of the module:

perl -MCPAN -e 'install DateTime'

This is just the most basic of usage, and there is probably a lot more you can do, but I have not had to use much more than this.

Gallery of Hello World!

Here is a list of the Hello World Programs for different languages:

C

#include <stdio.h>
int main()
{
printf("Hello World!");
}

C++

#include <iostream.h>
int main()
{
cout << "Hello World!" << endl;
}

C#

public class HelloWorld
  public static void Main()
  {
    System.Console.WriteLine("Hello World!");
  }

Java

class HelloWorld {
static void main(String[] args)
{
System.out.println("Hello World!");
}

SHELL

echo "Hello World"

Python 2

print "Hello World!\n"

Python 3

print ("Hello World!")

Ruby

puts "Hello World!"

Perl

print "Hello World!n";

PHP

  <?php      
    print "Hello World!";
  ?>

Rust

fn main() {
    println("Hello World!");
}

This is the simplest form of Hello World for most of these languages.

Java Exception java.lang.NoClassDefFoundError and how to resolve it

I had recently reinstalled my system and was trying to run a simple class that consisted
of a “Hello World” program in Java. I received the following:

Compile:

$> javac LottoMain.java

Run:

$> java LottoMain

Exception in thread “main” java.lang.NoClassDefFoundError: LottoMain
Caused by: java.lang.ClassNotFoundException: LottoMain
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:319)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:264)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:332)
Could not find the main class: LottoMain. Program will exit.

The compile line completed without errrors and the LottoMain.class file was there, but
what I didn’t know was that I no longer had the current directory “.” in my CLASSPATH variable.

After adding “.” to my CLASSPATH variable the run command gave me what I was expecting.

Run:

$> java LottoMain

Hello Eric!

Updating the CLASSPATH variable in Bash:
in my home directory/.bashrc file

export CLASSPATH=$CLASSPATH:.

Using Variable Argument lists in functions for C and C++

Using Variable Argument lists in functions for CC++

In C there are times when you may want to have a variable amount of arguments passed into a function.  This can be accomplished when you pass the ellipses(…)  in as the last argument on your function.  The ellipses ,(…),  stands for zero  or more arguments.
There are a set of functions available to handle accessing this data and making it available to your function.

The source code example displays a version of the code for a printf like function and how to handle the optional arguments.

One note is that the arguments passed in to this function are not typed.  The handling of the argument depends on either a specific type passed in(ints only) or as is the case of the example, a formatted string to define the types of the arguments. What this means is that if you pass random sets of arguments, (such as ints, strings,chars, floats) there is no data type that is directly associated to the variable being passed in.

Required include file
#include <stdarg.h>
/* Old include <varargs.h> From before ISO C standard, GNU C compilers still support this */

Available functions:
Macro: va_start(va_list , last-required argument)
This sets up the pointer for va_list with the avaiable argument list.

Macro: va_arg(va_list, type)

This returns the value of the next argument and modifies the va_list argument
to point to the subsequent(next) argument.  The type of the value returned by
va_arg is type as specified in the call. type must be a self promoting type
not char or short int) that matches the type of the actual argument.

Macro: va_end(va_list)

This ends the processing of the va_list element and subsequent va_arg calls
may no longer work.  Note: In the GNU C library implementation this does nothing
and is used for portability.

Sample Function Call:

  int int1 = 1;

    char char1 = "s";

    char *str1 = "test";

    /* Sample function call. */
    ecdprintf("Int=%d Char=%c String=%sn",int1,char1,str1);

Sample Code follows:

int ecdprintf(const char *pstr, ...)

{
    const char *lstr;
    va_list argp;
    int lint;
    char *lchar;
    char strarr[255];

    /* This is the start of vararg processing. The first argument is the
         container argument of the vararg list and the second argument
         is the last fixed parameter passed into the function. */

    va_start(argp, fmt);
    for(lstr = pstr; *lstr = ''; lstr++)
    {
        if (*lstr != '%')
        {
            putchar(*lstr);
            continue;
        }

        switch(*++lstr)
        {
            case 'd':
                i = va_arg(argp,int);
                s = itoa(i,strarr, 10);
                putchar(i);
                break;
            case 'c':
                i = va_arg(argp, int);
                putchar(i);
                break;
             case 's':
                 lchar = va_arg(argp,char *);
                 fputs(lchar,stdout);
                 break;
              case 'x':
                 i = va_arg(argp,int);
                 s = itoa(i, fmtbuf, 16);
                 fputs(lchar, stdout);
                 break;
               case '%':
                  putchar('%');
                  break;

               default:
                    break;

             }

    }

    va_end(argp);

    }

}

This example created the a simple printf like function using characters within the string to let the function know how to deal with the extra variables used.