~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Synchronizing this statement should block the second thread from accessing the queue correct?

No, because your code synchronizes on this inside the ProductConsumer class which means the current instance of the ProductConsumer object. Since each thread has a different ProductConsumer instance, it doesn't prevent the threads from adding items to the queue concurrently. It would be a different thing if you synchronized on the queue though.

I would personally recommend starting with the Java trail and working through the concepts incrementally instead of continuing down this path of haphazard changes. :)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I've fixed the code to pass a the queue but now I get null pointer exceptions...

Your constructor definition of ProductConsumer is hosed. You write prodQueue = this.prodQueue instead of writing it the other way round. Think about it, do you really want to assign the passed in argument the value of prodQueue instance, which is by default null?

Are you sure that it is supposed to instantiate that way???

Yes, it's possible with the new Java 7 type inference.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

You seem to be having multiple threads utilizing multiple instances of the ProductProducer class i.e. each thread operates on a separate instance of the ProductProducer class which explains each item count occurring twice, once for each queue. If you want different instances to operate on the same queue, either declare the queue somewhere where it's visible by all the threads or pass in the Queue when constructing ProductProducer instances.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I'm sorry I should said "Pattern pattern = Pattern.compile("^In our tests, downloads on port 6881\D+(\d+)\D+(\d+)");" is NOT working for me. But I think it is close. I just tried "^In our tests, downloads on port 6881\D+\d+\D+(\d+)\D+\d+\D+(\d+)" and that did not work either.

It really need not be that complicated. If you are sure of the format of the text, the simplest regex would be as shown in the below code:

public static void main(final String[] args) {
    final String sample = "In our tests, downloads on port 6881 achieved up to 12059 Kbps " +
            "while downloads on port 47649 achieved up to 9623 Kbps.";

    final Pattern pat = Pattern.compile(".+?(\\d+) Kbps.+?(\\d+) Kbps.*");
    final Matcher matcher = pat.matcher(sample);
    if(matcher.matches()) {
        int speed1 = Integer.parseInt(matcher.group(1));
        int speed2 = Integer.parseInt(matcher.group(2));
        System.out.printf("Speed 1 => %s and Speed 2 => %s", speed1, speed2);
    } else {
        System.out.println("No match found");
    }
}

This assumes that the speed is always followed by a space and then Kbps but I guess that's a fair enough assumption.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

After the 30 minute cutoff, you can't edit your original post. You now have two options:

  • Make a new post with the suggested edit
  • "Flag bad post" your original post and request a moderator to make changes on your behalf

I personally feel that the first option makes more sense since you don't have to wait for a moderator to make the changes so that you/others can see them. So yes, just make a new post saying that "edit: new snippet here" or something along those lines.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I was using the try-catch to make sure the program doesn't crash and stop running

That's understandable, just make sure that in such cases resort of using the minimum number of catch blocks you can do away with.

isn't everyone these days?

Unfortunately no. A lot of people are stuck on 1.5 and a minority still uses 1.4 for legacy reasons *shudders*.

What is the better way?

If you have the freedom to use Java 7, you can significantly reduce the code boilerplate. Below is a sample template of how it might look like:

public class Test {

    public static final OpenOption[] options = { StandardOpenOption.APPEND,
            StandardOpenOption.CREATE };

    public static void main(final String[] args) {
        new Test().start();
    }

    public void start() {
        final String host = "somehost";
        final int port = 1234;
        final Path path = Paths.get("some", "random", "path");  /* /some/random/path */
        while(true) {
            try (BufferedWriter out = Files.newBufferedWriter(path, Charset.forName("UTF8"), options);
                    Omega omega = new Omega(host, port)) {
                // connect omega; read data; write data; sleep for some time
            } catch (Throwable t) {
                t.printStackTrace();
            }
            // when code reaches here, `out` and `omega` will be closed
            // irrespective of any exceptions thrown by the contained code.
        }
    }
}

class Omega implements AutoCloseable {
    String host;
    int port;

    public Omega(String host, int port) {
        this.host = host;
        this.port = port;
    }

    @Override
    public void close() throws Exception {
        // your closing code here
    }
}

The above code assumes you are …

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

