Thursday, March 31, 2011

Tips for Junior Programmers

I'm in a situation where I got a job as a developer and there is no mentor or anything. This is my first software job. I'm 24 and working on a BS in Computer Information Science. I have experimented with some languages on my own time, took some classes, and did a few IT internships and software is definitely the career for me. I didn't lie about anything on the interview process and it was a long exhaustive one.

It's basically a regular full-time position. Everyone is much too busy to help and I'm on my own. So far I've been going about it well and learning quickly. I do the same type of work as everyone else. It is Java and C#/.NET. I develop and support a few apps among a host of other things.

What I'm concerned about is how will this lack of mentoring affect me in the future? I'm sure there are others out there who started from scratch with no help. I would like to hear your experiences and tips.

EDIT: At this point my only source of help is Google and Wikipedia...

From stackoverflow
  • I think the only way to learn programming is to program. So do your best and don't be offended by criticism.

    Reading is paramount too, but unless you have the practical experience, bad advice from written material can easily mislead you.

  • I have been on that path, its not so easy but makes you tough. You will need to read up a lot, analyze work done by your seniors, it tells how they think. Keep an open eye, your mentor will not always be right. Lack of mentoring can mean you need to do it all yourself. You can also see mentors in people like Martin Fowler, Scott Hanselman and get ideas from the community. Keep learning, keep coding, keep self analyzing.

    Good Luck!!

  • My #1 tip is that, if I were your team leader, I'd want you to ask me questions, even if I am busy (and, I'm always 'busy'). It's much easier for me, if you tell me what you information you lack (by asking me), instead of expecting me to:

    • Guess what it is that you don't know
    • Supervise you to check that you haven't gotten stuck or off-track on anything

    My #2 tip is, understand what the quality-control measures are: developer testing? Code inspections? Automated unit tests? Integration tests by a separate QA, working from functional specs which you write? Because, in the end, what matters is that your work has sufficient quality; and assuring quality is the team effort, of mutual interest. So discuss QA with people (what kind of testing, how much testing, can we do code reviews, etc.).

    My #3 tip is that code reviews are a good (perhaps the best) way to do knowledge transfer as well as QA: they're the opportunity for more experienced people to, not only verify that you're not checking in bugs, but to see where you have any weaknesses or anything they might have done differently, and tell you.

    jandersson : So you're saying it's too much to ask from a team leader to supervise team members to assure work is on track and progress in made?
    ChrisW : It depends on the team leader's responsibilities, which IME are to do other things as well as supervising: helping/mentoring junior developers is only a [small] part of the job. I'd prefer to be able to trust a person to 'interrupt' when appropriate than for me to need to continuously 'poll' them.
    AngerClown : Most people want to help you, but they are busy and working on their own tasks so they won't go out of their way to find you. You have to _ask_, which can be very hard to do for us introverted programmer types. Pick something that looks interesting in the code base, try and understand it, then schedule time with the developer who coded it to make sure you got it right. Offer to help them with something. Repeat and start making small contributions where you can. Log all your time doing this so you can show your manager occasionally (schedule a review meeting yourself, don't wait for your boss).
  • Assuming you are an experienced coder already (not neccesarily for team programming), all you need to do is check out other programs that have been made for your company, and try to adopt a close style / format / layout / approach so that you won't be breaking standards. The rest is trial and error.

    edit: style & format include how syntactic sugar is handled, as well.

  • If there aren't people there who can mentor you right now, you would do well to read some classic books for programmers, as discussed in a previous question:
    Stack overflow question about influential programming books

    Code Complete is very good, and there are others on the list worth checking out.

    Regarding your question of "What I'm concerned about is how will this lack of mentoring affect me in the future?" I think that it's highly unlikely that you will be irreparably damaged by having to find your own way right now. More likely, the experience will make you stronger. To be sure you lose something by not having experienced people to guide you directly, but consider that anyone that could have been supervising you would have their own biases. And therefore you would have to think yourself and teach yourself even if you did have many mentors available.

  • I started from scratch some 25 years ago. Obviously I was able to cope somehow, but I really feel my growth was stymied by the lack of constructive input from peers.

    Some of the junior folk at my last employer had it pretty good. They were surrounded by 4 very experienced developers with various backgrounds. We more senior types encouraged them to find answers own their own (this site makes that much easier) but were always around to help before frustration set in or serious mistakes were made.

    In your position, if you cannot get the support you need at work, involving yourself in communities such as found here or on sites more related to your work is probably your best bet. Everyone needs peers to help them through tough spots (or brain farts).

    Personally, I need people to bounce ideas off of... even if they dont respond to anything I say. The act of saying things to somebody out loud often helps me solve issues.

    ChrisW : There's a story (I forget where I read it, unfortunately) of a university computer lab, where the Teaching Assistants kept a plush toy on a chair outside their office. If you had a problem that you wanted help with, you had to explain it to the plush toy, before you would then go and ask a T.A.
    Sailing Judo : lol, too funny! Maybe thats what I should do at work... place a small Dilbert (or better yet, Dogbert) doll outside my cube for that purpose.
  • I agree to "unanswered" most of the people learn by themselves (atleast who are passionate about programming). No one will teach you how to program in an organization. They will train you about projects.

    1. Learn online
    2. Watch video tutorials (ex: www.asp.net, www.learnvisualstudio.net)
    3. Participate in unofficial tech camps or meets (ex: barcamps, MS user groups etc)
    4. Try to get a certification by going for a training : You have 2 advantage you will get to meet new people and learn new things
    5. Subscribe to good blogs (http://stackoverflow.com/questions/78955/what-are-the-best-programming-and-development-related-blogs)
    6. Listen to good podcasts
    7. Participate in tech forums and if interested start a new blog and record your learnings
    8. And most importantly Love what you do.

    Edit: 9. If you don't know. Ask!!!!! 10. Dont Assume (ASSUME .. You are just making an d ASS out of U and ME)

    This is how I learned. I am 23 now and work as a senior developer. I started @ the age of 19. All the best :)

    Shyju : Really Great Buddy
  • Mentoring is the exception rather then the rule, I'm afraid.

    Not having a mentor will probably mean you'll get to make many of the same mistakes others have made and waste a lot of time doing so.

    However, look at it this way, you'll truly understand why some things work and others don't, perhaps more so then if someone just tells you why something is incorrect.

  • start reading

    Refactoring: Improving the Design of Existing Code

    Code Complete

  • I learned and continue to learn most by reading code. If that's too boring for you, pick your favourite (small!) open source project and recreate it in a different language. Stay as close to the original behavior as possible. That way you have to go into the open source project's code and read how they solved it.

    Don't worry too much about which project to use and if it will teach you bad coding style. Because here is the kicker: After a while you will know if it's bad or good code you are reading. You'll get a feeling for it.

    Move on to the next project and reiterate.

  • I've been in a similar position as an intern. One thing I found helpful was the fact that the company I interned at had a corporate subscription to Safari. It allowed me to get up to speed on new technologies with out needing to constantly Google everything. You can find more info about it at http://safaribooksonline.com I would check to see if your company has a subscription.

  • Make a conscious effort to form ego-less opinions. Don't be afraid to express them, but more importantly, don't be afraid to let the opinions of others inform your own.

    Make a lot of mistakes. When in doubt, error on the side of 1) your customers and 2) the programmers who will have to comprehend and modify your code later.

    Build things, always build things.

  • If you are reading Stack Overflow, you are doing more than most software developers. I read a survey that the average software developers reads less than 1 software-related book per year!

    As other posters have said: read, read, read! Read blogs, books, and your co-workers' code.

    The technical books I found most enlightening include:

    • Code Complete: A Practical Handbook of Software Construction

    • Domain-Driven Design: Tackling Complexity in the Heart of Software (This book is very dense, but it blew my mind.)

    • Joel on Software: And on Diverse and Occasionally Related Matters That Will Prove of Interest to Software Developers, Designers, and Managers, and to Those Who, Whether by Good Fortune or Ill Luck, Work with Them in Some Capacity

    • Design Patterns: Elements of Reusable Object-Oriented Software

    • C++ Coding Standards: 101 Rules, Guidelines, and Best Practices

    • Refactoring: Improving the Design of Existing Code

    • About Face 3: The Essentials of Interaction Design

    • Extreme Programming Explained: Embrace Change

    • Fred Brook's Mythical Man-Month

    • Writing Secure Code (Yes, this book is from Microsoft Press and uses Windows for many examples, but the fundamentals are important and universal.)

    • Extra Credit: Structure and Interpretation of Computer Programs (SICP)

    talonx : I would add to the list - Prefactoring, The Art of Agile Development, The Productive Programmer, Algorithms (Cormen/Rivest et al)
  • The fact that you have no mentor may not be that bad. You only really need mentorship to help you with the project source code, internal libraries and mechanisms.

    As far as the general technology knowledge goes, you can pick up the missing bits and pieces on your own. A good mentor could be of great help. Just as a bad mentor could ruin you skills by teaching you to do things in the wrong way.

    For example, right now I myself could mentor our senior developer on a few things in C#/.NET and general software architecture.

    Maybe it is your destiny to become the CTO in your company? ;)

  • My first job I was a lone programmer in a non-software company, when I finally did work with others, they were peers at best. It was 4 years before I worked with anybody with more experience than myself.

    The pros to working by myself were:

    • I had total control over my projects
    • I learned quickly to write more robust code, since I maintained everything I wrote.
    • Communication was minimized to me and the business owner, which increased efficiency.

    The cons were:

    • My inexperience caused a lot of mistakes including; technology choice, design decisions, and not knowing / not wanting to tell my boss 'that's not possible'.
    • If you stop proactively expanding your technology exposure, it's easy to go stale real quick.
    • When you're stuck you're screwed.
    • I could only guess if I was doing good work or not

    In retrospect, if I could go back and do it again, the one thing I'd ask my boss to do is find a senior developer / architect who could review my decisions & code on a regular basis and provide honest objective feedback. This could have seriously accelerated my learning curve, and my company would have saved time/money, and would have easily paid for itself!

    In my case it would have been an external consultant, I don't know if your company would have somebody who could do this in house or not.

    Good luck.

    PS-I do feel privileged to have gotten the experience I did. I'm glad I didn't go straight into consulting.

  • I'd say that if you're lucky to be spoon-fed with mentoring, you'd be better off than most people. What ChrisW says is all good but many people don't even have a boss that is even able to answer your questions. What about all the entrepreneurs that start out single handedly? Everyone else being too busy is more the rule than the exception. It's a huge boost having a mentor, not something you should take for granted.

  • I think you can become a good programmer without a mentor. But having good people above you is really important for you in your professional career. If your boss is a good manager you will grow as a professional in a more general sense, and she can help you to realize your long-term goals. If he is incompetent it can really hurt your chances. To some extent that is true for your other colleagues as well.

    Having great people around you is what really matters.

  • When I got started into writing code for a living, my first few projects I worked on were pretty rough. No one wanted to help because we were busy, and no one had time to look at what I was doing.

    I started simply by asking the best (most talented and respected) guy in the group how he did things. If he had an example code or a "standard" he followed. By seeing and letting him set this standard, it gave him the feeling like he was molding me, almost like he was my "boss" even though he wasn't. He appreciated this, and I appreciated this as well. With this, I was able to learn from my team. After that, I'd try something new, and let the other team members pick it apart. Sometimes it was brutal, but I learned fast.

    Not sure if that's really where you want to go for an answer, but it's one guys humble story.

  • My boss once told me, if you're not breaking anything, then you're not working.

  • It's funny how you've titled this 'Junior' programmers. Does that mean that somewhere along the lines people slowly move up in the ranks and become seniors, experts, gurus? And who defines who gets which title?

    I've been in the Army for over 5 years now, and although I'm not sure who voiced it, I was once told a great piece of knowledge that I've kept true to.

    There are only **two mistakes** you can make in life...
    1. The mistake that costs you your life.
    2. The mistake that costs the life of someone else.
    

    In adherence to this... Nothing is a mistake in programming.

    It either works or doesn't.

    • If it doesn't work, fix it.
    • If it does work but not as planned, refine it
    • If it works, leave it!

    I started my life pulling apart an Apple 2E and progressed from there to a 386 with Windows 3.11 and then to a Pentium with Windows 95 and onward. My father hated me because I always found a way to break the computer or change it to something different.

    Today at 23, I own my own business where I manage over 200 corporate web sites with 40 ongoing clients who all turn to me for advice on anything related to computers and website design. I don't have a degree or any qualification in computing but I write extensive PHP/XHTML/CSS enabled websites using Joomla.

    I learnt everything I've needed to get this far from the internet and just playing around with code. I run two staging servers at home based on CentOS 5.2 which mirror my hosting server. On these staging servers I 'break' my code in, work out all the bugs then once I'm happy I replicate the site to the live servers.

    I wouldn't call myself an expert or a guru, I just know what I'm doing. I don't have a piece of paper attaining to what is in my head but I've got numerous examples of my work and most of it is displayed for free.

    As said above, you're in the right place to learn, as you've identified the hardest thing is to ask.

    Use Google, blogs, wiki's and any text book available, use the experience of people who have tried to do the same thing and you will slowly pick things up. There are no text-books called 'Programming in 7 days', there's no easy way to pick it up you've just got to experiment.

    JUST REMEMBER TO ALWAYS KEEP A GOOD BACKUP

    All the best

  • I was lucky enough to start my IT career working in a small shop as the sole junior developer under 4 extremely experienced developers from around the globe. Together they had more than 60 years combined programming experience and a lot of what they said in the beginning was honestly over my head.

    I began working with them as a fresh graduate with only a 2 year Associates degree. So, basically, I thought I knew a few things. What I found out pretty much right away on day 1 was I knew pretty much nothing.

    One of the senior programmers became both my supervisor and a true mentor. His initial conversation with me involved what he expected of me and what I could expect from him. He was very clear that I could come to him with anything at anytime and we would work through it together. He also told me while he would always be available if I had questions, part of the career of a software developer is solving problems and that I should try to answer my own questions first by other means. His point was simple, it was part of my job to research and expand my own skills. As I spent more and more time researching improved methods and alternate solution possibilities, my mentor told me researching is a requirement but at some point, I had to decide on a solution. With the amount of information available now, it is too easy to be in a constant state of looking for alternative answers. Be careful not to get into the state of over-thinking a problem, you may run across some new way of doing something, but you also risk coming across as indecisive.

    While I gained an immense amount of knowledge from him, and the other senior developers, I learned how to learn in a professional on-going nature, not as a college student (and there is a huge difference in those two methods, at least it for me). I would not have improved as quickly without a mentor but I was in a position where I either had to improve or it would have been a short-lived career path.

    So I will just re-iterate the overwhelming response of those before me in this thread. Read, read, read. I think in the first year of my professional programming career I read more white-papers, books, and other articles than my entire Associate Degree program required.

    Other than just reading, places like SO have always been helpful to me over the years. I would also recommend Dr. Dobbs as a potential source -- http://www.ddj.com/

    You already are ahead of the curve by knowing you need some feedback, absorb all the information you can find; become an information sponge. Good luck

  • My suggestion would be to ask your manager or team lead about the process for some of the rather basic things you are likely to be doing:

    1. Version Control System - Is there a specific way to use this software where I work? What conventions exist that are worth noting somewhere so my code doesn't stick out like a sore thumb? Can a check-in/commit break the build and this is OK, or does breaking the build be one of the greatest sins one can commit where one works?

    2. Promotion of code - If you have at least a couple of environments, development and production though there can be a few others possibly like a QA and staging for a couple of other examples, what is the process for pushing code into production? Is it cowboy style where whoever wants to push code into production can do so without any warning or is there a process for this?

    3. Coding conventions - Is there an agreed convention in naming variables and methods, e.g. camelCase or using underscores or hyphens? Are there code reviews to check my code by someone else? Are there tests to be bundled with my code so that anyone wanting to review the tests can do so in an easy manner? Does the team I'm on have a standards and practices meeting to share what conventions some may be using?

    If you are working with other developers this may make things a ton better so that you know how some of the other guys are working and blend in in a desirable way. Some of these questions may be met with a, "Do we do that here?" type of questioning though that should be OK as then you can help build the process which is an excellent way to develop that skill of helping future developers as well as yourself and other junior programmers around you.

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

