Thursday, May 5, 2011

IE8 issue: div breaks line even though its floated

This looks like IE8 issue. I have two divs that are side by side because I float one of them to left. However, if the content inside of right div gets too big for the window, the right div breaks line and goes under left div. How do I make both divs stay on same level, side by side?

Here is the code:

css:

    <style type="text/css">
    #left_div
    {
        float: left;
        width: 250px;
        height: 400px;
        border: solid 1px red;
    }
    #right_div
    {
        width: 3000px;
        border: solid 1px blue;
    }
</style>

html:

    <div id="left_div">
        text in left_div
    </div>
    <div id="right_div">
        text in right_div
    </div>
From stackoverflow
  • Add float: left to the right_div as well.

    If it is anything similar to the examples shown by Matthew James Taylor and his Perfect 2 Column Left Menu take a look at how he is doing it and maybe copy it!


    IE has in the past also had the issue that it took height and width to mean height-min and width-min, thus still allowing boxes to resize eventhough they had specific limits set. See Webcredible's article, most notably number 2 on their list!

    dev.e.loper : thank you. these are very helpful links!
  • You can also add a left margin of at least 250px (the width of the left_div) to the right_div, that way there will always be space for the left_div next to the right_div.

    dev.e.loper : that is not a problem. the problem is that in ie8, right div breaks line and goes under left div.
    jeroen : Maybe I am missing something here, but is that not normal behaviour for all browsers?
    dev.e.loper : not if you float one element to left.
  • change the doctype: (IE8 needs it to render correctly the webpage)

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd " >
    <html xmlns="h t t p://w w w.w3.org/1999/xhtml" xml:lang="en-GB">

    (I edited the urls with whitespaces so don't forget remove them :) )

Changing target directory for a pre-build command in VS 2005

I'm programming in VB using Visual Studio 2005 Professional.

I have a code munger perl script that generates some of the *.vb files that I want to compile. The script and the associated files are in my project directory, and when I run the script from the OS command prompt, it writes the files in the same directory, which is what I want.

Rather than do this, I want to invoke the perl script as a pre-build event. I've gotten it to work ... almost. The only issue now is that the files are now deposited in TargetDir (/bin/Release e.g.) instead of ProjectDir. I could just change TargetDir to be ProjectDir, but that seems like I'm asking for trouble.

Is there a way to separately specify the target directory for pre-build commands? Or change it to ProjectDir, then change it back after I'm done with the pre-build? Or maybe I just need to write a command that moves the files back where I want?

Thanks in advance!

From stackoverflow
  • You can simply prepend a cd command to your command:

    cd ProjectDir
    do_my_stuff
    

    Your custom build step will be written out as a batch file by Visual Studio and run with cmd.exe, so cd commands will work just fine.

    John at CashCommons : That did exactly what I need. Thank you!

Deitel Live Lessons C# 2008

Hi Everyone,

I've been trying to gain a better understanding of C# through books but I tend to learn things quicker with someone explaining them to me. Has anyone tried any of the Deitel live lessons DVD's, specifically the C# 2008 set? Just wondering if anyone has any opinions on them. Thanks!

Jon

From stackoverflow
  • I can really recommend the DVDs to you, i own them myself and they are really comprehensive and helped me understanding the fundamental principles of C# development when i was switching my preference from Delphi to C#.

  • Where do you get the DVD's? I'm looking on their site and I'm not seeing it.

    Jon : Amazon has the DVD's for a lot less than anywhere else I've seen.
  • I have some AppDev suites. I really like them. Any have both and can comment on the difference?

Memory leak in Eclipse RCP applications

How can the memory leak in Eclipse RCP applications detected?

From stackoverflow
  • You need some kind of profiling tool.

    There is a Memory Analyzer project at eclipse (wiki, blog).

    Also, it looks like TPTP also does profiling.

  • If you're on windows the simplest way is simply to monitor the e.g. eclipse.exe process in Task Manager while using the tool. If your RCP executable has a different name then this is what you'll need to monitor. On Unix you can use an analogous tool (proc maybe?).

    Perform the most intensive tasks available (or if you suspect certain functions cause the problem, use those). IF the amount of memory used by eclipse.exe rises does not eventually decrease after your intensive tasks have completed then you likely have a leak. This will eventually cause an out of memory error.

    You can accelerate an out of memory error by reducing the amount of memory available to the application via the "-Xmx" setting in eclipse.ini (or .ini). E.g. -Xmx256m means a maximum 256 megabytes is available. Obviously this setting still needs to be sufficient to run your app, but a lower setting will force more frequent garbage collection and make leaks more apparent.

  • You need a memory profiler (as others have mentioned.) Once you have a good tool, you can find the problems rather easily.

    We use: http://www.yourkit.com/

    for our testing, it works very well, has floating licenses so devs can use it locally on their machines.

    Basically, you take a snapshot of the actions that you are taking and then look at the items that were allocated and not released.

    Edit: I forgot to add, this tool integrates right into eclipse.

  • You might want try the Memory Leak Detector that comes with JRockit Mission Control together with Eclipse MAT. It's a powerful combination. Both tools are free to use for development.

    With JRockit Mission Control you can inspect the heap online and see the exact number objects of a certain type that are live, without the need to take time consuming snapshots. You can directly see if you got an an Editor, View or listener object left on the heap after you closed the View/Editor. It's usually a framework listener that holds on to your view/editor. Remember, you must go to Windows->Preferences->Memory Leak Detector->Trend and set Lowest Heap Usage to report to 0.0 to se all object instances.

    alt text

    With MAT you can then use the shortest path to thread root to find the chain that is holding on to the leaking object. See below

    alt text

    Modify your code and verify with the Memory Leak Detector that the object is garbage collected when you close the editor/view.

  • The simplest solution comes with Java JDK: Java VisualVM.

    It's located in the bin directory (jvisualvm.exe under Windows) since JDK 6 update 7.

    Also includes a memory profiler, a heap walker and an Eclipse integration.

    https://visualvm.dev.java.net/images/getstarted/vvm-anagram-profiler.png (too bad, I'm not allowed to use image tags)

    See https://visualvm.dev.java.net/

SQL Server: Retrieve auto-incremented ID inside a stored procedure?

My database has a parent table with an auto-incrementing primary key identity 'ID', and a normal 'TIMESTAMP column'. I have child tables with a foreign key that refer to the parent 'ID' column.

I want to write a stored procedure that inserts a new column into both the parent and child databases. How would I set the child 'ID' column to equal the new auto-incremented parent 'ID' column? Does this require a separate:

SELECT TOP 1 * FROM PARENT_TABLE

Or is there another way?

From stackoverflow
  • You can retrieve it from SCOPE_IDENITY(). For example:

    declare @myid int
    INSERT INTO table (field) VALUES ('value')
    SELECT @myid = SCOPE_IDENTITY()
    
  • select scope_identity();

Migrating Delphi App to Java or to Web App

We want to migrate UI rich application from delphi to java or Web Application.

Reason is that we want application to be portable on all Operating Systems.

Current Components and Modules of Application in Delphi :

  • In Delphi we are utilizing TWebBrowser component to display HTML content
  • We are playing mp3 that is extracted from FileStream on clicks in HTML.
  • All resources for HTML are retrieved from Embeded Database Firebird/Ms Access.
  • To sync some content we are doing HTTP post to PHP scripts to centralize the data on webserver.

Deployment: - Application has to be deployed on CD and installed on Desktop computer on Mac OS, Linux, Windows.

I need your help how to approach this migration. Is better to go with Java UI or Web App that will be deployed with WAMP/XAMP and appropriate distributions on Linux and Mac's.

EDIT: I have some specific requirements for audio functionality. Audio files are separate files distributed on CD or USB. Audio files are one solid file compiled from mp3's inside. Application will have to have ability to extract the mp3 based on offset and size of mp3 stored in index file and to play in real time... How this affects idea of Web App using this approach.

From stackoverflow
  • If I had to deploy on a CD, I'd probably go with Adobe's AIR. It is really fulfilling the promise Java made 10 years ago in a reasonable way. It isn't perfect, but it does a pretty good job.

    altCognito : +1 If it simply must be deployed locally, then AIR is really the way to go.
    Irfan Mulic : What do you mean it is not perfect? Look my latest EDIT regarding playing audio files from stream? How to do that in Air?
    Irfan Mulic : The reason for deploying locally is huge amount of audio data about 500 MB? If you wanna do that load from HTTP server locally still make sense but I am still not sure about the future architecture in this case...
    Travis Jensen : I'm not familiar with exactly how Air handles music streaming. Flex does support loading types from streamed data, but I don't know if you can give an offset and such. Perhaps understanding why you need to concatenate all the files into one big file would go further into helping build a solution.
  • I've heard this internet thing is really taking off.

    For all of the reasons that applications have gone online over the past 10 years, there really isn't much discussion to be had.

    While Java is reliable, distributing and rolling out subsequent updates to those applications is heavy and time consuming.

    I did Delphi development for over 9 years. I resisted the idea of distributing real applications over the web for quite some time. Today, I can't believe anyone would choose to continue in this way.

    One nice thing, you can probably reuse some of your Delphi logic on the backend if you get creative. (I would only recommend this for the short term)

    But, this answer doesn't really address your issue as you are saying that you must distribute it via CD.

    Chris Collins : How seamless would a migration from Delphi to Java be. I had the impression most Delphi migration is in the direction of .Net - that would solve the poster's cross-platform requirement but would it be a closer fit to the original source base?
    altCognito : Yeah, if you're looking to keep your original source code, .NET would be a better fit. I like the idea of doing AIR simply because it forces you to think to a day when you are simply running the application online.
    Irfan Mulic : .NET is probably the most easy way to do it but is not an option because of Linux and MAC OS.
  • The Java 6u10 release allows for distributing Java WebStart applications on media instead of from a Webserver, which might be exactly what you are looking for. You can also put the JRE installer for Windows on the CD too, if needed.

    What exactly are your requirements crossplatformwise?

    Irfan Mulic : I don't understand the question, I wanna solve the plaform constraints by moving application from Delphi to Java. Delphi only runs on Windows.
    Thorbjørn Ravn Andersen : Do you need to run a GUI client (difficult) or is it all being delivered through a browser(easier)? For embedded database, look at Apache Derby. For embeddable webserver look at Jetty.
  • If most of the application is HTML-based, why not make it a full web application, using Ajax and Java?

    I recommend NetBeans, and ICEFaces, which is a Java Server Faces implementation with Ajax support, including concurrent updates - if one user edits a record, all other users will see an update in their web page.

    It is possible to package the whole application in a single jar file, including the servlet container (Jetty for example), so a simple java -jar myapp.jar will run the application.

    NetBeans allows visual editing of the ICEFaces web pages, and even visual editing of the page relationships. The tutorials on NetBeans.org are excellent, and with tools like Maven, Hudson and others, code quality and development process can reach a very high level.

    Irfan Mulic : I like this approach. I have some specific requirements for audio part. Audio files are separate files distributed on CD or USB or whatever. Audio files are one solid file compiled from mp3's inside. Application will have to have ability to extract the mp3 based on offset and size of mp3 stored in index file and to play in real time... How this affects idea of Web app using this approach. Thanks.
    altCognito : Errr.... This is a bad reason to not make it a web application.
    mjustin : If it is a multimedia application, Suns new JavaFX client side technolgy might be an option for the user interface: http://en.wikipedia.org/wiki/JavaFX
  • If you have some Delphi application using Datasnap : you can also re use your server made in Delphi with Datasnap in Delphi Prism and make Silverlight application.

    And the same is true for DataAbstract

    Irfan Mulic : This is good idea but we don't wanna be dependent on Delphi platform anymore.
  • Why don't you give FreePascal a try? It uses the same language as Delphi, and can compile to a native application on Windows / Linux / Mac. Since you already have your app in Delphi, converting it shouldn't be too difficult.

    Have a look at the freepascal website

  • I suggest Air

How do I display the result of this query using Joomla pagination?

What can I do to display the result of this query in the fronted using the Joomla pagination?

<?php
  $database =& JFactory::getDBO();
  $sql = 'SELECT * FROM #__no_entreprise';
  $database->setQuery( $sql );
  $rows = $database->loadObjectList();
?
From stackoverflow
  • looking in the first result of google -> here

    Gabriel Sosa : btw, this was my query http://bit.ly/njOfI

How to show a loading graphic while a file is getting uploaded?

The file should be uploaded in the background via Ajax or Iframes. I should be able to detect via javascript when the upload has completed, so I can hide the loading graphic and redirect the user to a new URL. Using Jquery is fine.

From stackoverflow
  • Check out jQuery Uploadify

    EDIT: There's also a similar question: how-to-upload-file-jquery - you could display the graphic after the upload button has been clicked and hide in the success/onerror function callback.

    Click Upvote : I'm having troubles getting Uploadify to work with CodeIgniter. It always gives me an I/O error. Do you know how to make it work with Codeigniter?
    Jose Basilio : I have't used it with CodeIgniter, but there are some posts on that: http://codeigniter.com/forums/viewthread/109751/#554977
  • The jquery Form Plugin is capiable of doing Ajax upload (using an iframe i believe). It won't help you out directly with showing/hiding an loading image, but it has the appropriate events so you know when the upload starts and finishes.

NHibernate and multiple databases

I'm trying to solve pretty easy problem. I want to establish connection to 2 totally different databases ( but both mysql ). Now I tried to solve this by creating multiple config files and then creating multiple sessions. Everything works until I reached relations.

I have 2 tables in 2 databases:

db1 - News

db2 - News_Authors

I added News to db1 config and News_Authors to db2 config. When I try to build simple one-to-one relation error, I receive:

An association from the table songs refers to an unmapped class: db1.News_Authors

News.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="project.News, project" table="news" lazy="false">
    <id name="id" column="id" type="integer" length="11">
      <generator class="native" />
    </id>
    <property name="title" type="String" length="255" />
    <property name="authorid" type="integer" length="5" />

    <one-to-one name="NewsAuthor" cascade="all-delete-orphan" lazy="proxy" column="authorid" unique="true" />
  </class>     
</hibernate-mapping>

News_Authors.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="project.News_Authors, project" table="news_authors" lazy="false">
    <id name="id" column="id" type="integer" length="11">
      <generator class="native" />
    </id>
    <property name="name" type="String" length="255" />
  </class>     
</hibernate-mapping>

config I added this to enable mappings. Now If I set both in one config files, everything works...

<mapping resource="project.News.hbm.xml" assembly="project" />

So how could I during creating of session also "notify" nhibernate that I have multiple sessions? Or should I pick totally another approach?

From stackoverflow
  • What you are after is not multiple sessions but multiple session factories. See this for more details.

    The key here is that you don't have to initialize your session factory through config file - you can do it programatically. And it's just a step to have two session factories.

  • One other possible solution would be to create views in one of the sql server databases to reference the tables in the other. Views map just like tables and its easy to do a view that returns something like:

    select * from db2.News_Authors

    in the db1 database.

    this way you would only need a single .hbm.xml file that maps to one of the two databases.

    Hope this helps,

    -Max

System.Web.Script.Serialization.JavaScriptSerializer or System.Runtime.Serialization.Json.DataContractJsonSerializer?

What's the difference between the two? Why would you use one over the other?

From stackoverflow
  • The JavaScriptSerializer is marked as obsolete in framework 3.5. You shouldn't use it for that reason. However, back to your question. The JavaScriptSerializer doesn't require classes to be marked as [Serializable] or as [DataContract] but the DataContractJsonSerializer does. If you have compiled classes that you can't mark with attributes, you may want to use the older JSON serializer.

    Marc Gravell : Actually, it is unmarked again in 3.5 SP1
    W. Kevin Hazzard : Interesting, Marc. I didn't know that. Thanks for pointing that out.
  • Found here: http://aaron-powell.spaces.live.com/blog/cns!91A824220E2BF369!150.entry

    DataContractJsonSerializer The primary purpose of the DataContractJsonSerializer is to be used with WCF, since one serialization is a big focus of WCF. Also, it is also better equipped to handle complex classes which have only certain properties available for serialization. This class is more strongly typed, has more knowledge about the type(s) it's handling and better error handling for badly-formed JSON.

    JavaScriptSerializer This class on the other hand is much better equipped for quick serialization, it's a more cowboy approach. There's less error checking and less control over what properties which are serialized.

  • Personally, I'd look at Json.NET - this has the advantage of (for older versions at least) being .NET 2.0 compatible

    bdukes : JavaScriptSerializer is 2.0 compatible, too...
    Marc Gravell : Really? MSDN says 3.5...

SQL connection Issues.

We are having issues with our sql server. About two times a day we have to restart our server because SQL becomes unresponsive to our web applications. It doesn't look like we have a problem with to many connections, as there are never more then 20 active at a time. The weird thing is I can access sql from MS SQL Enterprise Manager 8.0 only. Connections from any other application (asp.net or SQL Server Management Studio 05) time-out. Querys work fine in enterprise manager, so i dont think its an issue with locks either. Any help is appreciated. Thanks

From stackoverflow
  • Are they the same two times every day?

  • I had a similar issue with MySQL previously where idle connections would get marked as stale and would time out and eventually I had to restart the application. Perhaps there is a configuration on your connection pool that can be used?

  • is it blocking? if you go the activity monitor (or whatever its called) you can see if any spids are blocked.

  • Some questions that might help someone help you:

    1. What version of SQL Server are you running?
    2. Is anything else running on the server box?
    3. You say you can't access it from certain clients - it times out. Do you mean it times out just connecting, or when executing queries?
    4. Does it behave the same across these apps on each client machine?
  • If SQL server itself sits idle and no blocking is noticed, then could be some network or firewall or antivirus issues? Or just server RAID array is dying.

    • Any environment changes, hardware or software?
    • What was the last change?

    Just a note from experience on network issues.. if network is failing, it can cause a build up of network connections, which you would only be able to see from performance counter in performance monitor (perfmon), so that would be the place that I'd look.

    If there are no environment changes, perhaps the database needs some good ol' maintenance, like consolidating tables and indexes, pushing logs to backup or purging them, and whatever DBA's do to clean up.

  • What happening whit RAM memory in that time. Maybe you ruining out with RAM

  • Are you looking at your SQL Logs to see if there is expansion or anything out of the ordinary occurring?

    Are you profiling to see what is running when it gets bogged down?

    Are you looking in the event logs on the box for abnormal activity?

    Are you restarting just SQL Server or restarting the entire box?

  • What does the SQL Server log say? If it is clean AND (you can connect to DB locally OR remotely) AND a reboot restores your app to a known state then it suggests a pooling problem and/or network problem

    We had a similar problem that was fixed for no stated reason by upgrading to latest service pack. Our problem manifested itself in the box keeping the underlying network connections open while the web app thought they were closed, so it would try to reinstate the pool and then run into max connections. Your question states you have not hit max connections but your symptoms are similar. Take a look at the network connections from the OS level. Some other things to consider...

    Can you connect from the same box that hosts your web apps, but using another client app, like Query Analyzer or even bcp or isql from the command line?

    Another thing to wonder: if you are able to connect from web app box, can you USE the db your app uses? If so can you do things once you are in there?

    What are the paramter settings for connection pool of web app? Have you tried adjusting these?

    good luck.

ByteArrayOutputStream to CharBuffer

I have an input ByteArrayOutputStream and need to convert that to a CharBuffer.

I was trying to avoid creating a new string. Is there anyway to do this.

I was trying to do the following, but I don't have the encoding for the string so the code below will not work (invalid output).

ByteBuffer byteBuffer = ByteBuffer.wrap(byteOutputStream.toByteArray());
CharBuffer document = byteBuffer.asCharBuffer();
From stackoverflow
  • You have to provide an encoding. How should the class know how to convert. Can't you determine the encoding before writing to a ByteOutputStream or avoiding the stream completely. If not you have to do assumptions and might fail

    Providing an encoding you can convert the byte buffer to a char buffer

    Charset charset = Charset.forName("ISO-8859-1");
    CharsetDecoder decoder = charset.newDecoder();
    CharBuffer charBuffer = decoder.decode(yourByteBuffer);
    
    Berlin Brown : I could set the encoding, but where do I set it to get a char buffer.
    Norbert Hartl : I edited the answer to show the conversion
  • ByteBuffer.asCharBuffer gives you a very literal two bytes to char (big or little endian) with updates reflected in both buffers.

    Presumably you want to go from bytes to chars through some reasonable encoding. There are many ways to do that. For instance [new String(byte[], String encoding)][1]. Mostly they will go through CharsetEncoder in some form. Then it should be straightforard to get a CharBuffer from there.

    CharBuffer is a quite low-level sort of thing. Are you sure that is really what you want?

    [1]: http://file:///C:/Users/tackline/sun/docs/api/java/lang/String.html#String(byte[], java.lang.String)

  • ByteBuffer.asCharBuffer() assumes that the bytes are UTF-16. (I can't find anything in the docs that says this explicitly, but the implementation just treats pairs of bytes as the low and high bytes of chars.) If you need another encoding you'll have to use a different approach.

    The simplest approach is to just create a String:

    CharBuffer document = CharBuffer.wrap(byteOutputStream.toString(encoding));
    

    I know you said you were "trying to avoid creating a new string", but your code snippet was allocating a separate byte array anyway (ByteArrayOutputStream.toByteArray() "Creates a newly allocated byte array" according to the docs). Because CharBuffer supports random access and many encodings (notably UTF-8) are variable-width, it's probably best to just convert the whole thing to chars upfront anyway.

    If you really just want streaming access (as opposed to random access) to the characters then perhaps CharBuffer isn't the best interface for the underlying code to accept.

    Berlin Brown : I went ahead and just used the string and scrapped the charbuffer. But, I liked what you did there. I forgot about the toString on byteoutputstream.
  • Charset charset = Charset.forName("ISO-8859-1"); CharsetDecoder decoder = charset.newDecoder(); CharBuffer charBuffer = decoder.decode(MyByteBuffer); system.out.println("string="+charBuffer.toString());

    on running this on console i am not getting String format output . i am getting output like

    þíþí clientdsakey1 +*

    please suggest why it is printing like this one....

Aggregate functions in ADO.NET with GROUP BY functionality

This is a more direct question stemming from an earlier more general question i had earlier now that I've spend more time looking into ADO.NET

I want to take an ADO.NET DataTable and perform the equivalent of a SQL SELECT query with aggregate functions (such as SUM) on some columns, and GROUP BY set for the remaining columns. I then want to take the result and display it in a DataGrid.

I understand that I can create a DataView of a DataTable that contains filter criteria and aggregate functions. But the MSDN page on Expressions say that

"If you use a single table to create an aggregate, there would be no group-by functionality. Instead, all rows would display the same value in the column."

How do I get GROUP BY type functionality out of ADO.NET without writing my Table to a separate database and running a query there? Is there some way to do it by creating or using a second table?

From stackoverflow
  • You can use the grouping ability of LINQ to accomplish this. Also, you can bind a DataGrid to a LINQ query, but the data will be read only.

    A web search for LINQ grouping should get you where you're going.

    Eric Anastas : Ahh I was thinking LINQ might be the answer. It's not a problem if the data is read only. Thanks!
  • One way around it, is to turn your linq query result into a DataTable using reflection. Here is an example. Once you have a DataTable, you will have full groupby, paging, etc...

        private static System.Data.DataTable ObjectArrayToDataTable(object[] data)
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            // if data is empty, return an empty table
            if (data.Length == 0) return dt;
    
            Type t = data[0].GetType();
            System.Reflection.PropertyInfo[] piList = t.GetProperties();
    
            foreach (System.Reflection.PropertyInfo p in piList)
            {
                dt.Columns.Add(new System.Data.DataColumn(p.Name, p.PropertyType));
            }
    
            object[] row = new object[piList.Length];
    
            foreach (object obj in data)
            {
                int i = 0;
                foreach (System.Reflection.PropertyInfo pi in piList)
                {
                    row[i++] = pi.GetValue(obj, null);
                }
                dt.Rows.Add(row);
            }
    
            return dt;
        }
    
        internal static DataTable GetAllStoredFileDetailsByUserID(int userID)
        {
            var db = GetDataContext();
            object[] result;
            try
            {
                result = (from files in db.Files
                          where files.OwnerUserID == userID && files.IsThumbnail == false
                          select new
                          {
                              FileID = files.FileID,
                              Name = files.Name,
                              DateCreated = files.DateCreated,
                              Size = files.Size,
                              FileHits = (from act in db.FileWebActivities where act.FileID == files.FileID select act).Count()
                          }).ToArray();
            }
            catch (Exception)
            {
               //omitted
            }
            return ObjectArrayToDataTable(result);
        }
    
  • i have the exact same question. however i am suing .net 2.0, so cant use LINQ..any other solution?

    Michael La Voie : If you have a question of your own, please delete this answer and ask a new question.
  • http://weblogs.asp.net/fmarguerie/archive/2007/09/05/linq-support-on-net-2-0.aspx

Why does my -scrollViewWillBeginDragging method of my UIScrollView delegate return such a strange contentOffset value?

PROBLEM SOLVED! STUPID TYPO IN MY CODE!

That's my method of my UIScrollView delegate:

- (void)scrollViewWillBeginDragging:(UIScrollView *)activeScrollView {
    NSLog(@"contentOffset: %f", activeScrollView.contentOffset);
}

Output in console is like:

2009-05-06 23:04:45.731 Demo[4851:20b] contentOffset: 21080643979530096233938944.000000

for sure my contentOffset isn't so huge ;)

From stackoverflow
  • Because contentOffset is a CGPoint.

    Thanks : Thanks! Damn, I really believed I had that .x there!! Thanks for that hint. What a stupid typo!
  • contentOffset returns a CGPoint struct, so you'd want to use activeScrollView.contentOffset.y instead of trying to pass the entire struct into %f, which is the format specifier for doubles.

  • use NSLog(@"ContenfOffset : %@", NSStringFromCGPoint(activeScrollView.contentOffset));

What's the difference between global variables and variables in main?

MyClass GlobalVar;

int main()
{
    MyClass VarInMain;
}
From stackoverflow
  • The variable VarInMain is a local variable and can only be used inside the function where it is declared, in your case, the main function. The GlobalVar can be used in every function of your program because it was declared outside of a function. This is called Scope.

  • Scope. VarInMain can be accessed directly only by code in main. GlobalVar can be accessed directly by code in any function in the file.

  • A couple of things:

    1. Typically, they're allocated in different places. Local variables are allocated on the stack, global variables are allocated elsewhere.
    2. Local variables in main are only visible within main. On the other hand, a global variable may be accessed anywhere.
  • globals can be used in functions declared outside of main, while anything declared in main, must be passed to another function first.

  • VarInMain is accessible only within the main() function. If main() calls another function, that function will not have access to it. This is function scope.

    GlobalVar is accessible in every function in the same file. If you put extern MyClass GlobalVar; in a header, then it can be used in any function in files which have or include that declaration. This is global scope.

  • A simple example:

    int y = 43;
    
    void foo() {
      // y is visible here, x is not
    }
    
    int main() {
      int x = 42;
      foo(); // x is visible here, but not when we enter the foo() function
    

    }

    A global variable is visible globally, across all functions. A local variable is visible in the scope in which it is declared only. if you declare a local variable inside main, it will be visible there, yes, but not in functions that are called from main.

  • More differences:

    1. If constructor/destructor of global object throws an exception, then function terminate is called and there is no chance to proceed. For local object, you can catch exception and do something (but it is still tricky to throw from destructor).
    2. Order of construction/destruction of global objects is not well specified. This means, that generally for two global objects you cannot say, which one is constructed first. From the other hand, local objects are created at point of defintion and destructed at end of block in order reverse to order of creation.
    3. Scope... (already mentioned)

    In general, it is not a good practice to use global objects without very strong reasons to do so. Using of globals often leads to code which is hard to maintain.

  • Another difference: the order of global object initilization is undefined. For example:

    static Integer Global_Integer(5);
    static Foo Global_Foo;
    

    As these are objects, the C++ runtime will call their constructors when initializing them, but we can't predict the order in which this will happen.

    Steve Jessop : They're initialized in the order they are declared (3.6.2:1), subject to the rule that all static initialization is done before any dynamic initialization. Anything initialized with a constant expression is static initialized, and the compiler may static-initialize some other things subject to certain rules. Initialization order is only undefined for globals declared in different compilation units and linked together.
  • Another one: The global variables (or variables in any other namespaces) are initialized to (T)0, with T being the type of the variable (in case it's a simple non-class type), arrays and classes are initialized like that for all their elements.

    But in my opinion, it's a good idea to explicitly initialize things anyway, and not rely on that zero initialization since it improves readability of the program when the initial value is explicitly mentioned. It's however still useful to know when reading someone else's code, always keeping in mind the compiler will initialize those automatically.

    The local variable when it is not declared static isn't automatically initialized. So you have to do any initialization on your own in case T has no constructor doing it for you. Always keep that in mind.

    Steve Jessop : initialized to T(0), or T()?
    Johannes Schaub - litb : all objects of static storage duration are zero-initialized prior to anything else, which is T(0) or (T)0 (0 converted to T) for scalar types. it's called zero-initialization. T() is value initialization and is different: It would yield the same value for scalars, but different values for non-Pods with user defined constructors. (zero initialization will initialize members to zero even for them and will not respect any constructor, because the whole purpose is to initialize everything to zero).
    Steve Jessop : Sorry, I mis-parsed your bracketed comment, and didn't realise that (T)0 only applied to non-class types and was therefore the same thing anyway...
    Johannes Schaub - litb : no worries :) hehe
  • Another difference: Global variables will be initialized before the program starts (i.e. main() gets called) whereas the local variables are initialized as execution reaches that point (i.e. just after main is called in the above example).

  • A global variable is accessible to any function. A variable in main acts exactly like any other local variable, and is only accessible to code in main. Also, if main (or another function) calls itself, the local variables will be copied, but global variables will not.

    int x = 0;
    void myfunction()
    {
        x++;
        printf("%i ",x);
    }
    int main()
    {
        myfunction();
        myfunction();
    }
    

    This example will output: 1 2

    Moving the "int x = 0;" into myfunction will output: 1 1

    Because the local variable gets initialised each time myfunction is called.

Preferred Python unit-testing framework

Hello,

So far I've been using the built-in unittest module for unit-testing Python code. However, for simple cases it seems like an overkill. Being a derivative of xUnit, it appears a bit heavy for the dynamic nature of Python, where I would expect to write less to achieve the same effects. On the other hand, it is built-in, makes you write your tests in an organized way, and tested by time.

The major alternatives I've seen online are:

Which of the frameworks do you prefer, and why ?

From stackoverflow
  • There's always doctest if you want to keep your unit tests close to the code.

    HTH

  • Regarding doctest: I don't consider it a unit-testing framework per-se. I definitely wouldn't use it to write a large suite of tests for a sizable application. doctest is more suitable for making sure that the examples you provide in the documentation work. It has its place for this need, but it isn't a competitor for unittest, py.test and other frameworks.

    S.Lott : This is part of your question. It's not an answer.
  • nose isn't really a unit testing framework. It's a test runner and a great one at that. It can run tests created using pyUnit, py.test or doctest.

    My preference for unit testing framework is pyUnit. It's similar to other xUnit frameworks and is easy to relate to for people without python background. There is also pretty good support for it in Eclipse/PyDev

    On py.test, I find multiple levels of setup/teardowns very confusing. I also find that it leads to highly unstructured and hard to read unit tests.

    doctest is OK for simple things, but I find that it's very limiting and doesn't really scale for complex and highly interactive code.

    Dave Cameron : Apparently the build-in unittest module is sometimes referred to as pyUnit: http://docs.python.org/library/unittest.html Are you referring to the build-in unittest module, or some other pyUnit?
    intuited : @Dave Cameron: I think he must be talking about the `unittest` module: google doesn't turn up any results for PyUnit that aren't actually the `unittest` module.
    hpk42 : funny enough, in 2010 the unittest2 and cpython-2.7's unittest have introduced the "multilevel" setup/teardowns you find confusing. (Being the original py.test author) I am now rather recommending more flexible ways to manage test resources and fixtures, aka "funcargs" :)
  • I just use the standard unittest. Not sure how you'd write tests as effectively with another style -- perhaps each test in a function, but then how would you handle setup / teardown?

  • The unittest.TestCase is a class. Feel free to subclass it with your own add-on features that allow you to "write less to achieve the same effects".

  • One of the nicest features of nose is its plugin system: for example the coverage plugin shows you how much of your code is covered by unittests. After writing lots of unittests it is often shocking to see how much of your code isn't covered ....

  • nose is not really a full unit testing framework in it's own right; however, it will run any function in a module whose name starts with "test" and it will fail if the function raises an AssertionError which makes writing simple tests really simple.

    It also has the concept of test generators which are a really nice implementation of data driven tests.

    ... and since nose will run unittest tests you can bail out to that when you need to write complicated setUp/tearDown tests.

    So: unittest + nose (+ doctest where appropriate) really is a pretty killer combination.

  • I agree that one nicest features of nose is its plugin system. For example, I started learning Python when the Google App Engine launched and there was a Nose plug-in to support GAE almost immediately. So Nose with its plugins helped me to start doing test-driven development with a new platform like GAE from the start. The coverage plugin was there when I was ready for it as well.

How to make model IDs in Rails unpredictable and random

I'm writing a rails app that, by its nature, CANNOT require users to register, and thus cannot use authentication as the usual means to protect records. (I know, I know...) User information here is limited to email addresses. So I do need a way to make my model IDs unpredictable so that other IDs cannot be easily guessed. (I know, I know...)

I have tried using plugins like uuidtools to randomize ids as records are created, like so:

require 'uuidtools'
class Post < ActiveRecord::Base 
 def before_create() 
  self.id = OpenSSL::Digest.SHA1.hexdigest(UUID.timestamp_create()) 
 end 
end

...This looks good at first, but funny things happen. ActiveRecord sometimes tries to insert a 0 value into the id and I get errors such as 'can't find Post with id=0' etc...

I've run out of ideas. Can anyone help? Thanks.

From stackoverflow
  • There's a plugin that should do what you want:

    http://codesnipers.com/?q=using-uuid-guid-as-primary-key-in-rails

    (All apologies to the SO censors for not pasting in the entire article. In my defense, it's loaded with links and formatting that would require quite a bit of effort to replicate. Not to mention that we'd be robbing the page's author of traffic and potential revenue.)

    drizzle : I don't hear anyone complaining about your link.
    tybro0103 : With this plugin, what happens when you create the model via a nested model form? I mean, if I have a create product form where you can add images as nested models will the images store the correct product_id?
  • An alternative is to generate a token or checksum or whatever in a second column during record creation, and in all cases your controllers query for an object, use Model.find_by_id_and_token.

    You'll then always generate URLs that contain and require both the id and token.

    Philip Hallstrom : The other reason to do it this way (adding a token/checksum) is that ActiveRecord is simply easier when the primary keys are integers -- as far as associations are concerned.
  • The thing that is going wrong here is that self.id requires an int and OpenSSL::Digest.SHA1.hexdigest(UUID.timestamp_create()) returns a string with non-numeric characters which would lead to the value '0' being actually stored in the database

Asp.NET / VB.NET: Getting the path from the URL / URI ?

Hello,

Say I have a project that I am deploying at

www.foo.com/path1/default.aspx

and

www.foo.com/path2/default.aspx

What would be the most reliable way to know if I was in the folder "path1", or "path2"? Can I grab that directly, or do I need to split() somehow on the Request.Url.AbsolutePath, or... ?

I just want to change colors, etc. based on which folder the user is in.

Thanks for any assistance!

From stackoverflow
  • If you want to code that logic directly into the page, then yeah, I'd go with split() on Request.Url.AbsolutePath.

    That said, I'd consider storing this kind of setting in the AppSettings section of web.config. That way if you decide to change the color in path2, you just need to edit the web.config for path2. If you need to add a new path, just deploy there and edit the web.config as appropriate.

  • yeah use Request.Url.AbsolutePath.

    i do it to create Breadcrumbs, using Split to split the URL, then in your case i suggest to use Switch statement to change color based on the case of the Switch statement

    here is a great article about Paths in ASP. http://www.west-wind.com/weblog/posts/269.aspx

  • Check out the MSDN docs on System.IO.Path. It contains a number of useful functions for dealing with path names. You can get GetDirectoryName() or GetFullPath() or GetFileName() or GetFileNameWithoutExtension().

IQueryable<> Serialization - C#-VS2008-WCF

I built my *.dbml file with the required tables and that generated the relationships, 1 to many.

One of my methods in my WCF Service library has this query

 IQueryable<Client>localClient = from c in db.Clients
              where c.ClientID.Equals(2612)
              select c;

 foreach(Client currentClient in localClient)
 {
    //Call serialize method here
 }

One of the table which client has a 1 to many relationships is Client - Employee

With 'localClient', I want to serialize that and return to the invoker. However it tells me that the the XML document could not be formed.

This is the InnerException: A circular reference was detected while serializing an object of type TestDB_Public.Employee.

My serialization code

    public string Serialize(object o, XmlSerializerNamespaces ns)
    {
        try
        {
            System.IO.MemoryStream m = new System.IO.MemoryStream();

            if (ns != null)
                serializer.Serialize(m, o, ns);
            else
                serializer.Serialize(m, o);

            m.Position = 0;
            byte[] b = new byte[m.Length];
            m.Read(b, 0, b.Length);

            return System.Text.UTF8Encoding.UTF8.GetString(b);
        }
        catch (Exception ex)
        {
            return "Ex = " + ex.ToString();
        }
    }

Is serialization of IQueryable<> with 1 to many relationships not possible?

From stackoverflow
  • What exactly is the error message? Note that you have to serialize something concrete like a list or array of objects (not a query).

    If you want queryable over the wire, look at ADO.NET Data Services, which does this.

    Also - have you set the serialization mode to "unidirectional" in the dbml designer? As long as there are no loops, it should work fine.

    Marc Gravell : The circular reference is the loop I was afraid of - for example, if an employee can see their manager, and the manager can see their subordinates, it gets into a state. However, you can enable the graph serialization mode of DataContractSerializer: http://chabster.blogspot.com/2008/02/wcf-cyclic-references-support.html or http://www.wearemappingyourdreams.com/andrew/ViewEntry.aspx?intLogId=1&intLogEntryId=622
  • Marc: For some reason it is not allowing me to add a comment;

    I added this

    [Table(Name="dbo.Client")]
    [DataContract(IsReference=true)]
    public partial class Client: INotifyPropertyChanging, INotifyPropertyChanged
    {
      ..//
      private EntitySet<ClEmp> _ClEmp;
    
      [Association(N...)]
      [DataMember(Order=70, EmitDefaultValue=false)]
      public EntitySet<ClEmp> ClEmps
    }
    

    My serialization is this:

    DataContractSerializer ser =
                        new DataContractSerializer(typeof(Client));
                    var ms = new System.IO.MemoryStream();
    
                    ser.WriteObject(ms, r);
    
                    ms.Seek(0, System.IO.SeekOrigin.Begin);
    
    
    
                    var sr = new System.IO.StreamReader(ms);
    
                    var xml = sr.ReadToEnd();
    

    when i look at var xml, i do not get my enity set ClEmp.

  • You can't serialise an object graph that has cyclical relationships:

    class Employee
    {
      Employee Manager;
      List<Employee> Employees;
    
    
    }
    
    
    var bossMan = new Employee();
    var emp2 = new Employee{Manager = bossMan}
    var bossMan.Employees.Add(emp2);
    

    If you now try to serialise bossman or emp2, you will get the exception.

    Have a look at this post, check the Cyclic Object Graphs for a solution.