The first piece of advice; catch stuff only if you plan on handling it. And by handling I don't mean printing stuff on the console and carrying on your merry way. One logical use case can be a retry-logic. If you plan on trying to connect to a host with a retry-counter, you would normally catch the connection exception, increase the failure count and try again.

Also, make sure you always close resources in the finally block since that's the only block which is guaranteed to be executed. So either you end up having try catch for each close method call or end up skipping closing a few resources. Since closing resources is a pretty repetitive task, a lot of folks end up using utility classes like the one posted below:

class Utils {

    private static final Logger log = Logger.getLogger(Utils.class.getName());

    /**
     * Close a list of AutoCloseable objects quietly. Works for pretty much all types of resources. But works only with
     * Java 1.7+
     * 
     * @param closeables
     */
    public static void closeQuietly(AutoCloseable... closeables) {
        for (final AutoCloseable resource : closeables) {
            try {
                if (resource != null)
                    resource.close();
            } catch (final Exception e) {
                log.log(Level.WARNING, "Exception when closing resource", e);
            }
        }
    }

    /**
     * Close a bunch of Closeable objects silently; doesn't work for DB resources like ResultSet, Connection etc.
     * 
     * @param closeables
     */
    public static void closeQuietly(Closeable... closeables) {
        for (final Closeable resource : closeables) {
            try {
                if (resource != null)
                    resource.close();
            } …
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Can you try the steps mentioned in this post and let us know if it helps?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

so like admins are working on daniweb, is this a full time job for them ? I mean is it their part time job or complete full time work ?

It depends. I'm one of the admins who isn't strictly employed by Daniweb/Dani. I contribute to Daniweb in my free time just like the other moderators here.

Davey and Deceptikon are employed by Dani for being a staff writer and Daniweb developer respectively though I can't comment on the "full time" part.

secondly, like sanjay is indian, so is he working from india ?

Yes, I "contribute" from India.

So they all work sitting in on place ? strange !

"Come together" as in bring together as a group of tight knit people who contribute to/work towards the betterment of Daniweb. We don't actually sit or "work" from a single place.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Also mods rely on the "flag bad post" reports by regulars to keep the forum clean so as long as any "regular" flags off-topic posts, it would be a big help and should make the life of moderators easier.

Also, to kickstart the thread, it will be a good idea to "mimic" the one in the Python forum and let the regulars decide the direction which the thread should take.

rotten69 commented: I agree with you on that! +4
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I have replied to James in the mod section and I'll reply here again. I'm favour of a new sticky thread as long as it stays on-topic and doesn't become a dumping ground for "plz halp me" posts. Someone will also need to ensure that "reponses" to the challenges/projects are not posted in the same thread so as to clutter it. It's a difficult task (e.g. take a look at the number of deleted posts in the current Java forum sticky) but if the Java forum members can pull it off, it would be a nice addition to the forum. That being said, I approve of the idea and would be more than happy if James lead the initiative.

rotten69 commented: Thank you for liking the idea. Yeah, it needs some serious action and someone keeps an eye on what is posted. +0
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

+ character has a special meaning when it comes to HTTP POST contents/URL etc. It is decoded to a "space". If you want a literal "plus" sign, you need to encode to something the server side encoder understands. This is where the URLEncoder class comes in. Make sure all the values on the RHS of your equal signs are url encoded with proper encoding.

Something like:

String mail = URLEncoder.encode("a+b@gmail.com", "UTF-8");
String pwd = URLEncoder.encode("yourpassword", "UTF-8");
String action = URLEncoder.encode("Login", "UTF-8");
// now create a POST data string out of these variables and submit them
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Some general advice. Don't use StringTokenizer; the Javadocs clearly state that it's a legacy class. Use the split method of the String class instead. Never catch exceptions only to print out something. Make sure you either propagate them, log them to a file/console or at least print the stack trace. The cast to String on line 62 is unnecessary. Calling matches on the String object compiles the passed in pattern for each iteration. If your regex doesn't change, consider creating/compiling a pattern just once and reusing it for different strings.

Regarding your problem, it seems you need to match words which have a c followed by e in a case insensitive manner. The trick is to use character classes i.e. use the pattern as .*[Cc].*[Ee].*. But use of wildcards at the start of string triggers a lot of backtracking so your pattern can be simply reduced to [Cc].*[Ee] along with using the find method of the Matcher class instead of matches. The difference between those two methods is explained here.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Important details are missing from your post. Which OS (Win 7 64 or 32 bit)? Which Java version (32 or 64 bit JVM; try doing java -version at the command line)?

If you are using a 32 bit JVM, you need to install 32 bit SWT. Likewise, for convinience, make sure everything is 64 bit (i.e. Java and SWT) in case your OS is 64 bit.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Your situation sounds a bit similar to what I've been through in the past so I'll try to put my 2 cents here. The wall of text presented below assumes that you want to land up in a good company and become a better programmer, not just the former.

Is it better to learn a maximum langage syntax, so im not limited to php, c and java or i better go deeper in 1 langage so i really get good at it and apply only on that langage, so far i really like Java?

Programming is not just about knowing the syntax; it's more about implementing your "logical problem solving" constructs. Let's say you want to write a method which returns a toString implementation of an array. No matter what the language, the core concept of this little exercise remains the same. Sure, you have to know Java to write it in Java, but if your only strength is the "syntax", then you would find yourself struggling with code even though you know Java. Try not to take on more than 3 langauges when starting out because it might turn out real confusing with your language expertise kind of "spread out".

nearly the same question as 1, but about the field of interest. should i take 1 field of expertise and develop my knowledge on that, exemple: its been 9 months, that i work around communication and the asterisk platform, going deeper in communication is good or …

Swordstech commented: thanks for the CS course links +0
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

The actual differences can be found here. And yes, Glassfish as an application container provides many more features when compared to a servlet container like Tomcat.

Also, depending on the complexity of your application to be ported, you should look into other lightweight alternatives like the Spring stack in case you are looking for migrating an enterprise or simple web app.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I couldn't find it. Turns out it wasn't included in my jdk.

If you are using JDK 1.5+, the visualvm binary should be present in the bin directory; not sure why it isn't in your case.

Does et load a .class file per instance or per class?

.class files are loaded once per classloader. Unless you have a web application, in normal cases, all .class files will be loaded only once. But once you start loading around thousand classes with each having a dependency of their own, it doesn't take time for memory consumed to build up.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Yes, as already mentioned, they can be found in the bin directory of your JDK. Plus, let's not forget the overhead for each object, the native libraries linked to the JVM executable, the thousands of .class files loaded etc.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

After searching around a bit, it seems that there are weird issues related to SQLite JDBC working fine on 32 bit Windows but not on 64 bit. Also, noteworthy is the point that the LIB file packaged inside the sqllite JAR is compiled against 32 bit Windows.

I would suggest either trying out a different driver or making sure you don't open up two simultaneous connections which result in this exception.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

free command is IMO not a good way to measure total memory in use since it also includes the "garbage" currently held by the VM before GC. Plus if no max or min heap sizes are provided, then the JVM will reserve a certain amount of memory in advance which depends on the architecture/OS. Also notice that it's not just 400K strings but also the assisting data structures like Node instances which are created during the lifetime of the application. If you want to be really sure, make sure you put a limit on the maximum memory used by your application by using the -Xmx JVM switch; initially set it to 100 MiB.

For proper profiling you need to either use the management extensions of Java (JMX memory bean) or an external tool like Visual VM which exists inside the JDK bin directory starting Java 5+.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Can you give me more information about how to get Tomcat log files that contain the entire stack trace. Which diercory should I look into?

The Tomcat logs are in the "logs" directory inside the Tomcat installation.

As to directory struction of any JBuilder project, it has been working with Tomcat 3.2 and 4.0, and 6.0.18. It should work under 7.0.28, isn't it?

Ideally it should, but it doesn't seem to be. I think JBuilder team is the only one who can authoritively answer as to why this isn't working as expected and provide a fix/workaround. Also, have you tried replacing Tomcat 7 with Tomcat 6 and checked if it still works?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

There is no entire stack trace for the exception

An exception always carries the entire stack trace. If not on the console, it's getting logged to some Tomcat log file. Anyways, with the single file you posted along with the short trace, the only obvious problem I see is that Apache Ant libraries are missing from the runtime classpath (though the question as to why they are required still remains). One suggestion might be to try this deployment outside JBuilder (manually create a web application directory structure), copy it to Tomcat's webapp directory and then try to run your application.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Nothing suspicous in the code itself apart from the non-standard imports for which I assume you have already added the JAR's to the classpath. Can you post the entire stack trace for the exception which occurs when compiling the JSP without trimming anything?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

What are the contents of your JSP file?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

JBuilder has different directory structure of web applications from other IDEs. It works in Tomcat 3 and 4. There should be a way to work it out in Tomcat 7, correct?

I'm afraid that's a question more suited for the JDeveloper support forums.

Another example is IBM RAD (Rational Application Developer). It has directory structure as follows:

That's the IDE project directory structure; when you deploy an application to the servlet container, it has to conform to the servlet specification. In case of RAD, it's quite possible that it copies the contents inside the WebContent directory without copying the directory itself.

You need to have a look at the directory structure of your deployed application which exists in Tomcat to understand what funny stuff JDeveloper does under the hood after deploying your application.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

IIRC, the Scanner class is notorious for consuming insane amount of memory due to it's regex based implementation and other implementation details. Try replacing it with a simple BufferedReader when reading the file contents.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Too little information to actually help you out:

  • Which Java version?
  • Which database and what version?
  • Which database driver are you using?
  • Is it possible for you to post the exact stack trace?
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

The project structure seems problematic and definitely doesn't resemble a regular web app. A normal web app looks like:

app/index.jsp
app/WEB-INF/web.xml
app/WEB-INF/classes

If you want to access FileUpload.jsp, it should be accessible if you add defaultroot after whoznextdoor in the URL though that would be really ugly or maybe add a redirection in the web.xml file.

I'd strongly recommend following the Java EE 5 tutorial if you want to learn about good JSP practices and an IDE like Eclipse. Also, have a look at how they structure their sample applications.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

And i assume the suggestions have the same problem?

No, really. Right now your code is inefficient and complicated because:

  • You are reading the entire file in memory; this is obviously going to cause problems in case multiple clients request several big files concurrently which would result in an OutOfMemoryError
  • If your only aim is transfer a file, there are simpler ways of knowing when a file ends; the trick is that read returns -1 when there is no more data to be read.
  • The actual code/algorithm is much simpler that what you have right now:

    • When client requests a file, open the file using FileInputStream on the server
    • Create an intermediate buffer as I have in my sample code snippet posted in my previous post
    • Keep reading data from the file input stream by passing in the buffer.
    • If there is more data to be read, read method call will always return the number of bytes read from the file. If end of file is reached, read returns -1 in which case you know you need not read any further.

Changing the code which you have should be as simple as just using the copy method on both the client and server piece of code. The only difference is where you get those streams from. In the case of client, the InputStream will be the input stream from the Socket which you created and the OutputStream will be the output stream for the new …

Krokcy commented: Informative, concise and understanding. +1
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Per your suggestion, I also tried http://localhost:8080/whoznextdoor/FileUpload.jsp, it does not render the web page based upon the JSP file, either. Nothing came up.

One possible case of blank page is when the JSP blows up when it is been rendered. You'll have to hunt the log files and look at the console logs. Or maybe you need to add an indication in your JSP, something like printing "hello" to sysout when the JSP is hit.

Any other suggestions?

One possible solution would be to ditch the JBuilder for the time being and deploy the project to Tomcat manually. This will help us know whether it's the JBuilder doing something strange or a problem with your project. Also, you still haven't posted the directory structure of your web application...

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

The code you posted is extremely confusing and doesn't make a whole lot of sense. What is numArrays? Why are you looping that many times? Why is each loop converting the file to an array? Why are you writing length to the stream on every iteration? Is that outDataStream variable of type DataOutputStream? If yes, why not simple OutputStream which you get from the established socket connection?

Also, more importantly, have you incorporated the suggestions provided in the thread which simply transfer across the data from one stream to another without assuming the file size and by using a single byte array?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I have attached the full message that comes in my console.

I don't see any attachments?

I am trying to hit the URL http://localhost:8080/FileUpload.jsp.

Are you sure that's the right URL to be invoked? Don't you need the application name in there, something like http://localhost:8080/myapp/FileUpload.jsp? How would the servlet engine know which application's FileUpload.jsp to invoke?

I am not sure what you mean by the structure of my project in Tomcat. Can you elaborate?

I'm assuming that you are copying the project to the webapps directory of tomcat in which case you need to tell me the directory structure of how your project looks like.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

My JSP does not come up engined by the web server as usual due to that warning message

Like I mentioned, it is just a warning message and shouldn't affect normal execution of JSP's/Servlets. The problem must lie somewhere else. Have you looked at all the log files and the logging done on the console? What is the URL you are trying to hit? What is the structure of your project which is deployed in Tomcat?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

This is not an error but just a warning message that the parameter -nonaming is not supported by the Bootstrap class as you can see from the source code. Any problems you are facing because of this?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

At the moment i'm not using buffered streams. I have never worked with them before. Should i use buffered streams for the network streams as well or just the file I/O?

I havn't been able to find another way to load the file than the Files.readAllBytes(Path) which doesnt allow me to split it up.

Reading the entire file in-memory is almost always a bad solution unless you always know you are dealing with really small files; streaming is the way to go. The de-facto solution is the one mentioned by James; have a small buffer which reads data from source and writes it to the destination. A helper method which might find helpful is:

public static long copy(InputStream from, OutputStream to, int bufsz) throws IOException {
    final byte[] buf = new byte[bufsz];
    long total = 0;
    int len = -1;
    while ((len = from.read(buf)) != -1) {
        to.write(buf, 0, len);
        total += len;
    }
    return total;
}

There are of course other efficient ways of doing it if you are really hard-pressed for performance (using Java NIO) but are a bit complicated.

I dont know how slow it acually is. It took about 12min+- to send a 75mb file from my harddisk to a flash drive...

I/O operations on flash drives are dog slow when compared to regular disk I/O hence the slowdown. But FWIW, sending across 70 MiB of file from disk to flash drive took me around 2:30 mins. Your code is …

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I may be mistaken but I believe you have to by QT

Jim, Qt has dual licensing of which one is LGPL which in turn in quite suitable for developing proprietary applications. The Python binding for Qt, PySide is again licensed under LGPL so developing with Qt (QtCreator) + PySide doesn't cost you anything. But I do agree that it doesn't buy you a lot if you are conversant with VB.NET and are free to use your language/tools of choice.

The first actual GUI app I developed was a Load Advisory Program for our control centre (in C under OS/2). No tools, and all GUI elements had to be coded by hand. It was brutal

TBH, I have always found UI development to be a bit brutal with varying levels of brutality depending on the toolkit you use. The trick IMO is to get into a comfortable zone with a few of them to the point that the quirks end up looking like features. ;)

Nice to see you back. I hope the move went well.

Yup, feels good to be back! :)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Based on my experience, Python is an outstanding first language and it maintains its appeal even to veteran programmers. But if your goal is to develop any kind of serious GUI, be prepared to invest a lot of time in learning details which you should not have to be concerned about.

A conclusion I don't agree with. IMO you are not comparing languages but the tooling support. There isn't anything inherent in VB.NET or Python as a language which makes one superior over the other when it comes to developing UI's. It's just that the tooling support for VB.NET is excelllent (Visual Studio) which makes it a breeze to create UI's. If you want to experience something similar with Python, take a look at Nokia's Qt (with QtCreator) and the corresponding Python bindings (PyQt and Pyside). Sure, the experience might not be the same as Visual Studio but is pretty decent when compared to creating UI's by hand.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

When i write my code, in the if statement the compiler gives me an error. It says that initialize enum

Whenever you declare a method scoped variable, you need to assign a value to it at least once before using it. In your code, the variable myStatus is not initialized before use. Either give it a default initial value or add an else to your existing if construct. Something like:

if (number != answer){ 
    myStatus = Status.CONTINUE;
} else {
    myStatus = Status.WIN;
}

You might also want to move the part where you accept user input inside the loop. Another good way of avoiding repetition would be to use a do...while loop.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

That's a valid but logically incorrect JSON representation of the data. Given that JSON objects are "string: value" pairs, having the same "string key" for all items will result in only one item being returned when you try to get all "STORE" elements.

For e.g. try pasting the following JSON in this validator and press validate: http://jsonlint.com/

{
    "STORE": [
        {"storeName":"<store name>"},
        {"emailAddresses": ["<email address1>","<email address2>"]}
    ],
    "STORE": [
        {"storeName":"<store name>"},
        {"emailAddresses": ["<email address1>","<email address2>","<email address3>"]}
    ],
    "STORE": [
        {"storeName":"<store name>"},
        {"emailAddresses": ["<email address1>"]}
    ]
}

As you can see, only the last element showed up. A better representation would be an array of stores keyed by "stores"; something like:

{
    "stores": [
        {
            "storeName": "<store name>",
            "emailAddresses": [
                "<email address1>",
                "<email address2>"
            ]
        },
        {
            "storeName": "<store name>",
            "emailAddresses": [
                "<email address1>",
                "<email address2>",
                "<email address3>"
            ]
        },
        {
            "storeName": "<store name>",
            "emailAddresses": [
                "<email address1>"
            ]
        }
    ]
}

As far as reading the JSON file is concerned, the simplest way I know of is to use the data binding offered by the Jackson JSON library. Download the library from: http://wiki.fasterxml.com/JacksonDownload under the Download 2.x section (all 3 jars).

To use the auto binding functionality, we need to create classes corresponding to the Stores and Store. Something like:

public class Stores {        
    private List<Store> stores;    
    public List<Store> getStores() {
        return stores;
    }    
    public void setStores(List<Store> stores) {
        this.stores = stores;
    }    
}



public class Store {        
    private String storeName; …
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I don't know exactly how you propose to use the given interfaces or how they fit in the big picture of your application so take this as a generic observation/food for thought about the way current code stands. :)

IMHO you are facing problems here with structuring code since the abstraction is leaking out a little bit. You create BufferValue class to abstract out how buffers work for floats, colors etc. but expose the internal type T when doing operations. Your operations return T which make it difficult to chain opeartions or work at an involved level with the returned results since there is no bound specified for T. With the current design, you'll also face issues when interoperating with different BufferValue's since the return type is T which is different for FloatBufferValue and AwtColorBufferValue.

Now back to your question: the lerp method sounds like a good candidate for the helper class which normally accompanies a widely used interface. For e.g. java.util.Collections used for manipulating and housing utility methods of the java.util.Collection classes. For e.g. one implementation can look like:

class BuffersValues {
    public static <T> BufferValue<T> lerp(double a, BufferValue<T> first, BufferValue<T> second) {
        // something here
    }
}

Now we have a problem here; we need a way for double values to interact with the containers of the BufferValue class, namely Float and Color. There are a few solutions which spring to mind:

