Thursday, April 28, 2011

How to pass an array in Django to a template and use it with JavaScript

I want to pass an Array to a template and afterwards use it via JavaScript.

In my views.py I have: arry1= ['Str',500,20] return render_to_response('test.html', {'array1': arry1})

var array1 = {{ array1 }};

but when I visit the website it puts out:

var array1 = [&#_39;Str&#_39;,500,20]; (without the _ sign (otherwise stackoverflow changes the formatting) with which obviously breaks my code and doesn't work as intended.

What do I have to change?

From stackoverflow
  • Try using {{ array1|safe }} and see if that makes any difference. I haven't tested this, so I hope I don't get too downvoted if this is incorrect...

  • As mentioned, you could use the |safe filter so Django doesn't sanitize the array and leaves it as is.

    Another option, and probably the better one for the long term is to use the simplejson module (it's included with django) to format your Python list into a JSON object in which you can spit back to the Javascript. You can loop through the JSON object just like you would any array really.

    from django.utils import simplejson

    list = [1,2,3,'String1']

    json_list = simplejson.dumps(list)

    render_to_response(template_name, {'json_list': json_list})

    And in your Javascript, just {{ json_list }}

    Christian : json_list becomes [1, 2, 3, & q u o t ;String1& q u o t ;] (I added the spaces after &,q,u,o,t to prevent stackoverflow from reformating the output) That also doesn't seem to work.
    Christian : Maybe the best way is to use simplejson.dumps and afterwards the |safe filter?
    Bartek : You're right, you'd still need to use |safe in this case. Normally when I do JSON with Django I fetch it using an AJAX method (like $.getJSON from jQuery) so I never deal with having to use |safe.

Loading Complete graph from Sql using LINQ

Assume we have a Menu class that has SubMenus (which is the same type of Menu therefore can have SubMenus and Items too) and Items (which has a different type) and we stored them in two tables(One for Menus and one for Items). Is there any way to load complete graph of the Menu class (all of its SubMenus and Items) using LINQ to SQL?

From stackoverflow
  • If you define the relationships properly in SQL, LINQToSQL should give you back all of the menus/items with a single query on menus. However, this won't give it back to use as a graph, but as an enumeration of the menus (with related menus and items). You would need to iterate through this enumeration and construct the graph on your own.

    On the other hand, you might be able to do something like this:

    var roots = db.Menus.Where( m => !m.SubMenus.Count == 0 );
    

    Then, roots would be a collection of the base menus. This might be sufficient if you don't intend to perform any graph analysis algorithms on it, but only intend to traverse it from top to bottom to construct the GUI components.

    Mohammadreza : I want to serialize the complete graph to a XML file using DataContractSerializer, so I think i need to load all objects. Can I use LoadOptions somehow to eager load them?
    tvanfosson : If you want to serialize the graph structure instead of just the elements, I think you will need to construct the actual graph. In the enumeration you'll have duplicate elements in the parent/child properties for any shared menus. Check your DBML - the relations may already be eager loaded.
    Mohammadreza : I want to serialize the elements.
    tvanfosson : Try using partial classes to mark your entities as Serializable and see if that results in a usable format. If not, you may need to implement ISerializable as well to serialize the entity the way you want.
    Mohammadreza : My problem is not with the serialization method. How can I LOAD the data from file with a single query to pass it to the WriteObject method.
    tvanfosson : From a file or from the database. LINQToSQL only works with a MS SQL Server database. Loading the data from the database should just be a matter of executing the query I referenced in my answer assuming you have your Menus and Items tables mapped using the DBML designer.
    Mohammadreza : Maybe you got me wrong. Yes, I have used LINQToSQL ORM designer to create objects. The Menu class could have nested menus which will increase the levels of the graph. I am looking for a way to load all the levels from SQL instead of writing a recursive method to load them.
    tvanfosson : If you create the proper foreign key relationships on your table -- they can be self-referential -- then the designer will add collections to your Menu entity that will contain the related menus. I believe that these are eagerly loaded by default, but you can check in the designer...
    tvanfosson : ...if the relationships don't already exist, you can add them then either update your DBML by hand (search MSDN for adding associations to DBML) or remove/readd the tables in the designer to pick up the new relationships.
    tvanfosson : I don't think, however, that the entire relationship hierarchy can be loaded at once (probably only two levels). But you should be able to construct the graph in memory once you've done the initial query (not the one I mention in my answer, but simply iterating through Menus)...
    tvanfosson : ...since you will have an object for each menu and all of the direct connections between them.
    tvanfosson : You'd need to be careful that there aren't any cycles (perhaps by using a data structure that doesn't allow them to be added) when you construct the graph.
    Mohammadreza : Then I think I have to write the recursive method anyways. Thanks.

Get the key of an item on a Collection object

The environment is that the members I'm pushing into the Collection are nameless, un-identifiable (to avoid bad abstractions, and please, don't freak out: members are actually other Collection instances). In order to be able to make fast searches, I'm creating a meaningfull hash name for each new member, and provide it as the Key string, on the Add method of the "topmost" Collection.

When I have a key to seach with, everything's dandy... Problem is I'd like to iterate the members of the collection and get the Key that was provided on Add (the generated Hash, that unfortunetely is not possible to reverse-Hash).

I'm moving on by defining that the first member of the inserted sub-collection instance is a string, containing the mentioned hash, but if anyone cracks this, I'll be much obliged.

From stackoverflow
  • The simple approach would be to use a Dictionary instead of a Collection. The Dictionary is essentially an associative array of key, item pairs and support retrieval of its keys as an array. To use the Dictionary you will need to add a reference to the Microsoft Scripting Runtime. The drawback to using the dictionary is that it is not enumerable in the same way as the collection. A more elaborate solution would be to wrap the collection and dictionary to create an enumerable dictionary as outlined below.

    NB To get NewEnum to work properly in VBA the class module has to be exported and manually edited as follows and then re-imported.

    Public Property Get NewEnum() As IUnknown
    Attribute NewEnum.VB_UserMemId = -4
       Set NewEnum = someKeys.[_NewEnum]
    End Property
    

    example

    Option Explicit
    Private someKeys As Dictionary
    Private someCols As Collection
    Public Function Add(o As Object, Key As String) As Object
        someKeys.Add Key, o
        someCols.Add o, Key
    End Function
    Public Property Get Count() As Long
        Count = someCols.Count
    End Property
    Public Property Get Item(vKey As Variant) As Object
        Set Item = someCols.Item(vKey)
    End Property
    Public Sub Remove(vKey As Variant)
        someKeys.Remove vKey
        someCols.Remove vKey
    End Sub
    Public Property Get NewEnum() As IUnknown
       Set NewEnum = someCols.[_NewEnum]
    End Property
    Public Property Get Keys() As Variant
        Keys = someKeys.Keys
    End Property
    Private Sub Class_Initialize()
        Set someKeys = New Dictionary
        Set someCols = New Collection
    End Sub
    
    jpinto3912 : It crawls. There are Buts: i) Key can't be optional on Add method; ii) how do you remove the corresponding key during remove method?; iii) it's dumb-possible to aC.Keys().Delete I suggest: ii) someKeys.Add(Key, Key) allowing someKeys.Remove(vKey) later on; iii) Get Keys(anIndex as long) as String
    cmsjr : i. good point. ii. I didn't give that any consideration, and your suggestion is the better of the two alternatives offered, but Key, Key irks me. Maybe Dictionary would be better for the keys. iii. That Get would be redundant since the default member of the collection returned would be .Item
    cmsjr : Also, crawls in the sense of performance, or in the sense of is not complete?
    jpinto3912 : "crawls" in correcteness (but it's on polish). I think I didn't came across on iii) If you're giving a ref to a priv. member, I guess it gives a user the opport. to mess with it (don't know if vba errors). E.G. set myKeys=thisWrapCol.Keys() Call myKeys.Delete() Agree on ii? (yeah it's weird)
    cmsjr : Ok, I'm with you on iii. For ii I still wonder if it wouldn't make sense to make someKeys a Dictionary, add the key and collection during Add and expose its Keys collection through a property, this would give you a way to get the set of Keys or an individual Key without encapsulation issues.
    cmsjr : so iii is addressed, and the dictionary can remove by key or index, so ii is addressed as well.
    jpinto3912 : I guess that now I lost you on iii)... are you re-editing to not pass the priv member? Can't chew Public Property Get NewEnum() As IUnknown Set NewEnum = someCol.[_NewEnum] End Property I'm vba-only...
    cmsjr : Not totally, I'm with you on iii if we use two collections, I'm just suggesting that may not be the best way. If you can't support the NewEnum in VBA I don't think you will be able to do a foreach iteration over its members. Does that present a problem?
    cmsjr : Give me a few minutes and I'll edit the sample to clarify what I'm suggesting now.
    cmsjr : I think there is a workaround for the NewEnum, but I'll have to do more research. I'm sans IDE at the moment, so please pardon any syntax issues.
    cmsjr : Note that the keys collection of the dictionary being returned by the Get is read only.
    cmsjr : I'm waiting for a process to finish on this machine before I can fire up my work computer, but I think I am going to try wrapping the Dictionary and seeing if I can get the new enum to work in a VBA friendly way, that would remove the need for two aggregate objects.
    cmsjr : Dictionary requires a reference to Microsoft Scripting Runtime, is that a deal breaker?
    cmsjr : Ok sample reworked above, NewEnum about note is up there. I verified that assignment will not alter the dictionaries keys collection, or an individually indexed key. So I think exposing the read only attribute of the private member should be safe.
    jpinto3912 : hihihi... why have a Collection encaps. a Dic., when the Dictionary alone solves all our problems? I can Add whatever I want to a Dictionary (in my case, adding collections), and this class has property Keys. I just didn't know this class (it's usable in vba, checked).
    jpinto3912 : So, please, trim down all the prev. answer, give us a lesson on Dictionary (not to me, I'm already using it thanks to you) and i'll be happy to mark this answer correct. Nice work! Thanks !
    jpinto3912 : Personal taste:"using a Dictionary". BTW, don't forget to tell the kids that Keys array stars at 0.
    jpinto3912 : Let's polish that other thought: we can enumerate by myDic(myDic.Keys(enum_index)). But we could also wrap a Dictionary and provide a P. Prop. Get Enum(anIndex as long) as Object, (code to figure out whether object or variant.. and anIndex is withibounds) set Enum = innerDic(innerDic.Keys(anIndex))
    cmsjr : If we need to pass it an index then that Enum would just duplicate our classes Item method (though I agree some logic to make sure an invalid key/index doesn't cause an exception might be in order) The real point of wrapping them together is to support for each syntax.
    cmsjr : Surely, the kids know that arrays are 0 base.
    Mark Nold : Nice effort on the answer guys. @cmsjr did you ever work out how to simplify the export/import solution on NewEnum for VBA?
    cmsjr : If one has access to the Visual Studio 6 IDE, it can be coded normally in VB6 then imported into your VBA project. Not sure if there's any other way to handle it.
  • You could wrap your member collections in you own collection call that store the key and the collection. The is just a matter of iterating throw the collection and asking the elements for their key (i.e. you hash).

Non ASCII char in PHP?

Hello, I am trying to send something to serial port (r232) with PHP. I am using this class: http://www.phpclasses.org/browse/package/3679.html

The problem is that I am allowed to send only 1 byte. But if I send something like "1", I am actually sending 49 (ASCII for 1). Instead of send("1"), I tried with send(1) but it is no good, because this is integer which has 2 bytes. So is there a way to send a "real" char, not ASCII equivalent?

From stackoverflow
  • The chr() function returns a character given by the integer for the corresponding ascii character.

    Alan Storm : It returns a character, but as a PHP string. That won't help the OP
    Mark : Doesn't the library take a PHP string? It passes it into fwrite...
    Gumbo : To be more precise: `chr` turns an integer into a byte.
  • It looks like the library is expecting characters as input. If you need to send the character which would encode to 0x01, you just send "\001". The function chr() would convert characters to integer values and would be no use here.

    One more thing: The byte size of integers depends on the underlying system and is mostly 4 bytes.

    Mark : Not so. ord() converts characters to integer values, and chr() does the opposite.
  • I'm not sure what you are trying to accomplish. Are you trying to to send the integer 1? Not being familiar with the class, have you tried to give just the value 1 as an argument? If that doesn't work, try to wrap it with the chr() function.

WCF here to stay?

Currently reading quite a heavy WCF book. I have used it myself in production just the once, using tcp, worked a charm. Anyway what are your opinions on this technology, is it here to stay, is it worth the time invested learning all the complex features etc etc?

From stackoverflow
  • I think it is here to stay. It is easily configurable for moving endpoints, it seems robust and allows you to do (pretty much) everything you could do in web services and remoting without the overhead of separate implementations.

    I can see where you are coming from, with MS's recent leaks about ongoing support for, and maintenance of Linq to SQL, but I see WCF as a different beast altogether. This is a technology that allows interoperability, as well as de-complixifying (I know this isn't a real word, but it should be) communications between systems.

    Dave Markle : I'll add to that. WCF is the culmination of the lessons learned by MS in creating their earlier Web Service and Remoting infrastructures. And there were a LOT of lessons that needed to be learned! ;-)
  • I second what ZombieSheep says. Although complex, it greatly simplifies distributing applications across physical and logical boundaries, facilitates interoperability, and mostly decouples implementation details like ports/protocols for communication.

    It's definitely worth the time to learn, although depending on the solution, it may sometimes be overkill. I think you'll find that configuration will become easier as versions continue -- although that's pure speculation.

    While Linq to SQL had a larger cousin in the Entity Framework, WCF has no such relative. It's here to stay.

break a word in letters php

I want to accept a string from a form and then break it into an array of characters using PHP, for example:

$a = 'professor';
$b[0] == 'p';
$b[1] == 'r';
$b[2] == 'o';
.
.
.
.
.
$b[8] = 'r';
From stackoverflow
  • You don't need to do that. In PHP you can access your characters directly from the string as if it where an array:

    $var = "My String";
    echo $var[1]; // Will print "y".
    
    gargantaun : I didn't know that. good tip.
    whichdan : FYI, $var{1} will work, but it's being deprecated as of PHP6 in favor of $var[1].
  • str_split($word);
    

    This is faster than accessing $word as an array. (And also better in that you can iterate through it with foreach().) Documentation.

    St. John Johnson : Why is it faster? It just returns an array.
    Seb : It is not faster; in fact, it's slower - it has to create an additional array and see where to split the original string depending on the second parameter.
    orlandu63 : You're correct: a benchmark confirms that this is 50% slower than your method.
  • Be careful because the examples above only work if you are treating ASCII (single byte) strings.

  • If you really want the individual characters in a variable of array type, as opposed to just needing to access the character by index, use:

    $b = str_split($a)
    

    Otherwise, just use $a[0], $a[1], etc...

    PROFESSOR : thanks for the answer............it worked

PHP: what's an alternative to empty(), where string "0" is not treated as empty?

In PHP, empty() is a great shortcut because it allows you to check whether a variable is defined AND not empty at the same time.

What would you use when you don't want "0" (as a string) to be considered empty, but you still want false, null, 0 and "" treated as empty?

That is, I'm just wondering if you have your own shortcut for this:

if (isset($myvariable) && $myvariable != "") ;// do something
if (isset($othervar  ) && $othervar   != "") ;// do something
if (isset($anothervar) && $anothervar != "") ;// do something
// and so on, and so on

I don't think I can define a helper function for this, since the variable could be undefined (and therefore couldn't be passed as parameter).