I want to be able to debug C structures without having to explicitly type every property that they consist of.

i.e. I want to be able to do something like this:

CGPoint cgPoint = CGPointMake(0,0);
NSLog(@"%@",cgPoint);

Obviously the '%@' won't work, hence the question.

From stackoverflow
  • You can try this:

    NSLog(@"%@", NSStringFromCGPoint(cgPoint));
    

    There are a number of functions that convert the various CG structs into NSStrings. The reason it doesn't work is because %@ signifies an object. A CGPoint is a C struct (and so are CGRects and CGSizes).

  • I use the following macro to help me out with NSRect:

    #define LogRect(RECT) NSLog(@"%s: (%0.0f, %0.0f) %0.0f x %0.0f",
        #RECT, RECT.origin.x, RECT.origin.y, RECT.size.width, RECT.size.height)
    

    You could do something similar for CGPoint:

    @define LogCGPoint(POINT) NSLog(@"%s: (%0.0f, %0.0f)",
        #POINT POINT.x, POINT.y);
    

    Using it as follows:

    LogCGPoint(cgPoint);
    

    Would produce the following:

    cgPoint: (100, 200)
    

NSManagedObjectContextObjectsWillChangeNotification

Hey!
I need something like an opposite to NSManagedObjectContextObjectsDidChangeNotification. Something like NSManagedObjectContextObjectsWillChangeNotification. I think this would solve this problem (stackoverflow-question).
It's importent that it notificates before it deletes the object (in that problem) for changing the selected NSMenuItem early enough. ;)

From stackoverflow
  • I don't think it's possible to be notified before an object is deleted. However, in the userInfo dictionary for NSManagedObjectContextObjectsDidChangeNotification there's a key called NSDeletedObjectsKey which will give you all the objects that have been deleted. Now, the word "deleted" is a little complicated here, since these objects have technically only been marked for deletion. Their attributes are still accessible to you if you happen to need them for some reason.

    As for your other problem, I think the person who answered that question is right. You should be looking at the NSArrayController you've bound the popup button to, not the popup button itself. It has to do with how you delete the object. If you're doing it right, the popup button will observe the deletion automatically. Your problem has to do with bindings, not Core Data, it would seem.

  • If your application is 10.6 only, check out [NSManagedObject prepareForDeletion] in the Apple docs. Another possible approach is to implement "validateForDelete:" on NSManagedObject. This gets called during the validation stage when a context gets saved. Be sure to call through to super as part of your implementation.

JavaScript Scroller Problem

I'm trying to incorporate the following JavaScript Scroller into a website but as soon as I include it in a HTML page that has layout eg. Tables/DIVs it seems to break and won't display. Was wondering if anyone had any advice.

<script language="javascript">
//ENTER CONTENT TO SCROLL BELOW.
var content='Content to be scrolled';

var boxheight=150;        // BACKGROUND BOX HEIGHT IN PIXELS.
var boxwidth=150;         // BACKGROUND BOX WIDTH IN PIXELS.
var boxcolor="#E9F0F8";   // BACKGROUND BOX COLOR.
var speed=50;             // SPEED OF SCROLL IN MILLISECONDS (1 SECOND=1000 MILLISECONDS)..
var pixelstep=2;          // PIXELS "STEPS" PER REPITITION.
var godown=false;         // TOP TO BOTTOM=TRUE , BOTTOM TO TOP=FALSE

// DO NOT EDIT BEYOND THIS POINT

var outer,inner,elementheight,ref,refX,refY;
var w3c=(document.getElementById)?true:false;
var ns4=(document.layers)?true:false;
var ie4=(document.all && !w3c)?true:false;
var ie5=(document.all && w3c)?true:false;
var ns6=(w3c && navigator.appName.indexOf("Netscape")>=0)?true:false;
var txt='';
if(ns4){
txt+='<table cellpadding=0 cellspacing=0 border=0 height='+boxheight+' width='+boxwidth+'><tr><td>';
txt+='<ilayer name="ref" bgcolor="'+boxcolor+'" width='+boxwidth+' height='+boxheight+'></ilayer>';
txt+='</td></tr></table>'
txt+='<layer name="outer" bgcolor="'+boxcolor+'" visibility="hidden" width='+boxwidth+' height='+boxheight+'>';
txt+='<layer  name="inner"  width='+(boxwidth-4)+' height='+(boxheight-4)+' visibility="hidden" left="2" top="2" >'+content+'</layer>';
txt+='</layer>';
}else{
txt+='<div id="ref" style="position:relative; width:'+boxwidth+'; height:'+boxheight+'; background-color:'+boxcolor+';" ></div>';
txt+='<div id="outer" style="position:absolute; width:'+boxwidth+'; height:'+boxheight+'; visibility:hidden; background-color:'+boxcolor+'; overflow:hidden" >';
txt+='<div id="inner"  style="position:absolute; visibility:visible; left:2px; top:2px; width:'+(boxwidth-4)+'; overflow:hidden; cursor:default;">'+content+'</div>';
txt+='</div>';
}
document.write(txt);

function getElHeight(el){
if(ns4)return (el.document.height)? el.document.height : el.clip.bottom-el.clip.top;
else if(ie4||ie5)return (el.style.height)? el.style.height : el.clientHeight;
else return (el.style.height)? parseInt(el.style.height):parseInt(el.offsetHeight);
}

function getPageLeft(el){
var x;
if(ns4)return el.pageX;
if(ie4||w3c){
x = 0;
while(el.offsetParent!=null){
x+=el.offsetLeft;
el=el.offsetParent;
}
x+=el.offsetLeft;
return x;
}}

function getPageTop(el){
var y;
if(ns4)return el.pageY;
if(ie4||w3c){
y=0;
while(el.offsetParent!=null){
y+=el.offsetTop;
el=el.offsetParent;
}
y+=el.offsetTop;
return y;
}}

function scrollbox(){
if(ns4){
inner.top+=(godown)? pixelstep: -pixelstep;
if(godown){
if(inner.top>boxheight)inner.top=-elementheight;
}else{
if(inner.top<2-elementheight)inner.top=boxheight+2;
}}else{
inner.style.top=parseInt(inner.style.top)+((godown)? pixelstep: -pixelstep)+'px';
if(godown){
if(parseInt(inner.style.top)>boxheight)inner.style.top=-elementheight+'px';
}else{
if(parseInt(inner.style.top)<2-elementheight)inner.style.top=boxheight+2+'px';
}}}

window.onresize=function(){
if(ns4)setTimeout('history.go(0)', 400);
else{
outer.style.left=getPageLeft(ref)+'px';
outer.style.top=getPageTop(ref)+'px';
}}

window.onload=function(){
outer=(ns4)?document.layers['outer']:(ie4)?document.all['outer']:document.getElementById('outer');
inner=(ns4)?outer.document.layers['inner']:(ie4)?document.all['inner']:document.getElementById('inner');
ref=(ns4)?document.layers['ref']:(ie4)?document.all['ref']:document.getElementById('ref');
elementheight=getElHeight(inner);
if(ns4){
outer.moveTo(getPageLeft(ref),getPageTop(ref));
outer.clip.width=boxwidth;
outer.clip.height=boxheight;
inner.top=(godown)? -elementheight : boxheight-2;
inner.clip.width=boxwidth-4;
inner.clip.height=elementheight;
outer.visibility="show";
inner.visibility="show";
}else{
outer.style.left=getPageLeft(ref)+'px';
outer.style.top=getPageTop(ref)+'px';
inner.style.top=((godown)? -elementheight : boxheight)+'px';
inner.style.clip='rect(0px, '+(boxwidth-4)+'px, '+(elementheight)+'px, 0px)';
outer.style.visibility="visible";
}
setInterval('scrollbox()',speed);
}
</script>
From stackoverflow
  • I know I'm not answering your question, but this will at least help me to sleep tonight. :)

    I'm not sure exactly what you are trying to do, but I wouldn't use that script. I'm guessing you've copied and pasted it from somewhere, but it looks like it was written a good few years ago, and doesn't really meet many of the best practise guidelines for JavaScript these days.

    If you are looking for scripts and libraries for these type of effects, I would recommend looking at:

    If you had to push me for one, I would recommend jQuery. Along with learning JavaScript of course, which is really required for use of any of the above libraries. :)

  • Your Script is quite old (IE4, Netscape era...), and it uses non standard tags (ilayer, layer).

    Continuing with the Andy's recommendation, there are some jQuery alternatives that may suit your needs, like jdNewsScroll or this ScrollUp Headline Reader.

  • Ahhh, my eyes! The goggles do nothing ;) You should definitely follow some of the advice a couple folks have put forth already and ditch this script.

    If you must use it, here are a couple observations:

    1. Ignoring the whole ns4 sections of code, the above will break in today's browsers as the width and height css rules being applied to the #ref, #outer, and #inner elements are missing a "px" quantifier. Those lines need to read:

      txt+='<div id="ref" style="position:relative; width:'+boxwidth+'px; height:'+boxheight+'px; background-color:'+boxcolor+';"></div>';
      txt+='<div id="outer" style="position:absolute; width:'+boxwidth+'px; height:'+boxheight+'px; visibility:hidden; background-color:'+boxcolor+'; overflow:hidden">';
      txt+='<div id="inner" style="position:absolute; visibility:visible; left:2px; top:2px; width:'+(boxwidth-4)+'px; overflow:hidden; cursor:default;">'+content+'</div>';
      

      Note the added "px".

    2. I don't know if this code came with instructions, but from the looks of the document.write line you need to place it inside your <body>, at the spot in the page where you want this scrolly thing (or whatever it is) to appear.

    ps What a wretched pile of code.

    privateace : I agree completely. I've had nothing but trouble with JavaScript and this is an old issue that was brought up by one of my users wondering if I ever solved the problem. Thank you for your advice

