Thursday, March 31, 2011

assembly.GetExportedTypes() show different result

Why does assembly.GetExportedTypes() show different result in C# and VB.NET?

These two give different results

var v = from a in AppDomain.CurrentDomain.GetAssemblies() from b in a.GetExportedTypes() select b; 
v.Count(); 

Dim v = From a In AppDomain.CurrentDomain.GetAssemblies(), b In a.GetExportedTypes()     Select b v.Count()
From stackoverflow
  • When you compile a VB.NET assembly, it includes some extra "helper" types. Use Reflector to have a look at your compiled assembly to see what I mean.

    I'm pretty sure you'll find that the only assembly with any differences in is the one you're using to do the reflection - i.e. the one which is built with either C# or VB.NET, depending on your scenario.

    EDIT: It depends on exactly how you define your classes.

    However, again this is only relevant to the code being compiled by the C# or VB compiler. When you call GetExportedTypes it doesn't matter what language you're calling from. You're getting confused by the fact that you're only writing out the total count. Here are two short but complete programs to show the difference:

    C#

    using System;
    using System.Reflection;
    
    public class ShowTypeCounts
    {
        static void Main()
        {
            AppDomain domain = AppDomain.CurrentDomain;
            foreach (Assembly assembly in domain.GetAssemblies())
            {
                Console.WriteLine("{0}: {1}",
                                  assembly.GetName().Name,
                                  assembly.GetExportedTypes().Length);
            }
        }
    }
    

    Results:

    mscorlib: 1282
    ShowTypeCounts: 1
    

    VB

    Imports System
    Imports System.Reflection
    
    Public Module ShowCounts
    
        Sub Main()
            Dim domain As AppDomain = AppDomain.CurrentDomain
    
            For Each assembly As Assembly in domain.GetAssemblies
    
                Console.WriteLine("{0}: {1}", _
                                  assembly.GetName.Name, _
                                  assembly.GetExportedTypes.Length)
    
            Next
        End Sub
    
    End Module
    

    Results:

    mscorlib: 1282
    ShowTypeCounts: 1
    

    As you can see, the results are the same - but if you remove "public" from either piece of code, the ShowTypeCounts result goes down to 0. This isn't a difference of how GetExportedTypes works between languages - it just depends on what types you're actually exporting.

    My guess is that in your console apps, one had a public type and the other didn't.

    Jon Skeet : Yes, one of the assemblies that's being reflected into *is* that console app though.

What can cause a UIView to be arbitrarily removed from the hierarchy?

I have an iPhone app that, for some users, sometimes behaves as if with the main UIView has been removed from the view hierarchy. It always happens coincident with a significant event in the game. Other Core Graphics-drawn UIViews that are above it in the z-order remain, but the main one (an OpenGL view) appears to be gone, leaving the background (a solid color).

The app does not crash (it keeps running, without the view), and this seems to happen very consistently for affected users. Unfortunately I am not able to reproduce it.

I suspect a memory issue -- that would be the easiest explanation -- but based on my reading it looks like didReceiveMemoryWarning only deallocs views that aren't visible, and aside from that the memory usage for my app is pretty small. Also, the "significant event" only results in OpenGL drawing and a SoundEngine call -- no view manipulation.

Anybody out there seen something like this before?

From stackoverflow
  • Yes, infact one of my applications very occasionally exhibits this problem and it does seem to be memory related.

    I have had no success tracking it down either by debugging or analyzing the program flow. I have verified that the view in question is destroyed and not just hidden in some way.

    It happens so infrequently that I haven't looked into it to deeply, but I do think it's caused by something in the OS in some way,

    Adam Preble : Check out my self-supplied answer below; it may help your app too.
  • As is made clear in the SDK documentation, when your app is running low on memory, views that are not in use can be collected. When it's needed again, it's re-created. This is to conserve precious iPhone resources. Your best bet is to retain the view so it can't be released.

    Andrew Grant : If the view in question is visible it's a pretty good bet that it's "in use"
    Adam Preble : August - Thanks for your attempt to help, but please read my question carefully. As Andrew points out the view in question is in use.
  • You can easily test low memory in the simulator to debug this problem if it is memory related.

    Adam Preble : True; unfortunately it does not reproduce the problem (or appear to have any effect on the app).
    Andrew Grant : All the simulator does is call the low memory methods on your classes. It does not simulate the OS running low on resources. Sadly there's a number of reasons it's called a simulator and not an eumlator.
  • The problem ended up being an uncaught NSException (from a third party library) thrown in the app's timer thread, which killed the timer thread but not the rest of the app. The good news is that crash reports are generated in this case, which can make tracking it down much easier if you know to look/ask for them.

Java (ME) on Windows Mobile

Does anyone have experience deploying Java ME apps to Windows Mobile? What are the high-level steps to getting started with this, and are there any major drawbacks?

