Sh int status

HI ,
When I see "sh int status" from core switch --access switch port, I am getting huge count of Broadcast/multicast packet
How to refrain that behaviour & how to check what machine/host is generating the traffic.
Also any fine-tuning needs to be done in our network to control that behaviour.
Br/Subhojit

Hi Subhojit,
The only way that you will be able to know the source of the broadcast / multicast traffic is by getting a sniffer capture and analyzing it.
In order to contain / limit unicast / broadcast / multicast traffic, you need to configure storm-control on the affected ports. You may refer the following link for detailed information.
http://www.cisco.com/c/en/us/td/docs/switches/lan/catalyst2950/software/release/12-1_22ea/SCG/scg/swtrafc.html
I hope this helps.
Thanks,
Arun

Similar Messages

  • System.exit( int status );

    What's diference between System.exit(0); and System.exit(-1);
    What mean "int_status"

    Some shells allow you to handle the status code and do useful things with it. Taking bash as an example, you can use && and || to get another program to execute after your Java program only if the Java program respectively did or didn't return 0 (success exit code, and the default if you don't use System.exit and don't throw a RuntimeException out of main); you can use the $? environment variable to get the value returned (as a byte), and thus handle different error conditions differently (using test, for instance).
    So return 0 if execution was clean, or non-zero if something went wrong.

  • How to reterive the status of instance of report

    iI am using java SDK i have to reetive the status of all the instances of report
    That is sucess , failure , pending..etc
    how can i do that.

    Hi Amita ,
    As per the APIs ,there is a method in ISchedulingInfo interface i.e. getStatus() which returns an int datatype.
    So you will get status of the instance as int value only.
    You can use the following code snippet
    IInfoObjects infoobjects=infostore.query("select * from ci)infoobjects where si_kind='Crystalreport'/''Webi' and si_instance=1");
    for(int i=1;i<infoobjects.size();i++)
    IInfoObject infoobject=(IInfoObject) infoobjects.get(i);
    ISchedulingInfo oSchedInfo=infoobject.getSchedulingInfo();
    int status=oSchedInfo.getStatus();
    out.println(status);
    Regards,
    Prithvi

  • Port status on a IOS Switch

    Hi
    Is there any command with which one can know the status of the ports on a Cisco IOS Switch? I need to know if some of the ports on a particular Switch have ever been used or not. Is it possible?
    Regards // Anoop

    Hi Anup,
    How abt "sh int" or "sh int status"
    Regards,
    Ankur

  • SQL Server 2008:hide any row associate with original ticket when Status is cancel

    How can I say to hide any "original ticket" when the column status is Cancel?
    Date Date Stamp Original Ticket Trade Number Status
    01 jan 01 jan 123 130 Modify
    01 jan 02 jan 123 140 Cancel
    03 jan 03 jan 145 150 Modify
    04 jan 04 jan 160 200 Cancel05 jan 05 janv 210 210 (empty because some trade are not modify)i wanna get this result: hide original ticket witch status are cancel Date Date Stamp Original Ticket Trade Number Status
    03 jan 03 jan 145 150 Modify05 jan 05 janv 210 210 Tks a lot

    Hello,
    You can try to create a View to filter the recoder you don't need. Please refer to the following statement:
    Create table ticket
    ([Date] date ,[Date Stamp] date, [orginial ticket] int, [trade number] int, [status] varchar(20))
    insert into ticket values
    ('2014-01-01', '2014-01-01' , 123, 130,'Modify'),
    ('2014-01-01', '2014-01-02' , 123, 140,'Cancel'),
    ('2014-01-03', '2014-01-03', 145, 150, 'Modify'),
    ('2014-01-04', '2014-01-04',160, 200, 'Cancel'),
    ('2014-01-05', '2014-01-05',210, 210,NULL)
    go
    create view v_ticket as
    with cte as(
    select [orginial ticket], [Date],[Date Stamp],[trade number],status,
    row_number() over (partition by [orginial ticket] order by [date stamp] desc ) as rn
    from ticket )
    select * from cte
    where rn = 1 and (status <>'Cancel' or status is null)
    go
    select * from v_ticket
    Regards,
    Fanny Liu
    Fanny Liu
    TechNet Community Support

  • Showing thread status

    Hi, I need help showing a threads status. I am trying to do an exercise out of a teach yourself book, using threads. I created 3 threads and gave them a priority of 10, 5, and 1. To make sure it is working, I want to start the threads and then stop them in order of max priority to show the lower priority threads running after the higher threads have stopped. Any ideas on how to demonstrate this, and how to get a threads current status (ie sleeping, running, stopped?). Thanks, john.

    public int status()
    Returns the thread's status. If the thread is not suspended the thread's current status is returned. If the thread is suspended, the thread's status before the suspension is returned (or THREAD_STATUS_UNKNOWN if this information is not available. isSuspended() can be used to determine if the thread has been suspended.
    Returns:
    one of THREAD_STATUS_UNKNOWN, THREAD_STATUS_ZOMBIE, THREAD_STATUS_RUNNING, THREAD_STATUS_SLEEPING, THREAD_STATUS_MONITOR, THREAD_STATUS_WAIT, THREAD_STATUS_NOT_STARTED,
    Throws:
    ObjectCollectedException - if this object has been garbage collected

  • Nexus5548 - "faulty" interface status

    One of our enclosures lost one of it's backup links to a Nexus5548.   Looking at the interfaces the status reads "faulty".  The interface in  question is Eth1/5, but what I also noticed there were a couple  interfaces not in use w/ the same status. I tried switching out the gbic  and disabling/enabling the interface, but nothing helped.  Any  thoughts?  Is a reboot my only option?
    <code>
    switch# show int status
    Port          Name               Status    Vlan      Duplex  Speed   Type
    Eth1/1        --                 connected 226       full    10G     10Gbase-SR
    Eth1/2        --                 connected 226       full    10G     10Gbase-SR
    Eth1/3        --                 connected trunk     full    10G     10Gbase-SR
    Eth1/4        --                 faulty    1         full    10G     --
    Eth1/5        --                 faulty    trunk     full    10G     10Gbase-SR
    Eth1/6        --                 connected trunk     full    10G     10Gbase-SR
    Eth1/7        --                 notconnec trunk     full    10G     10Gbase-SR
    Eth1/8        --                 connected trunk     full    10G     10Gbase-SR
    Eth1/9        --                 notconnec 1         full    10G     10Gbase-SR
    Eth1/10       --                 notconnec 1         full    10G     10Gbase-SR
    Eth1/11       --                 faulty    1         full    10G     --
    Eth1/12       --                 connected trunk     full    10G     10Gbase-SR
    Eth1/13       --                 faulty    1         full    10G     --
    Eth1/14       --                 connected trunk     full    10G     10Gbase-SR
    Eth1/15       --                 sfpAbsent 1         full    10G     --
    Eth1/16       --                 connected trunk     full    10G     10Gbase-SR
    Eth1/17       --                 sfpAbsent 1         full    10G     --
    Eth1/18       --                 sfpAbsent 1         full    10G     --
    Eth1/19       --                 sfpAbsent 1         full    10G     --
    Eth1/20       --                 sfpAbsent 1         full    10G     --
    Eth1/21       --                 sfpAbsent 1         full    10G     --
    Eth1/22       --                 sfpAbsent 1         full    10G     --
    Eth1/23       --                 sfpAbsent 1         full    10G     --
    Eth1/24       --                 sfpAbsent 1         full    10G     --
    Eth1/25       --                 sfpAbsent 1         full    10G     --
    Eth1/26       --                 sfpAbsent 1         full    10G     --
    Eth1/27       --                 sfpAbsent 1         full    10G     --
    Eth1/28       --                 sfpAbsent 1         full    10G     --
    Eth1/29       --                 sfpAbsent 1         full    10G     --
    Eth1/30       --                 faulty    1         full    10G     --
    Eth1/31       --                 connected trunk     full    10G     10Gbase-LR
    Eth1/32       --                 connected trunk     full    10G     10Gbase-SR
    switch#       --                 notconnec routed    auto    auto    --
    </code>

    Yes try reload. To me this looks like hardware issue might need replacement.
    NXOS version?
    Any recent upgrade?
    Thanks,
    Richard.

  • Installation problem on Linux?

    Hi ,
    i am installing Oracle Application Sever 10g on RHEL 3.0 or RHEL AS4.0
    for that i have to apply patch3006854 as per installation manuals.
    but after applying this patch linux wont allow me to do anything and gives error
    cannot read from /etc/libcwait.so.
    Thanks
    Sohil

    Hi,
    Try the followings
    - Use the latest JDK
    - Just set your LD_LIBRARY_path     $ORACLE_HOME/lib:/usr/lib
    LD_LIBRARY_path     $ORACLE_HOME/lib:/usr/lib
    allocate your libcwait.so & set the following LD_PRELOAD (the place in which libcwait.so
    is allocated.
    If U do'not find it then
    Execute the following as oracle user
    gcc -O2 -shared -o ~/libcwait.so -fpic -xc - <<\EOF
    #include <errno.h>
    #include <sys/syscall.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    pid_t
    __libc_wait (int *status)
    int res;
    asm volatile ("pushl %%ebx\n\t"
    "movl %2, %%ebx\n\t"
    "movl %1, %%eax\n\t"
    "int $0x80\n\t"
    "popl %%ebx"
    : "=a" (res)
    : "i" (__NR_wait4), "0" (WAIT_ANY), "c" (status), "d" (0),
    "S" (0));
    return res;
    EOF
    export LD_PRELOAD=~/libcwait.so
    Let me know,
    Cheers,
    Hamdy

  • GIF decoding

    This works on WinXP but not Linux. Why? It takes the first frame of an animated gif and writes a thumbnail.
                GifDecoder d = new GifDecoder();    
                try {
                    fis = new FileInputStream(file);          
                    bis = new BufferedInputStream(fis);            
                    log.debug("reading gif");
                    d.read(bis);
                    log.debug("reading framecount");
                    int n = d.getFrameCount();
                    log.debug("read framecount" + n);
                    for (int i = 0; i < 1; i++) {
                        BufferedImage frame = d.getFrame(i);  // frame i
                        int t = d.getDelay(i);  // display duration of frame in milliseconds
                        log.debug("resizing frame");
                            File gifoutputfile = new File("gif" + i + outputthumbFilename);
                        BufferedImage bdest = new BufferedImage(60, 60, BufferedImage.TYPE_INT_RGB);
                        Graphics2D g = bdest.createGraphics();
                        AffineTransform at = AffineTransform.getScaleInstance((double) 60 / frame.getWidth(), (double) 60 / frame.getHeight());
                        g.drawRenderedImage(frame, at);
                        ImageIO.setUseCache(false);
                        ImageIO.write(bdest, "GIF", new File(outputthumbFilename));           
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
    import java.awt.AlphaComposite;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.image.BufferedImage;
    import java.awt.image.DataBufferInt;
    import java.io.BufferedInputStream;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import java.util.ArrayList;
    * Class GifDecoder - Decodes a GIF file into one or more frames. <br>
    * <pre>
    *  Example:
    *     GifDecoder d = new GifDecoder();
    *     d.read("sample.gif");
    *     int n = d.getFrameCount();
    *     for (int i = 0; i < n; i++) {
    *        BufferedImage frame = d.getFrame(i);  // frame i
    *        int t = d.getDelay(i);  // display duration of frame in milliseconds
    *        // do something with frame
    * </pre>
    * No copyright asserted on the source code of this class. May be used for any
    * purpose, however, refer to the Unisys LZW patent for any additional
    * restrictions. Please forward any corrections to [email protected].
    * @author Kevin Weiner, FM Software; LZW decoder adapted from John Cristy's
    *         ImageMagick.
    * @version 1.03 November 2003
    public class GifDecoder {
       * File read status: No errors.
      public static final int STATUS_OK = 0;
       * File read status: Error decoding file (may be partially decoded)
      public static final int STATUS_FORMAT_ERROR = 1;
       * File read status: Unable to open source.
      public static final int STATUS_OPEN_ERROR = 2;
      protected BufferedInputStream in;
      protected int status;
      protected int width; // full image width
      protected int height; // full image height
      protected boolean gctFlag; // global color table used
      protected int gctSize; // size of global color table
      protected int loopCount = 1; // iterations; 0 = repeat forever
      protected int[] gct; // global color table
      protected int[] lct; // local color table
      protected int[] act; // active color table
      protected int bgIndex; // background color index
      protected int bgColor; // background color
      protected int lastBgColor; // previous bg color
      protected int pixelAspect; // pixel aspect ratio
      protected boolean lctFlag; // local color table flag
      protected boolean interlace; // interlace flag
      protected int lctSize; // local color table size
      protected int ix, iy, iw, ih; // current image rectangle
      protected Rectangle lastRect; // last image rect
      protected BufferedImage image; // current frame
      protected BufferedImage lastImage; // previous frame
      protected byte[] block = new byte[256]; // current data block
      protected int blockSize = 0; // block size
      // last graphic control extension info
      protected int dispose = 0;
      // 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev
      protected int lastDispose = 0;
      protected boolean transparency = false; // use transparent color
      protected int delay = 0; // delay in milliseconds
      protected int transIndex; // transparent color index
      protected static final int MaxStackSize = 4096;
      // max decoder pixel stack size
      // LZW decoder working arrays
      protected short[] prefix;
      protected byte[] suffix;
      protected byte[] pixelStack;
      protected byte[] pixels;
      protected ArrayList frames; // frames read from current file
      protected int frameCount;
      static class GifFrame {
        public GifFrame(BufferedImage im, int del) {
          image = im;
          delay = del;
        public BufferedImage image;
        public int delay;
       * Gets display duration for specified frame.
       * @param n
       *          int index of frame
       * @return delay in milliseconds
      public int getDelay(int n) {
        delay = -1;
        if ((n >= 0) && (n < frameCount)) {
          delay = ((GifFrame) frames.get(n)).delay;
        return delay;
       * Gets the number of frames read from file.
       * @return frame count
      public int getFrameCount() {
        return frameCount;
       * Gets the first (or only) image read.
       * @return BufferedImage containing first frame, or null if none.
      public BufferedImage getImage() {
        return getFrame(0);
       * Gets the "Netscape" iteration count, if any. A count of 0 means repeat
       * indefinitiely.
       * @return iteration count if one was specified, else 1.
      public int getLoopCount() {
        return loopCount;
       * Creates new frame image from current data (and previous frames as specified
       * by their disposition codes).
      protected void setPixels() {
        // expose destination image's pixels as int array
        int[] dest = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
        // fill in starting image contents based on last image's dispose code
        if (lastDispose > 0) {
          if (lastDispose == 3) {
            // use image before last
            int n = frameCount - 2;
            if (n > 0) {
              lastImage = getFrame(n - 1);
            } else {
              lastImage = null;
          if (lastImage != null) {
            int[] prev = ((DataBufferInt) lastImage.getRaster().getDataBuffer()).getData();
            System.arraycopy(prev, 0, dest, 0, width * height);
            // copy pixels
            if (lastDispose == 2) {
              // fill last image rect area with background color
              Graphics2D g = image.createGraphics();
              Color c = null;
              if (transparency) {
                c = new Color(0, 0, 0, 0); // assume background is transparent
              } else {
                c = new Color(lastBgColor); // use given background color
              g.setColor(c);
              g.setComposite(AlphaComposite.Src); // replace area
              g.fill(lastRect);
              g.dispose();
        // copy each source line to the appropriate place in the destination
        int pass = 1;
        int inc = 8;
        int iline = 0;
        for (int i = 0; i < ih; i++) {
          int line = i;
          if (interlace) {
            if (iline >= ih) {
              pass++;
              switch (pass) {
              case 2:
                iline = 4;
                break;
              case 3:
                iline = 2;
                inc = 4;
                break;
              case 4:
                iline = 1;
                inc = 2;
            line = iline;
            iline += inc;
          line += iy;
          if (line < height) {
            int k = line * width;
            int dx = k + ix; // start of line in dest
            int dlim = dx + iw; // end of dest line
            if ((k + width) < dlim) {
              dlim = k + width; // past dest edge
            int sx = i * iw; // start of line in source
            while (dx < dlim) {
              // map color and insert in destination
              int index = ((int) pixels[sx++]) & 0xff;
              int c = act[index];
              if (c != 0) {
                dest[dx] = c;
              dx++;
       * Gets the image contents of frame n.
       * @return BufferedImage representation of frame, or null if n is invalid.
      public BufferedImage getFrame(int n) {
        BufferedImage im = null;
        if ((n >= 0) && (n < frameCount)) {
          im = ((GifFrame) frames.get(n)).image;
        return im;
       * Gets image size.
       * @return GIF image dimensions
      public Dimension getFrameSize() {
        return new Dimension(width, height);
       * Reads GIF image from stream
       * @param BufferedInputStream
       *          containing GIF file.
       * @return read status code (0 = no errors)
      public int read(BufferedInputStream is) {
        init();
        if (is != null) {
          in = is;
          readHeader();
          if (!err()) {
            readContents();
            if (frameCount < 0) {
              status = STATUS_FORMAT_ERROR;
        } else {
          status = STATUS_OPEN_ERROR;
        try {
          is.close();
        } catch (IOException e) {
        return status;
       * Reads GIF image from stream
       * @param InputStream
       *          containing GIF file.
       * @return read status code (0 = no errors)
      public int read(InputStream is) {
        init();
        if (is != null) {
          if (!(is instanceof BufferedInputStream))
            is = new BufferedInputStream(is);
          in = (BufferedInputStream) is;
          readHeader();
          if (!err()) {
            readContents();
            if (frameCount < 0) {
              status = STATUS_FORMAT_ERROR;
        } else {
          status = STATUS_OPEN_ERROR;
        try {
          is.close();
        } catch (IOException e) {
        return status;
       * Reads GIF file from specified file/URL source (URL assumed if name contains
       * ":/" or "file:")
       * @param name
       *          String containing source
       * @return read status code (0 = no errors)
      public int read(String name) {
        status = STATUS_OK;
        try {
          name = name.trim().toLowerCase();
          if ((name.indexOf("file:") >= 0) || (name.indexOf(":/") > 0)) {
            URL url = new URL(name);
            in = new BufferedInputStream(url.openStream());
          } else {
            in = new BufferedInputStream(new FileInputStream(name));
          status = read(in);
        } catch (IOException e) {
          status = STATUS_OPEN_ERROR;
        return status;
       * Decodes LZW image data into pixel array. Adapted from John Cristy's
       * ImageMagick.
      protected void decodeImageData() {
        int NullCode = -1;
        int npix = iw * ih;
        int available, clear, code_mask, code_size, end_of_information, in_code, old_code, bits, code, count, i, datum, data_size, first, top, bi, pi;
        if ((pixels == null) || (pixels.length < npix)) {
          pixels = new byte[npix]; // allocate new pixel array
        if (prefix == null)
          prefix = new short[MaxStackSize];
        if (suffix == null)
          suffix = new byte[MaxStackSize];
        if (pixelStack == null)
          pixelStack = new byte[MaxStackSize + 1];
        // Initialize GIF data stream decoder.
        data_size = read();
        clear = 1 << data_size;
        end_of_information = clear + 1;
        available = clear + 2;
        old_code = NullCode;
        code_size = data_size + 1;
        code_mask = (1 << code_size) - 1;
        for (code = 0; code < clear; code++) {
          prefix[code] = 0;
          suffix[code] = (byte) code;
        // Decode GIF pixel stream.
        datum = bits = count = first = top = pi = bi = 0;
        for (i = 0; i < npix;) {
          if (top == 0) {
            if (bits < code_size) {
              // Load bytes until there are enough bits for a code.
              if (count == 0) {
                // Read a new data block.
                count = readBlock();
                if (count <= 0)
                  break;
                bi = 0;
              datum += (((int) block[bi]) & 0xff) << bits;
              bits += 8;
              bi++;
              count--;
              continue;
            // Get the next code.
            code = datum & code_mask;
            datum >>= code_size;
            bits -= code_size;
            // Interpret the code
            if ((code > available) || (code == end_of_information))
              break;
            if (code == clear) {
              // Reset decoder.
              code_size = data_size + 1;
              code_mask = (1 << code_size) - 1;
              available = clear + 2;
              old_code = NullCode;
              continue;
            if (old_code == NullCode) {
              pixelStack[top++] = suffix[code];
              old_code = code;
              first = code;
              continue;
            in_code = code;
            if (code == available) {
              pixelStack[top++] = (byte) first;
              code = old_code;
            while (code > clear) {
              pixelStack[top++] = suffix[code];
              code = prefix[code];
            first = ((int) suffix[code]) & 0xff;
            // Add a new string to the string table,
            if (available >= MaxStackSize)
              break;
            pixelStack[top++] = (byte) first;
            prefix[available] = (short) old_code;
            suffix[available] = (byte) first;
            available++;
            if (((available & code_mask) == 0) && (available < MaxStackSize)) {
              code_size++;
              code_mask += available;
            old_code = in_code;
          // Pop a pixel off the pixel stack.
          top--;
          pixels[pi++] = pixelStack[top];
          i++;
        for (i = pi; i < npix; i++) {
          pixels[i] = 0; // clear missing pixels
       * Returns true if an error was encountered during reading/decoding
      protected boolean err() {
        return status != STATUS_OK;
       * Initializes or re-initializes reader
      protected void init() {
        status = STATUS_OK;
        frameCount = 0;
        frames = new ArrayList();
        gct = null;
        lct = null;
       * Reads a single byte from the input stream.
      protected int read() {
        int curByte = 0;
        try {
          curByte = in.read();
        } catch (IOException e) {
          status = STATUS_FORMAT_ERROR;
        return curByte;
       * Reads next variable length block from input.
       * @return number of bytes stored in "buffer"
      protected int readBlock() {
        blockSize = read();
        int n = 0;
        if (blockSize > 0) {
          try {
            int count = 0;
            while (n < blockSize) {
              count = in.read(block, n, blockSize - n);
              if (count == -1)
                break;
              n += count;
          } catch (IOException e) {
          if (n < blockSize) {
            status = STATUS_FORMAT_ERROR;
        return n;
       * Reads color table as 256 RGB integer values
       * @param ncolors
       *          int number of colors to read
       * @return int array containing 256 colors (packed ARGB with full alpha)
      protected int[] readColorTable(int ncolors) {
        int nbytes = 3 * ncolors;
        int[] tab = null;
        byte[] c = new byte[nbytes];
        int n = 0;
        try {
          n = in.read(c);
        } catch (IOException e) {
        if (n < nbytes) {
          status = STATUS_FORMAT_ERROR;
        } else {
          tab = new int[256]; // max size to avoid bounds checks
          int i = 0;
          int j = 0;
          while (i < ncolors) {
            int r = ((int) c[j++]) & 0xff;
            int g = ((int) c[j++]) & 0xff;
            int b = ((int) c[j++]) & 0xff;
            tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b;
        return tab;
       * Main file parser. Reads GIF content blocks.
      protected void readContents() {
        // read GIF file content blocks
        boolean done = false;
        while (!(done || err())) {
          int code = read();
          switch (code) {
          case 0x2C: // image separator
            readImage();
            break;
          case 0x21: // extension
            code = read();
            switch (code) {
            case 0xf9: // graphics control extension
              readGraphicControlExt();
              break;
            case 0xff: // application extension
              readBlock();
              String app = "";
              for (int i = 0; i < 11; i++) {
                app += (char) block;
    if (app.equals("NETSCAPE2.0")) {
    readNetscapeExt();
    } else
    skip(); // don't care
    break;
    default: // uninteresting extension
    skip();
    break;
    case 0x3b: // terminator
    done = true;
    break;
    case 0x00: // bad byte, but keep going and see what happens
    break;
    default:
    status = STATUS_FORMAT_ERROR;
    * Reads Graphics Control Extension values
    protected void readGraphicControlExt() {
    read(); // block size
    int packed = read(); // packed fields
    dispose = (packed & 0x1c) >> 2; // disposal method
    if (dispose == 0) {
    dispose = 1; // elect to keep old image if discretionary
    transparency = (packed & 1) != 0;
    delay = readShort() * 10; // delay in milliseconds
    transIndex = read(); // transparent color index
    read(); // block terminator
    * Reads GIF file header information.
    protected void readHeader() {
    String id = "";
    for (int i = 0; i < 6; i++) {
    id += (char) read();
    if (!id.startsWith("GIF")) {
    status = STATUS_FORMAT_ERROR;
    return;
    readLSD();
    if (gctFlag && !err()) {
    gct = readColorTable(gctSize);
    bgColor = gct[bgIndex];
    * Reads next frame image
    protected void readImage() {
    ix = readShort(); // (sub)image position & size
    iy = readShort();
    iw = readShort();
    ih = readShort();
    int packed = read();
    lctFlag = (packed & 0x80) != 0; // 1 - local color table flag
    interlace = (packed & 0x40) != 0; // 2 - interlace flag
    // 3 - sort flag
    // 4-5 - reserved
    lctSize = 2 << (packed & 7); // 6-8 - local color table size
    if (lctFlag) {
    lct = readColorTable(lctSize); // read table
    act = lct; // make local table active
    } else {
    act = gct; // make global table active
    if (bgIndex == transIndex)
    bgColor = 0;
    int save = 0;
    if (transparency) {
    save = act[transIndex];
    act[transIndex] = 0; // set transparent color if specified
    if (act == null) {
    status = STATUS_FORMAT_ERROR; // no color table defined
    if (err())
    return;
    decodeImageData(); // decode pixel data
    skip();
    if (err())
    return;
    frameCount++;
    // create new image to receive frame data
    image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
    setPixels(); // transfer pixel data to image
    frames.add(new GifFrame(image, delay)); // add image to frame list
    if (transparency) {
    act[transIndex] = save;
    resetFrame();
    * Reads Logical Screen Descriptor
    protected void readLSD() {
    // logical screen size
    width = readShort();
    height = readShort();
    // packed fields
    int packed = read();
    gctFlag = (packed & 0x80) != 0; // 1 : global color table flag
    // 2-4 : color resolution
    // 5 : gct sort flag
    gctSize = 2 << (packed & 7); // 6-8 : gct size
    bgIndex = read(); // background color index
    pixelAspect = read(); // pixel aspect ratio
    * Reads Netscape extenstion to obtain iteration count
    protected void readNetscapeExt() {
    do {
    readBlock();
    if (block[0] == 1) {
    // loop count sub-block
    int b1 = ((int) block[1]) & 0xff;
    int b2 = ((int) block[2]) & 0xff;
    loopCount = (b2 << 8) | b1;
    } while ((blockSize > 0) && !err());
    * Reads next 16-bit value, LSB first
    protected int readShort() {
    // read 16-bit value, LSB first
    return read() | (read() << 8);
    * Resets frame state for reading next image.
    protected void resetFrame() {
    lastDispose = dispose;
    lastRect = new Rectangle(ix, iy, iw, ih);
    lastImage = image;
    lastBgColor = bgColor;
    int dispose = 0;
    boolean transparency = false;
    int delay = 0;
    lct = null;
    * Skips variable length blocks up to and including next zero length block.
    protected void skip() {
    do {
    readBlock();
    } while ((blockSize > 0) && !err());
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     

    Niklas wrote:
    This works on WinXP but not Linux. Why? Please don't just post reams of code without providing more context and information.
    How is it failing on Linux? Wrong results? What are they? Error messages? What do they say? You need to give us some place to start looking.

  • How do I run multiple java apps in one JVM to reduce memory use?

    Hi all,
    I saw an article either on the web or in a magazine not too long ago about how to "detect" if the app is already running, and if so, it hands off the new instance to the already running JVM, which then creates a thread to run the Java app in. As it turns out, my app will be used in an ASP environment, through Citrix. We may have as many as 50 to 100 users running the same app, each with their own unique user ID, but all using the same one server to run it on. Each instance eats up 25MB of memory right now. So the question is if anybody knows of a URL or an app like this that can handle the process of running the same (or even different Java) apps in one JVM as separate threads, instead of requring several instances of the JVM to run? I know this article presented a fully working example, and I believe I know enough to do it but I wanted ot use the article as a reference to make sure it is done right. I know that each app basically would use the same one "launcher" program that would on first launch "listen" to a port, as well as send a message through the port to see if an existing launcher was running. If it does, it hands off the Java app to be run to the existing luancher application and shuts down the 2nd launching app. By using this method, the JVM eats up its normal memory, but each Java app only consumes its necessary memory as well and doesn't use up more JVM instance memory.
    Thanks.

    <pre>
    import java.util.Properties;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.lang.reflect.Method;
    import java.lang.reflect.InvocationTargetException;
    import java.util.Enumeration;
    import java.util.NoSuchElementException;
    public class RunProg implements Runnable, Cloneable
    private String iProg;
    private String iArgs[];
    public static void main(String args[])
    new RunProg().main();
    // first step is to start main program itself
    private void main()
    Properties properties = System.getProperties();
    try
    properties.load(new FileInputStream("RunProg.properties"));
    catch(IOException e)
    System.setProperties(properties);
    int i = 0;
    System.out.println("enter main, activeCount=" + Thread.activeCount());
    while(true)
    String program = properties.getProperty("Prog" + i);
    if(program == null)
    break;
    StringTokenizer st = new StringTokenizer(program);
    String[] args = new String[st.countTokens() - 1];
    try
    RunProg rp = (RunProg)this.clone();
    rp.iProg = st.nextToken();
    for(int j = 0; st.hasMoreTokens(); j++)
         args[j] = st.nextToken();
    rp.iArgs = args;
    Thread th = new Thread(rp);
    th.setName("prog" + i + "=" + program);
    th.start();
    System.out.println("prog" + i + "=" + program + ", started");
    catch(CloneNotSupportedException e)
    System.out.println("prog" + i + "=" + program + ", can't start");
    i++;
         System.out.println("end of main, activeCount=" + Thread.activeCount());
    // next step is to start all others one by one
    public void run()
    try
    Class c = Class.forName(iProg);
    Class p[] = new Class[1];
    p[0] = String[].class;
    Method m = c.getMethod("main", p);
    Object o[] = new Object[1];
    o[0] = iArgs;
    m.invoke(null, o);
    catch(ClassNotFoundException e)
    System.out.println(iProg + "ClassNotFoundException");
    catch(NoSuchMethodException e)
    System.out.println(iProg + "NoSuchMethodException");
    catch(InvocationTargetException e)
    System.out.println(iProg + "NoSuchMethodException");
    catch(IllegalAccessException e)
    System.out.println(iProg + "NoSuchMethodException");
    System.out.println(Thread.currentThread().getName() + ", ended");
    System.out.println("exit run, activeCount=" + Thread.activeCount());
    // setup SecurityManager to disable method System.exit()
    public RunProg()
         SecurityManager sm = new mySecurityManager();
         System.setSecurityManager(sm);
    // inner-class to disable method System.exit()
    protected class mySecurityManager extends SecurityManager
         public void checkExit(int status)
              super.checkExit(status);
              Thread.currentThread().stop();
              throw new SecurityException();
    * inner-class to analyze StringTokenizer. This class is enhanced to check double Quotation marks
    protected class StringTokenizer implements Enumeration
    private int currentPosition;
    private int maxPosition;
    private String str;
    private String delimiters;
    private boolean retTokens;
    * Constructs a string tokenizer for the specified string. All
    * characters in the <code>delim</code> argument are the delimiters
    * for separating tokens.
    * <p>
    * If the <code>returnTokens</code> flag is <code>true</code>, then
    * the delimiter characters are also returned as tokens. Each
    * delimiter is returned as a string of length one. If the flag is
    * <code>false</code>, the delimiter characters are skipped and only
    * serve as separators between tokens.
    * @param str a string to be parsed.
    * @param delim the delimiters.
    * @param returnTokens flag indicating whether to return the delimiters
    * as tokens.
    public StringTokenizer(String str, String delim, boolean returnTokens)
    currentPosition = 0;
    this.str = str;
    maxPosition = str.length();
    delimiters = delim;
    retTokens = returnTokens;
    * Constructs a string tokenizer for the specified string. The
    * characters in the <code>delim</code> argument are the delimiters
    * for separating tokens. Delimiter characters themselves will not
    * be treated as tokens.
    * @param str a string to be parsed.
    * @param delim the delimiters.
    public StringTokenizer(String str, String delim)
    this(str, delim, false);
    * Constructs a string tokenizer for the specified string. The
    * tokenizer uses the default delimiter set, which is
    * <code>"&#92;t&#92;n&#92;r&#92;f"</code>: the space character, the tab
    * character, the newline character, the carriage-return character,
    * and the form-feed character. Delimiter characters themselves will
    * not be treated as tokens.
    * @param str a string to be parsed.
    public StringTokenizer(String str)
    this(str, " \t\n\r\f", false);
    * Skips delimiters.
    protected void skipDelimiters()
    while(!retTokens &&
    (currentPosition < maxPosition) &&
    (delimiters.indexOf(str.charAt(currentPosition)) >= 0))
    currentPosition++;
    * Tests if there are more tokens available from this tokenizer's string.
    * If this method returns <tt>true</tt>, then a subsequent call to
    * <tt>nextToken</tt> with no argument will successfully return a token.
    * @return <code>true</code> if and only if there is at least one token
    * in the string after the current position; <code>false</code>
    * otherwise.
    public boolean hasMoreTokens()
    skipDelimiters();
    return(currentPosition < maxPosition);
    * Returns the next token from this string tokenizer.
    * @return the next token from this string tokenizer.
    * @exception NoSuchElementException if there are no more tokens in this
    * tokenizer's string.
    public String nextToken()
    skipDelimiters();
    if(currentPosition >= maxPosition)
    throw new NoSuchElementException();
    int start = currentPosition;
    boolean inQuotation = false;
    while((currentPosition < maxPosition) &&
    (delimiters.indexOf(str.charAt(currentPosition)) < 0 || inQuotation))
    if(str.charAt(currentPosition) == '"')
    inQuotation = !inQuotation;
    currentPosition++;
    if(retTokens && (start == currentPosition) &&
    (delimiters.indexOf(str.charAt(currentPosition)) >= 0))
    currentPosition++;
    String s = str.substring(start, currentPosition);
    if(s.charAt(0) == '"')
    s = s.substring(1);
    if(s.charAt(s.length() - 1) == '"')
    s = s.substring(0, s.length() - 1);
    return s;
    * Returns the next token in this string tokenizer's string. First,
    * the set of characters considered to be delimiters by this
    * <tt>StringTokenizer</tt> object is changed to be the characters in
    * the string <tt>delim</tt>. Then the next token in the string
    * after the current position is returned. The current position is
    * advanced beyond the recognized token. The new delimiter set
    * remains the default after this call.
    * @param delim the new delimiters.
    * @return the next token, after switching to the new delimiter set.
    * @exception NoSuchElementException if there are no more tokens in this
    * tokenizer's string.
    public String nextToken(String delim)
    delimiters = delim;
    return nextToken();
    * Returns the same value as the <code>hasMoreTokens</code>
    * method. It exists so that this class can implement the
    * <code>Enumeration</code> interface.
    * @return <code>true</code> if there are more tokens;
    * <code>false</code> otherwise.
    * @see java.util.Enumeration
    * @see java.util.StringTokenizer#hasMoreTokens()
    public boolean hasMoreElements()
    return hasMoreTokens();
    * Returns the same value as the <code>nextToken</code> method,
    * except that its declared return value is <code>Object</code> rather than
    * <code>String</code>. It exists so that this class can implement the
    * <code>Enumeration</code> interface.
    * @return the next token in the string.
    * @exception NoSuchElementException if there are no more tokens in this
    * tokenizer's string.
    * @see java.util.Enumeration
    * @see java.util.StringTokenizer#nextToken()
    public Object nextElement()
    return nextToken();
    * Calculates the number of times that this tokenizer's
    * <code>nextToken</code> method can be called before it generates an
    * exception. The current position is not advanced.
    * @return the number of tokens remaining in the string using the current
    * delimiter set.
    * @see java.util.StringTokenizer#nextToken()
    public int countTokens()
    int count = 0;
    int currpos = currentPosition;
    while(currpos < maxPosition)
    * This is just skipDelimiters(); but it does not affect
    * currentPosition.
    while(!retTokens &&
    (currpos < maxPosition) &&
    (delimiters.indexOf(str.charAt(currpos)) >= 0))
    currpos++;
    if(currpos >= maxPosition)
    break;
    int start = currpos;
    boolean inQuotation = false;
    while((currpos < maxPosition) &&
    (delimiters.indexOf(str.charAt(currpos)) < 0 || inQuotation))
    if(str.charAt(currpos) == '"')
    inQuotation = !inQuotation;
    currpos++;
    if(retTokens && (start == currpos) &&
    (delimiters.indexOf(str.charAt(currpos)) >= 0))
    currpos++;
    count++;
    return count;
    </pre>
    RunProg.properties like this:
    Prog1=GetEnv 47838 837489 892374 839274
    Prog0=GetEnv "djkfds dfkljsd" dsklfj

  • Unable to save the data in a .CSV format

    Hi All,
    I am trying to pull some data with the help of the sql query from the database and then trying to save this string of data in csv file by using the following code as shown below.The problem iam facing here is that while the file Save as window opens stating to be saved as .CSV format but when i try to save it ,it doesnt givme a csv option ,only html option appears.Can any one help me on this..,,,,,,,,,,,,?
    <%@include file="jtfincl.jsp" %>
    <%@page session="false" %>
    <%@page import="java.io.PrintWriter"%>
    <%@page import="oracle.apps.ibe.util.RequestCtx"%>
    <%@page import="oracle.apps.iri.iribe.postsales.IrIbeOrderSearch"%>
    <%@page import="oracle.apps.ibe.util.*" %>
    <%@page import="java.io.IOException" %>
    <%
    pageContext.setAttribute("_securePage", "true", PageContext.REQUEST_SCOPE);
    pageContext.setAttribute("_guestNotAllowed", "true", PageContext.REQUEST_SCOPE);
    pageContext.setAttribute("_unapprovedNotAllowed", "true", PageContext.REQUEST_SCOPE);
    RequestCtx rCtx = RequestCtx.start(request, response);
    int status = Session.checkContextValues(request, response);
    if(RequestCtx.userIsAnonymous()) {
    signin(out, pageContext, request, response, false);
    return;
    // Set the response type which in this case will be a .csv file
    response.setContentType("application/csv");
    response.setHeader("Content-disposition","attachment;filename=SearchResults.csv");
    String queryStartDate = request.getParameter("queryStartDate");
    String queryEndDate = request.getParameter("queryEndDate");
    String queryField = request.getParameter("queryField");
    String queryOperator = request.getParameter("queryOperator");
    String queryValue = request.getParameter("queryValue");
    String queryOrderByField = request.getParameter("queryOrderByField");
    String showOpenOrdersOnly = request.getParameter("showOpenOrdersOnly");
    IrIbeOrderSearch orderSearch = new IrIbeOrderSearch(
    queryStartDate,
    queryEndDate,
    queryField,
    queryOperator,
    queryValue,
    queryOrderByField,
    showOpenOrdersOnly
    orderSearch.initialise();
    java.util.ArrayList results = orderSearch.getItemTrackerSearchResults();
         out.println("The result array size is======="+results.size()) ;
    // Output the results as the page resonse as a csv file
         try
    write(results, response.getWriter());
         catch(exception e)
         out.println("The stack trace is======="+e.printStackTrace()) ;
         if(IBE_logEnabled) IBEUtil.log("iribeCOtdOrdSearchExport.jsp","Inside the exception"+e.toString);
    %>
    <%!
    * This method will take a ResultSet and JspWriter object and print out the details of the ResultSet as a
    * comma seperated value file.
    * @param results
    * @param writer
    public static void write(java.util.ArrayList results, PrintWriter writer) {
    if(results == null || results.size() == 0) {
    writer.print("No Data Available");
    return;
    String [] data = null;
    String output = "";
              if(IBE_logEnabled) IBEUtil.log("iribeCOtdOrdSearchExport.jsp","Inside the write method");
    for(int i = 0; i < results.size(); i++) {
    data = (String []) results.get(i);
    output = "";
    for(int j = 0; j < data.length; j++) {
    // If its not the last column
    if(j != data.length - 1) {
    output += formatField(data[j]) + ",";
    // If it is the last column
    } else {
    output += formatField(data[j]);
    writer.println(output);
    writer.flush();
    * Format a string value so that it becomes a valid field in a .csv file. This involves making sure that any null
    * data is treated as an empty string, that any quotes are padded and if the file contains any commas that the
    * field is surrounded by quotes.
    * @param value
    private static String formatField(String value) {
    String output = null;
    // Check for null values
    if(value == null) {
    output = "";
    } else {
    output = value;
    // Pad any existing quotes
    output = output.replaceAll("\"", "\"\"");
    // If there is a space or commas then add surrounding quotes
    if(output.startsWith(" ") || output.endsWith(" ") || output.indexOf(",") != -1) {
    output = "\"" + output + "\"";
    return output;
    %>
    <%!
    void signin(
    JspWriter out,
    PageContext pageContext,
    HttpServletRequest request,
    HttpServletResponse response,
    boolean reauth
    ) throws IOException, SQLException, FrameworkException {
    String query = IBEUtil.passQueryString(request, null).toString();
    String uri = request.getRequestURI();
    String targetJsp = uri.substring(uri.lastIndexOf("/") + 1);
    String ref = null;
    if ("true".equals(pageContext.getAttribute("_securePage", PageContext.REQUEST_SCOPE))) {
    ref = RequestCtx.getSecureFormAction(targetJsp);
    } else {
    ref = RequestCtx.getNonSecureFormAction(targetJsp);
    if(!query.equals("")) {
    ref = oracle.apps.jtf.util.Utils.encode(ref + "?" + query);
    String redirect = RequestCtx.getSecureURL("ibeCAcpSSOLogin.jsp", "ref=" + ref + (reauth ? "&reauth=t" : ""));
    // don't add the ref if the session expired and restarted
    RequestCtx rCtx = RequestCtx.getRequestCtx();
    if(rCtx.startRequestException!=null) {
    redirect = RequestCtx.getSecureURL("ibeCAcpSSOLogin.jsp", "ibe_se=t"+(reauth ? "&reauth=t" : ""));
    RequestCtx.end(request);
    response.sendRedirect(redirect);
    regds
    manish
    %>

    This would occur if you were using IE and the requested URL doesn't contain the filename part. The real web browsers would pick up the filename from the response header flawlessly.
    Having said that, this kind of logic doesn't belong in a JSP. Use Java classes (Servlet, Bean, DAO). Further on, JSP/Servlet related questions should be posted in the JSP/Servlet forum.

  • A rant about C with a question at the end. :P

    C is okay. It's just really hard to understand.
    So this is my rant about it. It starts out by listing where I've been in terms of programming and then lists my difficulties with C itself.
    I discovered C many years ago. I'm not too sure how. All I know is that for many years I've wanted to know what this C thing was all about, but had no way or knowledge of how to. I didn't really know anybody before I got the 'net last year, so asking someone else was out of the question. Plus, I wouldnt've known what question(s) to ask.
    As I became more proficient with the whole technology thing, I began to go to the local libraries nearby and use their free internet access to look stuff up. But I didn't get the idea to do any research about C, most likely because I didn't have the mental capacity to plan well and my access was once or twice weekly at best. Plus, the only computer I had at home was 66MHz and ran DOS, and I only knew BASIC around that time which I was comfortable and content with, so wasn't looking for a new language. I think I knew about assembly language but didn't pursue it if I did.
    A couple of computer upgrades later, I finally got the 'net at home and began to see the convenience of being able to spontaneously look something up when I wanted to as good, rather than weird. Ideas gradually began to pop into my head that I'd run off and look up, and one day C became one of them. So I did some research on C and finally began to learn what it was: an incomprehensible mess of manually managed memory and low-level trickery. Since I knew a fair bit about assembly language now I decided C was worse than asm (and I had no chance of learning asm back then), and left it at that.
    Being the BASIC coder I was (pun intended), I found the syntax and concepts over my head by several miles. But the fascination never died, and kept poking at me again and again. And I just had to keep forgetting about it.
    I moved on from QuickBASIC, which I'd been using for just about everything, to FreeBASIC, which was in such a beta state when I tried it, I disliked it enough to move on and discovered PHP.
    PHP has been called the BASIC of the 21st century, and I can understand why. There are typically at least 10 ways to do something whether in principle or method, multiple functions do the same or an equivalent task, and overall it just doesn't look like a good language. But beyond all that, PHP made sense to me. As I went along many of the things I expected to perform in a given way performed in said way, which was a huge confidence boost. The model it followed might have been convoluted, but something inside my head "clicked" when I saw PHP, so I liked it, since I could understand it easily.
    But recently, I found myself hitting too many walls. I wanted to get into graphical software development, and none of the graphical extensions PHP had available would work for me. PHP-GTK did work but prevented PHP from outputting anything as an Apache module, without throwing a single error anywhere. PHP-QT wouldn't compile on my system. PHP-TK did compile, but both segfaulted when any tk_* function was called and also exhibited the Apache module issue.
    So I decided then and there that I needed to switch languages.
    The problem was, my current machine happens to be so slow that a GIMP operation that executes in 6 seconds on the lowest generation AMD CPU from 4-5 years ago will execute in 38 seconds on mine. I have no idea why; the machine is, after all, 2.66GHz.
    Although PHP is pretty snappy on my system, I don't know how other languages would fare and don't really want to risk the experiment; I want to switch to a language I know will be as fast as, or faster than, PHP. So I decided that a compiled language would have to be it, since I regarded PHP as the fastest language I knew. I was probably wrong, but whatever.
    So I set my mind to understanding C. I'd asked around online before, and someone took pity on me and explained the basics of C and I did my best to understand them. This was great for a couple of days, but didn't last all that long unfortunately. So I asked around again, dreading their responses, and with good reason too: most of the tutorials I read often left me boggled and flew over my head at one point or another, which didn't help.
    But I got some dreaded tutorial links, and did my best to read them. It took me a couple of weeks to finally convince my brain to understand the point of a language that utilizes variables that doesn't contain any data, but instead references to other variables. I eventually grasped the why, but am still having quite a hard time understanding the how.
    So then, after that initial hurdle, I moved onto other topics. Or rather tried to. I quickly discovered that C interconnects some of its issues so deeply that it's hard to learn one thing at a time, move on and learn the next thing - how I best learn. I don't create paths very well by reading information; I create those paths by staying away from information and letting it slowly process in my mind. But to actually remember it in the first place, it needs to make sense, and C doesn't make sense because things are so interconnected and... we come full circle.
    To be honest, after about a fortnight of trying to understand pointers, I still don't understand them. I've read what is probably the best the web has to offer about pointers. Has it helped? Not really.
    Either the documentation:
    - is too terse and I have to slow down, risking losing interest in what I'm reading
    - skips over vital points or assumes I know Pascal or some other language
    - is hard to understand or is poorly written
    - puts segments in the wrong order, so I don't understand everything something might depend on before I reach that something
    ...and in general I either give up on reading the documentation, give up on C or just cry. I've done the 3rd a few times, the 2nd quite a few times and the 1st pretty much as many times as I've read documentation.
    So what are my issues with C?
    Let me address the two I can think of right now:
    Pointers aren't addressed "simply"; if I declare a pointer to int named x I have to use *x to access what x points to, rather than use *x to get x's location, like one does with non-pointer variables where & is used to get an address. It'd be nice if we used &x to get x's value if x wasn't a pointer and *x to get x's value if x was a pointer, rather than use this convoluted scheme.
    Also, I've heard that it's a common misconception that C handles arrays natively. Elsewhere, I've heard that strings are merely arrays of char. I can understand the 2nd, but what do I do with the 1st?
    I do understand that if I say printf("%d\n", x[1]) I'm effectively saying x++; printf("%d\n", x), but I don't understand how this fully works. For example, let us consider the following code:
    char *filename = "<insert file here>";
    int i;
    struct stat filebuffer;
    int status;
    FILE *handle;
    handle = fopen(filename, "r");
    status = stat(filename, &filebuffer);
    char *buffer = malloc(filebuffer.st_size);
    for (i = 0; i < filebuffer.st_size; i++) buffer[i] = fgetc(handle);
    printf("%s\n", buffer);
    You'll of course notice the array notation. Do I understand why if I replace said notation with something to the effect of...
    buffer++
    buffer = fgetc(handle);
    ...the program segfaults? No. Likewise, I don't understand why the...
    buffer++
    *buffer = fgetc(handle);
    ...in the loop does work, printf("%s"...); causes segfaults and printf("%d"...); does not.
    Another thing I found is that declaring a char *, filling it with data, and then using memcpy on said char *, the program works fine, but if I declare for example char x[1] = "hi"; the compiler will shout at me for not allocating enough arrays. Only while writing this did I realize that the 2nd element is for the null byte.
    Suffice to say that C confuses me. To bits. Although I have written a 500 line program in it (579 to be exact). All said program does is display a message on the screen via Xlib, but I managed to figure out how to make a word wrapping engine using strsep and how to use XDrawPoint XDrawLine to not only create a nice UI but also let me define various UI "styles" which can be loaded at startup.
    Said program uses a very big helping of "if it doesn't work stab it until it does", so not only do I not understand how a lot of it works, it probably wouldn't compile under anything except gcc. Which is from a theory perspective quite a problem, IMHO. Almost every 2nd variable is typecast to this or that type.
    So put simply, every tutorial or introduction to C hasn't made a lot of sense to me. Maybe I learn slowly; I'm hoping it's that, because I can't see anything besides assembly language which would be faster than C. I plan to learn asm after I've mastered the very basics of C, but I may end up having to learn the other way around if I expect to get anywhere.
    Like I said in the title, I have one actual question in this post. So here it is:
    Are there any fun, easy reading tutorials out there that don't visually look like they came out of 1992 and read like http://poignantguide.net/ or http://learnyouahaskell.com/?
    -dav7

    dav7 wrote:Pointers aren't addressed "simply"; if I declare a pointer to int named x I have to use *x to access what x points to, rather than use *x to get x's location, like one does with non-pointer variables where & is used to get an address. It'd be nice if we used &x to get x's value if x wasn't a pointer and *x to get x's value if x was a pointer, rather than use this convoluted scheme.
    Pointer syntax is extremely unfortunate. The best part:
    char *a; // It's a pointer.
    *a; // It's a character. Good move, guys.
    Also, I've heard that it's a common misconception that C handles arrays natively. Elsewhere, I've heard that strings are merely arrays of char. I can understand the 2nd, but what do I do with the 1st?
    Insofar as C has arrays, C strings are character arrays. C arrays are just a promise that the system won't mess within a certain set of memory addresses. Array syntax is a concise way to calculate and dereference a specific location in memory, relative to an address that you hope is the beginning of some memory you reserved. array[n] = *(array + n), right? Personally, I would have left out the subscript notation entirely. Regardless, any time you choose to use brackets, you can mentally substitute in an explicit addition and dereference there. You're saying, "Give me the number stored at the memory address I have just calculated, which I know by my science holds something I put there intentionally, and not garbage at all."
    One more clarification with regard to pointer arithmetic is necessary: when you add 2 to an int*, the resulting address is actually 2*sizeof(int) bytes after your base address. Same for a double*: 2*sizeof(double).
    I do understand that if I say printf("%d\n", x[1]) I'm effectively saying x++; printf("%d\n", x), but I don't understand how this fully works.
    It's not the same! First of all, in example #2, you're passing a pointer to an int. In example #1, you're passing an integer, since [] dereferences pointers for you. Any time you use those brackets, it's as if you had typed an asterisk yourself. Second, in example #1 you're not messing with x. In example #2 you're incrementing x by four bytes (the likely size of one integer). Doesn't make a difference in this short example, but if x ever gets used again it will be very significant.
    Another thing I found is that declaring a char *, filling it with data, and then using memcpy on said char *, the program works fine, but if I declare for example char x[1] = "hi"; the compiler will shout at me for not allocating enough arrays. Only while writing this did I realize that the 2nd element is for the null byte.
    Looks like a counting problem. Arrays are indexed from 0, but sizes are specified from 1 on up. Your "char x[1]" has only index [0]. To hold a two-character string, you'll need at least size three (char x[3]), so that x[0]='h', x[1]='i', x[2]='\0', the null terminator.
    Suffice to say that C confuses me. To bits.
    Any time you get confused by pointers or arrays (which are the same thing), take a step back and think about what's happening in terms of memory addresses. Draw it out on paper if you think you're making a mistake. In some languages you can ignore low-level details like that and write perfectly fine programs, even though you won't be able to optimize them without knowing how your code maps onto the machine. But in C, everything that looks like a high-level feature is just shorthand for setting a few bytes to different numbers, and the abstraction is so leaky that you can't get by without understanding it. Types are just a way for the compiler to catch dumb mistakes (some people believe this is helpful) and to automate some math, like the pointer arithmetic above. In a running program there are no types, so when you're trying to figure out what a program is actually doing, you need to consider what the types are shorthand for.
    If you're having trouble "thinking like a programmer", by which I mean sanity-checking your use of syntax and stepping through a program so you know what it does, you might want to get up to speed in a different language, or by working through a book on algorithms.
    Last edited by pauldonnelly (2008-11-03 22:54:12)

  • Bug #18104 still exists

    Hello,
    I am quite disappointed about BDB 5. One of the most nasty bugs (#18104) still
    exists. As soon as you want to use the set_thread_count() feature, BDB will not
    free the thread-control-block. If you connect/disconnect, BDB will stop working
    quite early. You can re-produce this issue with any `db_*` tool.
    The testcase:
    #include <stdlib.h>
    #include <db.h>
    #define DIRECTORY "/tmp/db"
    int main()
        /* open environment */
        DB_ENV *handle;
        int status = db_env_create( &handle, 0 );
        status = handle->set_cachesize( handle, 0, 32*1024*1024, 0 );
        status = handle->set_thread_count( handle, 0x100 );
        status = handle->open( handle, DIRECTORY, DB_CREATE, 0644 );
        if( status != 0 )
            return 1;
        /* raise error "Unable to allocate thread control block" */
        for( ;; )
            system( "db_stat -e -h " DIRECTORY " | grep process/thread | wc" );
        return 0;
    }

    Hi Sandra,
    Hi Greg,
    Our architecture is quite simple: a cron-job runs ENV->failchk() and ENV->txn_checkpoint()
    once a minute (which should be fine, shouldn't it?)
    The problem, neither ENV->close() nor ENV->failchk() removes outdated items from the
    thread-control-block. One would expect, that the PID is added to the block as soon as the
    process connects and removed when the process disconnects. But it is not.
    If the block runs out of memory, BDB requires a recovery (see the down below testcase).
    Usually ENV->failchk() cleans the thread-control-block, as soon as there are more items in
    the block than "thread_count". Today three times it did not even remove them, if there were
    more than "thread_count" items in the block - but this happend sporadic so it was difficult
    to create a testcase.
    Once ENV->failchk() cleans the thread-control-block, BDB works as expected. If a process
    connects, the PID is added to the block, and as soon as the process disconnects, the PID is
    removed from the thread-control-block. You can test this by looping the first loop 1090 times.
    The testcase:
    #include <stdio.h>
    #include <stdlib.h>
    #include <signal.h>
    #include <db.h>
    #include <errno.h>
    #define DIRECTORY "/tmp/db"
    static int bdb_is_alive( DB_ENV *dbenv, pid_t pid, db_threadid_t tid, u_int32_t flags )
        int status;
        status = kill( pid, 0 );
        if( status != -1 )
            return 1;
        if( errno == ESRCH )
            return 0;
        exit( 1 );  /* should never happen */
    int main()
        system( "mkdir -p " DIRECTORY );
        system( "db_recover -h " DIRECTORY );
        system( "rm -rfv " DIRECTORY "/*" );
        /* open environment */
        int status, i;
        DB_ENV *handle;
        status = db_env_create( &handle, 0 );
        status = handle->set_cachesize( handle, 0, 32*1024*1024, 0 );
        status = handle->set_thread_count( handle, 1091 );
        status = handle->set_isalive( handle, bdb_is_alive );
        status = handle->open( handle, DIRECTORY, DB_CREATE, 0644 );
        if( status != 0 )
            return 1;   /* should never happen */
        status = handle->failchk( handle, 0 );
        status = handle->close( handle, 0 );
        /* Now start workers (`db_stat`) + failchks() */
        for( i=0; i < 1089; ++i )       /* thread_count - 2 */
            fprintf(stderr,"Number of items in the thread-control-block: "); fflush(stdout);
            system( "db_stat -e -h " DIRECTORY " | grep process/thread | wc -l" );
            status = db_env_create( &handle, 0 );
            status = handle->set_isalive( handle, bdb_is_alive );
            status = handle->open( handle, DIRECTORY, DB_CREATE, 0644 );
            if( status != 0 )
                return 1;   /* should never happen */
            status = handle->failchk( handle, 0 );      /* strange - does not remove the process-entries created by `db_stat` */
            if( status != 0 )
                return 1;   /* should never happen */
            status = handle->close( handle, 0 );
        /* raise error: "Unable to allocate thread control block" */
        for( i=1; i < 422; ++i )
            fprintf(stderr,"Number of items in the thread-control-block: "); fflush(stdout);
            system( "db_stat -e -h " DIRECTORY " | grep process/thread | wc -l" );
        /* You should see on stderr:
                db_stat: Unable to allocate thread control block
                db_stat: Unable to allocate thread control block
                db_stat: DB_ENV->open: /tmp/db: Cannot allocate memory
        fprintf(stderr,"BDB is dead now. Only `db_recover` helps...\n%s\n",db_version(NULL,NULL,NULL));
        return 0;
    }

  • Urgent Help Required for Connect Four Game

    Hi all,
    I am a student and I have a project due 20th of this month, I mean May 20, 2007 after 8 days. The project is about creating a Connect Four Game. I have found some code examples on the internet which helped me little bit. But there are lot of problems I am facing developing the whole game. I have drawn the Board and the two players can play. The players numbers can fill the board, but I have problem implementing the winner for the game. I need to implement the hasWon() method for Horizontal win, Vertical win and Diagonal win. I also found some code examples on the net but I was unable to make it working. I have 5 classes and one interface which I m implementing. The main problem is how to implement the hasWon() method in the PlayGame class below with Horizontal, vertical and diagonal moves.
    Sorry there is so much code.
    This the interface I must implement, but now I am only implementing the int move() of this interface. I will implement the rest later after solving the winner problem with your help.
    Interface code..............
    interface Player {
    void init (Boolean color);
    String name ();
    int move ();
    void inform (int i);
    Player1 class......................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class Player1 implements Player
    public Player1()
    public int move()
    Scanner scan = new Scanner(System.in);
    // BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
    int player1;
    System.out.println ("What is your Number, player 1?");
    player1 = scan.nextInt();
    System.out.println ("Hey number"+player1+" are you prepared to CONNECT FOUR");
    System.out.println();
    return player1;
    //Player.move();
    //return player1;
    }//end move method
    public void init (Boolean color)
    public void inform (int i)
    public String name()
    return "Koonda";
    }//end player1 class
    Player2 class...........................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class Player2 implements Player
    public int move()
    //int cup0,cup1,cup2,cup3,cup4,cup5,cup6;
    // cup0=5;cup1=5;cup2=5;cup3=5;cup4=5;cup5=5;cup6=5;
    //int num1, num2;
    Scanner scan = new Scanner(System.in);
    // BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
    int player2;
    System.out.println ("What is your Number, player 2?");
    player2 = scan.nextInt();
    System.out.println ("Hey "+player2+" are you prepared to CONNECT FOUR");
    System.out.println();
    //return player1;
    return player2;
    }//end move method
    public void init (Boolean color)
    public void inform (int i)
    public String name()
    return "malook";
    }//end player1 class
    PlayGame class which contains all the functionality.........................................................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class PlayGame
    //Player player1;
    //Player player2;
    int [][]ConnectFourArray;
    boolean status;
    int winner;
         int player1;
         int player2;
         public PlayGame()
              //this.player1 = player1;
              //this.player2 = player2;
         public void StartGame()
         try{
         // int X = 0, Y = 0;
         //int value;
         int cup0,cup1,cup2,cup3,cup4,cup5,cup6;
    cup0=5;cup1=5;cup2=5;cup3=5;cup4=5;cup5=5;cup6=5;
         int[][] ConnectFourArray = new int[6][7];
         int num1, num2;
         for(int limit=21;limit!=0;limit--)
    BufferedReader selecter = new BufferedReader (new InputStreamReader(System.in));
    String column1;
    System.out.println();
    for ( int row=0; row < ConnectFourArray.length; row++ ){
    System.out.print("Row " + row + ": ");
    for ( int col=0; col < ConnectFourArray[row].length; col++ )
    System.out.print( ConnectFourArray[row][col] + " ");
    System.out.println();
    System.out.println();
    System.out.println ("Please Select a column of 0 through 6 ");
    column1 = selecter.readLine();
    num1= Integer.parseInt(column1);
    System.out.println();
    if (num1==0){
    ConnectFourArray[cup0][0]=1;
    cup0=cup0-1;
    else if (num1==1){
    ConnectFourArray[cup1][1]=1;
    cup1=cup1-1;
    else if (num1==2){
    ConnectFourArray[cup2][2]=1;
    cup2=cup2-1;
    else if (num1==3){
    ConnectFourArray[cup3][3]=1;
    cup3=cup3-1;
    else if (num1==4){
    ConnectFourArray[cup4][4]=1;
    cup4=cup4-1;
    else if (num1==5){
    ConnectFourArray[cup5][5]=1;
    cup5=cup5-1;
    else if (num1==6){
    ConnectFourArray[cup6][6]=1;
    cup6=cup6-1;
    System.out.println();
    BufferedReader selecter2 = new BufferedReader (new InputStreamReader(System.in));
    String column2;
    System.out.println();
    for ( int row=0; row < ConnectFourArray.length; row++ ){
    System.out.print("Row " + row + ": ");
    for ( int col=0; col < ConnectFourArray[row].length; col++ )
    System.out.print( ConnectFourArray[row][col] + " ");
    System.out.println();
    System.out.println();
    System.out.println ("Please Select a column of 0 through 6 ");
    column1 = selecter.readLine();
    num1= Integer.parseInt(column1);
    System.out.println();
    if (num1==0){
    ConnectFourArray[cup0][0]=2;
    cup0=cup0-1;
    else if (num1==1){
    ConnectFourArray[cup1][1]=2;
    cup1=cup1-1;
    else if (num1==2){
    ConnectFourArray[cup2][2]=2;
    cup2=cup2-1;
    else if (num1==3){
    ConnectFourArray[cup3][3]=2;
    cup3=cup3-1;
    else if (num1==4){
    ConnectFourArray[cup4][4]=2;
    cup4=cup4-1;
    else if (num1==5){
    ConnectFourArray[cup5][5]=2;
    cup5=cup5-1;
    else if (num1==6){
    ConnectFourArray[cup6][6]=2;
    cup6=cup6-1;
    System.out.println();
    System.out.println();
    catch (Exception E){
    System.out.println("Error with input");
    System.out.println("Would you like to play again");
    try{
    String value;
    BufferedReader reader = new BufferedReader (new InputStreamReader(System.in));
    // Scanner scan = new Scanner(System.in);
    System.out.println("Enter yes to play or no to quit");
    // value = scan.nextLine();
    // String value2;
    value = reader.readLine();
    //value2 = reader.readLine();
    if (value.equals("yes"))
    System.out.println("Start again");
    StartGame(); // calling the StartGame method to play a game once more
    else if (value.equals("no"))
    System.out.println("No more games to play");
    // System.exit(0);
    else
    System.exit(0);
    System.out.println();
    catch (Exception e){
    System.out.println("Error with input");
    finally
    System.out.println(" playing done");
    //StartGame();
    //check for horizontal win
    public int hasWon()
    int status = 0;
    for (int row=0; row<6; row++)
    for (int col=0; col<4; col++)
    if (ConnectFourArray[col][row] != 0 &&
    ConnectFourArray[col][row] == ConnectFourArray[col+1][row] &&
    ConnectFourArray[col][row] == ConnectFourArray[col+2][row] &&
    ConnectFourArray[col][row] == ConnectFourArray[col+3][row])
    //status = true;//int winner;
    if(status == player1)
    System.out.println("Player 1 is the winner");
    else if(status == player2)
    System.out.println("Player 2 is the winner" );
    }//end inner for loop
    }// end outer for loop
    } // end method Winner
    return status;
    }//end class
    ClassConnectFour which designs the board........................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class ClassConnectFour
         //Player player1;
         //Player player2;
         public ClassConnectFour()
              //this.player1 = player1;
    public void DrawBoard()
    int[][] ConnectFourArray = new int[6][7] ;
    for ( int row=0; row < ConnectFourArray.length; row++ ){
    System.out.print("Row " + row + ": ");
    for ( int col=0; col < ConnectFourArray[row].length; col++ )
    System.out.print( ConnectFourArray[row][col] + " ");
    System.out.println();
    System.out.println();
    }//end class
    TestConnetFour class which uses most of the above class..................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class TestConnectFour
    public static void main(String[] args)
    ClassConnectFour cf = new ClassConnectFour();
    cf.DrawBoard();
    Player1 player1 = new Player1();
    Player2 player2 = new Player2();
    player1.move();
    player2.move();
    System.out.println("Number 1 belongs to player " + player1.name());
    System.out.println("Number 2 belongs to player " + player2.name());
    PlayGame pg = new PlayGame();
    pg.StartGame();
    pg.hasWon();
    //pg.Play();
    //System.out.println(player.name());
    //System.out.println(player2.name());
    }// end main
    }//end class
    I am sorry for all this junk code but I only understand it this way. Your urgent help is required. Looking forward to your reply.
    Thanks in advance.
    Koonda
    //

    Hi,
    Thanks for your help but I really don't understand the table lookup algorithm. Could you please send me some code to implement that.
    I will send you the formatted code as well
    Thanks for your help.
    looking forward to your reply.
    Koonda
    Hi all,
    I am a student and I have a project due 20th of this month, I mean May 20, 2007 after 8 days. The project is about creating a Connect Four Game. I have found some code examples on the internet which helped me little bit. But there are lot of problems I am facing developing the whole game. I have drawn the Board and the two players can play. The players numbers can fill the board, but I have problem implementing the winner for the game. I need to implement the hasWon() method for Horizontal win, Vertical win and Diagonal win. I also found some code examples on the net but I was unable to make it working. I have 5 classes and one interface which I m implementing. The main problem is how to implement the hasWon() method in the PlayGame class below with Horizontal, vertical and diagonal moves.
    Sorry there is so much code.
    This the interface I must implement, but now I am only implementing the int move() of this interface. I will implement the rest later after solving the winner problem with your help.
    Interface code..............
    interface Player {
    void init (Boolean color);
    String name ();
    int move ();
    void inform (int i);
    Player1 class......................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class Player1 implements Player
    public Player1()
    public int move()
    Scanner scan = new Scanner(System.in);
    // BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
    int player1;
    System.out.println ("What is your Number, player 1?");
    player1 = scan.nextInt();
    System.out.println ("Hey number"+player1+" are you prepared to CONNECT FOUR");
    System.out.println();
    return player1;
    //Player.move();
    //return player1;
    }//end move method
    public void init (Boolean color)
    public void inform (int i)
    public String name()
    return "Koonda";
    }//end player1 class
    Player2 class...........................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class Player2 implements Player
    public int move()
    //int cup0,cup1,cup2,cup3,cup4,cup5,cup6;
    // cup0=5;cup1=5;cup2=5;cup3=5;cup4=5;cup5=5;cup6=5;
    //int num1, num2;
    Scanner scan = new Scanner(System.in);
    // BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
    int player2;
    System.out.println ("What is your Number, player 2?");
    player2 = scan.nextInt();
    System.out.println ("Hey "+player2+" are you prepared to CONNECT FOUR");
    System.out.println();
    //return player1;
    return player2;
    }//end move method
    public void init (Boolean color)
    public void inform (int i)
    public String name()
    return "malook";
    }//end player1 class
    PlayGame class which contains all the functionality.........................................................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class PlayGame
    //Player player1;
    //Player player2;
    int [][]ConnectFourArray;
    boolean status;
    int winner;
    int player1;
    int player2;
    public PlayGame()
    //this.player1 = player1;
    //this.player2 = player2;
    public void StartGame()
    try{
    // int X = 0, Y = 0;
    //int value;
    int cup0,cup1,cup2,cup3,cup4,cup5,cup6;
    cup0=5;cup1=5;cup2=5;cup3=5;cup4=5;cup5=5;cup6=5;
    int[][] ConnectFourArray = new int[6][7];
    int num1, num2;
    for(int limit=21;limit!=0;limit--)
    BufferedReader selecter = new BufferedReader (new InputStreamReader(System.in));
    String column1;
    System.out.println();
    for ( int row=0; row < ConnectFourArray.length; row++ ){
    System.out.print("Row " + row + ": ");
    for ( int col=0; col < ConnectFourArray[row].length; col++ )
    System.out.print( ConnectFourArray[row][col] + " ");
    System.out.println();
    System.out.println();
    System.out.println ("Please Select a column of 0 through 6 ");
    column1 = selecter.readLine();
    num1= Integer.parseInt(column1);
    System.out.println();
    if (num1==0){
    ConnectFourArray[cup0][0]=1;
    cup0=cup0-1;
    else if (num1==1){
    ConnectFourArray[cup1][1]=1;
    cup1=cup1-1;
    else if (num1==2){
    ConnectFourArray[cup2][2]=1;
    cup2=cup2-1;
    else if (num1==3){
    ConnectFourArray[cup3][3]=1;
    cup3=cup3-1;
    else if (num1==4){
    ConnectFourArray[cup4][4]=1;
    cup4=cup4-1;
    else if (num1==5){
    ConnectFourArray[cup5][5]=1;
    cup5=cup5-1;
    else if (num1==6){
    ConnectFourArray[cup6][6]=1;
    cup6=cup6-1;
    System.out.println();
    BufferedReader selecter2 = new BufferedReader (new InputStreamReader(System.in));
    String column2;
    System.out.println();
    for ( int row=0; row < ConnectFourArray.length; row++ ){
    System.out.print("Row " + row + ": ");
    for ( int col=0; col < ConnectFourArray[row].length; col++ )
    System.out.print( ConnectFourArray[row][col] + " ");
    System.out.println();
    System.out.println();
    System.out.println ("Please Select a column of 0 through 6 ");
    column1 = selecter.readLine();
    num1= Integer.parseInt(column1);
    System.out.println();
    if (num1==0){
    ConnectFourArray[cup0][0]=2;
    cup0=cup0-1;
    else if (num1==1){
    ConnectFourArray[cup1][1]=2;
    cup1=cup1-1;
    else if (num1==2){
    ConnectFourArray[cup2][2]=2;
    cup2=cup2-1;
    else if (num1==3){
    ConnectFourArray[cup3][3]=2;
    cup3=cup3-1;
    else if (num1==4){
    ConnectFourArray[cup4][4]=2;
    cup4=cup4-1;
    else if (num1==5){
    ConnectFourArray[cup5][5]=2;
    cup5=cup5-1;
    else if (num1==6){
    ConnectFourArray[cup6][6]=2;
    cup6=cup6-1;
    System.out.println();
    System.out.println();
    catch (Exception E){
    System.out.println("Error with input");
    System.out.println("Would you like to play again");
    try{
    String value;
    BufferedReader reader = new BufferedReader (new InputStreamReader(System.in));
    // Scanner scan = new Scanner(System.in);
    System.out.println("Enter yes to play or no to quit");
    // value = scan.nextLine();
    // String value2;
    value = reader.readLine();
    //value2 = reader.readLine();
    if (value.equals("yes"))
    System.out.println("Start again");
    StartGame(); // calling the StartGame method to play a game once more
    else if (value.equals("no"))
    System.out.println("No more games to play");
    // System.exit(0);
    else
    System.exit(0);
    System.out.println();
    catch (Exception e){
    System.out.println("Error with input");
    finally
    System.out.println(" playing done");
    //StartGame();
    //check for horizontal win
    public int hasWon()
    int status = 0;
    for (int row=0; row<6; row++)
    for (int col=0; col<4; col++)
    if (ConnectFourArray[col][row] != 0 &&
    ConnectFourArray[col][row] == ConnectFourArray[col+1][row] &&
    ConnectFourArray[col][row] == ConnectFourArray[col+2][row] &&
    ConnectFourArray[col][row] == ConnectFourArray[col+3][row])
    //status = true;//int winner;
    if(status == player1)
    System.out.println("Player 1 is the winner");
    else if(status == player2)
    System.out.println("Player 2 is the winner" );
    }//end inner for loop
    }// end outer for loop
    } // end method Winner
    return status;
    }//end class
    ClassConnectFour which designs the board........................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class ClassConnectFour
    //Player player1;
    //Player player2;
    public ClassConnectFour()
    //this.player1 = player1;
    public void DrawBoard()
    int[][] ConnectFourArray = new int[6][7] ;
    for ( int row=0; row < ConnectFourArray.length; row++ ){
    System.out.print("Row " + row + ": ");
    for ( int col=0; col < ConnectFourArray[row].length; col++ )
    System.out.print( ConnectFourArray[row][col] + " ");
    System.out.println();
    System.out.println();
    }//end class
    TestConnetFour class which uses most of the above class..................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class TestConnectFour
    public static void main(String[] args)
    ClassConnectFour cf = new ClassConnectFour();
    cf.DrawBoard();
    Player1 player1 = new Player1();
    Player2 player2 = new Player2();
    player1.move();
    player2.move();
    System.out.println("Number 1 belongs to player " + player1.name());
    System.out.println("Number 2 belongs to player " + player2.name());
    PlayGame pg = new PlayGame();
    pg.StartGame();
    pg.hasWon();
    //pg.Play();
    //System.out.println(player.name());
    //System.out.println(player2.name());
    }// end main
    }//end classI am sorry for all this junk code but I only understand it this way. Your urgent help is required. Looking forward to your reply.
    Thanks in advance.
    Koonda

  • Getting java.lang.NullpointerException while closing resultset aft using it

    Hi,
    I kindly request to share your ideas reg. my problem.
    I am opening a database connection using connection pool and i am using two or more resultsets and statement objects.I am closing these objects at the end of their usage.But i am getting java.lang.NullpointerException when i close them(if i don't close them it works fine). what might be the reason. Had i did any thing wrong in the code.
    please view the code
    public String storeNewConnection(String CIRCLE,String DIVISION,String SUB_DIVISION,String SECTION,String CONSUMER_NAME,String FATHER_NAME,String STREET_NAME,String DOOR_NO,String TOWN_CITY,String LAND_MARK,String PINCODE,String STDCODE,String PHONE_NO,String EMAIL,String NEIGHBOUR_SCNO,String DOCUMENT_CODE,String LT_APR_NO,String year1,String month1,String day1,String PCBNO,String CONSUMER_STATUS,String SOCIAL_GROUP,String CATEGORY_SUPPLY,String LOCATION_PREMISES,String PURPOSE_OF_SUPPLY,String DURATION,String LOAD_TYPE,String CONNECTED_LOAD,String CONTRACTED_LOAD,String APPLICATION_FEE,String DEVELOPMENT_CHARGES,String SECURITY_DEPOSIT,String ADDL_SECURITY_DESPOSIT,String DEPOSITED_THRU,String DD_CHEQUE_DETAILS,String year2,String month2,String day2,String REMARKS,String POLE_NO)
              int count=0;
              Statement st=null;
              ResultSet rs=null,rs1=null,rs2=null,rs3=null;
              PreparedStatement pst=null;
              String result="",query="",sysDate="",sysDate2="";
              String reg_no = "";
              try
                   st=con.createStatement();
                   //Check dates with sys date
                   String date1 =null;                    
                   String date2 =null;
                   if(! (year1.equals("") || month1.equals("") || day1.equals("")) )
                        date1=day1+"-"+month1+"-"+year1;
                        rs2=st.executeQuery("select round(to_date('"+date1+"','dd-Mon-yyyy')-to_date(sysdate,'dd-Mon-yy')) from dual");
                        rs2.next();
                        if(rs2.getInt(1) != 0)
                             return "false";                              
                   if(! (year2.equals("") || month2.equals("") || day2.equals("")) )
                        date2=day2+"-"+month2+"-"+year2;
                        rs3=st.executeQuery("select round(to_date('"+date2+"','dd-Mon-yyyy')-to_date(sysdate,'dd-Mon-yy')) from dual");
                        rs3.next();
                        if(rs3.getInt(1) != 0)
                             return "false";     
                   rs1=st.executeQuery("select to_char(sysdate,'yyyyMONdd'),to_char(sysdate,'dd-Mon-yyyy') from dual");
                   rs1.next();
                   sysDate=rs1.getString(1);
                   sysDate2=rs1.getString(2);
                   rs=st.executeQuery("select max(SERIAL_NO) from NEW_CONNECTIONS where to_char(sysdate,'yyyy') = to_char(REG_DATE,'yyyy') and to_char(sysdate,'mm') = to_char(REG_DATE,'mm') and SUB_DIVISION_CODE = "+SUB_DIVISION+" and DIVISION_CODE = "+DIVISION+" and CIRCLE_CODE = "+CIRCLE+" ");
                   if(rs.next())
                        count = rs.getInt(1);
                        count++;                              
                   else
                        count=1;
                   query="insert into NEW_CONNECTIONS ( "+
                        " REG_NO,SERIAL_NO,REG_DATE,CIRCLE_CODE,DIVISION_CODE,SUB_DIVISION_CODE,SECTION_CODE, "+
                        " CONSUMER_NAME,FATHER_NAME,STREET_NAME,DOOR_NO,TOWN_CITY,LAND_MARK,PINCODE, "+
                        " STDCODE,PHONE_NO,EMAIL,NEIGHBOUR_SCNO,DOCUMENT_CODE,LT_APR_NO,LT_APR_DATE, "+
                        " PCBNO,CONSUMER_STATUS,SOCIAL_GROUP,CATEGORY_SUPPLY,LOCATION_PREMISES,PURPOSE_OF_SUPPLY,"+
                        " DURATION,LOAD_TYPE,CONNECTED_LOAD,CONTRACTED_LOAD,APPLICATION_FEE,DEVELOPMENT_CHARGES, "+
                        " SECURITY_DEPOSIT,ADDL_SECURITY_DEPOSIT,DEPOSITED_THRU,DD_CHEQUE_DETAILS,DD_CHEQUE_DATE,REMARKS,APPLICATION_STATUS,POLE_NO) "+
                        " values(?,?,'"+sysDate2+"',?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                   pst = con.prepareStatement(query);
                   String cnt ="";
                   if(count <= 9)
                        cnt="0000";
                   else if(count <= 99)
                        cnt="000";
                   else if(count <= 999)
                        cnt="00";
                   else if(count <= 9999)
                        cnt="0";
                   cnt+=Integer.toString(count);
                   reg_no = CIRCLE+DIVISION+SUB_DIVISION+SECTION+"N"+cnt+sysDate;               
                   int serial_no =count;
                   int pin = 0;
                   if(!PINCODE.equals(""))
                        pin =Integer.parseInt(PINCODE);
                   int std = 0;
                   if(!STDCODE.equals(""))
                        std = Integer.parseInt(STDCODE);
                   int status = Integer.parseInt(CONSUMER_STATUS);
                   int social_group = Integer.parseInt(SOCIAL_GROUP);
                   int supply = Integer.parseInt(CATEGORY_SUPPLY);
                   int location = Integer.parseInt(LOCATION_PREMISES);
                   int purpose = Integer.parseInt(PURPOSE_OF_SUPPLY);
                   int duration = Integer.parseInt(DURATION);
                   int laod_type = Integer.parseInt(LOAD_TYPE);
                   float conn_load = Float.parseFloat(CONNECTED_LOAD);
                   int cont_load = 0;
                   if(!CONTRACTED_LOAD.equals(""))
                        cont_load =Integer.parseInt(CONTRACTED_LOAD);
                   int app_fee = Integer.parseInt(APPLICATION_FEE);
                   int dev_chg = Integer.parseInt(DEVELOPMENT_CHARGES);
                   int sec_dep = Integer.parseInt(SECURITY_DEPOSIT);
                   int addl_sec_dep = 0;     
                   if(!ADDL_SECURITY_DESPOSIT.equals(""))
                        addl_sec_dep =Integer.parseInt(ADDL_SECURITY_DESPOSIT);
                   int dep_thru = Integer.parseInt(DEPOSITED_THRU);          
                   pst.setString(1,reg_no);
                   pst.setInt(2,serial_no);
                   pst.setString(3,CIRCLE);
                   pst.setString(4,DIVISION);
                   pst.setString(5,SUB_DIVISION);
                   pst.setString(6,SECTION);
                   pst.setString(7,CONSUMER_NAME);
                   pst.setString(8,FATHER_NAME);
                   pst.setString(9,STREET_NAME);
                   pst.setString(10,DOOR_NO);
                   pst.setString(11,TOWN_CITY);
                   pst.setString(12,LAND_MARK);
                   pst.setInt(13,pin);
                   pst.setInt(14,std);
                   pst.setString(15,PHONE_NO);
                   pst.setString(16,EMAIL);
                   pst.setString(17,NEIGHBOUR_SCNO);
                   pst.setString(18,DOCUMENT_CODE);
                   pst.setString(19,LT_APR_NO);
                   pst.setString(20,date1);
                   pst.setString(21,PCBNO);
                   pst.setInt(22,status);
                   pst.setInt(23,social_group);
                   pst.setInt(24,supply );
                   pst.setInt(25,location);
                   pst.setInt(26,purpose);
                   pst.setInt(27,duration);
                   pst.setInt(28,laod_type);
                   pst.setFloat(29,conn_load );
                   pst.setInt(30,cont_load);
                   pst.setInt(31,app_fee);
                   pst.setInt(32,dev_chg);
                   pst.setInt(33,sec_dep);
                   pst.setInt(34,addl_sec_dep);
                   pst.setInt(35,dep_thru );
                   pst.setString(36,DD_CHEQUE_DETAILS);
                   pst.setString(37,date2);
                   pst.setString(38,REMARKS);
                   pst.setInt(39,1);
                   pst.setString(40,POLE_NO);
                   pst.executeUpdate();
                   result=reg_no;                                   
                   rs.close();
                   rs=null;
                   rs1.close();
                   rs1=null;
                   rs2.close();
                   rs2=null;
                   rs3.close();
                   rs3=null;
                   st.close();
                   st=null;
                   pst.close();
                   pst=null;
              catch(Exception e)
                   e.printStackTrace();
                   result="false";
                   return result;
              finally
                   if (rs != null)
                        try
                             rs.close();
                        catch (SQLException e)
                        rs = null;
                   if (rs1 != null)
                        try
                             rs1.close();
                        catch (SQLException e)
                        rs1 = null;
                   if (rs2 != null)
                        try
                             rs2.close();
                        catch (SQLException e)
                        rs2 = null;
                   if (rs3 != null)
                        try
                             rs3.close();
                        catch (SQLException e)
                        rs3 = null;
                   if (st != null)
                        try
                             st.close();
                        catch (SQLException e)
                        st = null;
                   if (pst != null)
                        try
                             pst.close();
                        catch (SQLException e)
                        pst = null;
              return result;
    Also plz help me to improve the code if necessary so that it will work fine for multiple users
    thaks & regards
    Prasanth.C

    Thanks a lot.
    i replaced the code below
    if (rs != null)
                        try
                             rs.close();
                        catch (SQLException e)
                        rs = null;
                   if (rs1 != null)
                        try
                             rs1.close();
                        catch (SQLException e)
                        rs1 = null;
                   if (rs2 != null)
                        try
                             rs2.close();
                        catch (SQLException e)
                        rs2 = null;
                   if (rs3 != null)
                        try
                             rs3.close();
                        catch (SQLException e)
                        rs3 = null;
                   if (st != null)
                        try
                             st.close();
                        catch (SQLException e)
                        st = null;
                   if (pst != null)
                        try
                             pst.close();
                        catch (SQLException e)
                        pst = null;
    instead of blindly closing the resultsets and statements
    now it works fine.
    One more thing, is my code structurally correct, i mean the variables, try...catch blocks,results,statements,database connections and overall coding. whether it looks like professional code.
    thaks & regards,
    Prasanth.C

Maybe you are looking for