How can I delete Windows restore points in c#?

Hello,

Im looking for a way to delete Windows restore points using C# perhaps by invoking WMI.

Any code snippet would be very helpful.

Kind regards,

From stackoverflow
  • While I know nothing about WMI, this resource might get you started. It does not directly touch your issue, but perhaps it can be useful somehow. Anyhow, it seems that the relevant Win32/COM function is SRRemoveRestorePoint. I hope this was of any use.

    Alternatively, you can work with VBScript, if you're so inclined.

  • I can't imagine any reason why you would want to do this. What kind of software are you writing?

    Simon Svensson : +1 Don't mess with the operating system's ability to restore itself. I see no use for this at all, since Windows has this functionality already.
  • Touching on what Morten said you can use that API. WMI doesn't provide a method to delete a Restore Point as far as I can tell. The SRRemoveRestorePoint can remove a restore point, provided you have the sequence number. You can get that through WMI. Here is my code to Remove a restore point.

    [DllImport("Srclient.dll")]
    public static extern int SRRemoveRestorePoint(int index);
    
    private void button1_Click(object sender, EventArgs e)
    {
        int SeqNum = 335;
        int intReturn = SRRemoveRestorePoint(SeqNum);
    }
    

    I just threw in 335 since that was the farthest one back as I could find on my system. Its likely that the count starts at 1 and keeps incrementing. so it isn't as simple as just having an index like you would in an array.

    As for getting the sequence numbers, I converted the code from Microsoft to C# which will give you that info. Be sure to add System.Management as a reference. Otherwise this code won't work right.

        private void EnumRestorePoints()
        {
            System.Management.ManagementClass objClass = new System.Management.ManagementClass("\\\\.\\root\\default", "systemrestore", new System.Management.ObjectGetOptions());
            System.Management.ManagementObjectCollection objCol = objClass.GetInstances();
    
            StringBuilder Results = new StringBuilder();
            foreach (System.Management.ManagementObject objItem in objCol)
            {
                Results.AppendLine((string)objItem["description"] + Convert.ToChar(9) + ((uint)objItem["sequencenumber"]).ToString());
            }
    
            MessageBox.Show(Results.ToString());
        }
    

    I tested this on my box (Vista by the way) and it worked without issue. Also have to be running as Admin, but I think you figured that.

  • How could i get the sequence number of the restore point?? Thanks a lot!

    Helen : Don't post questions as answers to other questions -- Use the **Ask Question** button in the upper right to add questions.

