Friday, April 15, 2011

How can I fill the remaining space when dealing with an inline ul?

I used this CSS to make my ULs look fancy

ul, li
{
  padding: 0px;
  margin-left: 0px;
  margin-bottom: 0px;
  display: inline;
}

li
{
  border: solid 1px #333333;
  margin-right: 5px;
  padding: 2px;
  background-color: #222222;
  color: #999999;
}

I'd like to have a final, empty list item that has the same graphical style fill up the remaining space on the inline. Something like

[item A] [item B] [item C] [------big empty one----------]

Is is possible to figure out how much space you have left? Could you set one of the list items to have width 100% or something?

Thanks,

From stackoverflow
  • You could use a background colour/image on the UL, and make the UL and LIs the same height to give this effect

    Seb : And make your UL width: 100%

How to easily convert a DbDataReader object into something useful?

I am manually calling a stored procedure using an Entity Framework EntityConnection like so:

DbConnection storeConnection = entityConnection.StoreConnection;
DbCommand command = storeConnection.CreateCommand();
command.CommandText = "sp_GetMyComplexData";
command.CommandType = CommandType.StoredProcedure;

DbDataReader reader = command.ExecuteReader();

The reason for this is that the entity framework doesn't easily support entities that don't directly map to tables or views. I found this article (http://dotnet.dzone.com/news/mapping-stored-procedure), but it requires editing of the XML, which I would like to avoid.

In my case I'm just running a query that joins two tables using a LEFT JOIN. The reason for THAT is because I am trying to bind the results to a Telerik RadGrid, which doesn't support hierarchical data exports, but does seem to support grouped data exports.

The problem is, how do I convert the DbDataReader object into something useful that I can bind to my RadGrid? I've been passing around single objects, or IQueryable objects in my DAL methods. Any ideas? Thanks in advance?

EDIT:

I only need the data. I don't need to do any inserts, updates, deletes afterwards. Its a read-only view.

From stackoverflow
  • I don't know about RadGrid, but you can bind that datareader to the built-in grid controls like GridView. You just can't use it for updates, deletes, or inserts.

    Otherwise, you could turn it into a datatable using the datatable's .Load() method. But you'll still need to know how to do the insert/update/deletes manually.

    SkippyFire : I thank table.Load(reader); is what I am looking for. I'll let you know how it goes...
    SkippyFire : Yeah this was exactly what I needed. Thanks Joel!

append conditional html file output with xml response

hey guys i have a restful xml service where client passes current version of html they are viewing. if the version on the server is the same as the client, i just respond with the current server version in xml. example: <Response ServerHTMLVersion="1" />

however if server html version is greater than current client version, i still spit out the same response like above like <Response ServerHTMLVersion="2" />. but problem being my client application needs to do a seperate http request to download the html file incase response xml version is greater than clients version

for performance reasons, i wanted to cut down this http request and i wanted to know what is the best way to do this. should i simply encode the html to make it xml safe and append that with xml response - problem with this being html is FAT and encoding makes it even fatter

OR

is there a better way of managing this? note that i am already gziping my response for both, xml as well as html right now

i wanted to know the way to do this keeping performance in mind. the restful xml service is implemented via asp.net 3.5 and iis 7

From stackoverflow
  • Have you thought about using HTTP headers? Since really the primary data here is the HTML, and the ServerHTMLVersion is a sort of "meta data" about that html, it should work.

    Personally, I'd make the response to the request 1) blank when the versions match and 2) the HTML for non-matching versions; then, use the Pragma HTTP header to send something like Pragma: "ServerHTMLVersion=2". By doing this, you can easily check if the client and server versions differ, and just grab the full response if they're different.

    Some people would debate the idea of returning HTML from a REST service, but I personally would consider this totally valid, and an nice clean way of separating your meta data from the actual user data.

    -Jerod

    Raj : great idea jerod - i am more interested in performance than caring about returning html from a rest service - DOES NOT MATTER ;-)

Is it ever polite to put code in a python configuration file?

One of my favorite features about python is that you can write configuration files in python that are very simple to read and understand. If you put a few boundaries on yourself, you can be pretty confident that non-pythonistas will know exactly what you mean and will be perfectly capable of reconfiguring your program.

My question is, what exactly are those boundaries? My own personal heuristic was

  1. Avoid flow control. No functions, loops, or conditionals. Those wouldn't be in a text config file and people aren't expecting to have understand them. In general, it probably shouldn't matter the order in which your statements execute.
  2. Stick to literal assignments. Methods and functions called on objects are harder to think through. Anything implicit is going to be a mess. If there's something complicated that has to happen with your parameters, change how they're interpreted.
  3. Language keywords and error handling are right out.

I guess I ask this because I came across a situation with my Django config file where it seems to be useful to break these rules. I happen to like it, but I feel a little guilty. Basically, my project is deployed through svn checkouts to a couple different servers that won't all be configured the same (some will share a database, some won't, for example). So, I throw a hook at the end:

try:
    from settings_overrides import *
    LOCALIZED = True
except ImportError:
    LOCALIZED = False

where settings_overrides is on the python path but outside the working copy. What do you think, either about this example, or about python config boundaries in general?