From stackoverflow
  • Just beginning with the Samsung i900. FileConnection seems all bad with no obvious access to the internal hard drive or the memory card. Worried about the Applix jBlend base port.

    I hope others have a better experience of java on windows mobile.

  • Well at first you need to install a JVM on your device (if one isn't already installed). There are currently two players for this:

    • NSI Creme. This is a robust product but it only supports CDC profile (no MIDlets) and you need to buy a license for at least 1000 devices or so.
    • IBM J9. This has CLCD support and can run MIDlets. There is a demo version, but I wasn't able to find a download link. May be IBM has stopped supporting it.

    Some devices have a JVM pre-installed, but it is difficult to rely on certain profiles being present. Unless you are targeting a single device, I would say that is better to avoid J2ME for Windows Mobile.

  • kgiannakakis is right with the JavaVM that needs to be installed on Windows Mobile devices, but this only counts for older devices. Windows Mobile 5 and 6 come with a pre-installed Microsoft Java VM which works. Basically.

    You can actually just compile your J2ME application to a jar file, copy it on your Windows Mobile device and start it. That's pretty much it.

    As with all generic JavaME VM's you will not be able to access internal API's / hardware which is not accessible from within the standard CLDC/MIDP libraries the JavaVM you are using, supports.

.htaccess with or without slash

What do I need to do to the following rewrite rule to make it so it works whether or not their is a slash at the end of the URL?

ie. http://mydomain.com/content/featured or http://mydomain.com/content/featured/

RewriteRule ^content/featured/ /content/today.html
From stackoverflow
  • Use the $ to mark the end of the string and the ? to mark the preceding expression to be repeated zero or one times:

    RewriteRule ^content/featured/?$ content/today.html
    

    But I recommend you to stick to one notation and correct misspelled:

    # remove trailing slashes
    RewriteRule (.*)/$ $1 [L,R=301]
    
    # add trailing slashes
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule .*[^/]$ $0/ [L,R=301]
    
    Unkwntech : +1 mostly for the additional info, although I was gonna' give it to you anyway.

If I want to rebase my DLL's, how do I go about doing it?

This is a continuation of this question.

I'm in the process of testing whether rebasing the .NET DLLs, and NGENning them will provide me with more shared code in memory on terminal servers.

However, my plan seems to have a flaw, and it's that I seem unable to find a working method to figure out a working set of addresses.

What I thought I could do was as follows:

  1. Just build and NGEN everything
  2. Start the program, ensuring all the DLL's have been loaded
  3. Use LISTDLLS /R PROGRAMNAME to get a list of current in-use addresses for the running instance
  4. Use the addresses of those DLL's that was remapped as the new base-address for those dll's
  5. UN-NGEN everything, and start back at 1

However, this has turned into a Schrödinger exercise because the act of rebasing some DLLs apparently either change the load order or how the operating system relocates other DLLs.

For instance, let's say that after the initial run I have a list that says that DLLs A, B and C needs to be at address 1000, 2000 and 3000. There's no mention of DLL D, E and F, which are also part of the same system. Presumably these were loaded at their current baseaddress, otherwise I would assume LISTDLLS would tell me about that.

So I change the address of A, B, C, repeat everything, and now DLL C, D and E have been relocated. A and B are now OK, E and F now became relocated, and C is still being shuffled around.

I realize that this exercise is somewhat a futile one, since regardless of what I figure out on my machine, DLLs being used and injected on the target terminal server might disturb this picture but I thought that if I could at least make sure some of the DLLs could be located at their prescribed base address then the amount of shared code between multiple instances of the same program would go up. Just saying, just so that there is no need to "remind" me of that :)

Since the original base addresses of all our DLLs was the default, which meant every DLL (possibly except the first one loaded) was relocated, and thus mapped to the page file, I would think that there would be a potential gain above 0.

Any advice?

From stackoverflow
  • You can find out a DLLs preferred loading address and memory ranges using DUMPBIN (comes within Visual Studio) and do your planning based on those numbers.

    dumpbin /headers would give you:

     7DC90000 image base (7DC90000 to 7DD5FFFF)
    

    If you plan according to preferred loading addresses you should have no problems.

How to detect memory leak / battery drain in an iPhone app

I'm afraid I introduced a memory leak or something to version 1.2 of my iPhone app. When I use 1.2 version I notice that my battery drains a lot quicker then with 1.1 version. For comparison, with 1.1 version the battery would last whole day and still have plenty of juice in the evening but with 1.2 I find that I have to plug it in mid afternoon.

Would a memory leak (or a lot of them) cause an increased battery drainage, or do I have something else going on?

The only interesting thing my app uses is AVAudioPlayer class to play some caf audio files. Other than that it's just couple of views with a table view.

I do call AudioSessionSetAcvie(false) in my applicationWillTerminate method, so I don't think it's the audio session that's causing this. I don't have to have my app active for the battery to get drained. It's enough to use it for a while and then exit. So I'm pretty sure I'm leaving something behind, I'm just not sure what.

I tried playing with Instruments tool, but it looks like you can't used with the app running on the device (for some reason my app stopped working in the Simulator)

Any ideas on how to go about finding what's causing the battery to drain?

From stackoverflow
  • Memory leaks will not cause increased battery usage. However, if a memory leak persists, eventually you will get a memory warning, and if you can't clean up enough memory, your application will be killed.

    Increased battery utilization usually means something is causing your code to continue running. The best way to tackle this problem is to run your application under Instruments (with Sampler probably) and let it sit there in the state that you're confident it usually runs the battery down. Inspect the results of Sampler, and if you have code running, you'll be able to see the stack trace for it.

    Hopefully once you've located what code is running, it will become apparent how to stop it.

    subjective-c : I notice the battery draining even when my app is not running. So is it possible that some parts of my app are still executing even when I exit my app?
    NilObject : I highly doubt it. So you're noticing a faster battery drain when comparing a freshly booted phone to a freshly booted phone after quitting your application?
    subjective-c : Right. But I don't have any hard evidence, just my observation. I'm beginning to think now that it's not related to my app.
  • Memory leaks won't cause increased battery usage, as Nilobject says.

    I would try commenting out various areas of functionality, one at a time, to try to narrow down the area that is causing the problem. In your case, the first thing to try is obviously to remove the audio. If, once you've done that, battery usage is back to normal, you know where to look more deeply.

  • (for some reason my app stopped working in the Simulator)

    I would fix that and use instruments to fix the performance bug. It's never a good idea to fix the difficult defect and leave the easy one.

    subjective-c : I don't really feel like spending time debugging Apple's Simulator. The damned thing never really worked well for me, so I stopped using it. I develope with iPhone connected.