From stackoverflow
  • if ((isset($var) && $var === "0") || !empty($var))
    {
    
    }
    

    This way you will enter the if-construct if the variable is set AND is "0", OR the variable is set AND not = null ("0",null,false)

    thomasrutter : This looks quite correct; it isn't really a shortcut for if (isset($myvariable) && $myvariable != "") though as it's longer. Thanks for the answer.
  • This should do what you want:

    function notempty($var) {
        return ($var==="0"||$var);
    }
    

    Edit: I guess tables only work in the preview, not in actual answer submissions. So please refer to the PHP type comparison tables for more info.

    notempty("")       : false
    notempty(null)     : false
    notempty(undefined): false
    notempty(array())  : false
    notempty(false)    : false
    notempty(true)     : true
    notempty(1)        : true
    notempty(0)        : false
    notempty(-1)       : true
    notempty("1")      : true
    notempty("0")      : true
    notempty("php")    : true
    

    Basically, notempty() is the same as !empty() for all values except for "0", for which it returns true.


    Edit: If you are using error_reporting(E_ALL), you will not be able to pass an undefined variable to custom functions by value. And as mercator points out, you should always use E_ALL to conform to best practices. This link (comment #11) he provides discusses why you shouldn't use any form of error suppression for performance and maintainability/debugging reasons.

    See orlandu63's answer for how to have arguments passed to a custom function by reference.

    mercator : That will fail when the variable is undefined.
    Calvin : How do you mean? If passed an undefined variable, the function returns false--which is the opposite of what empty() returns: http://us2.php.net/manual/en/types.comparisons.php That is the desired behavior.
    Milan Babuškov : It does not fail, but produces a warning. So, although it does work, it is not The Right Way(tm). You should use isset() before checking the variable with ===
    Calvin : Strange, it doesn't produce any warnings when I have error reporting set to E_STRICT. If does however produce an error when I use E_ALL. But then using isset() inside of the function does not prevent the error either.
    Calvin : It seems that you can't pass an undefined variable to a custom function in E_ALL regardless of whether your use isset() or not. Gushiken's implementation without a custom function does work in all circumstances however.
    mercator : E_STRICT isn't a superset of E_ALL: http://www.php.net/manual/en/errorfunc.constants.php. You should use (E_ALL | E_STRICT). You *could* use the @ operator, but that adds overhead (see http://www.smashingmagazine.com/2009/03/24/10 "tip" #9 and comment #11) and isn't The Right Way™ either.
    thomasrutter : Unfortunately this will not work for me because it will fail (ie produce PHP notice) when the variable is undefined. I rely on PHP notices. I hadn't realised, I guess, that it's not possible to define a function that can accept an undefined variable; empty() and isset() are magical in that way.
  • if(isset($var) && ($var === '0' || !empty($var)))
    {
    }
    
  • function Void($var)
    {
        if (empty($var) === true)
        {
         if (($var === 0) || ($var === '0'))
         {
          return false;
         }
    
         return true;
        }
    
        return false;
    }
    
    thomasrutter : This has the problem that if $var is undefined, it fails as soon as it's passed as an argument (to a function other than isset or empty, such as your Void function). I think what I was wanting is actually impossible, sorry.
  • function isempty(&$var) {
        return empty($var) || $var === '0';
    }
    

    The key is the & operator, which passes the variable by reference, creating it if it doesn't exist.

  • The answer to this is that it isn't possible to shorten what I already have.

    Suppressing notices or warnings is not something I want to have to do, so I will always need to check if empty() or isset() before checking the value, and you can't check if something is empty() or isset() within a function.

  • If ($var != null)

SQl Delete from more than one table

Say, I have two tables Courses and faculty_courses - each has a primary key course_ID that is varchar(50) not null.

I am trying to delete a row from the Courses table - so assume have to delete that row from both tables since they are linked by a relationship.

I wrote this - doesn't work - says Incorrect syntax near the keyword 'JOIN'

DELETE FROM Courses JOIN faculty_courses ON Courses.course_ID = faculty_courses.course_ID WHERE faculty_courses.course_ID = 'ITM731'

Any ideas?

From stackoverflow
  • You have to issue two statements.

    DELETE Courses where course_ID = 'ITM731'
    DELETE faculty_courses WHERE course_ID = 'ITM731'
    

    Or, as mentioned here, use a delete cascade.

    JoshBerke : I typically recommend this instead of cascading deletes. This is a lot more visible as what the intention is.
    Tom H. : +1 on the comment Josh :)
  • What you want can be handled by having ON DELETE CASCADE links between the tables. Provided that your RDBMS allows for this.

  • You can create a FK reference with CASCADE Delete

    Edit

    I recommend that you use the approach from Ocedecio of explicitly deleting from the two tables as opposed to cascading. It makes your intention so much clearer.

  • DELETE only delete record from one table - the JOIN syntax is useful only for selecting the correct rows on that table, for example, on table with an 1:n relationship (not what you have here) and you want to delete all the records from the "n" table that pertain to a selectable record on the "1" table, then you'd do DELETE FROM ntable INNER JOIN reftable ON ntable.ref = reftable.ref WHERE reftable.column = 'whatyouneedtolookup'.

    Now as I said, this does not pertain to your current situation, in which you simply need to issue two DELETE statements - one for each table, on the same key.

    That being said, it sounds like you have a 1:1 reference between the table which strikes me as odd - normally with that kind of reference, the trivial normalization would be to merge the tables into a single table with the columns from both tables.

    Tom H. : 1:1 relationships can be valid in the case of subtyping an entity. In this case though I think he probably misspoke about the PK being the one column in both tables. Maybe faculty_courses is a composite key including the course_id?
  • alter table tablename drop column columnname