From stackoverflow
  • There is a Django wiki page, which addresses exactly the thing you're asking. http://code.djangoproject.com/wiki/SplitSettings

    Do not reinvent the wheel. Use configparser and INI files. Python files are to easy to break by someone, who doesn't know Python.

    S.Lott : -1: .INI are icky and limited.
    vartec : @S.Lott: They aren't perfect, but they are a standard that can be read in any language. Limited? Well, configuration files should not have business logic embedded.
    Jarret Hardie : +1 link to the wiki page... I had not seen that page and it's got some good stuff on it.
  • Your heuristics are good. Rules are made so that boundaries are set and only broken when it's obviously a vastly better solution than the alternate.

    Still, I can't help but wonder that the site checking code should be in the parser, and an additional configuration item added that selects which option should be taken.

    I don't think that in this case the alternative is so bad that breaking the rules makes sense...

  • I think it's a pain vs pleasure argument.

    It's not wrong to put code in a Python config file because it's all valid Python, but it does mean you could confuse a user who comes in to reconfigure an app. If you're that worried about it, rope it off with comments explaining roughly what it does and that the user shouldn't edit it, rather edit the settings_overrides.py file.

    As for your example, that's nigh on essential for developers to test then deploy their apps. Definitely more pleasure than pain. But you should really do this instead:

    LOCALIZED = False
    
    try:
        from settings_overrides import *
    except ImportError:
        pass
    

    And in your settings_overrides.py file:

    LOCALIZED = True
    

    ... If nothing but to make it clear what that file does.. What you're doing there splits overrides into two places.

  • As a general practice, see the other answers on the page; it all depends. Specifically for Django, however, I see nothing fundamentally wrong with writing code in the settings.py file... after all, the settings file IS code :-)

    The Django docs on settings themselves say:

    A settings file is just a Python module with module-level variables.

    And give the example:

    assign settings dynamically using normal Python syntax. For example:
    MY_SETTING = [str(i) for i in range(30)]
    
  • Settings as code is also a security risk. You import your "config", but in reality you are executing whatever code is in that file. Put config in files that you parse first and you can reject nonsensical or malicious values, even if it is more work for you. I blogged about this in December 2008.

    David Berger : That's a good point. I think this particular case falls into the category of all editors being superusers, but it's still something to remember in the general case.

How can i create a soap header like this?

Doing some SOAP calls to a 3rd party application. They provide this soap header as an example of what the application expects. How can I create a SOAP header like this in PHP?

<SOAP-ENV:Header>
 <NS1:Security xsi:type="NS2:Security" xmlns:NS1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:NS2="urn:dkWSValueObjects">
  <NS2:UsernameToken xsi:type="NS2:TUsernameToken">
   <Username xsi:type="xsd:string">XXXX</Username> 
   <Password xsi:type="xsd:string">XXX</Password> 
  </NS2:UsernameToken>
 </NS1:Security>
</SOAP-ENV:Header>

I do what i think is a correct call and keep getting in return that no headers were sent.

Here is a sample from my code.

class SOAPStruct 
{
    function __construct($user, $pass) 
    {
        $this->Username = $user;
        $this->Password = $pass;
    }
}

$client = new SoapClient("http://www.example.com/service");

$auth = new SOAPStruct("username", "password");
$header = new SoapHeader("http://example.com/service", "TUsernameToken", $auth);

$client->__setSoapHeaders(array($header));
$client->__soapCall("GetSubscriptionGroupTypes", array(), NULL, $header)

And this is the SOAP header i get back. (its more but i stripped info away that might be sensitive)

<SOAP-ENV:Header>
 <ns2:TUsernameToken>
  <Username>username</Username> 
  <Password>password</Password> 
 </ns2:TUsernameToken>
</SOAP-ENV:Header>
From stackoverflow
  • Aren't there PHP libraries for SOAP handling, that can generate PHP objects and Service interfaces from the WSDL / XSD for the web service?

    Ólafur Waage : I am using the SOAPClient library in PHP.
  • SOAP header handling in PHP is actually not very flexible and I'd go as far as saying that especially the use two namespaces within the header will make it impossible to inject the header simply by using a SoapHeader-construct of some type.

    I think the best way to handle this one is to shape the XML request yourself by overriding SoapClient::__doRequest() in a custom class that extends SoapClient.

    class My_SoapClient extends SoapClient
    {
        public function __doRequest($request, $location, $action, $version, $one_way = 0)
        {
            $xmlRequest = new DOMDocument('1.0');
            $xmlRequest->loadXML($request);
    
            /*
             * Do your processing using DOM 
             * e.g. insert security header and so on
             */
    
            $request = $xmlRequest->saveXML();
            return parent::__doRequest($request, $location, $action, $version, $one_way);
        }
    }
    

    Please see SoapClient::__doRequest for further information and some examples.

    Ólafur Waage : I did in the end create my own header, but with nuSOAP, but your answer led me the right way. :)

Occlusion algorithms collection

The occlusion algorithm is necessary in CAD and game industry. And they are different in the two industries I think. My questions are:

  1. What kind of occlusion algorithms are applied respectively in the two indurstries?
  2. and what is the difference?

I am working on CAD software development, and the occlusion algorithm we have adopted is - set the object identifier as its color (a integer) and then render the scene, at last, read the pixel to find out the visible objects. The performance is not so good, so I want to get some good ideas here. Thanks.


After read the anwsers, I want to clarify that the occlusion algorithms here means "occlusion culling" - find out visible surface or entities before send them into the pipeline.

With google, I have found a algorithm at gamasutra. Any other good ideas or findings? Thanks.