How to get Maximum bytes from a port using a serversocketchannel

hi guys, I'm developing a multiple port reading application using nio package.Actually these ports recieve packets continously.Using nio package we have to reAD packets using channels.There should not be a packet loss.Here is my code.I've confusion in else if ((key.readyOps() & SelectionKey.OP_READ)== SelectionKey.OP_READ) block.Please suggest a feasible way to handle the buffer so that i can dmp the whole data into database without loss.

import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;

public class MultiPortEcho
{
  private int ports[];
  private ByteBuffer echoBuffer = ByteBuffer.allocate(32000);

  public MultiPortEcho( int ports[] ) throws IOException
  {
    this.ports = ports;
    go();
  }

  private void go() throws IOException
  {
    // Create a new selector
    Selector selector = Selector.open();

    // Open a listener on each port, and register each one
    // with the selector
    for (int i=0; i<ports.length; ++i)
    {
      ServerSocketChannel ssc = ServerSocketChannel.open();
      ssc.configureBlocking( false );
      ServerSocket ss = ssc.socket();
      InetSocketAddress address = new InetSocketAddress( ports[i] );
      ss.bind( address );

      SelectionKey key = ssc.register( selector, SelectionKey.OP_ACCEPT );

      System.out.println( "Going to listen on "+ports[i] );
    }

    while (true)
    {
      int num = selector.select();
      System.out.println("num::::"+num);
      Set selectedKeys = selector.selectedKeys();
      Iterator it = selectedKeys.iterator();

      while (it.hasNext())
      {
        SelectionKey key = (SelectionKey)it.next();

        if ((key.readyOps() & SelectionKey.OP_ACCEPT)== SelectionKey.OP_ACCEPT)
          {
              // Accept the new connection
        ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
        SocketChannel sc = ssc.accept();
        sc.configureBlocking( false );

        // Add the new connection to the selector
        SelectionKey newKey = sc.register(selector,SelectionKey.OP_READ);
        it.remove();

        System.out.println( "Got connection from "+sc );
        }
          else if ((key.readyOps() & SelectionKey.OP_READ)== SelectionKey.OP_READ)
          {
        // Read the data
        SocketChannel sc =(SocketChannel)key.channel();
        System.out.println("sc::::"+sc);
        // data to fetched from channel and dump into the datatbase
        int bytesEchoed = 0;
        //while(true)
        {
        echoBuffer.clear();
        int r = sc.read(echoBuffer);
        System.out.println("r:::" + r);
        /*int pos=echoBuffer.position();
        System.out.println("pos:::" +pos);*/
        if (r == -1)
        {
         //echoBuffer.flip();
         echoBuffer.rewind();
         byte[] array = new byte[100000];
         while (echoBuffer.hasRemaining())
         {
          int n = echoBuffer.remaining();
          System.out.println("size:" + n);
          echoBuffer.get(array,0,n );
          System.out.println(new String(array,0,n));
          key.cancel();
          it.remove();

         }

        }

        /*int pos=echoBuffer.position();
        System.out.println("pos:::" + pos);
        if(r<=0)
        {
         echoBuffer.flip();
         for (int j = 0; j < pos; j++ )
         {
          String ss =Integer.toHexString(echoBuffer.get());
          if (ss.length() == 1)
           System.out.print("0" + ss + " ");
          else if (ss.length() > 2)
           System.out.print(ss.substring(6) + " ");
          else System.out.print(ss + " ");
                        }
          break;
        }

        echoBuffer.flip();

        sc.write( echoBuffer );
        bytesEchoed += r;*/
              }

             //System.out.println( "Echoed "+bytesEchoed+" from "+sc );
             //it.remove();
        }

      }

//System.out.println( "going to clear" );
//      selectedKeys.clear();
//System.out.println( "cleared" );
    }
  }

