Wednesday, March 23, 2011

Passing flashvars-style parameters to a loaded SWF

I have a Flex 3 app (player v9) which loads a Flash SWF (AS3, also player v9) and needs to dynamically pass it a collection of parameters which are known at run-time. These are parameters that are normally passed via the flashvars element in an HTML page. The embedded movie accesses these parameters via the loaderInfo.parameters object.

I've tried using SWFLoader and Loader classes with no success in param-passing.

Relevant details:

  • It's a local program, and cannot rely on query string parameters.
  • I've mucked with setting loaderInfo.parameters["foo"] = "123" from the embedding code, but the parameter never seems to wind up in the embedded movie.
  • I cannot place extra parameter-passing machinery in the embedded movie(s), as they are created by third parties.
From stackoverflow
  • When embedding a SWF on a web page you can pass flashvars as parameters on the URL to the SWF, perhaps the same could work in your case? If the SWF is located at file:///some/path/to/a.swf try using file:///some/path/to/a.swf?hello=world&foo=bar. It might work.

    David Grant : I'm afraid that doesn't work. It might work if the main SWF were in the browser, but this is running right out of Flash Player.
  • Passing this params in URL won't help, because they're taken using javascript code in the html-wrapper. The 'flashVars' params are taken using the Application.application.parameters, so, you have to set these params manually in your case.

    If you are using SWFLoader to load another app, you should create the object, that will represent the application loaded and apply all you need:

    <mx:Script>
     <![CDATA[
      import mx.managers.SystemManager;
      import mx.controls.Alert;
      import mx.events.FlexEvent;
    
      private var loadedApp:Application;
    
      private function onLoadComplete(event:Event):void {
       var smAppLoaded:SystemManager = SystemManager(event.target.content);
       smAppLoaded.addEventListener(FlexEvent.APPLICATION_COMPLETE, onLoadedAppComplete);
      }
    
      private function onLoadedAppComplete(event:FlexEvent):void {
       try {
        loadedApp = Application(event.target.application);
        if(!loadedApp) throw new Error();
    
        loadedApp.parameters["param1"] = "value1";
       } catch (e:Error) {
        Alert.show("Failed to get application loaded.", "Error", Alert.OK); 
       }
      }
    
      private function onLoadError():void {
       Alert.show("Failed to load an application.", "Error", Alert.OK);
      }
    
     ]]>
    </mx:Script>
    
    <mx:SWFLoader 
     width="100%" height="100%"
     source="./AppToLoad.swf" 
     complete="onLoadComplete(event)" 
     ioError="onLoadError()" securityError="onLoadError()" />
    

    davr : This is a good general idea. If you want to be more strict about it, you can define an interface for the loaded SWF, and use that to pass strictly-typed parameters into it.

Delphi 2009 COM/ActiveX Type Library support stability

Referring to TLB and maintenance issues ...

My question to people (often) using the new COM/ActiveX type library support in Delphi 2009:
How stable is the implementation?

Especially, I'm interested in: adding/deleting classes, changing GUIDs, renaming methods/properties, reordering methods/properties, huge type libraries (50+ classes), ...

Is it as stable as in Delphi 2007 (a nightmare) or Delphi 7 (quite OK, but sometimes you have to restore the TLB file from SVN) or super-stable (as in, ... uhm, .... do you remember any Delphi version)?

EDIT: Yes, of course, the text RIDL was an excellent idea, but my question is:
Is the (new) implementation of the TLB support stable (especially synchronization of the RIDL file with the visual TLB editor and the implementation classes when doing the tasks I described above).

From stackoverflow
  • have a look at type-libraries-in-delphi

  • My understanding is that the RIDL is stored as text and compiled as it is needed so maintaining the TLB file directly is no longer necessary. This is a brilliant move by the CodeGear team to greatly improve stability.

    Will it handle your mega sized type library? Hard to say as I don't have anything close to that large...but I can't see a reason why it wouldn't.

  • Well, again, I'm biased, but our internal testing indicates that the new solution is much, much, much more stable.

    And of course it was designed to be. All the 'intelligence' of your COM/ActiveX objects is now text based. And since it is text based, it is completely under your control. Since it is under your control, you can make it do what you want. No more black boxes. The process is transparent. As for importing big, hairy Type Libraries, we successfully import the whole MS Office type libraries and ActiveX controls, and those are pretty hairy.

    So from where we sit the answer to your question is: Yes, it is very stable.

Customizing a TListBox to resemble an Outlook list

Hey all,

Please down vote me if this is not appropriate, but I'm desperate to the point of pulling my hair out looking for this link. This is really a last resort.

Recently I browsed to a blog (at least I think it was) that had a very detailed description on how to modify a TListBox to have a multi-line look resembling some of the entries on an outlook list of emails, with a Title and the initial content. It was a particular good example because it had all the code for the modified TItem and TItemList objects and loads of images with that look

I've scoured my Firefox History, my Chrome history, my FeedDemon Feeds and my Google Bookmarks to no avail. I've done Google searches with TListBox, TListView, TItems, TItemList, Custom, Extending and some other variations and even looked 3 page results down to no avail...

Has anyone stumbled upon this article?
Please let an "old" man recover his memory, and his sanity :)

Cheers,
Gus

From stackoverflow
  • How to use is the one that "TListbox Ownerdraw Delphi" finds for me. Certainly Ownerdraw is what you are looking at to do this sort of thing. Good luck!

    Gustavo Carreno : Unfortunately this article is for TListView and I'm now certain that it was a TListBox.

Running background services on a PocketPC

Hi,

I've recently bought myself a new cellphone, running Windows Mobile 6.1 Professional. And of course I am currently looking into doing some coding for it, on a hobby basis. My plan is to have a service running as a DLL, loaded by Services.exe. This needs to gather som data, and do som processing at regular intervals (every 5-10 minutes).

Since I need to run this at regular intervals, it is a bit of a problem for me, that the system typically goes to sleep (suspend) after a short period of inactivity by the user.