From stackoverflow
  • In games occlusion is done behind the scene using one of two 3D libraries: DirectX or OpenGL. To get into specifics, occlusion is done using a Z buffer. Each point has a Z component, points that are closer occlude points that are further away.

    The occlusion algorithm is usually done in hardware by a dedicated 3D graphics processing chip that implements DirectX or OpenGL functions. A game program using DirectX or OpenGL will draw objects in 3D space, and have the OpenGL/DirectX library render the scene taking into account projection and occlusion.

  • The term you should search on is hidden surface removal.

    Realtime rendering usually takes advantage of one simple method of hidden surface removal: backface culling. Each poly will have a "surface normal" point that is pre-calculate at a set distance from the surface. By checking the angle of the surface normal with respect to the camera, you'd know that the surface is facing away, and therefore does not need to be rendered.

    Here's some interactive flash-based demos and explanations.

    Jim T : This process is necessary, but not sufficient. Any concave object will still need to have the surfaces rendered in the correct order, and if one object appears in front of another, then simple backface culling doesn't help.
    spoulson : I named backface culling because Z-buffering was already mentioned. If I wrote any more, then I'd just be mostly reiterating the Wikipedia page I linked.
  • Hardware pixel Z-Buffering is by far the simplest technique, however in high-density object scenes you can still be trying to render the same pixel multiple times, which may become a performance problem in some situations. - You certainly need to make sure that you're not mapping and texturing thousands of objects that just aren't visible.

    I'm currently thinking about this issue in one of my projects, I've found this stimulated a few ideas: http://www.cs.tau.ac.il/~dcor/Graphics/adv-slides/short-image-based-culling.pdf

  • It stuck me that most of the answers so far only discuss image-order occlusion. I'm not entirely sure for CAD, but in games occlusion starts at a much higher level, using BSP trees, oct trees and/or portal rendering to quickly determine the objects that appear within the viewing frustum.

    Vilx- : +1. DirectX/OpenGL already does a decent job of drawing just the things you see (via a Z-buffer). If you wish to limit the amount of stuff you're rendering to get a better performance you have to look into one of these algorithms.
    Cecil Has a Name : Yes; but apart from pixel based occlusion, D3D nor OpenGL do scene graph "magic". Clipping and culling isn't enough to justify sending all the polygons known to the rendering device, since clipping scales somewhat linearly.

Conditional clauses for linq to Db4O query?

In linq to sql i can do like this:

var q = db.Colors;
if(! string.IsNullOrEmpty(colorName))
   q = q.Where(c=>c.Name.Equals(colorName));
return q.ToList();

In Db4O linq I can't do it like this because I have to start with

var q = (from Color c in db
         select c);
if(! string.IsNullOrEmpty(colorName))
   q = q.Where(c=>c.Name.Equals(colorName));
return q.ToList();

This results in

  1. a complete enumeration of ALL the colors
  2. a filter by name.

That's not the solution I was aiming for off course. Any suggestions?

From stackoverflow
  • I'm not sure what you're getting at. Are you worried that in the first case some of the code executes server side so you optimize the values returned. But in the second case the enumeration is done locally so there is no optimization on the used values?

    If so, there is no way to avoid this with LINQ to Objects. The objects are in memory so there is no way to avoid enumerating through them to do a filter operation.

    borisCallens : That is indeed the question: How can I avoid that the where clause in the second example becomes a linq2objects? I would prefer it to be part of the linq2Db4o so the db4o engine can optimize it.
  • What if you split the expression:

    IDb4oLinqQuery<Color> q;
    if(! string.IsNullOrEmpty(colorName))
    {
      q = from Color c in db
          where c.Name.Equals(colorName)
          select c;
    }
    else
    {
      q = from Color c in db
          select c;
    }
    return q.ToList();
    

    This way the Db4O preprocessor sees 2 different LINQ Queries? Downside is off course this solution is much more verbose and not exactly DRY..

    borisCallens : Also, in my real world app it would be about 10 parameters that are all optional so this would make for one hell of an if.
  • Would something like this be suitable?

    return (from Color c in db
           where !String.IsNullOrEmpty(colorName) && c.Name.Equals(colorName)
           select c).ToList();
    

    You can then also use multiple parameters:

    return (from Color c in db
           where (!String.IsNullOrEmpty(colorName) && c.Name.Equals(colorName))
              || (!String.IsNullOrEmpty(color1Name) && c.Name.Equals(color1Name))
              || (!String.IsNullOrEmpty(color2Name) && c.Name.Equals(color2Name))
              ...
           select c).ToList();
    
    borisCallens : Wow, this is an old post. I think by now the linq to DB4O supports lambda expressions. Not sure, haven't had the chance to work with it lately. If not your sollution could probably work. Next evening I have some spare time I'll check it out :)
    borisCallens : I finally got to it, and it seems the linq 2 db4o still isn't capable of getting what I want. The syntax you suggest is possible, but I would still like to have a cleaner (lambda) syntax.

C/C++: Optimization of pointers to string constants

Have a look at this code:

#include <iostream>
using namespace std;

int main()
{
    const char* str0 = "Watchmen";
    const char* str1 = "Watchmen";
    char* str2 = "Watchmen";
    char* str3 = "Watchmen";

    cerr << static_cast<void*>( const_cast<char*>( str0 ) ) << endl;
    cerr << static_cast<void*>( const_cast<char*>( str1 ) ) << endl;
    cerr << static_cast<void*>( str2 ) << endl;
    cerr << static_cast<void*>( str3 ) << endl;

    return 0;
}

Which produces an output like this:

0x443000
0x443000
0x443000
0x443000

This was on the g++ compiler running under Cygwin. The pointers all point to the same location even with no optimization turned on (-O0).

Does the compiler always optimize so much that it searches all the string constants to see if they are equal? Can this behaviour be relied on?