Rendering HTML inside a DataList

I have a formatted text that contains Bolded, italicsed, and other styles implemented inside the message. I have this message stored in a Database. Now I want to implement these tags into work inside the a field inside the DataList. How do I do it?

<%# Eval("message") %>

Doesn't work. It just shows up the tags as such. Any help?

From stackoverflow
  • If you mean that your "message" contains formatted HTML, you should simply HTMLDecode it after the DataBinder has evaluated the value of the "message" property. For example:

    ' "message" contains the string "<b>Hello World!</b>"
    ' Within the DataList:
    <ItemTemplate>
      <asp:Label ID="lbl1" runat="server" Text='<%# Server.HtmlDecode(Eval("message").ToString()) %>' />
    </ItemTemplate>
    
    Cerebrus : lol, np. You can vote up answers that you think have merit. You can also vote up answers that you have accepted. Thanks for accepting! :-)

Read .NET configuration from database

The .NET 2.0 and up configuration system is quite powerful and extensible - as long as you don't want to change the fact it all comes from XML files in the filesystem.

In my requirement, I cannot change files since my app runs in a managed environment outside my reach - but I could change the SQL Server database.

So I am looking at storing configuration files or sections in a SQL table - but how can I tie the .NET 2.0 configuration system into this??

Is there a way to write a "custom config provider" that will read its config sections not from a *.config file in the file system, but from a table in the SQL database??