NSData - Which is better in terms of memory usage: initWithContentsOfURL or NSURLConnection

Hi

I want to get an NSData object's contents from a URL. What is the more efficient way of doing this in terms of memory usage dataWithContentsOfURL (or initWithContentsOfURL) or using NSURLConnection?

Should I use

NSData *data = [[NSData alloc] initWithContentsOfURL:myURL]

or

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
From stackoverflow
  • Pretty sure they are quite equivalent.

  • I don't know the internals of Apple's code but I would guess NSData's initWithContents of URL uses NSURLConnection internally. Memory usage differences will be negligible.

    Using the asynchronous apis of NSURLConnection would allow you to be more memory efficient by handling data as it came in but (without knowing what you are actually doing) I think this is a fairly agressive optimisation that you should leave until you have working code.

What is the best way to clean a string for placement in a URL, like the question name on SO?

I'm looking to create a URL string like the one SO uses for the links to the questions. I am not looking at rewriting the url (mod_rewrite). I am looking at generating the link on the page.

Example: The question name is:

Is it better to use ob_get_contents() or $text .= ‘test’;

The URL ends up being:

http://stackoverflow.com/questions/292068/is-it-better-to-use-obgetcontents-or-text-test

The part I'm interested in is:

is-it-better-to-use-obgetcontents-or-text-test

So basically I'm looking to clean out anything that is not alphanumeric while still keeping the URL readable. I have the following created, but I'm not sure if it's the best way or if it covers all the possibilities:

$str = urlencode(
    strtolower(
    str_replace('--', '-', 
    preg_replace(array('/[^a-z0-9 ]/i', '/[^a-z0-9]/i'), array('', '-'), 
    trim($urlPart)))));

So basically:

  1. trim
  2. replace any non alphanumeric plus the space with nothing
  3. then replace everything not alphanumeric with a dash
  4. replace -- with -.
  5. strtolower()
  6. urlencode() -- probably not needed, but just for good measure.
From stackoverflow
  • As you pointed out already, urlencode() is not needed in this case and neither is trim(). If I understand correctly, step 4 is to avoid multiple dashes in a row, but it will not prevent more than two dashes. On the other hand, dashes connecting two words (like in "large-scale") will be removed by your solution while they seem to be preserved on SO.

    I'm not sure that this is really the best way to do it, but here's my suggestion:

    $str = strtolower( 
      preg_replace( array('/[^a-z0-9\- ]/i', '/[ \-]+/'), array('', '-'), 
      $urlPart ) );
    

    So:

    1. remove any character that is neither space, dash, nor alphanumeric
    2. replace any consecutive number of spaces or dashes with a single dash
    3. strtolower()
    Darryl Hein : I would still do the trim() because of possible extra spaces.
    cg : Yes, you're probably right. You wouldn't want a leading or trailing dash. Thanks for accepting my answer anyway.
  • Duplicatehttp://stackoverflow.com/questions/465659/how-can-i-create-a-seo-friendly-dash-delimited-url-from-a-string

    Darryl Hein : Similar yes, except that the accepted answer is C# and the PHP answer is quite long and clumbersome. +1 for finding the question.
    Gumbo : There were no restrictions in language. And the “C#” thing was just the example string that should be formatted.

Solving nonlinear equations numerically

Hello,

I need to solve nonlinear minimization (least residual squares of N unknowns) problems in my Java program. The usual way to solve these is the Levenberg-Marquardt algorithm. I have a couple of questions

  • Does anybody have experience on the different LM implementations available? There exist slightly different flavors of LM, and I've heard that the exact implementation of the algorithm has a major effect on the its numerical stability. My functions are pretty well-behaved so this will probably not be a problem, but of course I'd like to choose one of the better alternatives. Here are some alternatives I've found:

  • Are there any commonly used heuristics to do the initial guess that LM requires?

  • In my application I need to set some constraints on the solution, but luckily they are simple: I just require that the solutions (in order to be physical solutions) are nonnegative. Slightly negative solutions are result of measurement inaccuracies in the data, and should obviously be zero. I was thinking to use "regular" LM but iterate so that if some of the unknowns becomes negative, I set it to zero and resolve the rest from that. Real mathematicians will probably laugh at me, but do you think that this could work?

Thanks for any opinions!

Update: This is not rocket science, the number of parameters to solve (N) is at most 5 and the data sets are barely big enough to make solving possible, so I believe Java is quite efficient enough to solve this. And I believe that this problem has been solved numerous times by clever applied mathematicians, so I'm just looking for some ready solution rather than cooking my own. E.g. Scipy.optimize.minpack.leastsq would probably be fine if it was pure Python..