I have been reading all the documentation I could find on MSDN, and MSDN blogs about this subject, and it seems to me, that there are three possible solutions to this problem:

  1. Keep the system in an "Always On"-state, by calling SystemIdleTimerReset periodically. This seems a bit excessive, and is therefore out of the question.

  2. Have the system periodically waken up with CeRunAppAtTime, and enter the unattended state, to do my processing.

  3. Use the unattended state instead of going into a full suspend. This would be transparent to the user, but the system would never go into sleep.

The second approach seems to be preferred, however, this would require an executable to be called by the system on wake up, with the only task of notifying my service that it should commence processing. This seems a bit unnecessary and I would like to avoid this extra executable. I could of course move all my processing into this extra executable, but I would like to use some of the facilities provided when running as a service, and also not have a program pop up (even if its in the background) whenever processing starts.

At first glance, the third approach seems to have the same basic problem as the first. However, I have read on some of the MSDN blogs, that it might be possible to actually conserve battery consumption with this approach, instead of going in and out of suspend mode often (The arguments for this was that the nature of the WM platform is to have a very little battery consumption, when the system is idle. And that going in and out of suspend require quite a bit of processing).

So I guess my questions are as following:

  • Which approach would you recommend in my situation? With respect to keeping a minimum battery consumption, and a nice clean implementation.

  • In the case of approach number two, is it possible to eliminate the need for a notifying executable? Either through alternative API functions, or existing generic applications on the platform?

  • In the case of approach number three, do you know of any information/statistics relevant to the claim, that it is possible to extend the battery lifetime when using unattended mode over going into suspend. E.g. how often do you need to pull the system out of suspend, before unattended mode is to be preferred.

  • Implementation specific (bonus) question: Is it necessary to regularly call SystemIdleTimerReset to stay in unattended mode?

And finally, if you think I have prematurely eliminated approach number one, please tell me why.


Please include in your response whether you base your response on knowledge, or are merely guessing (the latter is also very welcome!).

Please leave a comment, if you think I need to clarify any parts of this question.

From stackoverflow
  • CERunAppAtTime is a much-misunderstood API (largely because of the terrible name). It doesn't have to run an app. It can simply set a named system event (see the description of the pwszAppName parameter in the MSDN docs). If you care to know when it has fired (to lat your app put the device to sleep again when it's done processing) simply have a worker thread that is doing a WaitForSingleObject on that same named event.

    Unattended state is often used for devices that need to keep an app running continuously (like an MP3 player) but conserve power by shutting down the backlight (probably the single most power consuming subsystem).

    Obviously unattended mode uses significantly more powr than suspend, becasue in suspend the only power draw is for RAM self-refresh. In unattended mode the processor is stuill powered and running (and several peripherals may be too - depends on how the OEM defined their unattended mode).

    SystemIdleTimerReset simply prevents the power manager from putting the device into low-power mode due to inactivity. This mode, whether suspended, unattended, flight or other, is defined by the OEM. Use it sparingly because when your do it impacts the power consumption of the device. Doing it in unattended mode is especially problematic from a user perspective because they might think the device is off (it looks that way) but now their battery life has gone south.

    Simon Jensen : Thank you very much for your answer! I have been looking at the MSDN docs for CeRunAppAtTime which does not have the same elaboration on the pwszAppName parameter as CeRunAppAtEvent does. This is exactly what I need!
    Simon Jensen : Perhaps you could answer my bonus question too (or already did?), is it correctly understood, that I need to signal SystemIdleTimerReset regularly while I do my processing (in unattended mode), to keep the system from sleep? Or will it wait till I signal PowerPolicyNotify(PPN_UNATTENDEDMODE, FALSE)?
  • I had a whole long post detailing how you shouldn't expect to be able to get acceptable battery life because WM is not designed to support what you're trying to do, but -- you could signal your service on wakeup, do your processing, then use the methods in this post to put the device back to sleep immediately. You should be able to keep the ratio of on-time-to-sleep-time very low this way -- but as you say, I'm only guessing.

    See also:

    Power-Efficient Apps (MSDN)

    Power To The People (Developers 1, Developers 2, Devices)

    Power-Efficient WM Apps (blog post)

SQL Server - Syncing two database.

We have a warehouse database that contains a year of data up to now. I want to create report database that represents the last 3 months of data for reporting purposes. I want to be able to keep the two databases in sync. Right now, every 10 minutes I execute a package that will grab the most recent rows from the warehouse and adds them to the report db. The problem is that I only get new rows but not new updates.

I would like to know what are the various ways of solving this scenario.

Thanks

From stackoverflow
  • You should probably read about replication, or ask your DB admin about it.

  • look into replication, mirroring or log shipping

    James : I've ready about replication, mirroring, etc. They talk about 2 separate database servers. I need to sync two databases on the same server. Is this still possible with the technologies you spoke o?
    BradC : Yes, you can replicate between two databases on the same server.
  • Is it possible to add columns to this database? You could add a Last_Activity column to the DB and the write a trigger that updates the date/timestamp on that row to reflect the latest edit. For any new entries, the date/time would reflect the timestamp when the row was added.

    This way, when you grab the last three months, you'd be grabbing the last three months' activity, not just the new stuff.

    James : This is an interesting solution. I will have to give this some though.
  • If you are using SQL 2000 or below, replication is your best bet. Since you are doing this every ten minutes, you should definitely look at transactional replication.

    If you are using SQL 2005 or greater, you have more options available to you. Database snapshots, log shipping, and mirroring as SQLMenace suggested above. The suitability of these vary depending on your hardware. You will have to do some research to pick the optimal one for your needs.

Linux: launch window, capture screen

I need to write a Red Hat Linux command line tool that launches a window and captures its appearance to disk as a JPEG.

Typically the target machines don't have graphics cards, but we can install any software components (e.g., X).

Question or two:

What libraries or tools might you suggest for this?

If I were to use something like GTK+ to create this tool, would lacking a video card hamper its execution?

I saw scrot, but it doesn't appear to support capturing a specific window without user interaction.