  static public void main( String args[] ) throws Exception
  {
    FileOutputStream fileoutputstream = new FileOutputStream("MultiPort.txt", false);
    PrintStream printstream = new PrintStream(fileoutputstream);
    System.setOut(printstream);
    if (args.length<=0) {
      System.err.println( "Usage: java MultiPortEcho port [port port ...]" );
      System.exit( 1 );
    }

    int ports[] = new int[args.length];

    for (int i=0; i<args.length; ++i) {
      ports[i] = Integer.parseInt( args[i] );
    }

    new MultiPortEcho( ports );
  }
}
From stackoverflow
  • Isn't this a double post, I think I saw this question elsewhere?

    Anyway, the first thing you need to do is to remove the key.cancel(), which is completely invalidating your key so that it will not appear in future selects.

How to calculate sum of a DataTable's Column in LINQ (to Dataset)?

I'm just started to read up on LINQ and I want to start incorporating it into my code. I know how to compute the sum of a DataTable's column by either "Foreach"-ing through the rows or by doing a compute.sum on the specific column. How do I do the equivalent with LINQ to DataSet?

From stackoverflow
  • 101 Linq Samples

  • If untyped (replace int with the correct data type):

     var sum = table.AsEnumerable().Sum(x=>x.Field<int>(3));
    

    or:

     var sum = table.AsEnumerable().Sum(x=>x.Field<int>("SomeProperty"));
    

    If typed:

     var sum = table.Sum(x=>x.SomeProperty);
    
    rivera.reyrivera : That did the trick. Thank you very much
  • How to achieve this with Linq to XML Thanks. There is nothiug like TABLE

  • what if I have to add a where clause to the query?