From stackoverflow
  • I haven't actually used any of those Java libraries so take this with a grain of salt: based on the backends I would probably look at JLAPACK first. I believe LAPACK is the backend of Numpy, which is essentially the standard for doing linear algebra/mathematical manipulations in Python. At least, you definitely should use a well-optimized C or Fortran library rather than pure Java, because for large data sets these kinds of tasks can become extremely time-consuming.

    For creating the initial guess, it really depends on what kind of function you're trying to fit (and what kind of data you have). Basically, just look for some relatively quick (probably O(N) or better) computation that will give an approximate value for the parameter you want. (I recently did this with a Gaussian distribution in Numpy and I estimated the mean as just average(values, weights = counts) - that is, a weighted average of the counts in the histogram, which was the true mean of the data set. It wasn't the exact center of the peak I was looking for, but it got close enough, and the algorithm went the rest of the way.)

    As for keeping the constraints positive, your method seems reasonable. Since you're writing a program to do the work, maybe just make a boolean flag that lets you easily enable or disable the "force-non-negative" behavior, and run it both ways for comparison. Only if you get a large discrepancy (or if one version of the algorithm takes unreasonably long), it might be something to worry about. (And REAL mathematicians would do least-squares minimization analytically, from scratch ;-P so I think you're the one who can laugh at them.... kidding. Maybe.)

  • The closer your initial guess is to the solution, the faster you'll converge.

    You said it was a non-linear problem. You can do a least squares solution that's linearized. Maybe you can use that solution as a first guess. A few non-linear iterations will tell you something about how good or bad an assumption that is.

    Another idea would be trying another optimization algorithm. Genetic and ant colony algorithms can be a good choice if you can run them on many CPUs. They also don't require continuous derivatives, so they're nice if you have discrete, discontinuous data.

  • You should not use an unconstrained solver if your problem has constraints. For instance if know that some of your variables must be nonnegative you should tell this to your solver.

    If you are happy to use Scipy, I would recommend scipy.optimize.fmin_l_bfgs_b You can place simple bounds on your variables with L-BFGS-B.

    Note that L-BFGS-B takes a general nonlinear objective function, not just a nonlinear least-squares problem.

  • The FPL package is quite reliable but has a few quirks (array access starts at 1) due to its very literal interpretation of the old fortran code. The LM method itself is quite reliable if your function is well behaved. A simple way to force non-negative constraints is to use the square of parameters instead of the parameters directly. This can introduce spurious solutions but for simple models, these solutions are easy to screen out.

    There is code available for a "constrained" LM method. Look here http://www.physics.wisc.edu/~craigm/idl/fitting.html for mpfit. There is a python (relies on Numeric unfortunately) and a C version. The LM method is around 1500 lines of code, so you might be inclined to port the C to Java. In fact, the "constrained" LM method is not much different than the method you envisioned. In mpfit, the code adjusts the step size relative to bounds on the variables. I've had good results with mpfit as well.

    I don't have that much experience with BFGS, but the code is much more complex and I've never been clear on the licensing of the code.

    Good luck.

UrlRewriter+HttpModule+Session problem

I need to write a custom "UrlRewriter" using a HttpModule, in the moment of "rewriting" I need access to the Session and has followed the advice from another SO thread:

http://stackoverflow.com/questions/276355/can-i-access-session-state-from-an-httpmodule

Everything works, except the RewritePath/Redirect part. I don't get any exceptions, but the browser takes forever to load. Is this really the best way to build a urlrewriter like this?

using System;
using System.Web;
using System.Web.SessionState;
using System.Diagnostics;

namespace MyCompany.Campaigns
{

    public class CampaignRewriteModule : IHttpModule
    {
        public void Init(HttpApplication application)
        {
            application.PostAcquireRequestState += new EventHandler(Application_PostAcquireRequestState);
            application.PostMapRequestHandler += new EventHandler(Application_PostMapRequestHandler);
        }

        void Application_PostMapRequestHandler(object source, EventArgs e)
        {
            HttpApplication app = (HttpApplication)source;

            if (app.Context.Handler is IReadOnlySessionState || app.Context.Handler is IRequiresSessionState)
            {
                return;
            }

            app.Context.Handler = new MyHttpHandler(app.Context.Handler);
        }

        void Application_PostAcquireRequestState(object source, EventArgs e)
        {
            HttpApplication app = (HttpApplication)source;

            MyHttpHandler resourceHttpHandler = HttpContext.Current.Handler as MyHttpHandler;

            if (resourceHttpHandler != null)
            {
                HttpContext.Current.Handler = resourceHttpHandler.OriginalHandler;
            }

            Debug.Assert(app.Session != null);


            string path = HttpUtils.Path();

            if (!CampaignCodeMethods.IsValidCampaignCode(path)) return;

            string domain = HttpUtils.Domain();

            CampaignCode code = CampaignManager.RegisterCode(path, domain.Equals(Config.Instance.Domain.ToLower()) ? null : domain);

            if (code != null)
            {
               //app.Context.RewritePath(code.CampaignCodePath.Path, false);
               app.Context.Response.Redirect(code.CampaignCodePath.Path, true);
            }


        }

        public void Dispose() { }

        public class MyHttpHandler : IHttpHandler, IRequiresSessionState
        {
            internal readonly IHttpHandler OriginalHandler;

            public MyHttpHandler(IHttpHandler originalHandler)
            {
                OriginalHandler = originalHandler;
            }

            public void ProcessRequest(HttpContext context)
            {
                throw new InvalidOperationException("MyHttpHandler cannot process requests.");
            }