I've been looking at creating my own custom ConfigurationSection or ConfigurationElement, or even a custom Configuration per se - but it seems I always end up back at the point that I can extend the config-system in the filesystem as much as I like, but I can't make it read my XML fragments from a database table.....

What am I missing? Has someone done this already and care to explain / share?

Thanks! Marc

PS: I also tried to just read the config XML into a string, and then deserializing it into the appropriate e.g. ServiceModelConfigSection - that doesn't work, unfortunately, because the ConfigSection base class somehow doesn't implement a method that is required for it to be XML serializable ........ (YIKES!!!)

From stackoverflow
  • There's an article here that talks about doing what you are talking about:

    http://www.wrox.com/WileyCDA/Section/Redirecting-Configuration-with-a-Custom-Provider.id-291932.html

    In summary what they do is create a derived version of ProtectedConfigurationProvider, which is typically used to encrypt .config files. In the Decrypt method, instead of decrypting the configuration information, it's retrieved from a database.

    marc_s : +1 - thanks, very interesting! Can't quite make sense of the "ProtectedConfigurationProvider" as a base class just yet.... but I'll give it a try!
    marc_s : Hi Keltex - it works - mostly - but it's a pretty awful HACK in my opinion..... too bad there's no "proper", nice, official way to directly plug in config providers into the .NET config system.....
    Keltex : @marc_s I agree. But it is a work-around.