From stackoverflow
  • It sounds like you'll need to use the "virtual framebuffer" driver for the X.org server, combined with the xwd, NetPBM, and cjpeg utilities.

    I'm not sure about the particular configuration you'll need for the X server, but you will likely have to make sure the server you're using has the virtual framebuffer driver built into to. The virtual framebuffer driver is a display driver just like one you'd use to connect to an NVidia or ATI video card, except it's "output" is a chunk of memory that contains the pixels, not an LCD screen.

    xwd is one of the standard X tools, that can create a X Window Dump. xwd can be told on the command line which window to dump. It outputs a funky "xwd" formatted stream to standard out.

    The NetPBM utilities are a collection of command line tools that convert one image format to another. It includes one that converts xwdtoppm. PPM is a very basic, non-compressed format that is the intermediate format understood by most of the NetPBM tools.

    cjpeg is part of the standard JPEG tools collection, and is probably installed if you also have NetPBM. cjpeg can take a stream of PPM bytes and emit a stream of JPEG bytes.

    Through the magic of Unix scripting and pipes, you can string these utilities together to fire up the app with the window, call xwd, xwdtoppm, and cjpeg to dump the image to a file.

  • You might try running vncserver to create a virtual X window display - no graphics card needed. Be sure to set your DISPLAY variable to the display number that gets printed when vncserver starts. Next, start your app on the created display (in hte background) and use xwd with data formatters or a gimp command to capture the screen image to jpeg.

    By the way, check the similar answers for http://stackoverflow.com/questions/125951/command-line-program-to-create-website-screenshots-on-linux.

Accessing the iPhone's USB port?

Is there any way for developer to send data to the iPhone's USB port?

From stackoverflow

get stack trace when exception is thrown

Hi,

I am now debugging a program that utilizes many different threads.

there is an exception that is thrown from time to time. the problem is that there is no way to know what thread caused the problem...

does anyone know an easy way to get the stack trace after the exception is thrown? I thought about simply writing a debug messages but it is going to be a huge :-) i guess there are much better techniques than this one ...

I'm using visual studio 2008 - native c++ project....

From stackoverflow
  • The exception itself has the property StackTrace... so you just need return the ToString( ).

    But I belive your problem is more like how to catch a random exception. If it is so, what I do is put all the main code within a try/catch. I really not so sure if the exception is thrown in other thread, it this technique will work.

    You should catch also an ApplicationExeption, that is not derived from Exception.

    Timo Geusch : ofer mentions that his project is a native C++ project. I might be wrong but your suggestion is for .NET, right?
    Len Holgate : Not in C++ it doesn't...
    Romias : Yeap... my mistake... thought you where in .NET
  • Unless I'm very much mistaken, you need to know which thread triggered the exception in order to use the Visual Studio debugger's call stack view, which is obviously the catch-22 situation you're in at the moment.

    One thing I would try is to see if you can get the debugger to break when the exception is thrown (using Debug > Exceptions). You'll have to explicitly enable this, but if you know what type of exception is thrown, this might allow you to work out where it's thrown.

    Other than that, putting a breakpoint in the constructor of the exception (if it's one of your own) should also allow you to work out where it's triggered from.

    If those methods don't work for you I'd be looking at the debug messages as you already suggested.

  • Can you use Exceptions dialog (Debug | Exceptions... menu item, or Ctrl+Alt+E or Ctrl+D E, depending on your keyboard bindings) to break the running code into debugging at the moment the specific exception is being thrown?

  • This library looks like it fits the bill:

    http://www.codeproject.com/KB/threads/StackWalker.aspx

    Jochen Kalmbach looks to have done a very thorough job of wrapping the complexity of the low-level dbghelp.dll interface.

  • If you can't get a debugger to catch what is happening... and you can't printf the stack trace and thread...

    My guess is that you will have to put in some good ol' elbow grease and hard work. Start by understanding the system. Once you understand the system, try splitting the system into two halfs. The part that works and the part that doesn't work. Then keep trying to do that until you drill down to the problem.

    When you drill down far enough try surrounding the suspicious code with try/catch... hopefully then you can use the debugger to stop the execution and see what is happening.

  • You could put a break point in the exceptions constructor (i.e. the object you are about to throw).

    This of course assumes you have a common exception hierarchy.

  • This is trivially easy with WinDBG, which is free from Microsoft. You will also want to install symbols for your version of Windows, if you don't have them already.

    Simply setup WinDBG as your Crash Dump tool. I use this registry setting: (You may wish to edit the paths)

    Sample: CrashDumpSettings.reg:

    Windows Registry Editor Version 5.00
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug]
    "Auto"="1"
    "Debugger"="C:\\progra~1\\debugg~1\\cdb.exe -p %ld -e %ld -g -y SRV*c:\\mss*http://msdl.microsoft.com/download/symbols -c \"$<c:\\Dumps\\CrashDump.cdbscript\""
    

    Here is what your CrashDump.cdbscript might look like: (This is basically what I use... Edit the paths as appropriate.)

    Sample: CrashDump.cdbscript:

    .sympath+ c:\windows\symbols;c:\some\path\to\symbols\for\your\project
    
    as /c CrashFirstModule .printf "%mu", @@c++((*(ntdll!_LDR_DATA_TABLE_ENTRY**)&@$peb->Ldr->InLoadOrderModuleList.Flink)->BaseDllName.Buffer) 
    
    .logopen /t c:\dumps\${CrashFirstModule}_process.log
    .kframes 100
    !analyze -v
    ~*kv
    lmv
    .logclose
    
    .dump /mhi /u /b c:\dumps\${CrashFirstModule}_mini.cab
    .dump /mhia /u /b c:\dumps\${CrashFirstModule}_full.cab
    
    q
    

    And you get a nice log file and some dumps you can use to view the state of the process when the exception happened with WinDBG. The log file will have analysis of the error that occurred, including the line of code that caused the error. It will also list the call-stack for each thread. In the call stack listing, the thread with the # next to it's number is the one that caused the exception. There is a TON of information in these files. I recommend picking up Debugging Applications for Microsoft .Net and Microsoft Windows by John Robbins. It's a great book on Debugging, even if it's from a few years ago. You can get it from Amazon for about $20.00.

    ceretullis : +1 great answer!