  • Wrap the double value in a DoubleBufferValue and use the mul/add/etc. methods
  • Change double …
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I was able to upvote it; you just have to do it real quick. ;)

But jokes aside, I wasn't able to upvote once the rep comment box comes up after on-hover.

pritaeas commented: I have a slow mouse ;) +0
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Both are free as long you run it with public repos, as soon you want private repo you have to pay

Bitbucket allows you to have unlimited private and public repositories for upto 5 colloborating users. I always recommend Bitbucket to folks since you can pretty much host all your code privately and even run a small business (with < 5 programmers) for free!

peter_budo commented: Didn't know that +15
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

So should I continue Thinking in C++ or should I use one of the online resources? If the latter, which one? I will be sure to buy the book, but before that, some online education, right?

He should drop back to online tuts if "TICPP" is turning out to be difficult for him. The trick here is to flow through tutorials and settle on the ones which your kid finds worthy of a complete run.

But people say you shouldn't use an IDE when you are new to a language. I am sure you are an experienced C/C++/Java programmer. What do you recommend?

I recommend IDE if using command line tools is going to get the learner frustrated. Mind you, the aim here is to first make your kid learn C++ and not the chops required for being a super-cool C++ hacker. Once the basics are out of the way, learning the toolchain becomes an important point. All that being said, it's wrong assumption on your part that Visual Studio is IDE only. It comes with a command line utility for compiling C++ code. The steps are:

  • Open up command line and navigate to the Visual Studio directory in Program Files
  • Now move to "VC\bin" folder
  • Run: vcvars32.bat
  • Run: cl.exe your_file.cpp (assuming the CPP file is in same directory)
  • The above will create a your_file.exe file in the same directory.
  • Run "your_file.exe" and watch your C++ code execute!

