Monday, April 11, 2011

Can I develop an iPhone app using java?

Hi

Is it possible to develop applications for the iPhone using Java? And if so, does it allow the use of custom jar files?

Thanks.

From stackoverflow
  • That would be a no. The Apple agreement says that no interpreted/other languages are allowed. period.

    Marcelo Cantos : Java isn't an interpreted language. Of course, since you answered this, Java has become explicitly disallowed. :-/
  • objective c

  • AlcheMo might be worth a look (I haven't had time to investigate it at all yet)

  • Have you tried this: http://tinyurl.com/c9zpw2 the first link allows you to develop Java apps for iPhone. I haven't tested xmlvm but it might be what you need.

401.1 Error when accessing virtual directory pointing to network share

IIS5 is running on SERVER1.

One of the virtual directories in IIS, myfiles, is pointing to "A shared location on another computer", //SERVER2/myfilesshare

When I try to access the page: http://SERVER1/myfiles

... I get the error:

You are not authorized to view this page

HTTP 401.1 - Unauthorized: Logon Failed

Internet Information Services

I have triple-checked the "Connect As..." settings in IIS. The credentials I'm using to access the share are correct-- they work when connect to the share in Windows Explorer, but not through the IIS virtual directory. I've tried granting full permission to Everyone on the folder in SERVER2, but no luck.

Any thoughts?

From stackoverflow
  • try enabling windows authentication on the virtual directory security tab (in IIS).

    frankadelic : That causes a username/password prompt to pop up when I access the site. However, even if I then enter the correct credentials it doesn't work. Note the two servers are not part of the same domain.
  • Permission issues can be tricky. Try running filemon on the 'other computer' It can be downloaded over here: http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx (it's not a big application just a tiny lightweight tool)

    After you've started filemon, stop the monitor process (I believe it's turned on by default when you start the application), clear the logged data, create a filter for the folder you have trouble getting access to. Start the monitor process. Request your webpage. Stop the monitor process and look for "access denied" messages in filemon. When found, filemon will also mention the name of the actual user which is trying to get access. This might help you to get to a solution.

    Btw when using Windows Server 2008 you will need processmon instead: http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx

    frankadelic : For some reason, filemon isn't showing anything relevant to that file on the shared machine. Event Viewer revealed that ASPNET did not have permissions on the web.config file on the network share. How can I give the local ASPNET user on server1 access to server2?
    Lex Li : Well, can you also create an ASPNET account on that server and assign relevant permissions? Also you may try to run ASP.NET application under a domain account.

Google Spreadsheet range names

In Google Docs Spreadsheets, one can use Range Names to put labels on ranges of cells to make formulas more legible. In most formulas, one can use the range C:C to denote the entire C column, and C2:C to denote the entire C column after and including C2.

Is there a way to create range names of the same nature? When I try C:C or C2:C or Sheet!C:C or 'Sheet'!C:C I always get the error "The range you specified is not in a valid range format." I would like the range name to expand as my form adds rows to my spreadsheet. Thanks.

From stackoverflow
  • I don't think so... even if you select a column manually while in the Range Name selector, it complains. That would be a nice feature and it would make sense since they support column ranges for formulas already.

How to use the JFace FileDialog from within an Eclipse plugin in a modeless way?

I am writing an Eclipse plugin, and in response to some action I am interesting in starting a series of operations (within a separate job). One of these operations is to request the user to provide a filename, which I'm trying to do with the JFace JDialog.

However, I'm not clear how to do this in a modeless way; for example, where do I obtain a display and shell? How do I ensure the UI continues to work while the developer can edit stuff in the dialog?

From stackoverflow
  • May be you could see how Eclipse itself does it:

    FindAndReplaceDialog.java

     /**
      * Creates a new dialog with the given shell as parent.
      * @param parentShell the parent shell
      */
     public FindReplaceDialog(Shell parentShell) {
         super(parentShell);
    
         fParentShell= null;
    
         [...]
    
         readConfiguration();
    
         setShellStyle(SWT.CLOSE | SWT.MODELESS | SWT.BORDER | SWT.TITLE | SWT.RESIZE);
         setBlockOnOpen(false);
     }
    
     /**
      * Returns this dialog's parent shell.
      * @return the dialog's parent shell
      */
     public Shell getParentShell() {
         return super.getParentShell();
     }
    
    /**
     * Sets the parent shell of this dialog to be the given shell.
     *
     * @param shell the new parent shell
     */
    public void setParentShell(Shell shell) {
        if (shell != fParentShell) {
    
            if (fParentShell != null)
                fParentShell.removeShellListener(fActivationListener);
    
            fParentShell= shell;
            fParentShell.addShellListener(fActivationListener);
        }
    
        fActiveShell= shell;
    }
    

    It does manage its parent shell depending on the focus of the Dialog.

     /**
      * Updates the find replace dialog on activation changes.
      */
     class ActivationListener extends ShellAdapter {
         /*
          * @see ShellListener#shellActivated(ShellEvent)
          */
         public void shellActivated(ShellEvent e) {
             fActiveShell= (Shell)e.widget;
             updateButtonState();
    
             if (fGiveFocusToFindField && getShell() == fActiveShell && 
                   okToUse(fFindField))
                 fFindField.setFocus();
    
         }
    
         /*
          * @see ShellListener#shellDeactivated(ShellEvent)
          */
         public void shellDeactivated(ShellEvent e) {
             fGiveFocusToFindField= false;
    
             storeSettings();
    
             [...]
    
             fActiveShell= null;
             updateButtonState();
         }
     }
    

    A ShellAdapter is provides default implementations for the methods described by the ShellListener interface, which provides methods that deal with changes in state of Shell.

  • The importent thing is that the style value should include SWT.MODELESS.

    The style is one of the most important things in SWT you should look at, because you can control and initialize a lot only because of the styel value.

vector scope with struct

Hi,

Beginner question here:

im reading a file, storing the feilds into struct members, then storing the name of the struct into a vector.

I output the size of my vector and debug it to see if it worked and i have the feilds from the file isolated.

im doing this in a vector *ptrFunc() function.

and i return the &vectorObject so i dont need to use a vector type ptr obj declaration.

Moving from one function to the other, even with my return type, do i need to parse the file all over again?

Heres some code, im dont think im being very clear:

  //Varaible Declartions/Intializations
  //Open File

   vector<myStruct> *firstFunc()
   {

    while ( !inFile->eof() )
    {
 // Isolating each feild delimited by commas
 getline( *inFile, str1, ',' );
 myStruct.f1 = str1;

 getline( *inFile, str2, ',' );
 myStruct.f2 = str2;

 getline( *inFile, str3, ',' );
 myStruct.f3 =  atof( str3.c_str()  );

 getline( *inFile, str4 );
 myStruct.f4 = atof( str4.c_str() );

 v.push_back( myStruct );
       // We have the isolated feilds in the vector...
       // so we dance
        }
     return &v;
      }
   // Now do i still have to do the getlines and push_back with the vector again in  another function?

   vector<myStruct> *otherFunc()
   {
      sStruct myStruct;
      vector<myStruct> *v = firstFunc(),
      vInit;
      v = &vInit
      vInit.push_back( myStruct );
      ...

so thats where i debug it and my Structure Members have lost all data!

What should i prolly do in the first function so that my struct members do not lose their data?

My guess is to just create a void function or something. But then storing that into a vector would then be the problem.

Im just have scoping issues. :p

From stackoverflow
  • Is it perhaps so that the vector 'v' you return from firstFunc() is allocated on the stack? If so, then that's probably your problem, since you're returning the address of an object that is going out of scope as the function exits.

    So fix that, return the vector by value, or create it on the heap using new.

  • Declare your functions this way:

    void firstFunc(vector<myStruct> &v) 
    {
    ...
    }
    
    void otherFunc(vector<myStruct> &v) 
    {
    ...
    }
    

    and use them this way

    void foo()
    {
    vector<myStruct> v;
    firstFunc(v);
    otherFunc(v);
    }
    

Stack unwinding in case of structured exceptions

This question provides more clarity on the problem described here. I did some more investigation and found that the stack unwinding is not happening in the following piece of code:

class One
{
public:
    int x ;
};

class Wrapper
{
public:
    Wrapper(CString csText):mcsText(csText)
    {
     CString csTempText;
     csTempText.Format("Wrapper constructor :: %s\n", mcsText);
     OutputDebugString(csTempText);
    }

    ~Wrapper()
    {
     CString csTempText;
     csTempText.Format("Wrapper destructor :: %s\n", mcsText);
     OutputDebugString(csTempText);
    }
    CString mcsText;
};
class Test
{
    public:

    void notifyError()
    {
        try
     {
      int x = 10; 
     }
     catch(...)  {}
    }

    void OnRecvBuffer()
    {
     try
     {
      Wrapper a("AddRef"); 
      One* p = NULL;
      p->x = 10;
     }
     catch(...)
     {
      notifyError();
     } 
    } 
};



int main() 
{
    Test* pTest = new Test;

    pTest->OnRecvBuffer();

    OutputDebugString("Test");
}

I compiled this code using VC6 SP5 compiler and the output is "Wrapper constructor :: AddRef!!!" (i.e. the destructor of wrapper object which was constructed on stack is not called. Is this the expected behavior ? or is it a bug with VC compiler ? Can I use some compiler flags so that the stack unwinding happens in this case?

From stackoverflow
  • The C++ standard does not give anything to work with in case of Undefined Behavior. Even if MS does. That's a platform specific thing -- so beware. Some such floating point exceptions are turned to Win32 exceptions which you can attempt to catch with _set_se_translator(). The problem is you can catch Win32 exceptions but then your stack will not be unwound properly. At least that is not something you can bet your life on. Wherein lies the futility of the exercise.

    Update: The exception is thrown intentionally to check the stack unwinding. The question is why Wrapper class's destructor is not getting called. – Naveen

    If this is the case -- don't do it. There are better ways to throw exceptions than via Undefined Behavior.

    E.g:

    void OnRecvBuffer()
    {
        try
        {
            Wrapper a("AddRef");    
            throw 42; // this'll throw an exception without invoking UB
        }
        catch(...)
        {
            notifyError();
        }
    }
    

    You cannot dereference a NULL pointer. You are invoking Undefined Behavior here:

    One* p = NULL;
    p->x = 10;
    

    After that line all bets are off and you could have killed us all ;)

    p is a pointer to a One object. It should contain the address of an One object. You have initialized it to 0 -- there is no object at address 0. 0 is not a valid address for any object (this is guranteed by the standard).

    Naveen : The exception is thrown intentionally to check the stack unwinding. The question is why Wrapper class's destructor is not getting called.
    dirkgently : As I have pointed out that is UB -- what happens when you invoke UB is not defined. No point discussing that. There are other better ways to throw exceptions.
    bk1e : The example program invoked what is undefined behavior for standard C++, but the question is about Microsoft SEH (Structured Exception Handling), not standard C++ exceptions.
    dirkgently : I can figure that out. But a) SEH is never mentioned in OP's question. b) doing things wrong don't make it a right.
    dirkgently : So, stop downvoting my answer since this is perfectly correct.
  • Because C++ regular exception does not handle this kind of exception, you have to use SEH which does not know anything about the app and does not unwind.

  • If you want to use SEH, you must use _set_se_translator function and /EHa compiler option.

  • This is undefined behavior:

    One* p = NULL;
    p->x = 10;
    

    At this point the application is free to crash without unwinding the stack.
    If you want to test the stack unwinding replace this with:

     throw 42; // Life the Universe and Everything thrown away
    

    You should not dynamically allocate all your objcts this is C++ not Java!

    int main() 
    {
        Test    pTest;   // Note the lack of new!
    
        pTest.OnRecvBuffer();
    
        OutputDebugString("Test");
    }
    
  • This is indeed a problem with VC6.

    Please refer to the following article for a good explanation: http://www.thunderguy.com/semicolon/2002/08/15/visual-c-exception-handling/

Best Mind Map Software

I like to use mind mapping software when I first start a project to gather specifications. What are the best free and commercial mind mapping applications?

From stackoverflow
  • MindJet MindManager. I use it on my Tablet PC and love it.

  • I've used FreeMind before: http://freemind.sourceforge.net/wiki/index.php/Main_Page

    It's written in Java and a little clunky, but it gets the job done (for free!).

  • Mindomo is a nice web-based mind-mapping tool. There's both a free and a paid version available; I've used the free one on occasion, and it's really well done.

  • CMAP Tools is a very good one that I have used before. It generates websites of your maps and allow you to attach documents etc.

  • Personal Brain 4 is the best mind mapping software that I've come across. It's available on all major platforms and has free and commercial editions. It makes use of a dynamic GUI that is able to map both hierarchical as well as network relationships.

  • imindmap

  • You might also want to take a look at Tree, which is for the Mac.

  • [I am plugging my own product here, but it's 1) free 2) it's so free that currently I make no money from it in any form.]

    I recommend my .Net product, TheKBase, or the Flex/ASP.NET version (although I wouldn't mention that fact if we weren't on StackOverflow), which is hosted by me here. Why is it good for mind-mapping?

    • Because it works in a way that we are used to: Windows-Explorer type tree (or whatever you want to call it, you get the point).
    • But in TheKBase, instead, they are multiple-hierarchical (multiple children AND parents).
    • That's it. There are snippets which have a title, text (including links, but no attachments (yet? ever?)), and an icon. And they can be arranged in a multiple-hierarchical fashion. Totally simple, like your brain (we're trying to mind-map, right?), but able to handle structures of any complexity. Like your brain.

    Now you might want to see a giant cool clicky map like PersonalBrain, which is interesting and beautiful but in the end it's really cumbersome (even though their product is way more advanced in terms of overall features, like attachments, and obviously has more person-hours dedicated to it). How can I demonstrate that other maps are cumbersome? Because PersonalBrain, aside from the really cool map, uses 'tags.' In TheKBase, there are no tags. One concept covers everything: a multiple hierarchy running in one direction (because hierarchies need to have a flow direction: free will is too hard to handle).

    And it works and you can find stuff and once you do, you can work on it without worrying about 'where it really is' in the hierarchy. Because it's actually in multiple places, one of which is as a child of the Search Results snippet. Some of those other places might interest you... hence it's got a Parents' Pane as well (just the hierarchy flipped).

    And it works, and it's stable, and we, I mean I, fix a all known bugs so it's way more stable and dependable than many other freewares [sic] of its class... I keep my important stuff in it, in fact.

    Yar : For some reason this answer has been getting some attention of late, so I might add that I have an Alpha-running-on-Mono for OSX version now, that I hope to release sometime soon.
  • Forever conceptdraw mind map.

  • mindmeister is my favourite so far. Nice web interface. Its free to use online, and they offer an offline (that uses google gears) version that you pay a subscription for.

  • I find XMind (free) to be pretty good.

  • I use Mindmanager and it does the biz. It's commercial (a couple of hundred I seem to recall) and they seem to be very active in adding features. There is a web version as well as desktop and one thing I thought was cool (but haven't ever really used ;-) is that it can output your interactive mind maps into a pdf ...