            public bool IsReusable
            {
                get { return false; }
            }
        }

    }

}
From stackoverflow
  • I'm thinking the problem may be inside this block:

    if (code != null)
    {
        //app.Context.RewritePath(code.CampaignCodePath.Path, false);
        app.Context.Response.Redirect(code.CampaignCodePath.Path, true);
    }
    

    Try putting a breakpoint in the if statement and see if continually gets hit.

  • Is your URL rewriter handling requests that aren't for an actual page? If they are, then I don't think you can access Session... the last URL rewriter that I had written was there to handle 404 errors, and I remember digging around and finding (somewhere, can't remember where) that you don't get access to Session if that request is not for an actual .aspx page.

  • I think there should be a call to 'return' after you reset it to the original handler, else you will continually rewrite the path.

    Thinking about it, that's probably why the page is loading forever! :)

  • I wrote a simple URL rewriter module that did something similar. The url rewriting is done in BeginRequest by comparing the requested url to a list of known urls. If we find a mach we use HttpContext.RewritePath to change the requested url.

    This appears to work well with no serious side effects.

    I notice that you use Response.Redirect instead of Context.RewritePath. Using Redirect will cause the users browser to request a new page with the new url. Is this really what you want? The user will then see the new url in his browser. If this really is what you want you could use an alternative approach where you use a custom 404 page not found error handler to redirect the user to the appropriate page.

    If you set up IIS to redirect all 404 errors to a new page, say Custom404.aspx, that you have set up. In this page you can check the requested url to see if the url should be rewritten. If it should you can simply set the Response.Status to "301 Moved Permanently" and write a header with the name "Location" and the new url as the value. If the url should not be rewritten you can just output the standard 404 page not found error.

    This last approach works well, but as with your Response.Redirect approach the user will see the new url in his browser. Using Context.RewritePath allows you to serve a different page than the one requested.

  • I think I know what it is. Your module is executed on ALL requests and assigns a handler that throws an error unless there is a valid campaign code (where a rewrite/redirect occurs).

    But because this is not just for your "handler campaign code" url it is causing an error to be thrown, which is causing you to be redirected to your error page, which is being caught by the module, which is assigning the handler, which is throwing an error, which is redirecting... I think you get where I'm going ;)

    Otherwise I'd try a few things:

    • Setup Fiddler and check for an infinite redirect loop
    • Put a breakpoint on app.Context.Response.Redirect - make sure your not in an infinite loop
    • Put a breakpoint on MyHttpHandler.ProcessRequest - make sure it's not being called and the exception swallowed

Why main() in java is void?

In case any C syntax like languages we specify the main() method should return anything int, float, void also. But in java can we do so? If not then why only void is used for main() method. Does it mean any java program doen't return anything to OS?

From stackoverflow
  • You can return an int with System.exit().

    Returning anything other than an integer doesn't make much sense, as the OS expects an integer. In case nothing is returned the default is 0, which means OK. Other values typically are used to signal errors or special conditions.

  • Link to interesting discussion on velocityreviews on the same topic:

    http://www.velocityreviews.com/forums/t135045-why-does-main-in-java-returns-void-.html

    Highlight:

    Incidentally, this is considered bad style in C and C++ just because it's the wrong signature for main, not for any universal reason independent of programming languages. It's one of those things that is not really supposed to work, but might on your implementation.

    In Java, the reason main returns void is threads. C and C++ were both designed as languages before multithreading was a widely known technique, and both had threads grafted onto them at a later date. Java was designed from the beginning to be a multithreaded environment, and frankly, it would be unusual to write any non-trivial Java application that doesn't use more than one thread. So the idea that a program moves linearly from the beginning to the end of main is a bit outdated.

    written by

    www.designacourse.com

    The Easiest Way to Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer MindIQ Corporation

  • The main() method must indeed have a void return type. From the Java Language Specification on "Execution - Virtual Machine Start-Up" (§12.1.4):

    The method main must be declared public, static, and void. It must accept a single argument that is an array of strings.

    It goes on to describe when a program exits in "Execution - Program Exit" (§12.8):

    A program terminates all its activity and exits when one of two things happens:

    • All the threads that are not daemon threads terminate.
    • Some thread invokes the exit method of class Runtime or class System and the exit operation is not forbidden by the security manager.

    In other words, the program may exit before or after the main method finishes; a return value from main would therefore be meaningless. If you want the program to return a status code, call one of the following methods (note that all three methods never return normally):

    Of the three, System.exit() is the conventional and most convenient way to terminate the JVM.

  • Reason for main method having void as return type is that once main finishes, it doesn't necessariliy mean that entire program finished. If main spawns new threads, then these threads can keep program running. Return type of main doesn't make much sense at this point.

    For example, this is very common in Swing applications, where main method typically starts GUI on Swing thread, and then main finishes... but program is still running.

    Max : @Peter: Peter, could you clarify for myself (currently exploring java multithreading)... Is it deamon threads ONLY that are NOT permitted to outlive main() ?
    Peter Štibraný : @Max: no, main() method has no control over JVM. When JVM starts, it will run main() method, but when main() finishes, it doesn't mean that JVM terminaes. JVM continues to execute all threads until 1) Runtime.exit() is called OR 2) all normal (not daemon) threads have died. Daemon threads do not count for this second condition. In other words ... if main() method spawns some normal threads, JVM will **not** terminate when main() finishes. If main() doesn't spawn any threads, JVM will terminate. If main() spawns only daemon threads, JVM will also terminate when main() finishes.
    Max : @Peter: Pete, thanks for clarif.

Whats the best way to add variations of the same character to a view in Cocoa

I am confused about how to go adding objects (images,etc) into an app. I will keep my example very basic so I can get a grasp on this. Let's say I want simple objects in an app. Say they are the smilies like the ones that are available in this forum software. If you wanted to add a bunch (like 4 not 400) to a view, is it better to just add them with using a UIImage or should you create a "smilieGuy" class with the various smiley face images (happy, sad, mad) and a method to change their mood (image to reflect mood). From what I understand, with the class you could create a happy object, a sad object, etc in your view based off of the class and then at anytime you could say changeMood and change the image to whatever mood you wanted.

Is the class approach actually possible and is it a better approach?

From stackoverflow
  • The class approach is preferable.

    It allows you to separate the interface ([userFace setHappy]) from the implementation (self.image = [UIImage imageNamed:@"Happy.png"]). You can then change the logic, or create further variations without having to change any of the other display code.

  • I would also suggest creating an Emoticon class as a subclass of UIImageView. Inside the class, you could load your multiple images and use them to set the image property of your superclass.

    You might also want to check out the animation properties of UIImageView to achieve Skype style smilies.

Persistence in Ruby on Rails?

Is there a way to persist data between page loads in RoR? I guess I'm looking for something like memcached, but without the overhead of TCP/IP. For example, PHP has APC.

The ideal solution would be something in memory.

From stackoverflow
  • Why don't you just store it in the session? The session can have multiple backends like memcache or even a database. I think it is possible to deploy memcache locally so It wouldn't matter that much.

    Another posibility is to use a file backend and store it on a RAM drive. But maybe there are some memory libs for ruby which allow you to store these results directly into ram, but I got no experience with it.

  • How much data? If this is small, you could store it in the session data (i.e. session[:my_data] = "foo").

  • cookie based session stores are wicked fast, require no serverside storage or fetching, are secure, and the Rails default. As long as the data is less than 4K no reason not to just use that.

    Tomh : You don't want to use cookies for that, here is why: http://yuiblog.com/blog/2007/03/01/performance-research-part-3/
    Squeegy : Typically, the session contains very small bits of data, like a user ID. In these cases its trivial to send that along with the cookie the browser will be sending anyway. But I do agree that anything that needs more data than just that little bit should go through a server side store.
  • I wouldn't call the TCP/IP component "overhead" -- unless you are running the memcached server in another state or something. Memchached can be run locally just fine and rails works great with this. Perhaps memcached even has the ability to use a socket file instead of a IP and port, but I have not looked into this

  • You can also serialize ActiveRecord models. See the serialize method.

ASP.NET and System.Diagnostics tracing - have I missed something, or is this a bad idea?

For various common reasons I wanted to use tracing for my ASP.NET application. Especially since I found out about the possibility to use the Service Trace Viewer tool which allows you to examine your traces in a powerful way.

Since I had never used this trace thing before, I started stuying it. After a while of Google, SO and MSDN I finally have a good idea of how things work. But I also found one very distrubing thing.

When using trace in ASP.NET applications it makes a lot of sense to group the trace messages together by web requests. Especially since one of the reasons I want to use it is for studying performance problems. The above mentioned tool also supports this by using <Corrleation> tags in the generated XML files. Which in turn come from System.Diagnostics.Trace.CorrelationManager. It also allows other nice features like Activity starting/stopping, which provides an even better grouping of trace messages. Cool, right?

I though so too, until I started inspecting where the CorrelationManager actually lived. After all - it was a static property. After some playing around with Reflector I found out something horrifying - it's stored in CallContext! Which is the kind of thing we shouldn't be using in ASP.NET, right?

So... am I missing something here? Is tracing really fundamentally flawed in ASP.NET?

Added: Emm, I'm kinda on the verge of rewriting this stuff myself. I still want to use the neat tool for exploring the traces. Any reason I shouldn't do this? Perhaps there is something better yet? It would be really nice if I got some answers soon. :)