UITableViewController and NavigationController

I'm having a problem pushing a UITableViewController onto a NavigationController. With the following code:

ProblemEditController *problemEditController = [[[ProblemEditController alloc] initWithNibName:@"ProblemEditController" bundle:nil] retain];
problemEditController.problem = [[Problem alloc] init];
[self.navigationController pushViewController:problemEditController animated:YES];
[problemEditController release];

The navigation controller works as expected, however, the table view is not showing. numberOfSectionsInTableView is being called on my UITableViewController, but numberOfRowsInSection and cellForRowAtIndexPath aren't being called, and the view shows up blank.

Is there something obvious I am missing?

EDIT

I've changed something in the nib file (stupidly, can't remember what), and I'm seeing numberOfRowsInSection being called now.

From stackoverflow
  • Try now using retain or release on *problemEditController.

    This piece of code works fine for me:

    formationsController = [[FormationsController alloc] initWithNibName:@"Formations" bundle:nil];
    [navigationController pushViewController:formationsController animated:YES];
    
    Mr. Matt : Unfortunately this didn't work - same problem. I don't understand why the view isn't being shown when the numberOfSectionsInTableView function is called.
    Pablo Santa Cruz : Try showing the view with prensetModalViewController instead of pushing it. To see if something changes.
    Mr. Matt : Same thing - a blank view is displayed.
    Mr. Matt : I've changed something in the nib file (stupidly, can't remember what), and I'm seeing numberOfRowsInSection being called now.
    Mr. Matt : Thanks for your help, Pablo!
    Pablo Santa Cruz : No prob! Good luck w/ your project.
  • OK, I've found out what I was doing wrong. I had added a TableViewController to my nib rather than just added a table view.

    I'd basically messed up the connection to view in IB. For future reference, this is what a custom UITableViewController should look like in IB:

    alt text

    Now I feel like a cretin.