From stackoverflow
  • No, it can't be relied on, but storing read-only string constants in a pool is a pretty easy and effective optimization. It's just a matter of storing an alphabetical list of strings, and then outputting them into the object file at the end. Think of how many "\n" or "" constants are in an average code base.

    If a compiler wanted to get extra fancy, it could re-use suffixes too: "\n" can be represented by pointing to the last character of "Hello\n". But that likely comes with very little benifit for a significant increase in complexity.

    Anyway, I don't believe the standard says anything about where anything is stored really. This is going to be a very implementation-specific thing. If you put two of those declarations in a separate .cpp file, then things will likely change too (unless your compiler does significant linking work.)

  • You surely should not rely on that behavior, but most compilers will do this. Any literal value ("Hello", 42, etc.) will be stored once, and any pointers to it will naturally resolve to that single reference.

    If you find that you need to rely on that, then be safe and recode as follows:

    char *watchmen = "Watchmen";
    char *foo = watchmen;
    char *bar = watchmen;
    
  • It's an extremely easy optimization, probably so much so that most compiler writers don't even consider it much of an optimization at all. Setting the optimization flag to the lowest level doesn't mean "Be completely naive," after all.

    Compilers will vary in how aggressive they are at merging duplicate string literals. They might limit themselves to a single subroutine — put those four declarations in different functions instead of a single function, and you might see different results. Others might do an entire compilation unit. Others might rely on the linker to do further merging among multiple compilation units.

    You can't rely on this behavior, unless your particular compiler's documentation says you can. The language itself makes no demands in this regard. I'd be wary about relying on it in my own code, even if portability weren't a concern, because behavior is liable to change even between different versions of a single vendor's compiler.

    T.E.D. : I like how you put that. For me "no optimization" just means "don't do anything that might make it tougher to debug".
  • I would not rely on the behavior, because I am doubtful the C or C++ standards would make explicit this behavior, but it makes sense that the compiler does it. It also makes sense that it exhibits this behavior even in the absence of any optimization specified to the compiler; there is no trade-off in it.

    All string literals in C or C++ (e.g. "string literal") are read-only, and thus constant. When you say:

    char *s = "literal";
    

    You are in a sense downcasting the string to a non-const type. Nevertheless, you can't do away with the read-only attribute of the string: if you try to manipulate it, you'll be caught at run-time rather than at compile-time. (Which is actually a good reason to use const char * when assigning string literals to a variable of yours.)

  • It can't be relied on, it is an optimization which is not a part of any standard.

    I'd changed corresponding lines of your code to:

    const char* str0 = "Watchmen";
    const char* str1 = "atchmen";
    char* str2 = "tchmen";
    char* str3 = "chmen";
    

    The output for the -O0 optimization level is:

    0x8048830
    0x8048839
    0x8048841
    0x8048848
    

    But for the -O1 it's:

    0x80487c0
    0x80487c1
    0x80487c2
    0x80487c3
    

    As you can see GCC (v4.1.2) reused first string in all subsequent substrings. It's compiler choice how to arrange string constants in memory.

    Thomas L Holaday : +1 Nice experiment.
    Ashwin : I tried with g++ v4.3.2 on Cygwin, but am not seeing the behaviour where all the pointers are offset into the same string constant.
    Ashwin : It seems to be a problem with the platform. I tried it this time on Linux (instead of Cygwin) and saw the optimized behaviour. Thanks again for sharing this info :-)
  • You shouldn't count on that of course. An optimizer might do something tricky on you, and it should be allowed to do so.

    It is however very common. I remember back in '87 a classmate was using the DEC C compiler and had this weird bug where all his literal 3's got turned into 11's (numbers may have changed to protect the innocent). He even did a printf ("%d\n", 3) and it printed 11.

    He called me over because it was so weird (why does that make people think of me?), and after about 30 minutes of head scratching we found the cause. It was a line roughly like this:

    if (3 = x) then break;
    

    Note the single "=" character. Yes, that was a typo. The compiler had a wee bug and allowed this. The effect was to turn all his literal 3's in the entire program into whatever happened to be in x at the time.

    Anyway, its clear the C compiler was putting all literal 3's in the same place. If a C compiler back in the 80's was capable of doing this, it can't be too tough to do. I'd expect it to be very common.

    Peter : Wow--a DEC compiler in the mid-late '80s allowed assignments to literals?
    T.E.D. : I saw it happen. I wouldn't be surprised if there wasn't a patch the school hadn't taken or something.
    Ashwin : Thanks for sharing that tidbit from the past Ted. That was pretty cool! :-)

Is there a keyboard shortcut to toggle text size in IE8?

IE 6+ had the capability to hold ctrl + mousewheel to increase and decrease the text size on the page. However, now IE 8 has replaced that functionality with the widely accepted full page zoom +-. Has anyone found a keyboard shortcut that will just increase and decrease the text size again?

From stackoverflow
  • This isn't exactly a shortcut, but it can be accomplished from the keyboard.

    • ALT-V will bring up the View menu
    • "x" will bring up the Text size submenu
    • Up and down arrow keys choose the size
    • "Enter" selects.

    This works even if the menu bar isn't visible.

    Mister Lucky : thanks for the quick response, but hoping for something with far less keypresses.
    Andrew : Unfortunately, I'm pretty sure that's all you've got if you don't like the snazzy "full-page zoom" bug, er... I mean, feature.
  • Zoom:

    To increase:

    CTRL + "+"

    and

    To decrease

    CTRL + "-" or CTRL + "="

    Text size:

    alt + v

    x

    g or l or m or s or a

    Andrew : You just did the same thing I did. This does not work in IE8... like he says... in the question.
    thijs : I added keys to change the text size now, I jumped the gun before ;)

Solved: How to retrieve a user environment variable in CMake (Windows)

I know how to retrieve a normal machine wide environment variable in CMAKE using

$ENV{EnvironmentVariableName}

but I can not retrieve a user specific environment variable. Is it possible and how?

From stackoverflow
  • Ok, the CMake command as described works as it should. Even for user environment variables. I don´t know what I did wrong... ;)

Student projects: do they influence employment prospects?

I am a BSc student who is going to start the last year of my degree and I am wondering how relevant my final year project choice is going to be when looking for a job next year - and how it will affect what jobs will be open/closed to me when searching for my first programming/developer job.

I presently have a couple of options for my final year project/ dissertation:

  • Robotics/pattern recognition: one of my second year professors does research in Robotics/visual pattern recognition and has invited me to work with him during my final year project. It would be in Python as it has good APIs/libraries in this field.

  • A document repository system: with a database and some networked elements (client/server), probably using apache jackrabbit and java on the server and C#/WPF/.Net stack to develop the client. C# because bezier curves in WPF is a snap and I have a particular type of GUI in mind for the client component. This is my own idea/project.