Deep xml serialize a struct Options

Hi, I have the class and struct shown below. If I serialize the class as is using xmlserializer I get:

< Test>
< TestNumber1 >5< /TestNumber1 >
< InnerTest / >
< /Test >

what is the easiest way to make InnerTest serialise properly (preferably using xmlserializer) with out giving the Number property a setter?

Thanks, Nick

public class Test 
{ 
    private InnerTest innerTest; 
    private int testNumber; 


    public Test() 
    { 
        this.innerTest = new InnerTest(); 
        this.testNumber = 5; 
    } 


    public int TestNumber1 
    { 
        get { return this.testNumber; } 
        set { this.testNumber = value;} 
    } 


    public InnerTest InnerTest 
    { 
        get { return this.innerTest; } 
        set { this.innerTest = value;} 
    } 


} 


public struct InnerTest 
{ 
    private int number; 


    public InnerTest(int number) 
    { 
        this.number = number; 
    } 
    public int Number{get { return number; }} 
}
From stackoverflow
  • I've never done it myself, but I suspect you just need to implement the IXmlSerializable interface.

    As far as I can tell, that means you have to make your struct mutable - which is a pain. Ideally the XmlSerializer should recognise if your type has a constructor with a certain signature, but as that doesn't seem to be an option (as far as I can see) it would be worth implementing the interface using explicit interface implementation to at least discourage users from using it directly themselves.

    I wonder how other structs (e.g. DateTime) manage... perhaps they have explicit support in XmlSerializer.

  • As Jon Skeet quite correctly says, you'll need to use IXmlSerializable with the XmlSerializer if you don't want to have a public get/set for the properties because it's designed to work in a partial-trust environment so won't access any data that you couldn't have accessed anyway (to answer his last part - yes, some structs like DateTime do have explicit support in that serializer).

    Depending on what you're trying to achieve, and what version of .NET you're using, you could consider using the DataContractSerializer which doesn't require things to be public (for example you could put a DataMemberAttribute on a private field, or a property with public getter and private setter). This serializer gives you less control over the XML format (in fact it's very restrictive - for example it doesn't even support attributes!) but is somewhat faster as payback.

    (I've long hankered over something that's a combination of the two, i.e. the flexibility of XmlSerializer with the ability to serialize private members like DataContractSerializer but unfortunately there isn't one at the moment.)

  • If possible in this scenario, I would use DataContractSerializer (.NET 3.0), and I would use something like:

    [DataMember]
    public int TestNumber1 
    { 
        get { return this.testNumber; } 
        set { this.testNumber = value;} 
    } 
    
    // note **not** a data-member
    public InnerTest InnerTest 
    { 
        get { return this.innerTest; } 
        set { this.innerTest = value;} 
    } 
    
    [DataMember]
    private int InnerTestValue
    {
        get {return innerTest.Number;}
        set {innerTest = new InnerTest(value);}
    }
    

    thus side-stepping the issue. You can do similar with XmlSerializer, but you'd need to make InnerTestValue public (although you could decorate it with [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - but this isn't ideal).

    Of course, if you have multiple values on the struct... trickier. You can have multiple shim properties, of course, but that is a bit scrappy. Basically, [de]serialization and immutable objects (as structs should be) don't mix all that well.

    Another option is to maintain a separate POCO version that uses mutable classes throughout, and translate between the two; again, not very attractive as an option for large object models.

  • Hi Nick,

    You can definitely use the XmlSerializer on your object there and get the expected result:

    Test test = new Test { TestNumber1 = 5 };
    
    XmlSerializer xmlSer = new XmlSerializer(typeof(Test));
    MemoryStream memStm = new MemoryStream();
    
    xmlSer.Serialize(memStm, test);
    

    To verify the result, read out the memory stream again into a string and look at it in the debugger (or write it out to a file):

    StreamReader stmR = new StreamReader(memStm);
    memStm.Position = 0;
    string output = stmR.ReadToEnd();
    

    If you don't do anything special, all public properties of the class you're serializing will be rendered as XML elements ..... in your resulting XML.

    There's a bunch of attributes like [XmlIgnore] and many more to tweak that as needed.

    Enjoy!

    Marc

How to change default nls_date_format for oracle jdbc client

I have defined the global nls_date_format on Oracle 10.2 XE as follows:

alter system set nls_date_format='YYYY-MM-DD HH24:MI:SS' scope=spfile;

When connecting on Windows, the clients override it with session specific format, so I need to run this line at the beginning of every session:

alter session set nls_date_format='YYYY-MM-DD HH24:MI:SS';

However, I have some custom code that I can't change (jdbc code, using ojdbc14.jar), so I can't execute this line when receiving the connection. Is there a way to change the default value of nls_date_format for all jdbc connections? Perhaps adding something to the connection string, or some environment variable that I can use?

By the way, sqlplus and sqldeveloper also override the server's format with their own, but I found out how to change their defaults, so the problem is only with jdbc connections.

From stackoverflow
  • Set nls date format in an after logon trigger

  • Thanks, that worked for me. The trigger that I inserted is this:

    CREATE OR REPLACE TRIGGER LOGINTRG
    AFTER LOGON ON DATABASE
    BEGIN
    EXECUTE IMMEDIATE 'ALTER SESSION SET NLS_DATE_FORMAT=''YYYY-MM-DD HH24:MI:SS''';
    END LOGINTRG;
    

What's the recommended workaround if numeric_limits<double>::has_infinity is false?

I need to check a double value for infinity in a C++ app on Linux. On most platforms this works by comparing with std::numeric_limits<double>::infinity(). However, on some old platforms (RedHat 9 for example, with gcc 3.2.2) this is not available, and std::numeric_limits<double>::has_infinity is false there.

What workaround would you recommend for those platforms?