Code for splitter in vb.net

Hi guys, I have a treeview and a gridview in my page.My application is windows application in vb.I want to use splitter to move treeview and a gridview.Can anyone help to give the splitter code to do this.

From stackoverflow

Parse Error while using ScriptManager

I have a web application that was working fine two days before. When I moved this web site to another machine, then facing following problem.

In my web page, I have declared ScriptManager as:

<asp:ScriptManager ID="scriptMgr" runat="server">
</asp:ScriptManager>

And when I visit the web page, I am getting this error:

The base class includes the field 'scriptMgr', but its type (System.Web.UI.ScriptManager) is not compatible with the type of control (System.Web.UI.ScriptManager).

And on another web page, I am getting following error:

The base class includes the field 'upProgress', but its type (System.Web.UI.UpdateProgress) is not compatible with the type of control (System.Web.UI.UpdateProgress).

My web application is built on ASP.NET 2.0 and I have also verified that the correct(1.0.61025.0) version of System.Web.Extensions.Dll is present in my application's bin folder.

Entry for the System.Web.Extensions.Dll in the web.config are:

<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
  <section name="CSI.OLS.Library.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
  <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
    <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
    <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
      <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere" />
      <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" />
      <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" />
    </sectionGroup>
  </sectionGroup>
</sectionGroup>