Added 2: A colleague of mine confirmed that this is not just a theoretical issue. He has observed this in the system he's working on. So it's settled. I'm going to build a new little system that does things just the way I want it to. :)

Added 3: Wow, cool... the guys at Microsoft couldn't find anything wrong with using Correlation Manager in ASP.NET. So apparently we're not getting a fix for this bug after all...

From stackoverflow
  • Hello,

    You raise a very interesting question. After looking at Reflector, I also see that CorrelationManager is using the CallContext to store the activity id. I have not worked with tracing much, so I can't really speak on behalf of what types of activities it tracks, but if it tracks a single activity across the entire life cycle of a page request, per the article you referenced above, there is a possibility that the activity id could become disassociated with the actual activity. This activity would appear to die halfway through.

    HttpContext would seem ideal for tracking an entire page request from beginning to finish, since it will be carried over even if the execution changes to a different thread. However, the HttpContext will not be transferred to your business objects, where as the CallContext would. On a side note, I saw that CallContext can also be transferred when using remoting between client and server apps which is pretty nifty, but in the case of tracking the website, this would not really be all that useful.

    If you haven't already, check out this guy's site. The issue described in this article isn't specifically the same issue that Cup(Of T) article mentioned, but it's still pretty interesting. He also provides several very informative links on the page that describe components of the CorrelateionManager.

    Unfortunately, I don't really have an answer to your question, but I definitely find the topic interesting and will continue looking into it. So please update this post as you learn more. I'm curious to see what you or others (hopefully someone out there can shed some light on the topic) find while looking into this.

    Anyway, good luck. I'll talk to some of the peeps at my work about this and post more later if I find anything.

    Chris

    Vilx- : Nice. I haven't found that article yet. Actually, it's pretty impossible to Google anything about the subject either. Weird that more people haven't caught this.
    Chris Porter : The link to "this guy's site" has changed: http://sticklebackplastic.com/post/2007/08/14/One-mighty-gotcha-for-SystemDiagnostic-activity-Ids.aspx
    regex : link has been updated, thanks chris
  • OK, so this is how it ended.

    My colleague called Microsoft and reported this bug to them. Being certified partners means we get access to some more prioritized fixing queue or something... don't know that stuff. Anyway, they're working on it. Hopefully we'll see a patch soon. :)

    In the mean time I've created my own little tracing class. It doesn't support all the bells and whistles that the default trace framework does, but it's just what I need. :) More specifically:

    • It writes to the same XML format as the default XmlWriterTraceListener so I can use the tool to analyze the logs.
    • It has a built in log rotation - something my colleague had to do himself on top of XmlWriterTraceListener.
    • The actual logging is deferred to another thread so performance can be measured more accurately.
    • Correlations are now stored in HttpContext.Items so ASP.NET threading peculiarities don't affect it.

    Happy end, I hope. :)