From stackoverflow
  • For most cases, std::numeric_limits::max() can be a valid replacement for std::numeric_limits::infinity().

    You would have to be more careful about using it, however. With overflows I believe you would have to manually detect the overflow and set the result to the max explicitly if an overflow is detected.

  • If you're using IEEE 754 arithmetic, as you almost certainly are, infinities are well defined values and have defined outcomes for all arithmetic operations. In particular,

    infinity - infinity = NaN
    

    Positive and negative infinity and NaN values are the only values for which this is true. NaNs are special "not-a-number" values used to indicate domain errors of functions, e.g. sqrt(-1). Also:

    NaN != NaN
    

    NaNs are the only values for which this is true.

    Therefore:

    bool is_infinite(double x) {
        double y = x - x;
        return x == x && y != y;
    }
    

    will return true if and only if x is either positive or negative infinity. Add a test for x > 0 if you only want to check for positive infinity.

    MSalters : std::numeric_limits::has_infinity==false suggests you do NOT have IEEE 754
    j_random_hacker : That may be true, but in the OP's case it's likely to mean he has an incomplete C++ Standard Library implementation that **has** IEEE 754 but doesn't "realise it". Why? Because IEEE 754 is usually done in hardware, and upgrading to a newer compiler fixed the problem.
    j_random_hacker : But I agree that in the general case, if you do not know otherwise, then you should assume that std::numeric_limits::has_infinity==false implies no IEEE 754.
  • Ok, I have now resorted to using the INFINITY and NAN macros on that particular machine - seems to work fine. They come from math.h.

How to find out what languages are available on a Symbian device using the C++ APIs?

Does anyone know how to query at runtime a list of display languages that a Symbian (S60, specifically) device has installed? I've been able to query for the language set, but I haven't found anyway of getting what languages make up that set at runtime.

This needs to be the actual language code (i.e, ELangEnglish for UK English, ELangAmerican for US English, etc, etc) and not just that there is any English variant on the phone.

Thanks!

From stackoverflow
  • You may take a look at the CPtiEngine class reference. Quoting directly from the page:

    This is main class for PtiEngine API. This is the main client side API for PtiEngine. The purpose of PtiEngine API is to provide a single calling point for all the low level (below UI) text input functionality. The API provides methods for querying and activating installed languages, changing input modes and text cases and performing the actual text input operations.

    Dennis Munsie : This is exactly what I was looking for -- specifically, the GetAvailableLanguagesL() method gave me what I needed. Thanks!
    Dennis Munsie : Ok -- I have to take back my previous statement. What PtiEngine reports back is the base language code. For example, on a North American S60 device, it reports back English with a language code of 1, but that's incorrect -- it should be 10. Still looking for a way to get the actual language now.

Creating Win32 events from c#

I'd like create a kernel(aka named events) from C#.

Do I have to interop services and wrap the native CreateEvent function or is there already a .NET class that does the job?

The function that I need to run should be something like this: hEvent = CreateEvent ( NULL , false , false , "MyCSHARPEvent" );

This should notify all procs that probing forMyCSHARPEvent about the event.

If there is a need to wrap the function, how would I translate the SECURITY_ATTRIBUTES struct from C# to win32?

From stackoverflow
  • Take a look at the EventWaitHandle class. It's supported from .Net 2.0 onwards and allows creation of named events. It also supports setting event security, depending on which constructor you use.

  • If you still want to use interop, you can define the function like this:

    [DllImport("kernel32.dll")]
    static extern IntPtr CreateEvent(IntPtr lpEventAttributes, bool bManualReset, bool bInitialState, string lpName);
    

    and the struct like this(you may have to mess with the Pack attribute to make it fit):

    [StructLayout(LayoutKind.Sequential)]
    struct SECURITY_ATTRIBUTES{
      public int length;
      public IntPtr securityDesc;
      public bool inherit;
    }
    

    Also, here's a code example of putting it all together.

    ctacke : But why would you?
    JoshBerke : if your supporting .net 1.1
    ctacke : Wow - I thought only the CF was that crippled (it still doesn't support named EventWaitHandles).
    Sam : CF 3.5 now does support EventWaitHandles.

Entity Framework: Creating custom properties

Consider an implementation of the Entity Framework in a DAL assembly. I am needing to add a custom read-only property to an entity.

Person Class, as defined in the DB, contains fields like:

PersonID
FirstName
LastName

In the above example, I'd like to make a property called FullName. It would be the concatenation of

FirstName + " " + LastName;

Can anyone help point out in the .edmx file whereabouts to define this new property? Perhaps it's done within the GUI designer?

From stackoverflow
  • In the current version of the EF, the only way to do this is as a .NET function in your partial class for the entity. This means you can't use the new property in LINQ to entities or ESQL, but it works very well otherwise.

    A possible workaround is to do it on the DB server, but the EF would be totally unaware of the relationship between the properties.

    In a future version of the EF, this will be supported in the EDMX.

What causes this code not to work?

I'm trying to understand why this does not work. (Basic example with no validation yet)

When I test it, firebug states Product.addPage is not found.

var Product = function ()
{
    var Page = function ()
    {
        var IMAGE = '';

        return {
            image : function ()
            {
                return IMAGE;
            },
            setImage : function (imageSrc_)
            {
                IMAGE = '<img id="image" src="' + imageSrc_ + '" height="100%" width="100%">';
            }
        };
    };
    var PAGES = [];

    return {
        addPage : function ()
        {
            var len = PAGES.length + 1;
            PAGES[len] = new Page();
            return PAGES[len];
        },
        page : function (pageNumber_)
        {
            var result = PAGES[pageNumber_];
            return result;
        }
    };
};

// Begin executing
$(document).ready(function ()
{
    Product.addPage.setImage('http://site/images/small_logo.png');
    alert(Product.page(1).image());
});
From stackoverflow
  • How about Product.addPage().setImage('http://site/images/small_logo.png');?


    Edit: Turns out I only caught half the problem. Look at dtsazza's answer for the whole thing.

  • You're trying to reference the addPage property of the Product function (which in this case is a constructor), rather than on the returned object.

    You probably want something like:

    // Begin executing
    $(document).ready(function ()
    {
        var product = new Product();
        product.addPage().setImage('http://site/images/small_logo.png');
        alert(product.page(1).image());
    });
    which also adds the brackets to the addPage call (though this is not the problem that FireBug will have been complaining about as it will not be able to find that method anyway).

  • This would work too:

    Product().addPage().setImage('http://site/images/small_logo.png');
    
    Andrzej Doyle : It would on that line - but the next line would not be able to call page(1) on the same instance of product, which it needs to. Thus storing as a local variable is required.
  • How about:

    var Product = {
     Page : function() {    
      return {
       _image : '',
       Image : function() {
        return this._image;
       },
       setImage : function(imageSrc_) {
        this._image = '<img id="image" src="' + imageSrc_ + '" height="100%" width="100%">';
       }
      };
     },
     Pages : [],
     addPage : function() {
      var Page = new Product.Page();
      this.Pages.push(Page);
      return Page;
     },
     GetPage : function(pageNumber_) {
      return this.Pages[pageNumber_];
     }
    };
    
    // Begin executing
    $(document).ready(function ()
    {
     Product.addPage().setImage('http://site/images/small_logo.png');
     alert(Product.GetPage(0).Image());
    });
    

Restoring Team Foundation Server

Hi Guys,

We are thinking of moving from Subversion to Team Foundation Server for our source control requirements. The reasoning behind this being that our project teams are getting bigger and management feel more comfortable using a M'soft product rather than an open sourced solution (I know - I've tried to argue the foolishness of this statement but am not getting anywhere).