How can one manipulate the Start menu's "Recently Used Programs" list programmatically?

I'm looking for a way to make programs appear (frequently) used, so that they would appear in the Start menu's "Recently Used Programs" (after a zero touch install).

I'm trying to figure out how Windows stores information related to program usage frequency.

The only (maybe) related things I can see being changed when I run a program from the Start Menu, are some (seemingly undocumented) BagMRU registry keys which have no meaning to me.

I did found a way to get programs pinned, but that's not what I'm looking for here.

Update: please see the comments for explanation why I would like to do this...

Update2: I'm making progress... Now I know where they keys are stored and I know that the keys are ROT13 "encrypted". And the second 4 bytes of the values are the counter.. http://blog.didierstevens.com/2006/07/24/rot13-is-used-in-windows-you’re-joking/

This ROT13(wikipedia) encryption thing is funny. Well, of course there is a reason. They don't want you to be able to find it by simple search.

Lol, and in windows 7 they are using Vigenère crypto! much better :D

From stackoverflow
  • At the risk of downvotes, this is not something you should be doing. The "Recently Used Programs" belongs to the owner of the computer, not your program.

    If your program is as useful as you think it is, it will automagically show up there.

    Raymond Chen has done quite a few articles as to why this sort of thing is a bad idea.

    This rates among all those other bad ideas such as:

    • how can I force my program to be the handler for certain file types?
    • how can I keep my program always on top.
    • how can I annoy my users by making decisions for them when they previously had the power to make their own decisions as to how their software was configured? :-)

    Update:

    A couple of things you may want to try.

    • Copy a program (explorer.exe) to axolotl.exe and run it enough times to get it on the list. Then search the registry for it (assuming there's not another axolotl.exe somewhere on your disk).Be aware that some strings are stored as Unicode so it might not be a simple search. It also wouldn't surprise me if MS encoded them some way to make this more difficult.
    • Microsoft's sysinternals have a tool that can monitor the registry (regmon, look here, you could run that while you run a program a few times to see what gets updated when it's added to the list.
    Joey : +1 for educating people that are about to do Bad Things™ :) Raymond Chen should be a must-read anyway.
    Kalmi : I know and I agree with you. However my case is different. I only want to do this during deployment(or at first login). After some time that list will reflect what the user actually uses. (More or less your reasoning is why I don't want pinning.)
    paxdiablo : Fair enough Kalmi, and I'm sorry I don't have a better answer (I actually don't know), but I believe the list should reflect the users choices *all* the time. You've stated that it's only a temporary inconvenience to the user, my argument would be that no inconvenience would be better.
    paxdiablo : Why do you need to do this? The first run of your program will probably see it added to the MRU list.
    paxdiablo : If it can be done, I suspect Mr Chen (The Old New Thing) would know how. But he'd probably give you the same advice.
    paxdiablo : See http://blogs.msdn.com/oldnewthing/archive/2003/09/03/54760.aspx (I'm sure your program isn't one of the "want to be everywhere" variety but it explains why MS would make this difficult, if not impossible to game).
    Kalmi : Pax, we are not talking about my program, we are talking about OS deployment and setting up good defaults in an environment where people usually use a new profile.
    Kalmi : @Pax, "no programmatic access to the pin list"... I did found a way to get programs pinned as I stated it in my question, but I don't want no programs pinned (except for what's normally there), because pinned things don't get removed if they are not used(unless explicitly unpinned by the user).
    Kalmi : "Pax: You've stated that it's only a temporary inconvenience to the user, my argument would be that no inconvenience would be better." It's not an inconvenience. Do you think the default would be better? :D The defaults: Windows Media Player, Introduction to WinXp, Files and settings transfer wizard
    Kalmi : Those are no good defaults when they have all the useful programs pre-installed.
    Joey : It could be that you can set defaults there using group policies in a normal Windows Server environment.
    paxdiablo : Kalmi, if these are your environments you're setting up, then by all means try it. I'm stating why MS will make it exceedingly difficult for you to do. One thought - if the images are all identical, why can't you install, use (to get on the list) then ghost *that* image to all the other PCs?
    paxdiablo : I didn't mean to cause offense - I assumed your program was just another one that could be installed and you wanted to add it to the list no matter what. Again, if you're the admin setting up multiple environments, then maybe what you're proposing isn't the bad idea I thought it was.
    Kalmi : No offense taken. I spend a lot of time getting those "useful programs" to behave, so I know what Bad Things are.
    paxdiablo : Kalmi, see update for a couple of things to try (if you haven't already done so).
    Kalmi : I used to do that "install-use-ghost" thing, but this time I'm not doing image based install. Surprisingly most apps can be installed without any user interaction nowadays quite easily. Getting settings in an unattended way to your (and hopefully the users) preference is not too hard USUALLY either.
  • If this is possible, I do recommend against it. It is, as you say, undocumented behaviour and circumvents the intended usage of the frequently used programs list. What's wrong with a desktop icon and quick launch shortcut?

    Kalmi : This would be used in an environment where the machines would be used by a lot of people and each user would have his or her own profile. Most of the time people will use new profiles. This is why we need the first time user experience(defaults) to be good.
  • Use Win32 Shell COM interfaces
    It has been explained for decades, like for all undocumented features, on Google Groups (Win32), same method than on W95..

    Kalmi : All other MRU lists are stored in registry in cleartext and in a different format(no last used date, no usage counter, just a simple ordered list). I don't think that this approach would work here. This seems to be a special case.
  • I found what I was looking for here:

    http://blog.didierstevens.com/2006/07/24/rot13-is-used-in-windows-you’re-joking/

Easy way to retrive timestamp from SQL Server db

I have a timestamp column (updated) in my Microsoft Sql Server Database and wish to retrieve the value as a DateTime object using SqlConnection and SqlCommand.

What is the easiest way to do this?

From stackoverflow
  • A timestamp field in a SQL Server database is not related to the date and time, but is merely a sequence number.

    A timestamp in MySql is on the other hand a datetime-value.

    Tim : Could be usefull then with a solution on how to change the MSSQL DB to cope with timestamps like MsSQL
    Erik : You define your own DATETIME-field, and remember to update this field whenever you change the content of the row. This is done automatically with MSSQL timestamp field.

FInd Javascript Error In IE 7?

I had Put a digg button in my blog. The blog runs fine on firefox and opera,but when i open it in ie7 it shows javascript error.clicking on that little triangle doesn't show any information..how to remove that error?

From stackoverflow
  • You should try the (free) Fiddler2 for Internet Explorer tool. It gives you a range of additional information for scripts and the background goings on of your code etc, might make it easier to find exactly what and where the error is.

    Rahul Vyas : ok i'll try it.thanks for the info
  • Hi, try to search for Firebug Lite on Google. This is a version of Firebug that can be directly integrated into the webpage and allows so to have the great Firebug features also on IE. It may help to find your JavaScript problem.

  • You have to find out what kind of exception it's throwing, I think, then you can start solving.
    If you have not an IE debugger in hand (IE8 has one), let's try alerting the isuue:

    ...
    try {
        //digg
    } catch(err) {
        alert(err.description);
    }
    ...
    

Suggest a book on Oracle Application Framework

Hello, everyone.

Suggest me a book on Oracle Application Framework, please. OAF is not Oracle ADF.

From stackoverflow

How is setTimeout implemented in the javascript interpreters or timers in general?

How is a function called after a time has passed implemented in javascript or any other interpreted language?

In other words, is there a loop behind in the javascript interpreter that checks all the time a list of timers, or is there any particular way that the operating systems handle this?

Thanks

From stackoverflow
  • You could look at the source of Firefox or WebKit to see how they implemented it.

    alvatar : Yes. But actually I want to know if there is a general approach that could be used in any language.

Can't install Eclipse plugin

I'm trying to install an Eclipse plugin for Mylyn/Fogbugz, and I get the following error when I try either EclipseBugz or Foglyn:

Cannot find a solution satisfying the following requirements Match[requiredCapability: org.eclipse.equinox.p2.iu/org.eclipse.swt

I'm using Eclipse 3.4.1

From stackoverflow
  • Are you using Eclipse Classic?

    skriv : No, I'm pretty sure I downloaded the RCP distro.
  • Eclipse plungins require Equinox UI for dependency.Please read Equinox installer .I hope can help you. : )

    Peter Štibraný : Do you mean that ALL eclipse plugins require this dependency?
    Chatsiri.rat : No,I mean only iu package in Equinox.
  • Hi,

    what other update sites do you have enabled in your Eclipse installation?

    I had similar problem when upgrading from older Mylyn, and found out that it helps to disable other updates sites. When installing new plugins, or even updating old ones, Eclipse has a tendency to contact all enabled update sites. I don't know what exactly it is trying to do, but it helped me to disable all sites except one I wanted to use.

    Btw, Eclipse 3.5M6 has option to use only selected update site -- it is great help when updating/installing plugins. I cannot wait to see Eclipse 3.5 final released, just for this feature.

    skriv : This worked for Foglyn, but not EclipseBugz. I just disabled all other sites but yours. Thanks Peter!

Svn Post Commit Hook to copy committed files to a working copy for another repository?

The aim is to maintain 2 separate repositories that are not strictly mirrored. Both repositories are be subject to update by different developers so svnsynch is out of the question.

Hooking the script might not be the right solution either as I would much prefer to run the script at will rather than with every commit. Perhaps a script to compare timestamps and copy the youngest? Please dont recommend that we change to git.

From stackoverflow
  • I'm linking to a hook script I use to check out a part of a repository every time it's committed to. You could probably modify it to suit your needs; I imagine you'd want to change the svn checkout to svn export.

How do I get the source of a ContextMenu-originated event in WPF?

Hi

I have a TreeView with a ContextMenu with Click events. When the click event in the context menu fires, I get the MenuItem as the source of the event, obviously. How can I get which node in the TreeView was the one who triggered the ContextMenu?

From stackoverflow
  • Generally you store the TreeView node (e.g. the source of the pop-up event, maybe the selected node - depends on your interface to some degree) in a private class-level variable in the ContextMenu's "pop-up" event, then refer to that variable in the menu's click event.

    sker : That's a good idea. Do you know if the popup event is ContextMenuOpening? Because neither ContextMenuOpening nor ContextMenuClosing are firing when I open the menu.
    dommer : Should be the Opened event. http://msdn.microsoft.com/en-us/library/system.windows.controls.contextmenu.opened.aspx
    sker : Ok, I'm using telerik's treeview and it doesn't have an Opened event, but I managed to do it with the MouseRightButtonUp event. Thank you.
    sker : Oops, I was trying to use the Opened event in the TreeView rather than the ContextMenu. I'll use it in the ContextMenu now.
  • Alternatively, if you are using RoutedUICommands you can use the OriginalSource property on ExecuteRoutedEventArgs and CanExecuteRoutedEventArgs to find the FrameworkElement where Command started its bubble.

    The OriginalSource however maybe the inner TextBlock, or other element in the node's DataTemplate, so you will need to use the VisualTreeHelper to find the parent you want. I have implemented a wrapper around this functionality that is similar to: http://www.hardcodet.net/2008/02/find-wpf-parent/

    This approach is good if you want to separate/centralise your command logic in a large application.

    Greg D : I've had very good luck using the DataContext property on the OriginalSource when going all-the-way with data binding. OriginalSource should always be a FrameworkElement.
    sker : My problem is solved for now but your solution seems pretty good. I'll check it out in the next few days. Thank you.
  • //there has got to be a better way than this... TreeViewItem tvi = (((sender as MenuItem).Parent as ContextMenu).Parent as Popup).PlacementTarget as TreeViewItem;

    This works, but why SHOULDN'T I do it this way?