The first one sounds the most fun and in all likelihood will be the one time that I am involved in real research (I am 35 and have a family). The second one sounds closer to what real-world development is. My past work experience did not involve programming, or IT.

All thoughts/comments are appreciated! Thanks, Luis

From stackoverflow
  • My thoughts:

    The robotics project will probably help you out if you specifically want to work in robotics after graduation.

    The document repository system will help you get a position just about everywhere else since it's using a combination of all the most popular current technologies (Java, C#, WPF).

    Now if only you could figure out a way to write a C#/WPF UI to interact with the robotics project then you'd be golden :).

  • I am heavily involved in hiring at our work, so I can give my point of view. When we hire people who have no previous work experience, we are looking at only their programming acumen. Any student projects in relevant technologies (for our companies) do, however, serve as a little bonus (if they can answer questions on the technology).

    I think you should do both if you can. One for your dissertation, and another one as a self project on the side (maybe with reduced scope) and include that on your resume as well.

    J.F. Sebastian : Thanks to you, I've learned a new word "acumen".
  • As someone who hires regularly (and our last two hires had just graduated), I'll say this: If it's a group project, it doesn't help because it's too hard to figure out who did what. If it's a singleton project and you can answer deep questions about it, it's certainly a plus.

    In fact, anything that shows initiative is a plus -- school projects, side projects, even extra-curricular stuff that has nothing to do with programming.

  • The specifics of the project would not be as relevant as how you present the project - an interviewer wouldn't know if you had a choice or what the other choices were.

    In an interview I would look for someone who can talk about the project enthusiastically and make it clear that they enjoyed the challenge and solving the problems rather than that they simply put something together in the quickest way possible.

  • I can honestly say my BSc project has had no relevance in my employment history, save for the effect it had on my final degree classification. The project itself got a relatively high mark, but in terms of functional code, there was actually very little. I wrote a good report, and developed a solid foundation for further progress, but that was about it. I'd suggest you pick the area you'll enjoy the most and simply have fun with it - I actually wish I'd done that myself.

  • When I finished my fourth year university project, I took a job with the external company which had been supervising the project. I think more than anything else, that's because I chose a project which I was interesting in, and hence I stayed motivated throughout it, meaning the supervisors saw me in a good light.

    I would worry more about picking a project which will keep your interest, and which you can do well rather than some 'employability' factor in the project.

  • If it sounds interesting (like AI) your interviewer might want to grill you about it out of curiosity. Cue 10 minutes of answering softball questions that you likely know the answer to rather than technical questions you might get caught up on.

  • As a student my self, take this with some salt.

    Heck Yah!!

    My school does large, industry sponsored senior projects. Students regularly get jobs directly from them. Several of the sponsors have said up front "This program is good for your job prospects at my company"

  • You have to make yourself (and your family) happy. So be comfortable with your choice

    I base these sorts of choices with what do I want to be doing in 2 and 5 years time. What will choices will help me, what choices will not...

    Good luck!

  • The student project can help you if any of these are true:

    • You can answer deep questions about it
    • It shows that you have expertise in technologies that matter to the group doing the hiring
    • You create good collateral (papers which get cited, for example) as a result of the project
    • You can use it to demonstrate that you can be productive, enthusiastic, and communicative

    Otherwise, it won't make any difference.

  • When interviewing programmers newly out of school, I am most impressed by completed projects, especially those completed at least partly outside of school. In my experience, there's a close correlation between the ability to see a personal project through to completion, and the ability to get work done independently on a large project.

    So to answer your question, for resume purposes I'd advise the pattern recognition project only if you're confident that the result will be something solid that you can show.

    That said, you should work on the project that's most interesting to you, no question.

  • GSOC is not a bad way to get some "resuméable" experience. Involvement in OS projects works well too. Anything where there's a community that can vouch for your (good) work. Another trick is to start answering technical questions on user groups, Stack Overflow, etc. It will take some time to build up an online rep, but once you have a history of taking initiative, helping others, etc., it will be a nice little boost when the reviewer performs the inevitable Google search. ... of course this does require a fairly unique name.

    Wahnfrieden : and requires using your real name on these sites. and a *very* unique name. otherwise im sure it will just be ignored.
  • Short answer to your title question: yes, but not always in the ways you might expect.

    Longer answer (which is strongly focused on my priorities - your mileage may vary with other people when they are on the other side of the table):

    I spent all of yesterday giving interviews and had plenty of time to think about my interviewing style and priorities.

    My interest areas have definitely expanded beyond a tiny set of technical buzzwords and "what code can you type for me and how quickly?" These days, I'm very interested in the person that you'll be one, two and three-plus years from now. As a result, I'm less interested in ensuring that you are buzzword-compliant with the work that we're doing today and much more interested in things like:

    1. Are you interesting to talk to?
    2. Have you done any work that is interesting to you? Can you make me interested in this work?
    3. Can we have a disagreement about the approach that you used? Can you convince me that your approach was the right one?
    4. Are you a quick thinker? Can you understand my explanation about our work and get to the point where we can have a discussion?

    So, getting back to your question, if we were having an interview, I wouldn't really care which particular technology you used on a project. I would care about whether you could explain the strengths and weaknesses of that technology, how it lead to the success or failure of the project and what you learned from the whole exercise.

.NET Control Events and Page Life Cycle

Here's the problem....I have three components...A Page that contains a User Control and a Server-side control which is in the user control. The user control has a handful of events that the page listens to which change what the server-side control does.

The server control essentially creates a TV-Guide looking list filled with many many smaller ASP.NET controls that need to have events. All of these controls are created dynamically (server side obviously). Populating this server side control requires operations that are intensive in nature and should therefore be only done once per postback. Event1 and Event2 fire and basically will change things about the serverside controls rendering (sorting, filtering etc) so when they fire I need to call PopulateControls for sure.