It seems that both the error are related to using AJAX feature. Can anyone tell me, what may be causing the aforementioned error?

From stackoverflow
  • Doesn't asp.net 2.0 need an extensions patch to correctly support ajax apps?

    http://www.asp.net/AJAX/downloads/

    Sachin Gaur : I have already installed this patch. Still, I am facing error.
    BenB : then please post your web.config
    Sachin Gaur : I have added the web.config entry, Please look into this issue.
  • This seems to be a .NET 2.0 AJAX 1.0 vs .NET 3.5 AJAX issue. (IE, the AJAX library was included directly in .NET 3.5 and it appears that you're trying to use the .NET 3.5 version of the AJAX libraries.)

    I've encountered the same problem in an application and found this reference to the issue with two suggestions for solving the problem.

    One suggestion is in your project file's reference to the System.Web.Extensions.dll assembly to set the Specific Version property to True. Since you're explicitly referencing the 1.0.61025.0 version of this assembly, I suspect this would fix the problem.

  • Hi, a late answer :) but I had a similar problem in my product and solved it by adding the following to web.config

    <runtime>
         <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
           <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
           <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/></dependentAssembly>
          <dependentAssembly>
           <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
           <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/></dependentAssembly>
            </assemblyBinding>
    </runtime>
    

    This redirects assembly binding so that the new version is used, therefore solving the conflicts