So far we've had no issues except for in the case of replicating what would happen if the foundation server box completely died and we where left with just backups. We've tried following the plan at the following link - http://msdn.microsoft.com/en-us/library/ms404869.aspx - but its proving hellish difficult!

We're just wondering whether this is supposed to be such a pain or whether we're just really dim or something. I know with a combination of Subversion and Tortoise I could get the whole thing back up and running within a couple of hours but this is currently taking days. Anyone with any advice - it would be much appreciated!

Cheers!

From stackoverflow
  • Restoring a TFS server is a pain, you're not just dim. You might want to think about having a standby server instead (both for the app tier and data tier). It's not too painful to switch to the standby and can be done quickly. Though of course you'll still want backups just in case of anything.

  • It shouldn't be taking days. Do you have some huge WSS databases? If so, you can ignore those during an initial restore, since that's not where your core source code is at.

    The most important thing is to get your App Tier and Databases back online. The easiest thing might be just to email me at foyc at cornetdesign dot com and I can help either walk you through it, or get you in touch with the right people. But I've dealt with critical restores, and it's never taken days before.

  • hi guys,

    thanks for the replies. the reason we're being so slow is probably because we are being dim. we must have spent a day trying to get tfs installed onto our sql server... we downloaded SQL from MSDN where it was reported as being SQL2005 SP2 (@@version also reported this) however when i looked at the version number i realised that it wasnt (or it was some incompatible version of SP2). installing SP2 onto it eventually allowed us to install TFS

    i guess the problem is probably due to our lack of experience with TFS and WSS. i appreciate the offer of help cory - you may come to regret this! however we've been told to leave it for the immediate future and just stick with subversion. we'll probably have to come back to it soon though.

    thanks for the help anyway!

How do I write a Mock Object?

My first programming job introduced me to unit testing and the concept of mock objects, but something always felt wrong about it.

Let's say we were writing a bank app, and needed to mock a BankAccount object:


    // boilerplate code
    public interface IBankAccount {
        void Deposit(int amount);
        void Withdrawal(int amount);
        int getBalance();
        int getAccountNumber();
    }

    public interface IBankAccountFactory {
        IBankAccount getAccount(int accountNumber);
    }

    public class ProductionBankAccountFactory implements IBankAccountFactory { 
        public IBankAccount getAccount(int accountNumber) {
            return new RealBankAccount(accountNumber);
        }
    }

    public class MockBankAccountFactory implements IBankAccountFactory {
        public IBankAccount getAccount(int accountNumber) {
            return new MockBankAccount(accountNumber);
        }
    }

    public static class BankAccountFactory {
        // ewww, singletons!
        public static IBankAccountFactory Instance;
    }

    // finally, my actual business objects
    public class MockBankAccount implements IBankAccount {
        public MockBankAccount(int accountNumber) { ... }
        // interface implementation
    }

    public class RealBankAccount implements IBankAccount {
        public RealBankAccount(int accountNumber) { ... }
        // interface implementation
    }

Each class has a purpose:

  • The factory and factory interfaces exist to wrap up the constructors to our mock and real objects.
  • The static BankAccountFactory class allows us to assign BankAccountFactory.Instance an instance of IRealBankAccountFactory or MockBankAccountFactory at the start of our production app or tests respectively.
  • Once everything is set up properly, any class can grab an instance of IBankAccount simply by calling:

    BankAccountFactory.Instance.getAccount(accountNum);

This works, but it results in a lot of boilerplate code. I shouldn't have to write 5 new classes for each class I want to mock. I'm convinced there's an easier way, so I have to ask the SO community:

Is there a better or preferred way of writing mock objects?

[Edit to add:] I appreciate the links to the mocking and DI frameworks, but right now I'm working on a 500 KLOC application, and at least 60% of the code consists of the boilerplate mock classes in the style above.

I just want to reduce the size of the codebase without re-writing large chunks of code for Yet-Another-Framework™, so it helps me more to see mock classes written by hand. :)