Here's the problem: I cannot find the best place to put the call to PopulateControls. If i put it in the PageLoad, it fires and draws the list before any events. Then my events have to call PopulateControls themselves to respond to the event. If i put the call in PreRender, the server-side control's events do not fire because from what i read, they need to be created before or during PageLoad.

So where do i put this call so that I only have to call it once and so that it can respond to the proper events?

Here's some psuedo code

public class MyPage : System.Web.UI.Page
{
    protected UserControl MyUserControl;

    // Wire up event handlers
    MyUserControl.Event1 += OnEvent1;
    MyUserControl.Event2 += OnEvent2;

    public Page_Load()
    {
    }

    public PreRender()
    {
        PopulateControls();
    }

    private PopulateControls()
    {
        // Do intensive operation to populate controls
    }

    protected OnEvent1()
    {
    }

    protected OnEvent2()
    {
    }
}
From stackoverflow
  • Child controls ought to be created in CreateChildControls, which is called in the "Init" phase of control life-cycle.

    cjserio : Agreed but that doesn't solve my problem. If i create them there, I'll have to RECREATE them again when my event fires later because the event changes what needs to be drawn.
  • The best place to call events that you want called before anything else occurs on your page, or any child controls, is in the PageInit stage.

    Here is a decent article that discusses the page life cycle with user controls: http://www.codeasp.net/articles/asp.net/20/aspnet-page-lifecycle

    cjserio : I'm not calling any events...The events are in response to something the user did...For instance, OnClicks etc. They are hit after Page_Load just by the nature of the way .NET works.
    AaronS : If I understand your question correctly, you want an event in your usercontrol to fire before anything else does. This would then trigger events in other places, like in your page. In this case, then you need to put your control binding logic in the PageInit of your control, not the page itself.
    cjserio : I'm confused...I don't think the order of events can be adjusted. See http://msdn.microsoft.com/en-us/library/ms178472.aspx. Control Events always occur after the Page_Load has already completed.
  • I might be missing something here, but I will take a crack at this anyway. You have to create the control hierarchy the same as it was on the inital rendering for you ids to match and allow your events to fire properly. It sounds like you need to do some reordering after an event fires so you will need to create the controls twice.

    Edit: You need to be able to recreate your controls and the control hierarchy on post back. You should send enough information to the client so that you can recreate the controls correctly on Postback. This can be done by saving information in ViewState if necessary.

    You should only recompute the control inforation when it is required. In your case because of some post back event.

    The basic flow should be like this. In you Load event, if you don't have the ViewState needed to create your controls, call your populate method, otherwise create them from ViewState. When a post back occurs, the Load event will create them, but they are being reconstructed from viewstate so this should be cheap. When the post back event fires, call you populate method to recreate the controls in the new order or with the new information, depending on what event happened.

    Whenever I am building a control I like to think about how the control will behave if a post back occurs from some other control on the page. Your control should continue to look the same unless affected by that post back and it should be able to be recreated without doing any data access, but from information it has collected on previous calls.

    I edited my answer and hopefully this is a littler clearer now.

Oracle + C# Picture

How can I insert Picture to Oracle DataBase Oracle ?

can I get C# sample code ?

thank's in advance

From stackoverflow
  • There is an article showing how to do it.

Does this function exist in PHP?

I found myself needing this function, and was wondering if it exists in PHP already.

/**
 * Truncates $str and returns it with $ending on the end, if $str is longer
 * than $limit characters
 *
 * @param string $str
 * @param int $length
 * @param string $ending
 * @return string
 */
function truncate_string($str, $length, $ending = "...")
{
    if (strlen($str) <= $length)
    {
     return $str;
    }
    return substr($str, 0, $length - strlen($ending)).$ending;
}

So if the limit is 40 and the string is "The quick fox jumped over the lazy brown dog", the output would be "The quick fox jumped over the lazy brow...". It seems like the sort of thing that would exist in PHP, so I was surprised when I couldn't find it.

From stackoverflow
  • No it does not exist. Many libraries provide it however as you're not the first to need it. e.g. Smarty

  • It doesn't.

  • $suffix = '...';
    $maxLength = 40;
    
    if(strlen($str) > $maxLength){
      $str = substr_replace($str, $suffix, $maxLength);
    }
    

    Your implementation may vary slightly depending on whether the suffix's length should be count towards the total string length.

    Jeremy DeGroot : That's no good because it appends the suffix to a string shorter than $maxLength.
    Ron DeVera : True, you'd still have to wrap it in your own function, which only runs substr_replace() based on that condition.
  • Here's the one line version for those interested

    <?php 
        echo (strlen($string) > 40 ? substr($string, 0, 37)."..." : $string);
    ?>
    
    Jeremy DeGroot : That was my first response, too. Subtract the length of your suffix from your string length though, or else you'll have a 43-character result
    TravisO : Good work but imho it's better to use easy to read code than ternary code, unless it's an extreme speed situation where you're looping this a million times.
    Ólafur Waage : Of course, i agree. Hence my wording for those interested.
    outis : The ternary operator doesn't give a speed advantage over an if-else block. The main advantage of ?: is that, unlike if-else, it is an expression and can be used where if-else is syntactically invalid.

What are ways to solve Memory Leaks in C#

I'm learning C#. From what I know, you have to set things up correctly to have the garbage collector actually delete everything as it should be. I'm looking for wisdom learned over the years from you, the intelligent.

I'm coming from a C++ background and am VERY used to code-smells and development patterns. I want to learn what code-smells are like in C#. Give me advice!

What are the best ways to get things deleted?

How can you figure out when you have "memory leaks"?


Edit: I am trying to develop a punch-list of "stuff to always do for memory management"


Thanks, so much.