Wi-Fi Application

HI

I am developing game in that I want to Play that game through Wi-Fi. So more that one

player can also play the game. I want to develop this game for iphone. I gone through WiTap

application which is on developer.apple.com since it's very hard to use. So if anybody knows how to send a simple data such as integer or string etc. through Wi-Fi for iphone to iphone. Please help me to use simple application. :)

From stackoverflow

How can I make my simple .NET LRU cache faster?

UPDATE: Hey guys thanks for the replies. Last night and tonight I tried a few different approaches and came up with one similar to the one laid out below by Jeff (I had even already done what he suggested in his update, and put together my own simple LL implementation for additional gains). Here is the code, at this point it doesn't look particularily clean anymore, but I have been over this numerous times changing anything I could to beef up performance.

public class NewLRU2<K, V> where V : class
{
    int m_iMaxItems;
    Dictionary<K, LRUNode<K, V>> m_oMainDict;

    private LRUNode<K,V> m_oHead;
    private LRUNode<K,V> m_oTail;
    private LRUNode<K,V> m_oCurrent;

    public NewLRU2(int iSize)
    {
        m_iMaxItems = iSize;
        m_oMainDict = new Dictionary<K, LRUNode<K,V>>();

        m_oHead = null;
        m_oTail = null;
    }

    public V this[K key]
    {
        get
        {
            m_oCurrent = m_oMainDict[key];

            if (m_oCurrent == m_oHead)
            {
                //do nothing
            }
            else if (m_oCurrent == m_oTail)
            {
                m_oTail = m_oCurrent.Next;
                m_oTail.Prev = null;

                m_oHead.Next = m_oCurrent;
                m_oCurrent.Prev = m_oHead;
                m_oCurrent.Next = null;
                m_oHead = m_oCurrent;
            }
            else
            {
                m_oCurrent.Prev.Next = m_oCurrent.Next;
                m_oCurrent.Next.Prev = m_oCurrent.Prev;

                m_oHead.Next = m_oCurrent;
                m_oCurrent.Prev = m_oHead;
                m_oCurrent.Next = null;
                m_oHead = m_oCurrent;
            }

            return m_oCurrent.Value;
        }
    }

    public void Add(K key, V value)
    {
        if (m_oMainDict.Count >= m_iMaxItems)
        {   
            //remove old
            m_oMainDict.Remove(m_oTail.Key);

            //reuse old
            LRUNode<K, V> oNewNode = m_oTail;
            oNewNode.Key = key;
            oNewNode.Value = value;

            m_oTail = m_oTail.Next;
            m_oTail.Prev = null;

            //add new
            m_oHead.Next = oNewNode;
            oNewNode.Prev = m_oHead;
            oNewNode.Next = null;
            m_oHead = oNewNode;
            m_oMainDict.Add(key, oNewNode);
        }
        else
        {
            LRUNode<K, V> oNewNode = new LRUNode<K, V>(key, value);
            if (m_oHead == null)
            {
                m_oHead = oNewNode;
                m_oTail = oNewNode;
            }
            else
            {
                m_oHead.Next = oNewNode;
                oNewNode.Prev = m_oHead;
                m_oHead = oNewNode;
            }
            m_oMainDict.Add(key, oNewNode);
        }
    }

    public bool Contains(K key)
    {
        return m_oMainDict.ContainsKey(key);
    }
}


internal class LRUNode<K,V>
{
    public LRUNode(K key, V val)
    {
        Key = key;
        Value = val;
    }

    public K Key;
    public V Value;
    public LRUNode<K, V> Next;
    public LRUNode<K, V> Prev;
}

There are a few parts that look/feel wonky -- like reusing the old node when doing an add -- but I was able to get an appreciable boost in porformance out of them. I was also slightly surprised at the difference it made to switch from actual properties on the node to just public variables, but I guess that's how it goes with this stuff. At this point the code above is almost entirely performance-limited by the dictionary operations, so I'm not sure I'd get a lot more out of mashing it around. I'll continue to think on it and look into some of the responses.

Explanation From Original Post: Hello all. So I've written a simple lightweight LRU implementation for use in a compression library (I'm using it to find matching byte-strings in the input based on a hash, LZW-style), and I'm looking for ways to make it faster.