With this technology, would it be possible to compile and run silverlight IL in Flash?

I don't really understand this article. But it sounds like you can compile C/C++ for flash. If that's possible, how hard would it be to compile and run Mono inside flash?

Sounds stupid I know...maybe I'm going crazy with my age.

From stackoverflow
  • Probably is possible, at the first time, but just compile. Let me see if I got where you want go.

    Mono can run on-the-fly code, but even now that there is a C# Shell it first compiles to IL (and maybe JIT) and after that it executes. With that technology will be possible to make Flash generate .NET assemblies, but not run them!

    We will need a .NET IL to AS3 bytecode converter in order to run .NET assemblies in Flash. Probably you are thinking in this, right? But that's not crazy at all, it's compatibility!

    Richard Szalay : I think the OP is talking about porting Mono itself to run within LVVM, resulting in a CLR running within the AVM2.
    Augusto Radtke : True, you can't even compile as I remember the Mono csc.exe is in C#, you'll need the runtime first. But I doubt that could be easily ported because VMs are pretty optimized for specific architectures.
  • There's no reason you couldn't write a CLR in alchemy, but alchemy does not compile C to native code (it's compiled to bytecode) so it's going to be restricted both in performance and security in the same way as normal actionscript. Because of this, you'd probably need to rewrite alot of mono.

    So in short: it's possible but you aren't going to win any performance awards.

    tyndall : Any links to this alchemy thing?
    Richard Szalay : http://labs.adobe.com/technologies/alchemy/
  • Alchemy uses LLVM to translate compiled C/C++ code into ActionScript. LLVM (http://www.llvm.org/) is a compiler infrastructure (ripped from that page's headline!) that supports compiling C/C++ to a low-level instruction set. You can build a virtual machine on top of it, analyze things about compiled code (like data flow or code coverage or whatever), and generally do all sorts of cool things.

    I don't think you can use it to translate IL into flash though.

  • I'm sure a really good and dedicated hacker, able to change both the mono runtime and the flash player, could get a trivial hello-world-like program to run in a few months of work. That said, implementing all the features would be either extremely complex or extremely slow, so, from a practical point of view using this approach wouldn't work.

    If you'd like to run CLR-based managed code in the browser, check out the Moonlight 2.0 progress here: it works today, it is fast and it can be easily ported to run on a wide range of devices (there is also a Mono port to Android, for example).

Exposing the DescriptionAttribute of Enums from a WCF Service

how can i expose description attribute in enum values from service to client or web reference using WCF or

how can i expose enum with description attribute to client using WCF? while exposing Description attribute is not exposed only enum values are exposed in client. I want value in description attribue in enums.

From stackoverflow
  • you can do this using reflection. back in the client after you have the Enum value.. try picking up the attribute using GetField() & GetCustomAttributes()

    using System;
    using System.Reflection;
    using System.ComponentModel;
    
    namespace CustomAttributes
    {
        class Program
        {
            static void Main(string[] args)
            {
                Colors n1 = Colors.blue;
    
                object [] attribues = n1.GetType().GetField(n1.ToString()).GetCustomAttributes(true);
                Console.WriteLine((attribues[0] as DescriptionAttribute).Description);
                // WOULD PRINT  "DARK BLUE"
            }
        }
    
        enum Colors
        {
            [Description("DARK BLUE")]
            blue,
            [Description("PLAIN WHITE")]
            white
        }
    }
    
    Marc Gravell : This doesn't apply to the generated WCF proxy, since [Description] doesn't transfer
  • Check out the XmlEnum Attribute. That will allow you to specify the "Name" of the xml attribute. Eg:

    public enum MyEnum
    {
        [XmlEnum("Coolbox")]
        Esky,
        [XmlEnum("Sandles")]
        Thong,
        [XmlEnum("MoreLikeGridironThanRealFootball")]
        Footy,
    }
    
  • You can't force this - the mex/WDSL descriptors only contain a tiny subset of the information associated with a type.

    If you control the client, one option is to declare the enum (or even all the types) locally, and consume from there. You should be able to use the svcutil /reference: switch to use types from an existing assembly (the IDE offers the same). But note that this partly breaks the rules of SOA (i.e. you are using more information than the service contract promises).

What's a good way to perform hit testing on a FormattedText?

I'm rendering text using FormattedText, but there does appear to be any way to perform per-char hit testing on the rendered output. It's read-only, so I basically only need selection, no editing.

I'd use RichTextBox or similar, but I need to output text based on control codes embed in the text itself, so they don't always nest, which makes building the right Inline elements very complex. I'm also a bit worried about performance with that solution; I have a large number of lines, and new lines are appended often.

I've looked at GlyphRun, it appears I could get hit-testing from it or a related class, but I'd be reimplementing a lot of functionality, and it seems like there should be a simpler way...

Does anyone know of a good way to implement this?

From stackoverflow
  • The best way is to design a good data structure for storing your text and which also considers hit-testing. One example could be to split the text into blocks (words, lines or paragraphs depending on what you need). Then each such block should have a bounding-box which should be recomputed in any formatting operations. Also consider caret positions in your design.

    Once you have such facility it becomes very easy to do hit-testing, just use the bounding boxes. It will also help in subsequent operations like highlighting a particular portion of text.

    Eric : FormattedText already allows me to get boxes for ranges of text, but I need actual selection; so I'd probably need boxes for each char, and that'd quickly get messy. It's a possible solution, but not a very good one...
    Sesh : There is a fly-weight or some other design pattern that addresses similar problem (bbox for single char). Can you please check the Gamma book on design patterns? its there in it.
  • Completely agree with Sesh - the easiest way you're going to get away with not re-implementing a whole load of FormattedText functionality is going to be by splitting up the individual items you want to hit-test into their own controls/inlines.

    Consider using a TextBlock and adding each word as it's own Inline ( or ), then either bind to the inline's IsMouseDirectlyOver property, our add delegates to the MouseEnter & MouseLeave events.

    If you want to do pixel-level hit testing of the actual glyphs (i.e. is the mouse exactly in the dot of this 'i'), then you'll need to use GlyphRuns and do manual hit testing on the glyphs (read: hard work).

Geting Platform info of iphone

Hi There, How can one get iphone system information such as sdk version? The infomration i need is similar to the device information you see when your iphone/itouch is connected to itunes. I can use UniqueDevice to get the serial number but cant seem to find any system properties or request methods in there. Look forward to your thoughts on this. Tony

From stackoverflow
  • i think by SDK you mean the system version...so check UIDevice systemVersion

  • Check out the UIDevice class - that's pretty much all you're going to get from the SDK.

  • Hey folks, Thanks for your answers. I must be blind, they were right infront of my eyes all along. Here is the code I'm using to get data I need.

    serial_no = [[UIDevice currentDevice] uniqueIdentifier]; version = [[UIDevice currentDevice] systemVersion]; system = [[UIDevice currentDevice] systemName];

How to: Font smoothing test

The real question is this:

I am trying to figure out the effect of font smoothing in my web page. On my LCD panel the text looks the same with font smoothing on/off.

Are there are any particular fonts that need smoothing. Can you suggest any example font best suited for font-smoothing (i.e. it gives good result on applying smoothing).

From stackoverflow
  • By default most modern web browsers are going to use font smoothing. You can turn it off though to see how it will look on people that are not using it. For example here is an article on doing so in IE7.

  • In theory all fonts should benefit, but in pratice how much they benefit depends both on the font used and the font rasterization technique used.

    A couple of good articles on font rasterization are How Sub-Pixel Font Rendering Works and Text Rasterization Exposures

WCF Recommend approaches for serializing multiple objects

I am attempting to optimise around a possible bottleneck.

I have a server application that is serving objects from a database to applications remotely, who can work with 1 - n objects of 1 - n different types (where n can be a relatively high number) that all implement a common interface but may contain many unique properties on different types.

The client applications store the server objects in a local cache, until they are ready to persist them back, through the server, to the database.

This is being done currently in WCF with each class defining a DataContract.

Due to the possibly large amount of objects that may need to be passed back to the server (it changes depending on implementation), I would prefer not to do these all as individual calls any more, rather wrap all the objects in a single serialized (or better still compressed) stream and send them through as one connection to the server.

I can quite simply roll my own, but would prefer to use a recommended approach, and hoping someone may suggest one. If you can convince me, I am also willing to accept that my approach is probably not the best idea.

From stackoverflow
  • How high is "relatively high"?

    For example, one option that occurs is to use a wrapper object:

    [DataContract]
    public class Wrapper {
        [DataMember(Order = 1)]
        public List<Foo> Foos {get {...}}
    
        [DataMember(Order = 2)]
        public List<Bar> Bars {get {...}}
    
        [DataMember(Order = 3)]
        public List<Blop> Blops {get {...}}
    }
    

    Then you should be able to send a single message with any number of Foo, Bar and/or Blop records. My inclusion of the Order attribute was deliberate - if you want to reduce the size of the stream, you might consider protobuf-net - with the above layout, protobuf-net can hook into WCF simply by including [ProtoBehavior] on the method (in the operation-contract interface) that you want to attack (at both client and server). This switches the transfer to use google's "protocol buffers" binary format, using base-64 to encode. If you are using the basic-http binding, this can also use MTOM if enabled, so even the base-64 isn't an issue. Using this, you can get significant data transfer savings (~1/5th the space based on the numbers shown).

    (edit 1 - protobuf-net assumes that Foo, Bar and Blop also use the Order attribute)

    (edit 2 - note that you could always break up the request into a number of mid-size Wrapper messages, then call a method to apply all the changes once you have them at the server (presumably in a staging table in the database))

    johnc : Thanks for that Marc, some food for thought
    Marc Gravell : As always, other options are available and your mileage may vary ;-p
    Jonathan Parker : Yeah, programming is so deterministic isn't it guys? lol.