From stackoverflow
  • The better way is to have someone else write it. Some options here are:

    Moq - http://code.google.com/p/moq/

    Rhino Mocks - http://ayende.com/projects/rhino-mocks.aspx

  • There are Mock libraries that simplify the process by allowing you to specify the object and it behaviour in the unit testing code.

    A good example is the Moq library (http://code.google.com/p/moq/)

  • I guess my first question is why you need to use a factory pattern to wrap the construction of your objects; in particular your Mock object. Since each unit test in a suite should run completely independently of any other unit tests, it seems like you would be able to instantiate your MockBankAccount directly in the setUp method of your unit test class, or even in the test itself. If I were in the situation above, I would write something like this:

    public interface IBankAccount {
        void Deposit(int amount);
        void Withdrawal(int amount);
        int getBalance();
        int getAccountNumber();
    }
    
    public class MockBankAccountFactory implements IBankAccountFactory {
        public IBankAccount getAccount(int accountNumber) {
            return new MockBankAccount(accountNumber);
        }
    }
    
    public class BankAccountUnitTest extends TestCase {
        IBankAccount testBankAccount;
    
        public void setUp() {
            testBankAccount = new MockBankAccount(someAccountNumber);
        }
    
        // Unit tests here
    }
    

    If you're using the factory in order to unit test another class that uses IBankObject, then you should look into dependency injection to supply a mock object to that class, rather than having the class under test instantiate a mock object.

java and javascript callbacks compared

Hello,

It seems I don't understand javascript callbacks quite as well as I thought.

In the following example, I would think that each copy of function in setTimeout would refer to its own copy of the variable "index". Therefore, running the example should produce the following alerts: "zero" "one" "two".

var array = ["zero", "one", "two"];
var out = "";
for(var i = 0; i < 3; i++){
    var index = i;
    setTimeout(  function(){alert(array[index])},  1 );
}

However, it seems that theres only one copy of the index variable, and all copies of the callback function point to the same variable, giving me the following alerts: "two" "two" "two".

The following analagous (I thought) example in java prints "zero" "one" "two", as expected.

import java.util.ArrayList;
import java.util.List;


public class CallBacks {

  public static void main(String[] args) {

    String[] array = {"zero", "one", "two"};
    List<Callback> callBacks = new ArrayList<Callback>();
    for(int i = 0; i<3; i++){
      final String print = array[i];
      callBacks.add(
              new Callback(){
                public void execute(){
                  System.out.println(print);
                }
              }
      );
    }
    for(Callback cb : callBacks){
      cb.execute();
    }
  }

  private interface Callback{
    public void execute();
  }

}

Can anyone explain to me why the js example doesn't work, and perhaps compare what's going on in the two examples?

From stackoverflow
  • index changes with each iteration of the loop. What you want is to place index into a closure not affected by the loop:

    var array = ["zero", "one", "two"];
    var out = "";
    for(var i = 0; i < 3; i++) {
        (function(index) {
            setTimeout(  function(){alert(array[index])},  1 );
        })(i)
    }
    
    morgancodes : Thanks. I guess I thought that each iteration of the for loop would create a closure.
    Crescent Fresh : Well yes, technically I left that part out. There *is* a closure around index. But it is declared in an outer scope to the function passed to setTimeout. "closure" != "unchanging variable".
    morgancodes : Cool. One more question: why does the function declaration need to be wrapped in parens?
    Christoph : @morgancodes: that's just convention; also, there might be some cases where the parser might otherwise produce incorrect results
    morgancodes : Firefox tells me there's a syntax error if I leave them out.
    Jason S : closures in javascript (references to variables outside the function) retain their association... if you refer to a loop variable in a function called after the loop ends, in the function call you get the value of that variable after the loop.
    Jason S : the function call/parens/etc create a copy of the value "i" into the variable "index", at the time of each iteration of the loop.
  • In javascript the for loop does not have it's own scope - so a var you create inside a loop is not different from one defined outside of it.

  • I asked an almost identical question yesterday and got a couple of different variations in the answers and some discussion on the merits of each. Might be worth a look

  • Private Members In JavaScript is my favorite reference on closures. It is written as a recipe for providing private variables in JS objects (maybe useful, maybe not) but in the process goes through an excellent introduction of how closures work in general, and especially in JS.

    The comp.lang.javascript FAQ has a worthwhile section on closures as well.

    Closures can be confusing so I put together a working example of the shortest useful closure I've come across, which was in the Rhino book.

    Oh and I don't have enough rep to comment yet :) but I saw your question above about why you have to put parenthesis around functions sometimes. That's only necessary when you invoke an anonymous function inline. For example the parenthesis are required here:

    (function (arg) {alert(arg);})('hi world');
    

    Because you are creating a function and then immediately invoking it. But the parens are not necessary in the usual case where you are just declaring a named function for later use.

    morgancodes : Thanks Noah. that rhino book example is cool.

Weird ItemRenderer behavior

I have a really odd issue with an ItemRenderer. I have a main.mxml container with a ViewStack. When a user logs in, the initial view contains an AdvancedDataGrid--containing some data and the ItemRenderer below--which simply displays a Delete button. When the user logs in, this AdvancedDataGrid is automatically refreshed from the database. The Delete button should be enabled or disabled based on the user's role membership.

Scenario 1 (Logging in as an admin):

  1. Admin user logs in -- datagrid view is immediately displayed and Delete button is properly enabled for every row
  2. Logout
  3. Login as a non-admin user -- Data is refreshed and all of the rows are still enabled except for one. It could be the first, second or third rows--it's completely random. It's really wierd . . .

I restart my browser and follow scenario 2 . . .

Scenario 2 (Logging in as an non-admin):

  • Non-admin user logs in -- datagrid view is immediately displayed and Delete button is properly disabled for every row
  • Logout
  • Login as a admin user -- All of the rows are still disabled except for one. It could be the first, second or third rows--it's completely random. Just the reverse of the first scenario.

INTERESTING FACT-- If I put a breakpoint in checkDeleteSecurity, it reaches it ONLY WHEN THE FIRST USER LOGS IN AND THE DATAGRID IS FIRST REFRESHED. When I logout and the next user logs in, the data grid is refreshed, but the checkDeleteSecurity breakpoint is never caught.

[Bindable]
private function checkDeleteSecurity ():Boolean
{
     return (SecurityProxy.CheckSecurity(SecurityProxy.UserName));
}

<mx:LinkButton label="Delete" click="onDeleteClick()" id="lbDelete" enabled="{checkDeleteSecurity()}"/>
From stackoverflow
  • what you should be doing is when your data is refreshed call lbDelete.enabled = checkDeleteSecurity(); This will make sure that the security function is called each time the data is refreshed.

    I think that whats happening is your component is being created which calls the security function, but once its created then there is nothing to update the linkbutton.

    Once an itemrender is created, say it generates 6 then when you refresh the data it will use those 6 itemrenders which are already created for the next set of data (but with updated data). If the next set of data needs 8 itemRenderers then it will only need to create another 2 renderers. So only those 2 itemrenders will call the security function as they haven't been created yet.

  • It sounds like you might have a couple of things going on here. First, it's worth noting that ItemRenderers are re-used; in a grid (or list, etc.) containing, say, a list of ten album tracks, one row for each track, each row gets rendered properly when the list is initially created -- but when the underlying album, to extend the example, gets changed, the album-track renderers themselves will only respond automatically to the change if they're properly wired up to do so. Generally this involves overriding the setter of the data property of the renderer:

    override public function set data(value:Object):void
    {
        super.data = value;
    
        // .. Take some action
    }
    

    That's probably why your CheckSecurity method doesn't get called on data changes -- because the button's enabled property is the only way into it, and the button's already been rendered.

    Also, binding to a function has its own issues. Someone actually asked this question last night, doing something quite similar to what you're doing (setting state on a button by binding to the result of a Boolean function):

    http://stackoverflow.com/questions/445313/can-i-bind-a-flex-component-property-to-a-function#445669

    Hope that helps! I'll keep an eye on the thread for follow-up comments if you have any.

    : That was my question . . . This was part 2 ;)
    : The data property setter will be called every time the item row is bound? That's interesting. So, if I have 10 rows of data in datagrid with a Delete button in an ItemRenderer. I pull new data and only get 3 rows. Even though rows 4-10 look empty, you're saying the Delete button is still rendered?
    : Overriding set data did it!
    Christian Nunciato : Awesome, good to hear. Yeah, I'm surprised it took me so long to learn that one myself; I've read several Flex books, and loads of docs, and for how useful it is to know, you'd think it'd be more prominently documented. Oh, well -- glad it helped!