From stackoverflow
  • UPDATE #2

    This reduces the need for list traversal on a linked list Remove. It introduces a LruCacheNode that has both the key and the value. The key is only used when you trim the cache. You could get better performance if you wrote your own linked list implementation where each node essentially is an LruCacheNode along with a Next and Back reference. This is sort of what a LinkedHashMap does (see these two questions).

    public class LruCache<K, V>
    {
        private readonly int m_iMaxItems;
        private readonly Dictionary<K, LinkedListNode<LruCacheNode<K, V>>> m_oMainDict;
        private readonly LinkedList<LruCacheNode<K, V>> m_oMainList;
    
        public LruCache(int iSize)
        {
            m_iMaxItems = iSize;
            m_oMainDict = new Dictionary<K, LinkedListNode<LruCacheNode<K, V>>>();
            m_oMainList = new LinkedList<LruCacheNode<K, V>>();
        }
    
        public V this[K key]
        {
            get
            {
                return BumpToFront(key).Value;
            }
            set
            {
                BumpToFront(key).Value = value;
            }
        }
    
        public void Add(K key, V value)
        {
            LinkedListNode<LruCacheNode<K, V>> newNode = m_oMainList.AddFirst(new LruCacheNode<K, V>(key, value));
            m_oMainDict.Add(key, newNode);
    
            if (m_oMainList.Count > m_iMaxItems)
            {
                m_oMainDict.Remove(m_oMainList.Last.Value.Key);
                m_oMainList.RemoveLast();
            }
        }
    
        private LruCacheNode<K, V> BumpToFront(K key)
        {
            LinkedListNode<LruCacheNode<K, V>> node = m_oMainDict[key];
            if (m_oMainList.First != node)
            {
                m_oMainList.Remove(node);
                m_oMainList.AddFirst(node);
            }
            return node.Value;
        }
    
        public bool Contains(K key)
        {
            return m_oMainDict.ContainsKey(key);
        }
    }
    
    internal sealed class LruCacheNode<K, V>
    {
        private readonly K m_Key;
        private V m_Value;
    
        public LruCacheNode(K key, V value)
        {
            m_Key = key;
            m_Value = value;
        }
    
        public K Key
        {
            get { return m_Key; }
        }
    
        public V Value
        {
            get { return m_Value; }
            set { m_Value = value; }
        }
    }
    

    You'll have to profile things to see if this is an improvement in your environment.

    Minor Update: I updated BumpToFront to check to see if the node is already at the front per comment from Tim Stewart.

    David Hay : I tried this code out, and unfortunately it has demolished the performance. All other operations are now dwarfed by Contains which now uses 96% of all execution time -- I would expect due to traversing the entire list on every lookup.
    Jeff Moser : Try it again, I updated it to use a HashSet to optimize the .Contains code. If you can't use HashSet because you're working before 3.5, you can replace it with a Dictionary
    sixlettervariables : Very nice. @Jeff may I suggest you use Dict in order to enjoy better JIT? That suggestion was passed onto me so you can take advantage of probably already JIT'd Dict rather than Dict.
    sixlettervariables : Actually, after doing some runtime analysis it looks like yours is slower D: Definitely looks nicer though.
    Jeff Moser : What type of access patterns did you test?
    sixlettervariables : @Jeff: hit rates from 0-100% at 3 different cache sizes for 5 different sized working sets. Your update now outperforms both.
    Tim Stewart : Nice implementation! BumpToFront() could be optimized by checking to see if the node it's bumping is already at the front and, if so, there's no need to bump.
    Jeff Moser : @Tim Stewart: Fair point. I updated the code. Thanks!
  • With hardware caches, instead of having say 128 elements, and maintaining the order of items 1-128, you might have it as 32 x 4, so 32 rows of 4 elements each. The first 5 bits of an address would determine which of the 32 rows that address would map to, then you would search only the 4 items, and if not found replace the oldest of the 4.

    This is much faster, and is IIRC within 10% of the hit rate of a 1 x 128 cache.

    To translate, you would instead of one linked list, have multiple ones, so traversing them was much faster. You would have to have a way of determining which list a particular item mapped to.

    The point being, as your list grows in size, you get diminishing returns from trying to maintain with perfect accuracy the exact order of each element in the list. You might even be better off with an unordered list, and randomly replacing any element when you have a cache miss. Depends on the size of your list, and the penalty for a miss vs the cost of maintaining the list.

  • Isn't the point of a LRU cache to allow you to trim the cache and throw out the least-recently-used stuff? :-) I don't see any code to trim the cache. Since you most likely want high performance for the retrieve use-case, and the trim use-case is less important why not offload the list maintenance to the trim process?

    IOW, just throw the entries into the cache, but timestamp them on retrieval. Don't reorder the entries, just mark them whenever they're used. Could be a true DateTime timestamp, or could be a simple counter in the class, highest number was most recently used. Then in the trim process just walk the whole tree and remove the entries with the oldest stamps.

  • After considering Jeff's point, here is the solution I came up with, which should be much faster. To recap, your code was slow at list.Remove(key) operations since it needed to iterate over each item in the list. Instead we are here keeping KeyValuePair objects in the list and have the dictionary point to "LinkedListNode"s. This way we can find list item from dictionary entry as fast as we can find dictionary entry from the list item.

    I didn't test it but idea should be solid. Sorry for not adhering to the exact interface of yours :)

    // not thread-safe
    class LruCache<K, V>
    {
        Dictionary<K, LinkedListNode<KeyValuePair<K, V>>> dict;
        LinkedList<KeyValuePair<K, V>> list;
        int internalSize;
    
        public LruCache(int size)
        {
            internalSize = size;
            Debug.Assert(size > 1); // 1 wouldn't work right
            dict = new Dictionary<K, LinkedListNode<KeyValuePair<K, V>>>(size);
            list = new LinkedList<KeyValuePair<K, V>>();
        }
    
        public V this[K key] {
            get
            {
                var node = dict[key];
                if (node != list.First)
                {
                    list.Remove(node);
                    list.AddFirst(node);
                }
                return node.Value.Value;
            }
            set
            {
                if (!dict.ContainsKey(key))
                {
                    // open space for old item if cap reached
                    if (dict.Count == internalSize)
                    {
                        var oldNode = list.Last;
                        list.Remove(oldNode);           
                        dict.Remove(oldNode.Value.Key); 
                    }
                    // create new pair 
                    var pair = new KeyValuePair<K, V>(key, value);
                    // and wrap with a linkedlistnode object
                    var node = new LinkedListNode<KeyValuePair<K, V>>(pair);
                    dict.Add(key, node);
                    list.AddFirst(node);
                }
                else
                {
                    var node = dict[key];
                    // set value
                    node.Value = new KeyValuePair<K,V>(key, value);
                    // just refresh the newly set key
                    if (node != list.First)
                    {
                        list.Remove(node);      
                        list.AddFirst(node);    
                    }
                }
            }
        }
    }
    