The course starts tomorrow. Isn't it …

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Do you think this website is appropriate?

It seems like a decent free online choice. This thread from SO has a lot of resources for online C++ though over the years I have grown a bit wary of all the beginner resources available on the internet. But definitely worth a try if it helps.

I am using Borland C++ from the command line and not Code::Blocks which was mentioned on the website.

I think it'll be worthwhile to download the free version of Visual Studio since it has a pretty good C++ support (I personally use it to teach C++ programming to kids).

Sorry, I meant "Thinking in C++" instead of Thinking in Java. I meant, should he read Thinking in C++ quarter way or halfway first and then buy the book?

I think the kid should proceed at his own pace and ask you for buying the book if he thinks he wants to continue C++.

And also, Thinking in C++ is proving a little complicated for him.

The sad fact is that C++ is indeed difficult for beginners as compared to say Python or Scheme. I think C++ Primer is the lowest denominator C++ beginner text you'll find on the bookshelf.

BTW, has your kid looked at the CS-101 courses offered by Udacity and Coursera. The interactive learning material should definitely keep him involved.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

All admins, moderators, team colleages are employees or some of them just contribute their time to site

All moderators are voluntary contributors (not employees) to this forum who help out Daniweb with answering questions and forum maintenance in their free time. Except for me, all other co-admins are Daniweb employees (namely Davey & James).

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Should he read the article like, quarter way or halfway first and then buy the book?