From stackoverflow
  • What are the best ways to get things deleted?

    NOTE: the following works only for types containing unmanaged resources. It doesn't help with purely managed types.

    Probably the best method is to implement and follow the IDisposable pattern; and call the dispose method on all objects implementing it.

    The 'using' statement is your best friend. Loosely put, it will call dispose for you on objects implementing IDisposable.

  • C#, the .NET Framework uses Managed Memory and everything (but allocated unmanaged resources) is garbage collected.

    It is safe to assume that managed types are always garbage collected. That includes arrays, classes and structures. Feel free to do int[] stuff = new int[32]; and forget about it.

    If you open a file, database connection, or any other unmanaged resource in a class, implement the IDisposable interface and in your Dispose method de-allocate the unmanaged resource.

    Any class which implements IDisposable should be explicitly closed, or used in a (I think cool) Using block like;

    using (StreamReader reader = new StreamReader("myfile.txt"))
    {
       ... your code here
    }
    

    Here .NET will dispose reader when out of the { } scope.

    Marc Gravell : That "or" is confusing - even IDisposable objects are garbage collected. The GC knows nothing about IDisposable. Often Dispose() calls SuppressFinalize, but that is unrelated.
    Dead account : Good point. So the containing class is garbage collected, but it's resources are explicity deallocated. I never thought about that.
    Cecil Has a Name : "It is safe to assume that managed types are always garbage collected." This statement is so wrong. Nothing can be garbage collected if it can still be reached, the programmer must still always have in mind to nullify his/her root references when no longer needed.
  • The first thing with GC is that it is non-deterministic; if you want a resource cleaned up promptly, implement IDisposable and use using; that doesn't collect the managed memory, but can help a lot with unmanaged resources and onward chains.

    In particular, things to watch out for:

    • lots of pinning (places a lot of restrictions on what the GC can do)
    • lots of finalizers (you don't usually need them; slows down GC)
    • static events - easy way to keep a lot of large object graphs alive ;-p
    • events on an inexpensive long-life object, that can see an expensive object that should have been cleaned up
    • "captured variables" accidentally keeping graphs alive

    For investigating memory leaks... "SOS" is one of the easiest routes; you can use SOS to find all instances of a type, and what can see it, etc.

    Quibblesome : amen to static events being dangerous.
  • In general, the less you worry about memory allocation in C#, the better off you are. I would leave it to a profiler to tell me when I'm having issues with collection.

    You can't create memory leaks in C# in the same way as you do in C++. The garbage collector will always "have your back". What you can do is create objects and hold references to them even though you never use them. That's a code smell to look out for.

    Other than that:

    • Have some notion of how frequently collection will occur (for performance reasons)
    • Don't hold references to objects longer than you need
    • Dispose of objects that implement IDisposable as soon as you're done with them (use the using syntax)
    • Properly implement the IDisposable interface
  • You can use tools like CLR profiler it takes some time to learn how to use it correctly, but after all it is free. (It helped me several times to find my memory leakage)

  • The main sources of memory leaks I can think of are:

    • keeping references to objects you don't need any more (usually in some sort of collection) So here you need to remember that all things that you add to a collection that you have reference too will stay in memory.

    • Having circular references, e.g. having delegates registered with an event. So even though you explicitly don't reference an object, it can't get garbage collected because one of its methods is registered as a delegate with an event. In these cases you need to remember to remove the delegate before discarding the reference.

    • Interoperating with native code and failing to free it. Even if you use managed wrappers that implement finalizers, often the CLR doesn't clean them fast enough, because it doesn't understand the memory footprint. You should use the using(IDisposable ){} pattern
    Marc Gravell : "circular references" aren't the real issue - the problem is that one of the two items still *can* be validly seen, and the event is keeping the second object alive.
  • One other thing to consider for memory management is if you are implementing any Observer patterns and not disposing of the references correctly.

    For instance: Object A watches Object B Object B is disposed if the reference from A to B is not disposed of property the GC will not properyly dispose of the object. Becuase the event handler is still assigned the GC doesn't see it as a non utilized resource.

    If you have a small set of objects you're working with this may me irrelevant. However, if your working with thousands of objects this can cause a gradual increase in memory over the life of the application.

    There are some great memory management software applications to monitor what's going on with the heap of your application. I found great benefit from utilizing .Net Memory Profiler.

    HTH

  • I recommend using .NET Memory Profiler

    .NET Memory Profiler is a powerful tool for finding memory leaks and optimizing the memory usage in programs written in C#, VB.NET or any other .NET Language.

    .NET Memory Profiler will help you to:

    • View real-time memory and resource information
    • Easily identify memory leaks by collecting and comparing snapshots of .NET memory
    • Find instances that are not properly disposed
    • Get detailed information about unmanaged resource usage
    • Optimize memory usage
    • Investigate memory problems in production code
    • Perform automated memory testing
    • Retrieve information about native memory

    Take a look at their video tutorials:

    http://memprofiler.com/tutorials/

  • The best way to ensure that objects get deleted, or in .NET lingo, garbage-collected, is to ensure that all root references (references that can be traced through methods and objects to the first method on a thread's call stack) to an object are set to null.

    The GC cannot, and will not, collect an object if there are any rooted references to it, no matter whether it implements IDisposable or not.

    Circular references impose no penalty or possibility of memory leaks, as the GC marks which objects it has visited in the object graph. In the case of delegates or eventhandlers it may be common to forget to remove the reference in an event to a target method, so that the object that contains the target method can't be collected if the event is rooted.

  • Others have already mentioned the importance of IDisposable, and some of the things to watch out for in your code.

    I wanted to suggest some additional resources; I found the following invaluable when learning the details of .NET GC and how to trouble-shoot memory issues in .NET applications.

    CLR via C# by Jeffrey Richter is an excellent book. Worth the purchase price just for the chapter on GC and memory.

    This blog (by a Microsoft "ASP.NET Escalation Engineer") is often my go-to source for tips and tricks for using WinDbg, SOS, and for spotting certain types of memory leaks. Tess even designed .NET debugging demos/labs which will walk you through common memory issues and how to recognize and solve them.

    Debugging Tools for Windows (WinDbg, SOS, etc)

    Martin C. : Tess' blog is absolutely recommended for this topic, yes.

Why isn't keyword DateField.input_formats recognized in django 1.0.2 and Python 2.5?

With django 1.0.2 and Python 2.5, when I use the keyword DateField.input_formats, I get the error that __init__() got an unexpected keyword argument 'input_formats'. When I look in the __init__ file, I don't see input_formats as one of the acceptable keyword arguments.

I thought that input_formats had been around long enough that it should be in there. Is the input_formats keyword not supported in this configuration? If not, how can I acquire an updated __init__ that does support it? Thank you.

As suggested in the comment, I have added code below. I suspect the problem is that I am confusing the DateField form and DateField model, but I would be pleased if someone could confirm that.

from django.db import models

class Payment(models.Model):
    date_paid = models.DateField(blank=True, db_index=True, input_formats=['%m/%d/%y'])
From stackoverflow

GWT: How to avoiding calls to dynamicCast and canCastUnsafe in generated JavaScript code?

I'm writing some special purpose data structures in Java, intended for use in the browser, (compiled to JavaScript with GWT).

I'm trying to match the performance of some of the built-in JDK classes I'm noticing things run reasonably fast, but when I compare my code trace to some of the emulated JDK code, mine has lots of calls to dynamicCast and canCastUnsafe, while the JDK emulated classes do not. And it just about accounts for the difference in performance too...

Any GWT gurus out there know how to avoid this? It's amounting to a 20% overhead :-(

Details:

Here's the profile output (captured in Firebug) for 10,000 insertions of random integers, between 0 and 100,000 into two different data structures:

Google's TreeMap implementation for java.util.TreeMap (a red-black tree):

Profile (4058.602ms, 687545 calls)
Function              Calls      Percent   Own Time
$insert_1             129809     41.87%    1699.367ms
$compare_0            120290     16%        649.209ms
$isRed                231166     13.33%     540.838ms
compareTo_0           120290      8.96%     363.531ms
$put_2                 10000      6.02%     244.493ms
wrapArray              10000      3.46%     140.478ms
createFromSeed         10000      2.91%     118.038ms
$TreeMap$Node          10000      2.38%      96.706ms   
initDim                10000      1.92%      77.735ms   
initValues             10000      1.49%      60.319ms   
$rotateSingle           5990      0.73%      29.55ms  
TreeMap$Node           10000      0.47%      18.92ms

My Code (An AVL tree):

Profile (5397.686ms, 898603 calls)
Function              Calls      Percent   Own Time
$insert               120899     25.06%    1352.827ms
$compare              120899     17.94%      968.17ms
dynamicCast           120899     14.12%     762.307ms <--------
$balanceTree          120418     13.64%     736.096ms
$setHeight            126764      8.93%     482.018ms
compareTo_0           120899      7.76%     418.716ms
canCastUnsafe         120899      6.99%     377.518ms <--------
$put                   10000      2.59%     139.936ms
$AVLTreeMap$Node        9519      1.04%      56.403ms   
$moveLeft               2367      0.36%      19.602ms   
AVLTreeMap$State        9999      0.36%      19.429ms   
$moveRight              2378      0.34%      18.295ms   
AVLTreeMap$Node         9519      0.34%      18.252ms   
$swingRight             1605      0.26%      14.261ms   
$swingLeft              1539      0.26%      13.856ms

Additional observations:

  • Same problem for another data structure I made (SkipList).
  • dynamicCast is being applied in the compare function:

    cmp = dynamicCast(right.key, 4).compareTo$(key);

  • dynamicCast goes away if the class does not implement Map (ie: just removing " implements Map" from the class. Doesn't matter if it's accessed through the interface or directly. This results in the same line compiling to:

    cmp = right.key.compareTo$(key);

This is the relevant section of Java source from SkipList:

private int compare(Node a, Object o) {
    if (comparator != null)
        return comparator.compare((K) a.key, (K) o);

    return ((Comparable<K>) a.key).compareTo((K) o);
}

public V get(Object k) {
    K key = (K) k;
    Node<K, V> current = head;

    for (int i = head.height - 1; i >= 0; i--) {
        Node<K, V> right;

        while ((right = current.right[i]) != null) {
            int cmp = compare(right, key);

            ...
        }
    }
}
From stackoverflow
  • Does the use of java 1.5 generics and wildcards could avoid this ?

    Mark Renouf : Actually I think it should, but doesn't... from what I've found out, it seems to be a shortcoming of the compiler.
  • Dunno if you've seen this thread in the GWT Contributor's forum...

    Basically, it starts with the same problem you've identified, proposes some new compiler flags, and goes on to show how to use some JSNI to get around the casts.

    Edit In the GWT trunk there's a new compiler flag. See the wiki...

    Mark Renouf : Coincendence, I found that thread yesterday, and that was actually my JSNI workaround that I came up with yesterday.
  • Unfortunately I'm still not exactly clear on the cause, but from my experience, it seems from explicit casts, like:

    ((Comparable) obj).compareTo(other)
    

    The Javascript generated looks like:

    dynamicCast(obj, 1).compareTo(other);
    

    Where 1 is a generated typeId representing the target of the cast. dynamicCast in turn calls canCastUnsafe and if false, it throws a ClassCastException. The value of this has been debated, since this would already be caught in hosted mode.

    It can be sidestepped with JSNI:

    public static native int compare(Object a, Object b) /*-{
        return a.@java.lang.Comparable::compareTo(Ljava/lang/Object;)(b); 
    }-*/;