recognise combobox deselect when using Swing + models?

I'm trying to write a nice GUI in Swing that uses the proper Model-Delegate pattern as much as possible. I have a JComboBox that when changed, needs to update the model with the new data. To get the currently selected item, I am using:

fooCombo.addItemListener(new ItemListener() {
    public void itemStateChanged(final ItemEvent arg0) {
        fooChangedHandler((Foo) fooModel.getSelectedItem());
    }
});

Which returns what the data was changed to as a nice Object. However, I can't find a way to find out the old value, so I don't know which object needs to be changed. Any ideas here?

From stackoverflow
  • As the default ComboBoxModel and ItemEvent does not let you get the previously selected value you could implement your own ComboBoxModel with this feature.

  • Foo oldFoo;
    ....
    fooCombo.addItemListener(new ItemListener() {
        public void itemStateChanged(final ItemEvent arg0) {
            Foo newFoo = (Foo) fooModel.getSelectedItem();
            fooChangedHandler(oldFoo, newFoo);
            oldFoo = newFoo;
        }
    });
    
    Mark : I agree that this is the simplest solution. However, I suggested a custom ComboBoxModel as Kieran says he wants to use the proper Model-Delegate pattern as much as possible. I would say this breaks that pattern by keeping the last selected item outside the model.
  • ended up not going to the model at all but getting my object from the getItem method like so:

    public void itemStateChanged(final ItemEvent event) {
        if (event.getStateChange() == event.DESELECTED) {
            deselectedFoo = (Foo) event.getItem();
        } 
        else if (event.getStateChange() == event.SELECTED) {
            FooChangedHandler(deselectedFoo,(Foo) event.getItem());
        }
    }
    

SharePoint Registration Form - How to Hide Fields

I created a basic registration form using a SharePoint 2007 custom list where users complete fields on the form. I created an 'Approver' field that I'm trying to hide from customers so that only the form's approver will edit that field (approve the request - Customers tend to approve their own request). How can I hide this approval field so it can be edited by the approver only?

Attempted Solutions: 1. I set the content type for that approval column to 'hidden'. How would I access the URL to the hidden approval field so the approver can access the field and update it for that specific item? The hidden field is not visible if I click 'Edit Item'. Did I miss something with the hidden content type so that I would see the column on the edit page? 2. I customized newform.aspx in designer by removing the hidden approval field and it worked. But 'Attach File' doesn't work when the new form is customized. It spews out an errors.

Any suggestions?

From stackoverflow
  • May be create a custom field control (how?) that will check the current users role agains the site before choosing to display the field.

    This is pretty hard core customisation compared to creating lists though.

  • Thanks Nat for the response but that is a little too hard core for me. I'm looking more for the click of a button or two. Unfortunately I'm not a coder at all.

  • Why not just use the Approval workflow with this list? Users would be able to create approval requests, which would automatically trigger the Approval workflow, which would create a task and send an e-mail for the approver to approve the request. Once it's approved - the status of the request would change to approved. The approver can also add a comment on the approval form, if needed.

  • The boss would like for the person who completes the form to be able to select from a list of approximately 30 approvers (depending on the department the requester is in) and that one approver must get the email request with all the details of the item (not an email that only includes a link to the task as the approval workflow does). With the approval workflow, I can only enter 1 user or a group where all of the members of that group get the email - not just the one person that needs to approve it. If I could add a variable to the workflow 'Approver' box which holds the person selected in the registration form, that would solve my problem but I don't think that is an option. If I'm missing something, please let me know.

  • Have a look at the SPListDisplaySettings component from codeplex. Adding this solution will allow you to specify how to show the fields in display, new and edit mode based on SharePoint users and groups.

Passing an "in" list via stored procedure...

Duplicate of: http://stackoverflow.com/questions/43249/t-sql-stored-procedure-that-accepts-multiple-id-values/43767#43767

How can I construct a stored procedure that will allow me to pass (for example) an @IDList so that I can write:

Select * from Foo Where ID in @IDList

Is this doable?

TIA! Kevin

From stackoverflow
  • Write the individual IDs to table B, all with the same "key" (a GUID perhaps).
    Then, your query against table A would include

    where ID in (select ID from B where key = @TempKey)
    

    (You might then delete the keys if you are finished with them. Or, timestamp them and have a sql job do it later.)

    Pros:

    • You don't send a string, which could expose you to sql injection in some circumstances.
    • Depending on your other app logic, you don't have to track or write the possibilities all at once.

    Cons:

    • It could be extremely inefficient, especially under heavy loads.
  • see this answer...

    http://stackoverflow.com/questions/43249/t-sql-stored-procedure-that-accepts-multiple-id-values/43767#43767

  • With SQL2005 and above you can send an array from code directly.

    First create a custom type

    CREATE TYPE Array AS table (Item varchar(MAX))
    

    Than the stored procedure.

    CREATE PROCEDURE sp_TakeArray
        @array AS Array READONLY
    AS BEGIN
        Select * from Foo Where ID in (SELECT Item FROM @array)
    END
    

    Then call from code passing in a DataTable as the array

    DataTable items = new DataTable();
    items.Columns.Add( "Item", typeof( string ) );
    
    DataRow row = items.NewRow();
    row.SetField<string>( "Item", <item to add> );
    items.Rows.Add( row );
    
    SqlCommand command = new SqlCommand( "sp_TakeArray", connection );
    command.CommandType = CommandType.StoredProcedure;
    SqlParameter param = command.Parameters.Add( "@Array", SqlDbType.Structured );
    param.Value = items;
    param.TypeName = "dbo.Array";
    
    SqlDataReader reader = command.ExecuteReader();
    