Computer Graphics: Raytracing and Programming 3D Renders

I've noticed that a number of top universities are offering courses where students are taught subjects relating to Computer Graphics for their CS majors. Sadly this is something not offered by my university and something I would really like to get into sometime in the next couple of years.

A couple of the projects I've found from some universities are great, although I'm mostly interested in two things:

  • Raytracing:
    • I want to write a Raytracer within the next two years. What do I need to know? I'm not a fantastic programmer yet (Java, C and Prolog are my main languages as of today) but I'm slowly learning every day. Also, my Math background isn't all that great, so any pointers on books to read or advice on writing such a program would be fantastic. I tend to pick these things up pretty quickly so feel free to chuck references at me.
  • Programming 3D Rendered Models
    • I've looked at a couple of projects where students have developed models and used them in games. I've made a couple of 2D games with raster images but have never worked with 3D models. What would I need to learn in regards to programming these models? If it helps I used to be okay with 3D Studio Max and Cinema4D (although every single course seems to use Maya), but haven't touched it in about four years.

Sorry for posting such vague and, let's be honest, stupid questions. It's just something I've wanted to do for a while and something that'd be good as a large project for me to develop in my own time.

Related Questions

From stackoverflow
  • The briefest useful answer I can give is that most of the important algorithms can be found in Real-Time Rendering by Tomas Akenine-Möller, Eric Haines, and Naty Hoffman, and the bibliography at the end has references to the necessary maths. Their website has a recommended reading list as well.

    The most useful math book I've read on the subject is Eric Lengyel's Mathematics for 3D Game Programming and Computer Graphics. The maths you need most are geometry (obviously) and linear algebra (for dealing with all the matrices).

  • The 2000 ICFP Programming Contest asked participants to build a ray tracer in three days. They have a good specification for a simple ray tracer, and you can get code for the winning entries and some other entries as well. There were entries in a large number of different programming languages. This might be a nice way for you to get started.

    EnderMB : That looks fantastic! I'll have great fun going over some of those programs. Thank you!
  • I took such a class last year, and I believe that the class was wonderful for forcing students to learn the math behind the computer graphics - not just the commands for making a computer do what you want.

    My professor has a site located here and it has his lecture notes and problem sets that you can take a look through.

    Our final project was indeed a raytracer, but once you know the mathematics behind it, coding (an inefficient one) is trivial.

  • The book "Computer Graphics: Principles and Practice" (known in the Computer Graphics circles as the "Foley-VanDam") is the basic for most computer graphics courses, and it covers the topic of implementing a ray-tracer in much detail. It is quite dated, but it's still the best, afaik, and the basic principles remain the same.

    I also second the recommendation for Eric Lengyel's Mathematics for 3D Game Programming and Computer Graphics. It's not as thorough, but it's a wonderful review of the math basics you need for 3D programming, it has very useful summaries at the end of each chapter, and it's written in an approachable, not too scary way.

    In addition, you'll probably want some OpenGL or DirectX basics. It's easier to start working with a 3D API, then learn the underlying maths than the opposite (in my opinion), but both options are possible. Just look for OpenGL on SO and you should find a couple of good references as well.

    Crashworks : I didn't care much for Foley-VanDamm; it's dated enough that many of the techniques just aren't relevant any more (it hardly mentions fixed-function shaders) and the style is so terse that it's hard to take the math into code.
    Kena : I agree, it's pretty terse. But compared to most "Weee, Computer Graphics is fun fun fun, look what I can do with those nice pixels" textbooks, it gives solid mathematical foundations. But then I'm a math geek.
  • For a mathematical introduction into these topics, see

    http://graphics.idav.ucdavis.edu/education/GraphicsNotes/homepage.html

  • I can recommend pbrt, it's a book and a physically-based renderer used to teach computer science graduates. The description of the maths used is nice and clear, and since it is written in the 'literate programming' you can see the appropriate code (in C++) too.