I am looking for a webbased text editor that supports collaboration

I am looking for a web based text editor that supports collaboration with 2 or more people.

I am hoping to work on a fairly 'small' project with a couple other people from afar and would really like for us to be able to work on the same file at the same time and see the changes each other make in 'real time'.

Language built on is not much of an issue, would prefer to have syntax highlighting, but not really required.

From stackoverflow

Can you call a WCF with basicHttpBinding in a .net 2.0 winforms app?

Hi,

From what I know basichttpbinding is backward compatible to .net 2.0 correct?

It seems that when you reference the WCF service, the API is different.

My service uses SSL, and it has a username and password you have to set.

In .net 2.0 the API is totally different, and having issues calling an endpoint correctly.

From stackoverflow
  • WCF services are present in the .NET 3.0 and 3.5 frameworks. While your service will be executing in the 2.0 runtime (.NET 3.0 and 3.5 are just additional layers to the 2.0 framework), as long as it serializes types that are easily understood (i.e. can be resolved to basic types like strings and integers), all is well. In fact, a Java client could call into the WCF service since at the wire level, what matters is compliance with widely accepted specifications like SOAP 1.1 for example.

    From your windows forms client, you need to create a reference to the service using wsdl.exe (or using Visual Studio's Add Web Reference wizard). As far as it knows, it looks like any ASP.NET web service.

    Now, using the basicHttpBinding is not all there is to ensure your service is compatible with non-WCF clients. You also need to be sure you're sticking to the DataContractSerializer or the XmlSerializer. You'll want to avoid the use of the NetDataContractSerializer since that requires that types be shared on both the service and the client. Not that it could not be done, but you'd have to make sure your types are in a .NET 2.0 assembly and aren't using functionality only available in 3.0 or later (e.g. System.Core).

Looking for a DataGridView that allows grouping

Basically I'm looking for a control that allows for grouping in a DataGridView control that can also be editted (I.E. somthing like DataGridView and TreeView into a single control).

Thanks in advance.

From stackoverflow
  • DevExpress has a great control that is a tree/gridview with grouping.

    Demo here.

    Index of some ASP.Net controls can be found here.

    : Anything free controls?
    achinda99 : No good ones that I know of. You can do a combination of Trees and Gridviews but its ugly and complicated.
  • Infragistics UltraWebGrid (ASP.NET) and UltraWinGrid (Windows Forms) support grouping and can be setup as edittable grids. These controls are part of their NetAdvantage Suite.

  • Herre Kuijpers made a OutlookGrid in CodeProject, which derives from DataGridView, and allows grouping of rows.

Copying file from PC to VPC?

I'm running VPC 2007 and the OS is windows 3.1 I need to copy a C++ compiler from my real computer to the virtual one. How do I do this, it doesn't seem to read the .iso that I made. I don't have a floppy drive since I'm using a laptop.

From stackoverflow
  • You can drag files from your PC and drop them on the VPC. Windows 3.1 supported drag & drop, so (in principle) this should work.

    Lucas McCoy : WOW I did not know that! Thanks a lot +16!
    Michael Burr : Does VPC provide "Guest Additions" (the drivers that support things like drag-n-drop from host to guest) for Win 3.1? I didn't think they did (or they dropped it at some point over the last couple years).
  • In VPC 2007, click on the yellow folder in the lower left hand corner of the frame around your guest OS. This will let you map a folder on the host to a drive letter on the guest. Then in the guest you can access the mapped drive as if it were a network drive.

C++ Pointer Snippet

Greetings everyone. This is my first question here at stackoverflow so please bear with me.

My programming class this semester is Java; last semester was C++. My Java teacher feels (justifiably, I think) that it is very important for we students to understand the mechanics of memory management.

Since Java has automatic garbage collection, he has seen fit to give us an assignment in which we must write a very basic program in C++ that creates a two-dimensional array using pointers. Specifically, we are to first create an array of pointers; each pointer in the first array should reference its own array of integers. Then we must deallocate the memory associated with the two arrays.

This assignment is supposed to consist of two functions: one to allocate the 2-D array, and a second to deallocate. I just want to make sure that the following code is logically sound before I proceed.

I'm sure this all seems very simple, but the hitch is that my C++ teacher spent all of two days on pointers. While I somewhat understand the mechanics, I am pretty clueless on implementation. That being said, the following is a very rough start. Is this logically sound? Am I completely off the mark? My most profound thanks in advance for any help.

EDIT: I have created a new question with updated code. You can view it by clicking Here.

From stackoverflow
  • Looks correct to me, with one exception - when you delete arrays you need the following syntax:

    delete [] arrayName;
    
    ninj0rc : Many thanks for the help. I will make the change and get to work on the functions. Thanks again.
  • When you use

    int* i = new int;
    

    you pair it with

    delete i;
    

    and when you use

    int* i = new int [12];
    

    you pair it with

    delete [] i;
    

    If there are brackets in the new, there should be brackets in the delete. Otherwise, your program looks reasonable to me, except that you haven't implemented those two functions that your prof wants you to.

    ninj0rc : Thank you very much for the explanation. I did not want to start writing the functions until I was sure that I could...write them :D
  • You need to use delete [] instead of just delete.

  • It looks sound(logically). By the way - it's ok to run a program and have it fail. :-)

    ninj0rc : Yeah, it's just that I have basically zero experience with pointers. I've known about this site for some time, and it seemed the perfect time to pose a question.
  • Your code looks fine. I think you will like Java alot since pointers are a really hard subject to grasp and like you said Java has Garbage Collection! (Thank God!)

    ninj0rc : I think you're absolutely right :) However, as my professor says, it's important that I understand memory management...I just wish my C++ teacher had spent more time on the subject ><
    Lucas McCoy : Yeah my C++ teacher spent quite some time on the subject of pointers (about 2 weeks). I really came to appreciate that
    ninj0rc : It is certainly the most unintuitive concept I have experienced; however, it is incredibly interesting to say the least.
  • That's a well-asked question.

    I don't think I'd call it a "2-D array": it's an array of arrays, not a 2-D array.

    I think I'd call my index i or iColumn or iRow instead of nCount (your nRows and nColumns are logically const and used as fencepost/high-water-mark values, whereas your nCount is a loop index).

    For bonus points, think about how to test your solution. You can run it to see if it faults ... but the converse, i.e. not faulting, isn't proof that it's correct. What O/S are you running it on? If you're using Linux then a worthwhile test is to run your code using valgrind (because when you run it valgrind can automatically detect a lot of the ways in which it's possible to misuse memory).