Simultaneously Iterating Over Two Sets of Elements in jQuery

I have a table containing many pairs of text input fields in separate columns. I want to iterate through the input fields in the first column and use those values to set the value of the corresponding input field in the adjacent column.

<table>
    <tr>
         <td><input type="text" class="left" /></td>
         <td><input type="text" class="right" /></td>
    </tr>
    <tr>
         <td><input type="text" class="left" /></td>
         <td><input type="text" class="right" /></td>
    </tr>
  ...
</table>

I have just started learning jQuery so perhaps the answer is obvious. So far I have only

$("input.left").each(function() {
    // use the value of $(this) to set the 
    // value of the text field to the .right
})
From stackoverflow
  • Lots of ways to do this. Here's one.

    $("tr").each(function() {
      $(this).find(":last-child input").val($(this).find(":first-child input").val());
    });
    

    or another:

    $("input.left").each(function() {
      $(this).parent().nextSibling().find("input.right").val(this.value);
    });
    

    and so on.

  • What you are wanting to do is known as a 'zip' operation. This is something seen in functional programming languages quite a lot. It is a function that combines two sequences of equal length into a single sequence containing a pair (or n-tuple) of elements.

    Here you can find an implementation of 'zip' for jquery. It's a jQuery plugin. Available on Google Code

    It looks like you can use it like tihs:

    $.zip($("input.left"), $("input.right")).each(function () {
       var left = this[0];
       var right = this[1];
    })
    
    alex : didnt know this existed!!
    cletus : Me either. While I think the OP is currenlty more interested in learning basic jQuery syntax/selectros/etc, this is a pretty cool plug-in.

Speed-optimise Windows Forms application

How to speed optimize WinForm applications. I am not talking about apparent .NET opt. technics - like ngen-ing, caching objects, etc. Already tried that and what I am up to is to reduce the form initilization time from a 1500 msec down to 500msec.

Profiling has identified the slowest code and almost all of it is in the InitializeComponent, and within this method the slowest lines is

  1. creation of the (just new-ing) WebBrowser component
  2. loading icon from a resource (hideous 500msec)
  3. creation of the ContextStripMenu
  4. several this.Controls.Add() calls contribute a lot too.

At the moment can only see how to fix point (2) - move icon data from being stored as embedded resource to a private field (e.g. base64-encoded string)

but I have no idea what to do with points 1, 3 and 4.

Your ideas would be greatly appreciated!

Thank you.

From stackoverflow
  • The only thing I can think of that you could do is rewrite the controls that you want to use and optimize them to initialize faster (as well as the Form class to optimize adding the adding of the controls to the form).

    I can't see how that is feasible though, and I think you are going to be stuck with this, depending on your reliance on these controls.

  • Can you do lazy loading for your Webbrowser control ? If it's in a tab which is not the main view then you might load webbrowser when that tab activated.

    Or you might load the form then load the webbrowser (this might help you to show something first then show everything, just like you'd do in a website)

  • If this is not the main form, create the form as hidden in another thread and show it right away when user asks for it.

    If it's the main form you can still initialize the controls in parallel using multithreading: webbrowser in a thread, icons in another, strip menu in another etc. But form still needs to be hidden I guess as Window messages in multiple threads can confuse things.

    Also you might still need to do "controls.add" part in the main thread as Controls collection may not be thread-safe.

    configurator : +1 I like the idea of multi-threaded InitializeComponent. It would sacrifice the VS form editor, though, so I suggest cloning the form, desinging the form's clone, and keeping them in sync.
    configurator : Also, the Controls.Add *must* be done in the main thread, after a Thread.Join is done for all initializing threads, because otherwise the different controls would live in a different thread and using them would always require Invoke if I'm not mistaken.
    ssg : Process memory is shared between threads, so a memory structure or a code cannot belong to a thread. However threads can conflict in accessing memory of course.
  • Load the icon in a separate InitializeComponentAsync thread.

  • Regarding #1 - there's no way just newing up a WebBrowser component should take 500ms. What properties do you have set on it?

    1. Just take another class like “ClsAppearance.cs” as I taken.
    2. Initialize all controls like static Infragistics.Win.Appearance txtBoxMidAppr = null;

    I take my own name like txtBoxMidAppr instead if the appiarance1 . due to it can be use for all textbox, by only once initialization.

    1. Make a function where we can initialize the appearance and call it on the MDI/Main form loading only once. public static void LoadAll() { txtBoxMidAppr = new Infragistics.Win.Appearance(); }
    2. Make another function here and take the appearance code from designing window public static Infragistics.Win.Appearance App_txtBoxMidAppr //text_box_small { get { txtBoxMidAppr.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(93)))), ((int)(((byte)(93)))), ((int)(((byte)(93))))); txtBoxMidAppr.ImageBackground = global::CS_POS.Properties.Resources.text_box_small; txtBoxMidAppr.ImageBackgroundStyle = Infragistics.Win.ImageBackgroundStyle.Stretched; txtBoxMidAppr.ImageHAlign = Infragistics.Win.HAlign.Right; return txtBoxMidAppr; }

      }
      
    3. In the deigning code of the form comment all appearance setting of the text box and put the function name for getting appearance from the ClsAppearance.cs class //appearance4.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(93)))), ((int)(((byte)(93)))), ((int)(((byte)(93))))); //appearance4.ImageBackground = global::CS_POS.Properties.Resources.text_box_small; //appearance4.ImageBackgroundStyle = Infragistics.Win.ImageBackgroundStyle.Stretched; //appearance4.ImageHAlign = Infragistics.Win.HAlign.Right; this.uteNABoth.Appearance = CS_POS.App_Appearance.ClsAppearance.App_txtBoxMidAppr;

    take all controls appearance and make a function in the class and call it from there.

    So the appearance initialization will goes only once and can use many time.

  • I have change the strategy of form loading, this will made a great change on form load timing, now it’s take average 37MS instead of 466MS.

    Method:- On First time Click on Top-tab/Icon, application load all form under that tab/icon and on click on Form Icon it will only switch visibility. And again visit on Top-tab will not load the form under that tab.

  • the above comment working are as follow:----------------------

    1. make a global form object like -Appointment ObjfrmAppointment = new Appointment();
    2. take a bool varieble bool HomeLoaded = false;
    3. on click the top-tab do the following if (!HomeLoaded) { ObjfrmAppointment.Show(); ObjfrmAppointment.Visible = false; ObjfrmAppointment.Location = new Point(0, 0); HomeLoaded = true; }

    4. on click on form icon do the following childForm.MdiParent = this; childForm.Parent = pnlForm; childForm.Visible = true; childForm.SendToBack(); CloseAllChildform(childForm.Name); childForm.BringToFront();

    where childform is the form which we want to be load. and the closeallform function make visible false for all other forms. like

    public void CloseAllChildform(string frmname) { foreach (Control childform in pnlForm.Controls) { if (childform is Form) { if (childform.Name != frmname) (childform as Form).Visible = false; } } }

    where frmname is the name of form to be loading.

  • One technique I have used in the past was to multi-thread the data load, so that it runs simultaneously to the form creation. In this instance data was being loaded out of AD, it cut about 1/3 of the load time.

