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.