Which express edition to use for ASP.NET web apps in C#?

Which Express edition is best suitable for starting ASP.NET web applications in C#? I imagine Visual Web Developer Express is designed for this, but what about Visual C# Express?

From stackoverflow
  • Visual C# can support WPF Browser application. Other than that, it is not going to support any kind of web development.

  • For web dev / practice, I would recommend Visual Web Developer Express, Visual Studio Express Edition, and SQL Server Express. With SQL express, you can create MDF files in your app_code folder in your web app. You will probably do the majority of your web development in Web Dev Express. However, it is useful to have VS Express installed as well.

    Here is a good source of info for starting out with these apps.

Does Silverlight download the assemblies everytime?

Does a Silverlight application get downloaded everytime you visit the site or will it check version/size information and only download a newer version of files?

From stackoverflow
  • It depends on how you configured your webservers headers and how the client configures his browser caching policies.

    Usually the browser settings are ok by default. You might want to check your webserver that the appropriate header values for expiration, etags and caching are properly configured. You can use a tool like Firebug to check these settings and use Yslow to meassure other client side performance things.

    Phil Wright : So this is determined by standard web settings and nothing that is Silverlight specific then?
    BenMaddox : That's correct Phil.
  • There is nothing specific to Silverlight 2 in this regard, the most concise explanation I've read is from this post on silverlight.net:

    "Silverlight falls under the same caching rules as any other web content. If the user clears their cache, your xap will have to be downloaded again. In normal circumstances, the xap is downloaded only when changed or when the cache expires."

    You can control when the cache expires by following the steps outlined here:

    You can turn the Enable Content Expiration HTTP header option on for your XAP file. Open IIS Manager, goto Default Web Site and find your Web site for the silverlight project. Find the XAP file under ClientBin. Goto the properties page of the XAP file, on HTTP Headers Tab, Turn on "Enable Content Expiration", click the "Expire Immediately" radio button. Save the change.

    This way the new XAP (only there is a new XAP) will get downloaded when you refresh your page without having to close the browser.

    This related post may also be of interest.