Which article? I linked you to the download page for Thinking in C++ in my previous post.

Or should he complete that Thinking in Java first?

One thing at a time; frequently jumping between stuff is bad and leads to confusion, especially when you are trying to learn/teach something new. If he has decided to start C++, concentrate on C++.

Also, that C++ primer book you showed me on flipkart.com was the 4th edition of the book. In my local library I saw the 3rd edition. Should I take the book?

4th Edition is the latest one so is definitely recommended over the old 3rd edition. Like already mentioned, start off with the Thinking in C++ books. If your kid expresses desire to learn more or in depth, grab the paperback copy on Flipkart.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

There aren't many authoritive free resources on the internet for C++ that I know of. One is the free ebook (vol 1 and vol 2) offered by Bruce Eckel, found at: http://nyll.com/ebooks/index.html

If your kid starts enjoying the material in the above mentioned books, spending Rs. 440 on C++ Primer wouldn't be a bad option.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

If he thinks it's awesome to know many languages, C++ with its unique feature set and "close to C" performance should definitely be on the "to dabble in" list. Plus, C++ has tons of game engines written in which makes it a good practical language to write games in.

I'd say go for it! I'd recommend C++ primer and Accelerated C++ as starting points.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Should he learn C++?

This question is incomplete without the follow up answer for "for what purpose?". If for fun, C++ isn't fun to write, at least when compared to the newer breed of managed/scripting languages which make it a lot simpler to do stuff. If for curiosity and usefulness, sure. C++ is pretty much the new standard for native/low level languages. And of course, the third possibilty might be "just because he wants to", in which case it's not like anything can stop him. ;)

The challenge for you here would be to ensure he doesn't get frustrated. Moving from Java to C++ or vice versa can be frustrating because these languages look so similar but are quite different when it comes to expressing solutions.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Plz explain this line. What is IE6?

That means 1 * 10^6 i.e. 1 followed by 6 zeroes. I use this number to convert from nanoseconds (10^-9) to milliseconds (10^-3).

Is the given cpu time included in real time?

These are two different things. The "real time" is the "wall clock" time. This means that you run your Java code, start a stopwatch and stop it when the program completes. The time you get is the "real time" taken by your code to execute. Even if you don't explicitly create threads, the JVM has its own set of threads: the main thread which executes your code, the GC thread etc. If your code is doing a lot of IO and waiting around for stuff, it's quite possible that the "CPU" time might be quite lower than the real time but if you are doing extensive computations on a multi-core box, the figures might be reversed.

You can always verify your timings by running the same program using the *nix time command as already mentioned in my previous post but it will give you the time in millisecond resolution and not nanosecond.