Running Activex control and Maintaining security

Hi Techies,

In my a web application, I have a part to invoke an activex control .The Activex control is available in all the client PCs who are accessing my web application from web server. But When trying to run this ActiveX control from the browser in client machine (using Wshell), It was not getting invoked since "Run Activex Controls and Pluggins" are disabled in my browser. So I changed the browser settings to enable mode and Then the Activex control gave me the expected output. I afraid that this change in browser settings would allow any other website to harm my system. How could I get rid of this problem? Any thoughts? Thanks in advance

From stackoverflow
  • There had been a lotta secutiry changes introduced from Vista + IE7 onwards. Where in the IE starts in the procted mode, which helps protect users from attack by running the Internet Explorer process with greatly restricted privileges. Protected Mode significantly reduces the ability of an attack to write, alter or destroy data on the user's machine or to install malicious code.

    More details : http://msdn.microsoft.com/en-us/library/bb250462.aspx#wpm_aarwm

    So developers have to modify the applications to confirm to the new standards like starting the process from the plugin - sending widows messages from LI(Low Intergirty) to HI process etc.

  • You can digitally sign your ActiveX so that users do not have to compromise the security of their browser too much in order to allow it to run. But, essentially, ActiveX isn't very secure and these problems always pop up when you choose ActiveX...

Hibernate fetching strategy - when to use "join" and when to use "select"?

Most Hibernate associations support "fetch" parameter:

fetch="join|select"

with "select" being default value.

How to decide which one to use for which association?

I tried changing all from "select" to "join" application wide - number of generated queries decreased probably 10 times but performance stayed exactly the same (even become a tiny bit worse).

Thanks.

From stackoverflow
  • Select will fetch child items by issuing a new query to the database for them. Join will fetch child items by joining them into the parent's query. So that's why you're seeing similar performance, even with a drop in number of queries.

    Select:

    SELECT * FROM parent WHERE id=(whatever)
    SELECT * FROM child WHERE id=(parent.child.id)
    

    Join:

    SELECT *
    FROM parent
    LEFT OUTER JOIN child ON parent.child.id=child.id
    WHERE parent.id=(whatever)
    

    As to when to use one over the other... Not entire sure. It likely depends on the database system. If one was always better than the other, I doubt they would bother to give you the option! If you're seeing similar performance for each, I wouldn't worry about it.

  • Join is supposed to solve the n+1 problem. If you have 10 parents, each with 10 children, join will require one query and select will require 11 (one for the parents and one for the children of each parent). This may not be a big deal if the database is on the same server as the application or if the network is really fast, but if there is latency in each database call, it can add up. The join method is a little less efficient on the initial query because you're duplicating the parent columns in every row, but you only make one round-trip to the database.

    Generally, if I know I'm going to need the children of all the parents, I go with join. If I'm only going to need the children of a few parents, I use select.

    serg : Hm, I tried it on the production (we have remote db server with slaves) and behavior stayed exactly the same - a tiny bit worse than "select". To help with n+1 problem we are using "default_batch_fetch_size", so it will run select queries in batches, not one by one.

Where are the schemas for XML files on an Android project?

Where are the schemas (DTD or XML schema) for the XML files used on Android like AndroidManifest.xml or the layouts?

From stackoverflow
  • The schemas don't exist as an xml file. Schemas are dependent upon what UI classes your program uses. There's a slightly better discussion here.

    Casebash : What does it mean to write: `xmlns:app="http://schemas.android.com/apk/res/com.example.android.apis"` then?