Export PDF pages to a series of images in Java

I need to export the pages of an arbitrary PDF document into a series of individual images in jpeg/png/etc format. I need to do this in in Java.

Although I do know about iText, PDFBox and various other java pdf libraries, I am hoping for a pointer to some working example, or some how-to.

Thanks.

From stackoverflow
  • Here is one way to do it, combining some code fragments from around the web.

    How do I draw a PDF into an Image?

    https://pdf-renderer.dev.java.net/examples.html

    Creating a Buffered Image from an Image

    http://www.exampledepot.com/egs/java.awt.image/Image2Buf.html

    Saving a Generated Graphic to a PNG or JPEG File

    http://www.exampledepot.com/egs/javax.imageio/Graphic2File.html

    Combined together into something that works like this to turn all the pages into images:

    import com.sun.pdfview.PDFFile;
    import com.sun.pdfview.PDFPage;
    import java.awt.Image;
    import java.awt.Rectangle;
    import java.io.*;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    import javax.swing.*;
    import javax.imageio.*;
    import java.awt.image.*;
    
    public class ImageMain {
    
    public static void setup() throws IOException {
    
        //load a pdf from a byte buffer
        File file = new File("test.pdf");
        RandomAccessFile raf = new RandomAccessFile(file, "r");
        FileChannel channel = raf.getChannel();
        ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
        PDFFile pdffile = new PDFFile(buf);
    
        int numPgs = pdffile.getNumPages();
    
    
       for (int i=0; i<numPgs; i++)
       {
       // draw the first page to an image
        PDFPage page = pdffile.getPage(i);
    
        //get the width and height for the doc at the default zoom 
        Rectangle rect = new Rectangle(0,0,
                (int)page.getBBox().getWidth(),
                (int)page.getBBox().getHeight());
    
        //generate the image
        Image img = page.getImage(
                rect.width, rect.height, //width & height
                rect, // clip rect
                null, // null for the ImageObserver
                true, // fill background with white
                true  // block until drawing is done
                );
    
    
        //save it as a file
        BufferedImage bImg = toBufferedImage( img );
        File yourImageFile = new File("page_" + i + ".png");
        ImageIO.write( bImg,"png",yourImageFile);
        }
    }
    
    
    // This method returns a buffered image with the contents of an image
    public static BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage)image;
        }
    
        // This code ensures that all the pixels in the image are loaded
        image = new ImageIcon(image).getImage();
    
        // Determine if the image has transparent pixels; for this method's
        // implementation, see e661 Determining If an Image Has Transparent Pixels
        boolean hasAlpha = hasAlpha(image);
    
        // Create a buffered image with a format that's compatible with the screen
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        try {
            // Determine the type of transparency of the new buffered image
            int transparency = Transparency.OPAQUE;
            if (hasAlpha) {
                transparency = Transparency.BITMASK;
            }
    
            // Create the buffered image
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(
                image.getWidth(null), image.getHeight(null), transparency);
        } catch (HeadlessException e) {
            // The system does not have a screen
        }
    
        if (bimage == null) {
            // Create a buffered image using the default color model
            int type = BufferedImage.TYPE_INT_RGB;
            if (hasAlpha) {
                type = BufferedImage.TYPE_INT_ARGB;
            }
            bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
        }
    
        // Copy image to buffered image
        Graphics g = bimage.createGraphics();
    
        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();
    
        return bimage;
    }
    
    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    ImageMain.setup();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
    }
    
    dasp : This is exactly what I was looking for, thank you!
    zaletniy : the hasAlpha method missed can be found here http://www.biddata.net/joel/photo/final/Photo.java
  • If you consider the JPedal PDF library, its built in and documented with eample source at http://support.idrsolutions.com/default.asp?W22

  • Hi,

    I was looking for similar kind of solution for myself. When I tried the same example with a pdf file with more than 1 page, all output png files are coming for first page only. Any idea whats wrong here.

    Thanks, Abhi

  • hi.

    jst start your for loop from 1 instead of 0...Your problem will be solved..

    cheers, Ravie

How do I reference the GroovyObject instance from MetaClass methods in Groovy?

This is a contrived example of what I want to do, but minimally expresses the behavior desired. I want to reference the instance of the object on which the property access is being invoked. I tried 'this' first, but that refers to the enclosing class rather than either the MetaClass or the String instance.

String.metaClass.propertyMissing = { String name ->
    'I do not exist, but my name is ' + <the String instance> + '.' + $name
}
From stackoverflow
  • You can refer to the object with "delegate":

    String.metaClass.propertyMissing = { String name ->
        "I do not exist, but my name is $delegate.$name"
    }
    
    
    println "a".me