input
stringlengths
51
42.3k
output
stringlengths
18
55k
When should I be concerned about transaction size? <p>I have a feature where we need to merge user records. The user chooses a user to keep and and a user to discard.</p> <p>We have 59 relations to user records in our database so for each one I need to do:</p> <p><code> UPDATE (Table) set UserNo=(userToKeep) WHERE UserNo=(userToDiscard) </code></p> <p>and then DELETE the userToDiscard and their user prefs (118).</p> <p>Should I be worried about the transaction size? This is MS-SQL 2005.</p> <p>Is there anything I could do?</p> <p>Thanks</p>
<p>Have you tested how long the process actually takes? How often are users merged?</p> <p>If you have indexes on the user ID in each of this table (and I would think that would be the natural thing to do anyway) then even with 59 tables it shouldn't take too long to perform those updates and deletes. If you only actually merge users a couple times a week then a little blip like that shouldn't be an issue. At worst, someone has to wait an extra couple seconds to do something once or twice a week.</p> <p>Another option would be to save these user merge requests in a table and do the actual work in a nightly process (or whenever "off-hours" is for your application). You would need to make it clear to the users of your application though that merges do not take effect immediately. You would also need to account for a lot of possible contingencies: what if the same user is set to merge with two different users that night, etc.</p>
Delete Chars in Python <p>does anybody know how to delete all characters behind a specific character??</p> <p>like this:</p> <pre><code>http://google.com/translate_t </code></pre> <p>into </p> <pre><code>http://google.com </code></pre>
<p>if you're asking about an abstract string and not url you could go with:</p> <pre><code>&gt;&gt;&gt; astring ="http://google.com/translate_t" &gt;&gt;&gt; astring.rpartition('/')[0] http://google.com </code></pre>
Write Dataset to SQL Table <p>I have converted a complex XML File to a Dataset that has 7 Tables and around 70 Columns I have created the tables in SQL Server to match the ones in the Dataset using the XML Schema. How can I easily write my Dataset to the SQL tables?</p>
<p>Depending on how many rows you have in the DataSet, probably the best thing to do would be to use a SqlCommandBuilder, like so:</p> <pre><code>var connection = new SqlConnection("my connection string"); connection.Open(); // repeat for each table in data set var adapterForTable1 = new SqlDataAdapter("select * from table1", connection); var builderForTable1 = new SqlCommandBuilder(adapterForTable1); adapterForTable1.Update(myDataSet, "Table1"); </code></pre> <p>If you have complex relationships defined between the tables in the DataSet, I'm afraid you can't use the SqlCommandBuilder. What you'll need to do, instead, is define a data adapter for each table in your DataSet. Then, update the tables in the DataSet in dependency order (i.e., do the tables with no dependencies first, then the dependent tables). </p> <p>Here's an example of a parent/child insert (note that you would do similar things for updates). Table1 is the parent, and has ParentId (the identity column), and an NVARCHAR field ParentValue. Table2 is the child, has its own identity column (ChildId), the foreign key field (ParentId), and its own value (ChildValue). </p> <pre><code>var myDataSet = new DataSet(); // ** details of populating the dataset omitted ** // create a foreign key relationship between Table1 and Table2. // add a constraint to Table2's ParentId column, indicating it must // existing in Table1. var fk = new ForeignKeyConstraint("fk", myDataSet.Tables["Table1"].Columns["ParentId"], myDataSet.Tables["Table2"].Columns["ParentId"]) { DeleteRule = Rule.Cascade, UpdateRule = Rule.Cascade }; myDataSet.Tables["Table2"].Constraints.Add(fk); myDataSet.EnforceConstraints = true; var connection = new SqlConnection("my connection string"); var adapterForTable1 = new SqlDataAdapter(); adapterForTable1.InsertCommand = new SqlCommand("INSERT INTO MasterTable (ParentValue) VALUES (@ParentValue); SELECT SCOPE_IDENTITY() AS ParentId", connection); adapterForTable1.InsertCommand.Parameters.Add("@ParentValue", SqlDbType.NVarChar).SourceColumn = "ParentValue"; var adapterForTable2 = new SqlDataAdapter(); adapterForTable2.InsertCommand = new SqlCommand("INSERT INTO ChildTable (ParentId, ChildValue) VALUES (@ParentId, @ChildValue); SELECT SCOPE_IDENTITY() AS ChildId", connection); adapterForTable2.InsertCommand.Parameters.Add("@ParentId", SqlDbType.Int).SourceColumn = "ParentId"; adapterForTable2.InsertCommand.Parameters.Add("@ChildValue", SqlDbType.NVarChar).SourceColumn = "ChildValue"; connection.Open(); adapterForTable1.Update(myDataSet, "Table1"); // insert rows in parent first adapterForTable2.Update(myDataSet, "Table2"); // child second </code></pre>
How to declare a variable/param of type "Control implementing interface ISomething"? <p>I wish to declare a variable in such a way as it can be assigned only values which derive from Control and also implement the ISomething interface.</p> <p>I intend to add the ISomething interface to derivatives of controls. </p> <p>I would like to derive SpecialTextBox and SpecialDatePicker From TextBox and DatePicker and implement the ISomething interface on each.</p> <p>I would like to be able to assign each of these controls to a variable whose type is "Control which also implements ISomething" so that from there they could either have their ISomething methods invoked or could be added to a control collection on a form.</p> <p><strong>So.... How do I declare a variable of Type "Control which also implements ISomething"</strong>?</p> <p>Ideally the answer to be in VB.Net but I would be interested in a C# method also.</p>
<p>One way to do this is with generics - i.e. a generic method:</p> <pre><code>void Foo&lt;T&gt;(T control) where T : Control, ISomething { // use "control" // (you have access to all the Control and ISomething members) } </code></pre> <p>Now you can call Foo <strong>only</strong> with other variables that are a <code>Control</code> that implements <code>ISomething</code> - you don't need to specify the generic, though:</p> <pre><code>Foo(someName); </code></pre> <p>is all you need. If you've given it something that isn't both a <code>Control</code> and <code>ISomething</code>, the compiler will tell you.</p> <p><hr /></p> <p>Update: I don't "do" VB, but reflector tells me that the above translates as:</p> <pre><code>Private Sub Foo(Of T As { Control, ISomething })(ByVal control As T) End Sub </code></pre>
Should I add AJAX logic to my PHP classes/scripts? <p>I just started making a PHP/AJAX site and I was wondering where I should add the functionality to <strong>"only include the content"</strong>.</p> <p>Should I have if statements in my header and footer scripts that check for a <strong>"ContentOnly"</strong> get parameter? And then append that parameter to the query strings in my AJAX calls?</p> <p>Or should I use a filter on the AJAX side to only grab the main content Div. Like in jquery:</p> <pre><code>$(this).load("/myPhpPage.php #mainContentDiv") </code></pre> <p>The first method would be faster right? But the second method would keep the AJAX functionality on the presentation side, and out og my PHP.</p> <p>Or is there a third method? I want to keep my PHP scripts intact, so that if oyu go to them directly, the header and footer are there. Thanks in advance!</p>
<p>Please don't use AJAX for the sake of using AJAX.</p> <p>That said, most AJAX libraries pass a <code>X-Requested-With</code> HTTP header indicating that it's an AJAX request. You can use that header to decide whether to include your header/footer etc.</p>
In the windows python console, how to make Tab = four spaces? <p>Hello I would like that when I am in the python console tabbing will give me four spaces. Any ideas? </p>
<ol> <li>Download and install <a href="http://www.autohotkey.com" rel="nofollow">AutoHotkey</a></li> <li><p>Write this script:</p> <pre><code>SetTitleMatchMode 2 #IfWinActive python tab:: Send, {SPACE} Send, {SPACE} Send, {SPACE} Send, {SPACE} </code></pre></li> </ol> <p>Save it as tab-to-space.ahk, and doubleclick on the file.</p> <p>Note: you might have to captalize "Python" to match your window tite. Or you can have "yhton" and it will match Jython too.</p>
How do I make a reusable XIB with it's own UIViewController? <p>I am trying to create a reusable "picker". It is basically like a keypad of a phone. Since I will be using this a lot in my iPhone app, I have been frustrated with trying to make it appear.</p> <p>It is in its own XIB file and has its own UIViewController subclass as the FileOwner. However, when I instantiate this with:</p> <pre><code>MonthPickerViewController *mpvc = [[MonthPickerViewController alloc] initWithNibName:@"MonthPicker" bundle:nil]; </code></pre> <p>Nothing happens on the screen. Yet is does fire the <code>-viewWillAppear</code> methods, etc.</p> <p>So, what am I doing wrong either in code or in InterfaceBuilder that is preventing my view to appear?</p>
<p>Are you pushing the view controller? </p> <pre><code>[[self navigationController] pushViewController:mpvc animated:YES]; </code></pre> <p>Or are you adding the view controller's view as a subView of your current view?</p>
Any resource/codes on how fiddler works? <p>I need to track http/url requests &amp; redirects from a windows forms application using C#. It should handle both IE &amp; firefox. Not sure if Fiddler is open-source but if i'm not mistaken, it's written using .NET. Sample codes or online articles on how to listen to http/url requests &amp; redirects will be appreciated.</p> <p>Thanks!</p>
<p>Fiddler works as standard HTTP <a href="http://en.wikipedia.org/wiki/Proxy_server">proxy</a>. There is no magic here. See HTTP protocol for details. In both IE/Firefox, you need to set Fiddler (or your custom program) as proxy, and then browser will use it for all outgoing requests. Proxy is responsible for forwarding request to correct server, and returning response. Proxies are typically used for 1) caching, 2) controlling access (and avoiding firewalls), 3) debugging.</p> <p>See also <a href="http://stackoverflow.com/questions/311181/open-source-proxy-library-for-net">http://stackoverflow.com/questions/311181/open-source-proxy-library-for-net</a> for <a href="http://www.mentalis.org/soft/projects/proxy/">.NET proxy library</a> (just quick googling... I have no experience with it).</p>
Is there a fundamental difference between backups and version control? <p>How does version control differ from plain backups?</p> <p>Let's forget about the feature decoration, and concentrate on the soul of version control. Is there a clear line that backups must cross before they can be called a VCS? Or are they, at heart, the same thing with different target markets?</p> <p>If there is a fundamental difference, what is the absolute minimum requirement for something to reach the status of version control?</p> <p><em>When you answer, please don't just list features (such as delta compression, distributed/central repositories, and concurrent access solutions) that most version control systems have or should have, unless they actually are necessary for a VCS by definition.</em></p>
<p>The fundamental idea of version control is to manage <em>multiple revisions</em> of the same unit of information. The idea of backup is to copy the <em>latest version</em> of information to safe place - older versions can be overwritten.</p>
How to dynamically change shortcut key in Firefox? <p>I have a firefox extension which can be activated by a shortcut key. I want users to be able to change the key combo dynamically.</p> <p>My XUL looks like this</p> <pre><code>&lt;keyset id="ksMain"&gt; &lt;key id="keyDoMyThing" modifiers="control,shift" key="e" command="cmdDoMyThing"/&gt; &lt;/keyset&gt; </code></pre> <p>cmdDoMyThing is a reference to an element in a commandset. When I press ctrl+shift+e, the command fires.</p> <p>I tried both modifying the existing element and creating a new element using JavaScript, but while I can get the old key combo to <em>stop</em> working, I can't get the new one to happen. Here's an example of the code I'm using</p> <pre><code>keyelem = document.createElement('key'); keyelem.setAttribute('id', 'keyDoMyThing'); keyelem.setAttribute('command', 'cmdDoMyThing'); keyelem.setAttribute('key', key); keyelem.setAttribute('modifiers', modstr); keyset.appendChild(keyelem); </code></pre> <p>I can use the debugger to verify that modstr is set to the proper string and key is set to the key I want to use.</p> <p>How can I make this happen the way I would like?</p>
<p>Turns out I need to delete the keyset as well and create an entirely new keyset. </p> <pre><code>ksparent = keyset.parentNode ksparent.removeChild(keyset); keyset = document.createElement('keyset'); keyset.id = 'my-keyset'; keyelem = document.createElement('key'); keyelem.setAttribute('id', 'keyDoMyThing'); keyelem.setAttribute('command', 'cmdDoMyThing'); keyelem.setAttribute('key', key); keyelem.setAttribute('modifiers', modstr); keyset.appendChild(keyelem); ksparent.appendChild(keyset); </code></pre> <p>Once this is done, the new key combo will take effect.</p>
I get "Missing these required gems", but gems are installed <p>since I updated ruby using Mac Ports (on Leopard) I have got several problems and I also had to reinstall gems. Now when I run Mongrel I keep getting the error "Missing these required gems" followed by the list of gems that I required in environment.rb but that gems seems to be correctly installed as I see running <code>gem list</code>. I think that rails is looking for a previous installation, but I don't know how to configure it to use the new ruby/gem path.</p> <p>Thanks!</p>
<p>You should use :</p> <pre><code> config.gem 'rspec', :lib =&gt; 'spec' config.gem 'rspec-rails', :lib =&gt; 'spec/rails' </code></pre> <p>because rspec libs are not named as it should ...</p>
Cygwin: Control-r reverse-i-search in bash: how do you "reset" the search? <p><strong>Question:</strong> How do you tell <kbd>Ctrl</kbd>+<kbd>r</kbd> reverse-i-search to "reset itself" and start searching from the bottom of your history every time?</p> <p><strong>Background:</strong> When using reverse-i-search in bash, I always get stuck once it is finished searching up through the history and it cannot find any more matches. Sometimes I hit <kbd>Esc</kbd> and re-invoke <kbd>Ctrl</kbd>+<kbd>r</kbd> a second time, expecting it to start a fresh new search from the bottom of my history. However the "pointer" still seems to be at the previous place it left off in my history. </p> <p>The problem is, I usually do not want this behavior. If I hit <kbd>Esc</kbd>, and then re-invoke <kbd>Ctrl</kbd>+<kbd>r</kbd>, I would like that to indicate it should re-start from the bottom again and work its way back up.</p> <p><strong>Update:</strong> I guess I should have mentioned I am using Cygwin on windows, as none of the so-far mentioned solutions work.</p> <p><strong>Update:</strong> This question was marked as a <a href="http://stackoverflow.com/questions/791765">potential duplicate question</a>. This question is not a duplicate for the following reasons:</p> <ul> <li>The alternate question does not deal with Cygwin</li> <li>The alternate question does not deal with how to <strong>reset</strong> the search to its initial state (instead it deals with simply going backward in search as well as forward).</li> </ul>
<p>My bash works as you are expecting. Maybe hitting "ctrl+C" instead of "esc" can help.</p> <p>Also, you can search forward using "ctrl+s" </p> <p><em>edit</em>: ctrl+s works if it does not send a "stop" to your terminal, i.e. if "stty -a" gives you "-ixon". You can change it by "stty -ixon". Thanks to @Phil for reminder.</p>
Is it possible to alias a branch in Git? <p>I am looking into using git on a massive scale. I was hoping to increase adoption and make things easier by calling the master branch trunk. </p> <p>This can and will give SVN users some feelings of comfort. I know I can create a branch called trunk but that seems to deviate from the git norms and might cause some users to get confused. </p> <p>I know that I can also create and delete tags to my heart's content but when I checkout those tags it tells me it is a non local branch which is just fine with me but probably not what I want to be doing. </p> <p>I am a total git newb but a seasoned professional at release and build systems. </p> <p><strong>What I want to do is to be able to call master trunk.</strong> I have seen the ability to alias commands does this apply for the names of versioned objects as well? </p> <p>I know git-svn exists and other tools but the overhead of layered repository systems frightens me.</p>
<p>You can rename the master branch trunk as Greg has suggested, or you can also create a trunk that is a symbolic reference to the master branch so that both git and svn users have the 'main' branch that they are used to.</p> <pre><code>git symbolic-ref refs/heads/trunk refs/heads/master </code></pre> <p>Note that trunk isn't a first class citizen. If you checkout <code>trunk</code> and perform a <code>git status</code> you will actually be on <code>master</code>, however you can use the <code>trunk</code> command in all places that you use the branch name (log, merge, etc.).</p>
Removing the TK icon on a Tkinter window <p>Does anybody know how to make the icon not show up? I'm looking for a way to have no icon at all.</p>
<h3>On Windows</h3> <p><strong>Step One:</strong></p> <p>Create a transparent icon using either an icon editor, or a site like <a href="http://www.rw-designer.com/online_icon_maker.php" rel="nofollow">rw-designer</a>. Save it as <code>transparent.ico</code>.</p> <p><strong>Step Two:</strong></p> <pre><code>from tkinter import * tk = Tk() tk.iconbitmap(default='transparent.ico') lab = Label(tk, text='Window with transparent icon.') lab.pack() tk.mainloop() </code></pre> <h3>On Unix</h3> <p>Something similar, but using an <code>xbm</code> icon. </p>
Cocoa Application Finished Launch <p>Is there any way to tell if a Cocoa application, such as Safari, has finished launching and able to respond? I know it's easy to do using delegates within the actual code but that isn't possible for what I'm doing.</p> <p>Thanks</p>
<p>Check out NSWorkspace and NSWorkspaceDidLaunchApplicationNotification. Something like this:</p> <pre><code>[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(appDidLaunch:) name:NSWorkspaceDidLaunchApplicationNotification object:nil] </code></pre> <p>The NSNotification object passed to the specified method will contain information about what application launched, its path, etc. For example:</p> <pre><code>- (void)appDidLaunch:(NSNotification*)note { NSLog(@"app launched: %@", [note userInfo]); } </code></pre> <p>EDIT: this is for desktop cocoa applications only - I'm fairly sure this is impossible in Cocoa Touch. Just clarifying that.</p>
How can I allow a user to assign different site functions to different roles in an asp.net role provider? <p>I am debating on whether or not to write my own authentication class. It's almost done but I think it could be better to use a role provider (either custom or the default.) I know you can assign users to roles, and then display info to the user based upon the current role. But what if you want to assign permission based upon a task? For example, say sometimes I want a role of editor to be able to modify other peoples posts, but other times I don't. That is a simple situation but I would like to have a finer grained level of authorization, instead of having a ton of roles (editor, editor-all-posts, etc.) Is this possible using a custom asp.net role provider, or should I just continue finishing my own system?</p>
<p>The basic ASP.NET Role provider is flat structured - so a user needs to belong to all the roles they are a member of.</p> <p>You would need to find/<a href="http://msdn.microsoft.com/en-us/library/8fw7xh74.aspx" rel="nofollow">write a role provider</a> that supports hierarchies - I'd recommend this route over something completely different as you will get some benefits from it such as the other aspects of the framework that work with these providers (login controls, config settings for authorisation/access etc).</p> <p>Really you want something like:</p> <ul> <li>User Role - Can post to forum, can edit their own posts.</li> <li>Editor Role - Can do anything a user can, and can edit other posts.</li> <li>Admin Role - Can do anything an editor can, and other adminy things.</li> </ul> <p>So if a user is in the Editor role, they are automatically given rights as a user, etc.</p> <p>Then your choices are either:</p> <ol> <li>Duplicate those roles for each forum, assign users to them etc.</li> <li>Add a couple of properties to your users profiles, say "ForumEdit" and "ForumAdmin", and store a list of forums they are able to edit/admin in there.</li> </ol> <p>The advantage of (1) is that you only need to do one check to see if the user can perform admin/edit tasks, but you have a higher overhead of managing all these roles.</p> <p>The advantage of (2) is that it's easy to manage the roles, you can remove a user from the editors group, and they lose all editor rights for example, but you have a higher cost to determine whether they are actually an editor for that forum as you need to query their profile.</p> <p>Similar answer to <a href="http://stackoverflow.com/questions/756299/how-can-i-implement-a-role-hierarchy-in-an-asp-net-mvc-app-using-activedirectorym/758469#758469">this one here really</a>.</p>
Uses for MachineKey in ASP.NET <p>What different ways are Machine Keys useful in asp.net? I think the following are correct but thought there may be more.</p> <ol> <li>Multiple applications can use the same cookie</li> <li>Multiple servers can work with the same viewstate</li> </ol>
<p>MachineKey is used for:</p> <ul> <li>ViewState encryption and validation</li> <li>Forms Authentication (or Federated Authentication) uses this key for signing the authentication ticket</li> </ul> <p>Having a Web App installed on multiple servers requires same Machine Key configured on all of them in order for Load Balancing to work.</p> <p>To see all details, please refer to: <a href="http://msdn.microsoft.com/en-us/library/ms998288.aspx#paght000007_machinekeyexplained">MSDN How To: Configure MachineKey in ASP.NET 2.0</a></p>
Django Model API reverse lookup of many to many relationship through intermediary table <p>I have a Resident and can not seem to get the set of SSA's the resident belongs to. I've tried <code>res.ssa_set.all()</code> <code>.ssas_set.all()</code> and <code>.ssa_resident_set.all()</code>. Can't seem to manage it. What's the syntax for a reverse m2m lookup through another table? </p> <p>EDIT: I'm getting an 'QuerySet as no attribute' error. Erm?</p> <pre><code>class SSA(models.Model): name = models.CharField(max_length=100) cost_center = models.IntegerField(max_length=4) street_num = models.CharField(max_length=9) street_name = models.CharField(max_length=40) suburb = models.CharField(max_length=40) post_code = models.IntegerField(max_length=4, blank=True, null=True) def __unicode__(self): return self.name class Resident(models.Model): cris_id = models.CharField(max_length=10, primary_key=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) ssas = models.ManyToManyField('SSA', through='SSA_Resident', verbose_name="SSAs") def __unicode__(self): return self._get_full_name() def _get_full_name(self): return u"%s %s" %(self.first_name, self.last_name) full_name = property(_get_full_name) class SSA_Resident(models.Model): id = models.AutoField(primary_key=True) resident = models.ForeignKey('Resident') ssa = models.ForeignKey('SSA', verbose_name="SSA") active = models.BooleanField(default=True) def __unicode__(self): return u"%s - %s" %(self.resident.full_name, self.ssa.name) </code></pre>
<p>I was trying to evaluate a query set object, not the object itself. Executing a get on the query set and then a lookup of the relation set worked fine. I'm changing to community wiki and leaving this here just incase someone else is as stupid as I was.</p> <p>A working example:</p> <pre><code>resident = Resident.objects.filter(name='Johnny') resident.ssa_set.all() # fail resident = resident.get() # will fail if more than one returned by filter resident.ssa_set.all() # works, since we're operating on an instance, not a queryset </code></pre>
How can I debug this line of code in Visual Studio? <p>I have the following line of code in VS2008.</p> <pre><code> VirtualPathData virtualPathData = RouteTable.Routes.GetVirtualPath(_viewContext.RequestContext, "Home", pageLinkValueDictionary); </code></pre> <p>I wish to debug this <code>GetVirtualpath(..)</code> method .. to see what it's trying to do.</p> <p>I'm assuming I need to grab the symbols from the MS symbol server.</p> <p>What I did was </p> <ul> <li>Turn OFF <em>Enable just my code</em></li> <li>Turn ON <em>Enable source server support</em></li> <li>Show the <em>Modules</em> window when debugging (to manually load the correct module)</li> </ul> <p>Compile in debug mode, put a breakpoint on that line about and debug-run. When I hit the line, I manually load in <code>System.Web.Routing(..)</code> from <em>MS Symbol server</em>. This works (the pdb is downloaded locally) and when i step INTO this line, I goto some Dissassemler code :(</p> <p>Can anyone see what I'm doing wrong?</p>
<p>That the symbols file is downloaded doesn't mean that sources are available for it, the pdb needs to be source indexed as well.</p> <p>From <a href="http://weblogs.asp.net/scottgu/archive/2007/10/03/releasing-the-source-code-for-the-net-framework-libraries.aspx" rel="nofollow">Scott Guthrie's announcement</a>:</p> <blockquote> <p>We'll begin by offering the source code (with source file comments included) for the .NET Base Class Libraries (System, System.IO, System.Collections, System.Configuration, System.Threading, System.Net, System.Security, System.Runtime, System.Text, etc), ASP.NET (System.Web), Windows Forms (System.Windows.Forms), ADO.NET (System.Data), XML (System.Xml), and WPF (System.Windows). We'll then be adding more libraries in the months ahead (including WCF, Workflow, and LINQ). The source code will be released under the Microsoft Reference License (MS-RL).</p> </blockquote> <p>It seems System.Web.Routing isn't included here.</p> <p>You can however <a href="http://www.codeplex.com/aspnet" rel="nofollow">download the MVC Source</a>, then you should be able to use the pdbs you downloaded against that source.</p>
Appropriate VS Project for Multiple .Net Sites <p>Here's what I'm working with:</p> <ul> <li>Several websites</li> <li>Classes/data shared between them (registration systems on individual sites, and management on a central site)</li> <li>A workflow application that runs nightly.</li> </ul> <p>I need to be able to cleanly and easily share the classes between the websites and workflow component. I know this is textbook 'DLL!', but I'm wondering what kind of Visual Studio (2008) project(s) you recommend to make all this happen in a clean, logical fashion.</p> <p>What do you suggest?</p> <p>Edit: I seem to remember some kind of project type (in VS05?) that allowed me to contain several sites and projects (all related) in the same solution. Am I nuts?</p>
<p>this is sort of a no brainer, unless I am missing something in your question.</p> <p>You would have a website project for each website, and a class library project for your dll.</p> <p>But what I THINK you meant is how to easily share the DLL(s) across all sites? In that case try coding some post build events for the DLL to deploy it to all appropriate BIN folders</p>
jQuery: form returned on "success" needs re-binding <p>a quick question. I am using the jQuery.forms.js plug-in. </p> <p>I have a form that posts to a php page and returns data with jSon. </p> <p>The data that is returned is code for a new form (it replaces the form that was used to post the information). The new form is not bound to any jQuery functions, as it was not around when the page loaded. </p> <p>So, how can I get ajax form to recognize the new form, so that if i need to use the form a second time, it is also utilizing the jQuery function?</p> <pre><code>// jQuery for submitting info to php doc and, on success, replacing the form $(document).ready(function() { jQuery('form[id*=postOnline]').ajaxForm({ dataType: 'json', success: function(data) { $('#onlineStatus' + data.rid).html(data.formed).slideDown('slow'); bindNote(); } }); }); &lt;!-- /////////////////////// POST ONLINE /////////////////////// --&gt; &lt;div id='onlineStatus&lt;?php echo $b_id ?&gt;' class='postOnline'&gt; &lt;form name="postOnline" id="postOnline&lt;?php echo $b_id ?&gt;" action="postOnline.php" method="post"&gt; &lt;input type="hidden" value="&lt;?php echo $b_id ?&gt;" name="b" /&gt; &lt;input type="hidden" value="1" name="p" /&gt; &lt;input type="submit" class="button" value="Post Online" /&gt; &lt;/form&gt; &lt;/div&gt; &lt;!-- /////////////////////// POST ONLINE /////////////////////// --&gt; // ... code for entering data into database and then... $result = mysql_query( $sql ); if($result) { if($show == '1'){$val = 'remove from online'; $num='0';} if($show == '0'){$val = 'show online'; $num='1';} $return = " &lt;form name='postOnline' id='postOnline$id' action='postOnline.php' method='post'&gt; &lt;input type='hidden' value='$b_id' name='b' /&gt; &lt;input type='hidden' value='$num' name='p' /&gt; &lt;input type='submit' class='button' value='$val' /&gt; &lt;/form&gt; "; print json_encode(array("rid" =&gt; $id, "formed" =&gt; $return)); } ?&gt; </code></pre>
<p>The easiest solution to this is not using jQuery's form plugin and doing it manually, which is really not very difficult:</p> <pre><code>$(document).ready(function() { jQuery('form[id*=postOnline]').live('submit', function() { var formdata = $(this).serialize(); $.ajax({ type: $(this).attr('method'), url: $(this).attr('action'), dataType: 'json', data: formdata, success: function(data) { $('#onlineStatus' + data.rid).html(data.formed).slideDown('slow'); bindNote(); } }); return false; }); }); </code></pre> <p>Now since you are using jQuery's new (1.3) <a href="http://docs.jquery.com/Events/live" rel="nofollow"><code>live</code></a> functionality, any forms you add that match the <code>form[id*=postOnline]</code> selector will still be wired with this event.</p> <p>Alternatively, you can open up the jquery forms code and find wherever it does its binding and try to modify it so that it uses it <code>live</code>. Even another alternative would be to encompass the wiring in a function, and call it at the end of your success function, like so:</p> <pre><code>function bindForm() { jQuery('form[id*=postOnline]').ajaxForm({ dataType: 'json', success: function(data) { $('#onlineStatus' + data.rid).html(data.formed).slideDown('slow'); bindNote(); bindForm(); } }); } $(document).ready(function() { bindForm(); }); </code></pre> <p>I don't think it is very neat, but it should work.</p>
Is it a bad idea to use php in css documents? <p>I have created css page called style.php and included this the top: </p> <p><code>&lt;?php header("Content-type: text/css"); ?&gt;</code></p> <p>Does this make you cringe. Is it a terrible idea? I am doing this because I have created a CMS that allows the admin to control colors on pages (so the style.php script queries the database and grabs the hex values).</p> <p>Any thoughts?</p>
<p>It's not a bad idea (subject to the notes about caching + content-type), but think about the cost of firing up a PHP instance (mod_php) or passing the script to an already running php (fastcgi style). Do you really want that overhead?</p> <p>You might be better off writing a "cached" version of your CSS page to a static file, and serving that (or if you need per-page flexibility, selecting which style sheet to include; I assume your main page is PHP already)</p>
Quick primer on implementing a COM object that implement some custom IDLs in python? <p>Does anyone have experience using python to create a COM object that implements some custom IDLs? </p> <p>Basically I'd like to know if it's extremely simple to do compared to c++, and if it is do you know of a good tutorial?</p>
<p>The tutorial you are looking for is in the <a href="http://oreilly.com/catalog/9781565926219/" rel="nofollow">Python Programming On Win32</a> book, by Mark Hammond and Andy Robinson. A bit old, and the COM object creation info is distributed across some chapters.</p> <p>A more recent example, <a href="http://techarttiki.blogspot.com/2008/03/calling-python-from-maxscript.html" rel="nofollow">simple COM server using Python</a>, can give you a quick start.</p>
overload print python <p>Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file.</p> <p>Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but <a href="http://stackoverflow.com/questions/550470/overload-print-python/550477#550477">http://stackoverflow.com/questions/550470/overload-print-python/550477#550477</a> just told me i cant overload print in 2.x which is what i am using.</p>
<p>For those reviewing the previously dated answers, as of version release "Python 2.6" there is a new answer to the original poster's question.</p> <p>In Python 2.6 and up, you can disable the print statement in favor of the print function, and then override the print function with your own print function:</p> <pre><code>from __future__ import print_function # This must be the first statement before other statements. # You may only put a quoted or triple quoted string, # Python comments, other future statements, or blank lines before the __future__ line. try: import __builtin__ except ImportError: # Python 3 import builtins as __builtin__ def print(*args, **kwargs): """My custom print() function.""" # Adding new arguments to the print function signature # is probably a bad idea. # Instead consider testing if custom argument keywords # are present in kwargs __builtin__.print('My overridden print() function!') return __builtin__.print(*args, **kwargs) </code></pre> <p>Of course you'll need to consider that this print function is only module wide at this point. You could choose to override <code>__builtin__.print</code>, but you'll need to save the original <code>__builtin__.print</code>; likely mucking with the <code>__builtin__</code> namespace.</p>
How can I put $HOME/opt/git/bin to my PATH? <p>I tried to include the following unsuccessfully to my ~/.profile:</p> <pre><code>export PATH='$HOME/opt/git/bin' </code></pre> <p>It seems not to work because $git gives me nothing. I am trying to install Git.</p> <p>I have also tried commands <a href="http://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide/323764#323764">here</a>. </p>
<p>You'll want to be careful with that command. It will <strong>override</strong> your $PATH.</p> <p>You might need to put it in <code>~/.bash_profile</code> and change it to this:</p> <pre><code>export PATH="$HOME/opt/git/bin:$PATH" </code></pre>
ASP.net: What type of application/website is more suitable to Webform or MVC? <p>I have read all the post regarding the pro and con of ASP.net webform vs mvc.</p> <p>However, I'm wondering under what circumstance does one use webform or mvc? would it come down to what you or your team is more familiar with?</p>
<p>Typical business application with lots of controls, their behavior rules, with enabling/disabling them in response to the events fired by other controls would be a lot more complicated task with MVC while with WebForms you can do it during a coffee-pause.</p> <p>Also with MVC you get nice SEO-friendly urls out of the box, which is great for publicly exposed sites. WebForms do not offer that convenience, however, for internal applications or the public ones protected by customer login it is no concern at all.</p>
Growing Amazon EBS Volume sizes <p>I'm quite impressed with Amazon's EC2 and EBS services. I wanted to know if it is possible to grow an EBS Volume.</p> <p>For example: If I have a 50 GB volume and I start to run out of space, can I bump it up to 100 GB when required?</p>
<p>You can grow the storage, but it can't be done on the fly. You'll need to take a snapshot of the current block, add a new, larger block and re-attach your snapshot.</p> <p>There's a simple walkthrough <a href="http://blog.edoceo.com/2009/02/amazon-ebs-how-to-grow-storage.html">here</a> based on using <a href="http://docs.amazonwebservices.com/AWSEC2/2009-11-30/CommandLineReference/">Amazon's EC2 command line tools</a></p>
Printing window with GtkTreeView in C? <p>I have some reports in my application that are represented as window with GtkTreeView widget reading data from GtkListStore model. These reports are much like Excel tables with usual stuff: column names, some header and footer text, maybe small image, ...</p> <p>What should I use/read/learn to be able to print this, having in mind that I am a C programmer using GTK+ and I want code to be portable to Linux and Windows.</p> <p>Can you give me some tips what is best way to do this and maybe put some (pseudo or real) code?</p>
<p>That should be possible with <a href="http://cairographics.org/" rel="nofollow">libCairo</a>, it supports many <a href="http://cairographics.org/backends/" rel="nofollow">backends</a> such as Windows GDI, PostScript and PDF.</p> <p>Sure, that doesn't spawn a printing dialog but that should not be very complicated if the data to be printed can be computed automatically in all important formats. I think Mozilla Firefox does printing with libCairo, too.</p>
List of HTML Helpers you use <p>I have found Html Helpers extremely useful to simplify view pages code. </p> <p>Apart from the ones included in the latest release of Asp.Net Mvc which one do you use? </p> <p>How much you can reuse them in different projects and are they linked only to html generation or did you put some custom logic inside?</p>
<p>Check out <a href="http://www.codeplex.com/MVCContrib" rel="nofollow">MvcContrib</a>.<a href="http://lunaverse.wordpress.com/2008/11/24/mvcfluenthtml-fluent-html-interface-for-ms-mvc/" rel="nofollow">FluentHtml</a>.</p>
Speed up Rails App on development env.? <p>I have <em>huge</em> Rails app on development right now, which run <em>VERY</em> slow on -e development. I use Mongrel as web server. Is there any way to speed up a little bit everything? Because i have to wait 3-10 sec. to reload a page. Thanks. </p>
<p>This is the answer to all of your woes:</p> <p><a href="https://github.com/thedarkone/rails-dev-boost">https://github.com/thedarkone/rails-dev-boost</a></p>
Making HTML content expand to fill the window <p>I have an HTML page divided vertically into</p> <ul> <li>Header</li> <li>Body</li> <li>Footer</li> </ul> <p>The body in turn is divided horizontally into</p> <ul> <li>A large DIV on the left surrounded by scrollbars, displaying a portion of a diagram</li> <li>A form on the right</li> </ul> <p>The header and footer are fixed-height. The body should expand vertically to fill the portion of the window not occupied by the header and footer.</p> <p>Similarly the form is fixed-width and the scroll pane should expand horizontally to fill the window width.</p> <p>The diagram is very large (up to 10x10 screenfuls) so I cannot display all of it. Instead I want to display as much as possible (using the whole window) so that the user needs to scroll as little as possible.</p> <p>I also cannot use javascript, because some users are necessarily paranoid and must disable it.</p> <p>Some options I have considered:</p> <ul> <li>A table with the scroll pane cell's width and height set to 100% and all others to 1% <br /><em>Doesn't work. The table (and hence the page) expands to contain the entire diagram, even with absolute positioning on the scroll pane DIV.</em></li> <li>Absolute positioning to offset the pane from the bottom of the page by the height of the footer<br /><em>Works but inaccurate: the footer's height depends on the current font size and whether text is wrapped. This means I must leave a large margin to ensure they do not overlap.</em></li> <li>Place the diagram in an IFRAME<br /><em>The best solution I've found with scripts disabled, but limits what I can do in scripts when they <strong>are</strong> enabled.</em></li> </ul> <p>I notice that Google Maps uses a fixed-size area for the map when scripts are disabled. If Google has given up on this problem does that mean it's not feasible?</p>
<p>Using the height: 100% CSS attribute should make it work.</p> <p>See if <a href="http://www.dave-woods.co.uk/?p=144">Dave Woods 100% Height Layout Using CSS</a> works for you.</p>
Microsoft Visual Studio (2008) - Filters in the Solution Explorer <p>In the Solution Explorer when working with C++ projects there is the standard filters of Header Files, Resource Files, and Source Files. What I'm wanting to accomplish is essentially Filters by folder.</p> <p><hr /></p> <p>Lets say the structure of the files was like this:</p> <ul> <li>../Folder1/Source1.cpp</li> <li>../Folder1/Header1.h</li> <li>../Folder1/Source2.cpp</li> <li>../Folder1/Header2.h</li> <li>../AnotherFolder/Source1.cpp</li> <li>../AnotherFolder/Header1.h</li> <li>../AnotherFolder/Source2.cpp</li> <li>../AnotherFolder/Header2.h</li> <li>../SomeOtherSource.cpp</li> </ul> <p>In the Solution Explorer, it would look like:</p> <ul> <li>Header Files/Header1.h</li> <li>Header Files/Header1.h</li> <li>Header Files/Header2.h</li> <li>Header Files/Header2.h</li> <li>Source Files/SomeOtherSource.cpp</li> <li>Source Files/Source1.cpp</li> <li>Source Files/Source1.cpp</li> <li>Source Files/Source2.cpp</li> <li>Source Files/Source2.cpp</li> </ul> <p>And I would like to have it look like this:</p> <ul> <li>Header Files/AnotherFolder/Header1.h</li> <li>Header Files/AnotherFolder/Header2.h</li> <li>Header Files/Folder1/Header1.h</li> <li>Header Files/Folder1/Header2.h</li> <li>Source Files/AnotherFolder/Source1.cpp</li> <li>Source Files/AnotherFolder/Source2.cpp</li> <li>Source Files/Folder1/Source1.cpp</li> <li>Source Files/Folder1/Source2.cpp</li> <li>Source Files/SomeOtherSource.cpp</li> </ul> <p><hr /></p> <p>How would this be accomplished?</p>
<p>You are free to manually create folders yourself and move the files around. I agree this is a much more convenient way to arrange files but AFAIK there is no way to make VS do this automatically.</p>
How to dynamically change the number of columns in an SSRS body <p>In SQL Server Reporting Services (SSRS), the number of columns on a page for a report is set in the Report Properties (this is not the same as the number of field columns which vary with the data).<br /> By default this is set one, but it could be two or more, flowing down then across. </p> <p>I want to be able to set this dynamically, depending on the type of printer I'm using (label roll or sheet). However, SSRS does not allow you to enter an expression for this value. Does anyone have a way of doing this via code? </p>
<p>What you can do is to define several custom rendering options in rsreportserver.config:</p> <pre><code>&lt;Render&gt; &lt;Extension Name="PDF (1 column)" Type="Microsoft.ReportingServices.Rendering.ImageRenderer.PdfReport, Microsoft.ReportingServices.ImageRendering"/&gt; &lt;OverrideNames&gt; &lt;Name Language="en-US"&gt;PDF (1 column)&lt;/Name&gt; &lt;/OverrideNames&gt; &lt;Configuration&gt; &lt;DeviceInfo&gt; &lt;OutputFormat&gt;PDF&lt;/OutputFormat&gt; &lt;PageHeight&gt;11in&lt;/PageHeight&gt; &lt;PageWidth&gt;8.5in&lt;/PageWidth&gt; &lt;Columns&gt;1&lt;Columns&gt; &lt;/DeviceInfo&gt; &lt;/Configuration&gt; &lt;/Extension&gt; &lt;Extension Name="PDF (2 columns)" Type="Microsoft.ReportingServices.Rendering.ImageRenderer.PdfReport, Microsoft.ReportingServices.ImageRendering"/&gt; &lt;OverrideNames&gt; &lt;Name Language="en-US"&gt;PDF (2 columns)&lt;/Name&gt; &lt;/OverrideNames&gt; &lt;Configuration&gt; &lt;DeviceInfo&gt; &lt;OutputFormat&gt;PDF&lt;/OutputFormat&gt; &lt;PageHeight&gt;11in&lt;/PageHeight&gt; &lt;PageWidth&gt;8.5in&lt;/PageWidth&gt; &lt;Columns&gt;2&lt;Columns&gt; &lt;/DeviceInfo&gt; &lt;/Configuration&gt; &lt;/Extension&gt; &lt;/Render&gt; </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/ms156281.aspx" rel="nofollow">Customizing Rendering Extension Parameters in RSReportServer.Config</a><br /> <a href="http://msdn.microsoft.com/en-us/library/ms154682.aspx" rel="nofollow">PDF Device Information Settings</a><br /> Then, before printing, just choose appropriate rendering format.</p> <p>However, it will be easier to specify thouse settings in Report url:</p> <pre><code>http://servername/reportserver?/SampleReports/Employee SalesSummary &amp;EmployeeID=38&amp;rs:Command=Render&amp;rs:Format=HTML&amp;rc:Columns=1 http://servername/reportserver?/SampleReports/Employee SalesSummary &amp;EmployeeID=38&amp;rs:Command=Render&amp;rs:Format=HTML&amp;rc:Columns=2 </code></pre> <p>See <a href="http://msdn.microsoft.com/en-us/library/ms155046.aspx" rel="nofollow">Specifying Device Information Settings in a URL</a><br /> You can also create some Main Report and place thouse links there.</p>
Load an assembly in parent folder - probing? <p>I'm developing a class library that uses a very simple plugin structure - to simple to start creating new appdomains for each plugin. This is the folder structure:</p> <pre><code>Bin Modules Plugins.dll Main.dll Library.dll </code></pre> <p>During runtime I load the types in Plugins.dll using Reflection. I would like to pass one of my own objects that I have created in Library.dll to a class in Plugins.dll. But on the MethodInfo invoke line e.g.</p> <pre><code>pMi.Invoke({My Own Objects()}) </code></pre> <p>it gives me a FileNotFound Exception as it cannot find Library.dll. What would be the best way of telling my library to look in the parent folder for the assembly?</p> <p>Thanks for any help.</p>
<p>When constructing you new app domains what are you setting as the ApplicationBase and the PrivateBinPath? Simply keeping the application base as "Bin" and putting Modules as the PrivateBinPath should be sufficient but not knowing how you are doing it I can't give you a definite answer.</p> <p>As an aside is there any reason you aren't using the basic AddIn model present in <a href="http://www.codeplex.com/MEF" rel="nofollow">MEF</a>? (you can use System.AddIn without needing the full MEF bells and whistles)</p>
Where Is The Recommended Place To Store Instance Variables For Layouts <p>If you have a layout that has in a menu which gets its menu items from a database. Where is the recommended place in a Rails application to place that call and assigns it to the instance variable that the layout uses?</p> <pre><code>1. @menuitems # exists in application.html.erb 2. @menuitems = MenuItem.find(:all) # code exists somewhere (where should this exist?) </code></pre> <p>@womble - Yes a before_filter would be helpful, but I would have to include it in all controllers using this layout, or is this something I can put in the application_controller.rb, would the child controllers and accompanying views be able to see that instance variable?</p>
<p>Yes, you can define and set this as a <code>before_filter</code> in your application controller. All your controllers will call that before filter. It's not all that uncommon to set global instance variables this way.</p> <p>An alternative is to use a memoization method in application controller and set is as a helper method, in a similar way to the popular <code>current_user</code> methods. The instance variable would then be nicely wrapped by your memoization function. For example:</p> <pre><code>def menu_items @menu_items ||= MenuItem.all end helper_method :menu_items </code></pre> <p>Now just call <code>menu_items</code> from your layout instead of using <code>@menu_items</code> directly.</p> <p><hr /></p> <p>I suppose its worth mentioning that putting this in application controller is somewhat unnecessary. If you're only going to use this in your view / layout, you could put it directly in a helper module, such as LayoutHelper. You will need to use <code>helper :all</code> (or at least <code>helper :layout</code>) in your application controller.</p> <p>This is somewhat of personal preference - you may or may not like having ActiveRecord calls in your helpers. But, if there's a time to do so, this would be it.</p>
Strange char* compile error? <p>Anything wrong with my code below? I got the compile error!</p> <pre><code>typedef unsigned char BYTE; void foo(char* &amp; p) { return; } int main() { BYTE * buffer; // error C2664: 'foo' : cannot convert parameter 1 from 'char *' to 'char *&amp;' foo ((char*)buffer); return 0; } </code></pre> <p>Thanks in advance, George</p>
<p>When you cast the <code>BYTE*</code> to <code>char*</code> a unnamed temporary entity is created with the type <code>char*</code>. The function you call takes a reference to a <code>char*</code> but you can't take a reference to such a temporary entity because it is not a real variable.</p>
Writing XSS Filter for (X)HTML Based on White List <p>I need to implement a simple and efficient XSS Filter in C++ for <a href="http://cppcms.sourceforge.net" rel="nofollow">CppCMS</a>. I can't use existing high quality filters written in PHP because because it is high performance framework that uses C++.</p> <p>The basic idea is provide a filter that have a while list of HTML tags and a white list of options for these tags. For example. typical HTML input can consist of <code>&lt;b&gt;</code>, <code>&lt;i&gt;</code>, tags and <code>&lt;a&gt;</code> tag with <code>href</code>. But straightforward implementation is not good enough, because, even allowed simple links may include XSS:</p> <pre><code>&lt;a href="javascript:alert('XSS')"&gt;Click On Me&lt;/a&gt; </code></pre> <p>There are many other examples can be found <a href="http://ha.ckers.org/xss.html" rel="nofollow">there</a>. So I though also about a possibility to create a white list of prefixes for tags like href/src -- so I always need to check if it starts with <code>(https?|ftp)://</code></p> <p><strong>Questions:</strong></p> <ul> <li>Are these assumptions are good enough for most of purposes? Meaning that If I do not give an options for <code>style</code> tags and check src/href using white list of prefixes it solves XSS problems? Are there problems that can't be fixes this way?</li> <li>Is there a good reference for formal grammar of HTML/XHTML in order to write simple parser that would cleanup all incorrect of forbidden tags like <code>&lt;script&gt;</code></li> </ul>
<p>You can take a look at the Anti Samy project, trying to accomplish the same thing. It's Java and .NET though.</p> <ul> <li><a href="http://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project#.NET_version" rel="nofollow">http://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project#.NET_version</a></li> <li><a href="http://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project_.NET" rel="nofollow">http://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project_.NET</a></li> </ul> <p><strong>Edit 1, A bit extra :</strong></p> <p>You can potentially come up with a very strict white listing. It should be structured well and should be pretty tight and not much flexible. When you combine flexibility, so many tags, attributes and different browsers generally you end up with a XSS vulnerability.</p> <p>I don't know what is your requirements but I'd go with a strict and simple tag support (only b li h1 etc.) and then strict attribute support based on the tag (for example src is only valid under href tag), then you need to do whitelisting in the attribute values as you stated http|https|ftp or style="color|background-color" etc.</p> <p>Consider this one:</p> <p><code>&lt;x style="express/**/ion:(alert(/bah!/))"&gt;</code></p> <p>Also you need to think about some character whitelisting or some UTF-8 normalization, because different encodings can cause awkward issues. Such as new lines in attributes, non valid UTF-8 sequences.</p>
Do people provide multiple mechanisms for doing the same thing in an API? <p>Is it confusing to design an API with multiple ways of achieving the same outcome? For example, I have my own <code>Date</code> library (which is a simple wrapper around the Java <code>Date</code>/<code>Calendar</code> classes to distinguish a <em>year-month-day</em>, <code>Date</code>, from an <em>instant-in-time</em>, <code>Instant</code> and provide mechanisms to convert between the two). I started off with one method to create an instance of a <code>Date</code>:</p> <pre><code>Date.valueOfYearMonthDay(int year, int month, int day); </code></pre> <p>But then I found that the resultant code using the API was not very readable. So I added:</p> <pre><code>Date.yearMonthDay(int year, int month, int day) Date.ymd(int year, int month, int day) Date.date(int year, int month, int day) </code></pre> <p>Then I started getting fluent:</p> <pre><code>Date.january().the(int day).in(int year); </code></pre> <p><em>(I find that the fluent version is really useful for making readable tests).</em> All these methods do identical things and have accurate JavaDoc. I think I've read that a strength of <code>perl</code> is that each programmer can choose exactly which method he/she prefers to solve something. And a strength of <code>Java</code> is that there is usually only one way of doing things :-)</p> <p>What are people's opinions?</p>
<p>I've been doing academic research for the past 10 years on different issues that have to do with API usability in Java.</p> <p>I can tell you that the statement about having one way to do things in Java is fairly incorrect. There are often <em>many</em> ways to do the same thing in Java. And unfortunately, they are often not consistent or documented.</p> <p>One problem with bloating the interface of a class with convenience methods is that you are making it more difficult to understand the class and how to use it. The more choices you have, things become more complex.</p> <p>In an analysis of some open-source libraries, I've found instances of redundant functionality, added by different individuals using different terms. Clearly a bad idea. </p> <p>A greater problem is that the information carried by a name is no longer meaningful. For example, things like putLayer vs. setLayer in swing, where one just updates the layer and the other also refreshes (guess which one?) are a problem. Similarly, getComponentAt and findComponentAt. In other ways, the more ways to do something, the more you obfuscate everything else and reduce the "entropy" of your existing functionality.</p> <p>Here is a good example. Suppose you want in Java to replace a substring inside a string with another string. You can use String.replace(CharSequence, CharSequence) which works perfectly as you'd expect, literal for literal. Now suppose you wanted to do a regular expression replacement. You could use Java's Matcher and do a regular expression based replacement, and any maintainer would understand what you did. However, you could just write String.replaceAll(String, String), which calls the Matcher version. However, many of your maintainers might not be familiar with this, and not realize the consequences, including the fact that the replacement string cannot contains "$"s. So, the replacement of "USD" with "$" signs would work well with replace(), but would cause crazy things with replaceAll().</p> <p>Perhaps the greatest problem, however, is that "doing the same thing" is rarely an issue of using the same method. In many places in Java APIs (and I am sure that also in other languages) you would find ways of doing "almost the same thing", but with differences in performance, synchronization, state changes, exception handling, etc. For instance, one call would work straight, while another would establish locks, and another will change the exception type, etc. This is a recipe for trouble.</p> <p>So bottom line: Multiple ways to do the same thing are not a good idea, unless they are unambiguous and very simple and you take a lot of care to ensure consistency. </p>
Customizing UIAlertView <p>Anyone have code to make this:</p> <p><img src="http://booleanmagic.com/uploads/UIAlertViewHack.png" alt="UIAlertViewHack"></p> <p>or better yet, a 3x2 grid of buttons with images using the UIAlertView object?</p> <p>I don't care about the textfield, it's the buttons in a grid I want (preferably with images rather than text).</p>
<p>I think your best bet is to forget customizing UIAlert view and build a custom view yourself.</p> <p>For one, what you're showing really isn't an "alert" so it's counter to what UIAlertView is designed to be for. This means that you're changing the UI paradigm on the user which is never a good idea.</p> <p>Second, it would be much easier to animate a custom view into place than to try and hack UIAlertView to get it to do what you want.</p>
Testing a sweeper with RSpec in Rails <p>I want to make sure my sweeper is being called as appropriate so I tried adding something like this:</p> <pre><code>it "should clear the cache" do @foo = Foo.new(@create_params) Foo.should_receive(:new).with(@create_params).and_return(@foo) FooSweeper.should_receive(:after_save).with(@foo) post :create, @create_params end </code></pre> <p>But I just get:</p> <pre><code>&lt;FooSweeper (class)&gt; expected :after_save with (...) once, but received it 0 times </code></pre> <p>I've tried turning on caching in the test config but that didn't make any difference.</p>
<p>As you already mentioned caching has to be enabled in the environment for this to work. If it's disabled then my example below will fail. It's probably a good idea to temporarily enable this at runtime for your caching specs.</p> <p>'after_save' is an instance method. You setup an expectation for a class method, which is why it's failing.</p> <p>The following is the best way I've found to set this expectation:</p> <pre><code>it "should clear the cache" do @foo = Foo.new(@create_params) Foo.should_receive(:new).with(@create_params).and_return(@foo) foo_sweeper = mock('FooSweeper') foo_sweeper.stub!(:update) foo_sweeper.should_receive(:update).with(:after_save, @foo) Foo.instance_variable_set(:@observer_peers, [foo_sweeper]) post :create, @create_params end </code></pre> <p>The problem is that Foo's observers (sweepers are a subclass of observers) are set when Rails boots up, so we have to insert our sweeper mock directly into the model with 'instance_variable_set'. </p>
Why will this function using CURL work for some URLs but not others? <p>I'm writing a website in PHP that aggregates data from various other websites. I have a function 'returnPageSource' that takes a URL and returns the html from that URL as a string.</p> <pre><code>function returnPageSource($url){ $ch = curl_init(); $timeout = 5; // set to zero for no timeout curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // means the page is returned curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOUT_CONNECTTIMEOUT, $timeout); // how long to wait to connect curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); // follow redirects //curl_setopt($ch, CURLOPT_HEADER, False); // only request body $fileContents = curl_exec($ch); // $fileContents contains the html source of the required website curl_close($ch); return $fileContents; } </code></pre> <p>This works fine for some of the websites I need, like <a href="http://atensembl.arabidopsis.info/Arabidopsis_thaliana_TAIR/unisearch?species=Arabidopsis_thaliana_TAIR;idx=;q=At5g02310" rel="nofollow">http://atensembl.arabidopsis.info/Arabidopsis_thaliana_TAIR/unisearch?species=Arabidopsis_thaliana_TAIR;idx=;q=At5g02310</a>, but not for others, like <a href="http://www.bar.utoronto.ca/efp/cgi-bin/efpWeb.cgi?dataSource=Chemical&amp;modeInput=Absolute&amp;primaryGene=At5g02310&amp;orthoListOn=0" rel="nofollow">http://www.bar.utoronto.ca/efp/cgi-bin/efpWeb.cgi?dataSource=Chemical&amp;modeInput=Absolute&amp;primaryGene=At5g02310&amp;orthoListOn=0</a> . Does anybody have any idea why?</p> <p><b>Update</b></p> <p>Thanks for the responses. I've changed my useragent to be the same as my browser (Firefox 3, which can access the sites fine), changed timeout to 0 and I still can't connect, but I can get some error messages. curl_error() gives me the error "couldn't connect to host", and curl_getinfo($ch, CURLINFO_HTTP_CODE); returns HTTP code 0...neither of which is very helpful. I've also tried curl_setopt($ch, CURLOPT_VERBOSE, 1);, but that displayed nothing. Does anybody have any other ideas?</p> <p><b>Final Update</b></p> <p>I just realised I didn't explain what was wrong - I just needed to enter the proxy settings for my university (I'm using the university's server). Everything worked fine after that!</p>
<p>You should use <a href="http://www.php.net/curl_error"><code>curl_error()</code></a> to check which error has occurred (if any)</p>
asp.net textbox onley remembers initial value <p>In my Page_Load I set the text equal to a value e.g. txtNote.text="note text ex"</p> <p>If I change that text on my actual form to something else, then try to write my new value to a db ... the textNote.text is still "note text ex" what it was set to in the Page_Load...not what I changed it to on the form....can this be changed?</p> <p>Thanks,</p>
<p>Take your assignment into IsPostBack control like that : </p> <pre><code>if (!IsPostBack) { txtNote.Text="note text ex"; } </code></pre>
Help me implement Blackjack in Python (updated) <p>I am in the process of writing a blackjack code for python, and i was hoping someone would be able to tell me how to make it:</p> <ol> <li>Recognize what someone has typed i.e. "Hit" or "Stand" and react accordingly.</li> <li>Calculate what the player's score is and whether it is an ace and a jack together, and automatically wins.</li> </ol> <p>Ok, this is what i have gotten so far.</p> <pre><code>"This imports the random object into Python, it allows it to generate random numbers." import random print("Hello and welcome to Sam's Black Jack!") input("Press &lt;ENTER&gt; to begin.") card1name = 1 card2name = 1 card3name = 1 card4name = 1 card5name = 1 "This defines the values of the character cards." Ace = 1 Jack = 10 Queen = 10 King = 10 decision = 0 "This generates the cards that are in your hand and the dealer's hand to begin with. card1 = int(random.randrange(12) + 1) card2 = int(random.randrange(12) + 1) card3 = int(random.randrange(12) + 1) card4 = int(random.randrange(12) + 1) card5 = int(random.randrange(12) + 1) total1 = card1 + card2 "This makes the value of the Ace equal 11 if the total of your cards is under 21" if total1 &lt;= 21: Ace = 11 "This defines what the cards are" if card1 == 11: card1 = 10 card1name = "Jack" if card1 == 12: card1 = 10 card1name = "Queen" if card1 == 13: card1 = 10 card1name = "King" if card1 == 1: card1 = Ace card1name = "Ace" elif card1: card1name = card1 if card2 == 11: card2 = 10 card2name = "Jack" if card2 == 12: card2 = 10 card2name = "Queen" if card2 == 13: card2 = 10 card2name = "King" if card2 == 1: card2 = Ace card2name = "Ace" elif card2: card2name = card2 if card3 == 11: card3 = 10 card3name = "Jack" if card3 == 12: card3 = 10 card3name = "Queen" if card3 == 13: card3 = 10 card3name= "King" if card3 == 1: card3 = Ace card3name = "Ace" elif card3: card3name = card3 if card4 == 11: card4 = 10 card4name = "Jack" if card4 == 12: card4 = 10 card4name = "Queen" if card4 == 13: card4 = 10 card4name = "King" if card4 == 1: card4 = Ace card4name = "Ace" elif card4: card4name = card4 if card5 == 11: card5 = 10 card5name = "Jack" if card5 == 12: card5 = 10 card5name = "Queen" if card5 == 13: card5 = 10 card5name = "King" if card5 == 1: card5 = Ace card5name = "Ace" elif card5: card5name = card5 "This creates the totals of your hand" total2 = card1 + card2 total3 = card1 + card2 + card3 print("You hand is ", card1name," and", card2name) print("The total of your hand is", total2) decision = input("Do you want to HIT or STAND?").lower() "This is the decision for Hit or Stand" if 'hit' or 'HIT' or 'Hit' in decision: decision = 1 print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if 'STAND' or 'stand' or 'Stand' in decision: print("You have selected STAND") "Dealer's Hand" dealer = card4 + card5 print() print("The dealer's hand is", card4name," and", card5name) if decision == 1 and dealer &lt; total3: print("Congratulations, you beat the dealer!") if decision == 1 and dealer &gt; total3: print("Too bad, the dealer beat you!") </code></pre> <p>Ok, nevermind, i fixed it :D</p> <p>I just changed the Hit and Stand to Yes or No</p> <pre><code>if total2 &lt; 21: decision = input("Do you want to hit? (Yes or No)") "This is the decision for Hit or Stand" if decision == 'Yes': print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if decision == 'No': print("You have selected STAND") </code></pre>
<p>This can get you started:</p> <p><a href="http://docs.python.org/library/random.html">http://docs.python.org/library/random.html</a></p> <p><a href="http://docs.python.org/library/strings.html">http://docs.python.org/library/strings.html</a></p> <p><a href="http://docs.python.org/library/stdtypes.html">http://docs.python.org/library/stdtypes.html</a></p> <p><a href="http://docs.python.org/reference/index.html">http://docs.python.org/reference/index.html</a></p> <p>I see you have added some code; that's good.</p> <p>Think about the parts of your program that will need to exist. You will need some representation of "cards" -- cards have important features such as their value, their suit, etc. Given a card, you should be able to tell what its value is, whether it's a Jack or an Ace or a 2 of hearts. Read up on "classes" in Python to get started with this.</p> <p>You will also have a hand of cards -- the cards your dealer is currently holding, and the cards your player is currently holding. A "hand" is a collection of cards, which you (the programmer) can add new cards to (when a card is dealt). You might want to do that using "lists" or "arrays" or "classes" that contain those arrays. A hand also has a value, which is usually the sum of card values, but as you know, Aces are special (they can be 1 or 11), so you'll need to treat that case correctly with some "if statements".</p> <p>You will also have a deck; a deck is a special collection -- it has exactly 52 cards when it starts, and none of the cards are repeated (you could, of course, be using several decks to play, but that's a complication you can solve later). How do you populate a deck like that? Your program will want to "deal" from the deck -- so you'll need a way to keep track of which cards have been dealt to players.</p> <p>That's a lot of stuff. Try writing down all the logic of what your program needs to do in simple sentences, without worrying about Python. This is called "pseudo-code". It's not a real program, it's just a plan for what exactly you are going to do -- it's useful the way a map is useful. If you are going to a place you've been to a 100 times, you don't need a map, but if you are driving to some town you've never been to, you want to plan out your route first, before getting behind the wheel..</p> <p>Update your question with your pseudocode, and any attempts you have made (or will have made) to translate the pseudocode to Python.</p>
What are your recommended Windows Server 2003 Backup Tools? <p>What tools do you guys recommend for backing up files and SQL Server databases on Windows 2003?</p> <p>I'm looking for tools to run daily backups of both files and SQL Server databases. Compress them up and stick them on NAS drives.</p> <p>I'm looking for cheap / FREE options if possible.</p>
<p>Here at my company I do the following.</p> <p>At the end of the day I take a full back-up, using a SQL Server job. The syntax for this is well documented in BOL however here is an example:</p> <pre><code> BACKUP DATABASE [DATABASE] TO DISK = '[PATH]\[DATABASE].BAK' WITH INIT; </code></pre> <p>I then execute a .bat file that runs a compression process using a free Zip utility to make the files smaller before been shipped off.</p> <p>During the day I have 4 transaction log backup jobs that run every 10-12 minutes. Each backing up to a separate file. </p> <p>Then Every hour I run a differential back-up (this will back-up only the differences since the last back-up) I then destroy the transaction files and start again.</p> <p>Hope that gives you a little info on how it can be done in SQL Server without any 3rd party costly tools.</p>
Which group messaging technology to use? <p>I feel a little bit kind of confused — for about 24 hours I have been thinking which group broadcasting technology to use in my project.</p> <p>Basically, what I need is:</p> <ul> <li>create groups (by some backend process)</li> <li>broadcast messages by any client (1:N, N:N)</li> <li>(potentially) direct messages (1:1)</li> <li>(important) authenticate/authorize clients with my own backend (say, through some kind of HTTP API)</li> <li>to be able to kick specific clients by backend process (or server plugin) </li> </ul> <p>Here is what I will have: </p> <ol> <li>Backend-related process(es) in either Ruby or haXe</li> <li>Frontend in JS+haXe(Flash9) — in browser, so <em>ideally</em> communicating through 80/443, but not necessarily.</li> </ol> <p>So, this technology will have to be easily accessible in haXe for Flash and preferably Ruby.</p> <p>I've been thinking about: RabbitMQ (or OpenAMQ), RabbitMQ+STOMP, ejabberd, ejabberd+BOSH, juggernaut (with a need to write a haXe lib for it).</p> <p>Any ideas/suggestions?</p>
<p>Yurii,</p> <p>RabbitMQ, Haxe and as3: <a href="http://geekrelief.wordpress.com/2008/12/15/hxamqp-amqp-with-haxe/" rel="nofollow">http://geekrelief.wordpress.com/2008/12/15/hxamqp-amqp-with-haxe/</a></p> <p>RabbitMQ, Ruby and ACLs: <a href="http://pastie.org/pastes/368315" rel="nofollow">http://pastie.org/pastes/368315</a></p> <p>You might also want to look at using Nanite with RabbitMQ to manage backend groups: <a href="http://brainspl.at/articles/2008/10/11/merbcamp-keynote-and-introducing-nanite" rel="nofollow">http://brainspl.at/articles/2008/10/11/merbcamp-keynote-and-introducing-nanite</a> </p> <p>You say you need:</p> <pre><code>* broadcast messages by any client (1:N, N:N) * (potentially) direct messages (1:1) </code></pre> <p>You can easily do both using RabbitMQ. RabbitMQ supports both cases, 1:N pubsub and 1:1 messaging, with 'direct' exchanges. </p> <p>The direct exchange pattern is as follows: </p> <p>Any publisher (group member) sends a message to the broker with a 'routing key' such as "yurii". RabbitMQ matches this key with subscription bindings in the routing table (aka "exchange") for you. Each binding represents a subscription by a queue, expressing interest in messages with a given routing key. When the routing and binding keys match, the message is then routed to queues for subsequent consumption by clients (group members). This works for 1:N and 1:1 cases; with N:N building on 1:N.</p> <p>Introduction to the routing model: <a href="http://blogs.digitar.com/jjww/2009/01/rabbits-and-warrens/" rel="nofollow">http://blogs.digitar.com/jjww/2009/01/rabbits-and-warrens/</a></p> <p>General intro: <a href="http://google-ukdev.blogspot.com/2008/09/rabbitmq-tech-talk-at-google-london.html" rel="nofollow">http://google-ukdev.blogspot.com/2008/09/rabbitmq-tech-talk-at-google-london.html</a></p> <p>You also require:</p> <pre><code>* (important) authenticate/authorize clients with my own backend (say, through some kind of HTTP API) </code></pre> <p>Please see the ACLs code for this (link above). There is also a HTTP interface to RabbitMQ but we have not yet combined the HTTP front end with the ACL code. That shouldn't hold oyu back though. Please come to the rabbitmq-discuss list where this topic has been talked about recently.</p> <p>You also require:</p> <pre><code>* create groups (by some backend process) * to be able to kick specific clients by backend process (or server plugin) </code></pre> <p>I suggest looking at how tools like Nanite and Workling do this. Group creation is not usually part of a messaging system, instead, in RabbitMQ, you create routing patterns using subscriptions. You can kick specific clients by sending messages to them by whichever key they have used to bind their consuming queue to the exchange.</p> <p>Hope this helps!</p> <p>alexis</p>
Anybody written a tool for static analysis of an ASP.NET MVC application? <p>Has anyone written a tool to do static analysis of an ASP.NET MVC application?</p> <p>Disclaimer: I'm not sure what I want really is <a href="http://en.wikipedia.org/wiki/Static_code_analysis" rel="nofollow">static analysis</a> - it just was the closest term I could come up with.</p> <p>What I'd like is to get a tabulated list of all my controllers, my actions, show whether they respond to GET or POST, what their cache settings are etc.</p> <p>I'm sure you could keep going and goin with this - and go on to more advanced issues like whether or not every action is actually accessible by a route.</p> <p>If nobody has done this - is it something that people think would be useful ? What else ought it to do?</p>
<p>In order to test routes you can use <a href="http://www.codeplex.com/MVCContrib" rel="nofollow">MvcContrib</a>. It contains many various cool features and route debugging handler is one of them. And at the moment this is all what I saw. It will be rather hard to create a good tool to show all information that you described because architecture of asp.net mvc is very flexible and architecture of projects can be very different. But if you use NHibernate in your projects you should have a look at <a href="http://nhprof.com/" rel="nofollow">NHibernate Profiler</a>. </p>
ASP.NET page events - Button click event comes after GridView bind <p>My understanding of the order of page events is this:</p> <blockquote> <p>Page : Load</p> <p>Control : DataBind (for a GridView or whatever)</p> <p>Control : Load</p> <p>Control : Clicked (for a Button)</p> <p>Page: PreRender</p> <p>Control : PreRender</p> </blockquote> <p>(There are lots of others - but these are the ones I'm interested in)</p> <p>The important thing to notice here is that the button's click event comes <em>after</em> the gridview's bind event. If the button causes a change to the data, the GridView displays the old data. I could rebind the control in the PreRender event, but that seems totally ugly.</p> <p>This must be a very common pattern (a button that updates data). How do I put this together so that the GridView binds to the data <em>after</em> the Button click changes it?</p>
<p>The answer was in the Button Click event, after the data has been changed, call DataBind() on the page to cause the GridView (and anything else that needs it) to rebind. I didn't realise you could do that.</p> <p>Thank you Ocdecio &amp; Mufasa - I would mark your answers as helpful, but I got no rep yet.</p>
Android - How Do I Set A Preference In Code <p>I have an Android application in which I have my preferences in a xml file, which works fine. I've now want to set one of the preferences using code instead of displaying the entire preference screen, how would I go about doing this?</p>
<p>I assume by preferences you are referring to your application's preferences and not Android phone settings.</p> <p>To store preferences between runs of you application you need to do the following</p> <ol> <li><p>Create a SharedPreferences object</p> <pre><code>SharedPreferences settings = getSharedPreferences(String n, MODE_PRIVATE); </code></pre> <p><em>String n identifies your preferences and the second argument is the mode they'll be accessed</em></p></li> <li><p>Instantiate an Editor object</p> <pre><code>SharedPreferences.Editor editor = settings.edit(); </code></pre> <p><em>Note: do not try settings.editor.edit(), this will not make a persistent object and the code below will not work</em></p></li> <li><p>Write your preferences to the buffer</p> <pre><code>editor.put...(String, value) </code></pre> <p><em>There are numerous put function, putString, putBoolean, etc. The String is the key ("version", "good run") and the value is the value ("1.5.2", true)</em></p></li> <li><p>Flush the buffer</p> <pre><code>editor.commit(); </code></pre> <p><em>This actually writes you put to the preferences. If your app crashes before this line then the preferences will not be written. There is also a documented bug: commit() is supposed to return a boolean indicating success or failure. Last I checked it always returned false.</em></p></li> </ol> <p>These preferences will by stored on the phone and will only be accessible to your application.</p> <p>More documentation is <a href="http://developer.android.com/guide/topics/data/data-storage.html">here</a></p>
Using the context of the 'this' keyword with jQuery <p>As a jQuery neophyte I am somewhat confused by the different contexts in which the <strong><em>this</em></strong> keyword is used. Sometimes it refers to a DOM element e.g. <em>this.id</em> and sometimes it refers to a jQuery object e.g. <em>$(this).val()</em>.</p> <p><a href="http://remysharp.com/2007/04/12/jquerys-this-demystified/">Remy Sharp's blog post</a> is helpful but I would like to know how you would explain the difference to a novice. Is the difference strictly a jQuery issue or common to all Javascript?</p> <p>Thanks for all the responses so far - great stuff, I will pick an answer tomorrow. Here is another blog post I subsequently came across that was also helpful: <a href="http://www.learningjquery.com/2007/08/what-is-this">What is this? by Mike Alsup</a>.</p>
<p>Remy Sharp's post is confusing if you don't read it carefully, in my opinion. The meaning of <code>this</code> never changes. In the example you gave, there were 2 uses of <code>this</code>. As a DOM element in an event:</p> <pre><code>$('a').click(function() { alert(this.tagName); }); </code></pre> <p>and wrapped as a jQuery object in an event: </p> <pre><code>$('a').click(function() { alert($(this).val()); }); </code></pre> <p>If you read the 2 snippets above very carefully you'll notice that <code>this</code> never changes meaning. It always refers to the DOM element. The difference comes in how it is used.</p> <p>In jQuery, by default, <code>this</code> refers to the DOM element (not a jQuery object) which triggered an event. In the second code snippet above, it is <strong>still</strong> the same DOM element, only it is wrapped in a jQuery element by wrapping <code>$()</code> around it. As with any argument to the jQuery constructor, passing <code>this</code> into the constructor transforms it into a jQuery object.</p> <p>I think the confusion comes in when Remy starts talking about jQuery plugins in the same article as jQuery events. jQuery plugins are something that people rarely write and frequently use. When writing a jQuery plugin, you're working within the context of the jQuery object prototype. In this case, you're using the word <code>this</code> to refer to the plugin you're writing. In normal use-cases, you won't be writing plugins often so this is a much less common scenario. When not in the scope of the plugin, you can't use <code>this</code> to refer to the jQuery object.</p> <hr> <p>In the JavaScript language, the keyword <code>this</code> refers to the current instance of an object in JavaScript. When being used in a JavaScript prototype, it refers to the instance of the prototype. Depending on the browser, when using the non-jquery event model, <code>this</code> also refers to the DOM element. Because some browsers (Internet Explorer) don't refer to <code>this</code> as the DOM element in an event, it makes working with events difficult. To get around this, jQuery performs some JavaScript magic that <em>always</em> makes <code>this</code> refer to the DOM element which triggered the event. That is (one of the many) reasons to use a JavaScript framework instead of rolling your own. </p>
What obscure syntax ruined your day? <p>When have you run into syntax that might be dated, never used or just plain obfuscated that you couldn't understand for the life of you.</p> <p>For example, I never knew that comma is an actual operator in C. So when I saw the code</p> <pre><code>if(Foo(), Bar()) </code></pre> <p>I just about blew a gasket trying to figure out what was going on there. </p> <p>I'm curious what little never-dusted corners might exist in other languages.</p>
<p>C++'s syntax for a default constructor on a local variable. At first I wrote the following. </p> <pre><code>Student student(); // error Student student("foo"); // compiles </code></pre> <p>This lead me to about an hour of reading through a cryptic C++ error message. Eventually a non-C++ newbie dropped by, laughed and pointed out my mistake. </p> <pre><code>Student student; </code></pre>
How to implement drag and drop in Flex Grid control? <p>I have a simple Grid control with some buttons that I want to be able to move around. The code below does work, but it takes a lot of effort to actually do the drag&amp;drop and it is not clear where the drop will happen. I have to move the mouse around a lot to get to a state where the drop is not rejected. I would appreciate any suggestions on how to make this more "user friendly".</p> <pre> <code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" horizontalAlign="center" height="200" width="200"&gt; &lt;mx:Script&gt; &lt;![CDATA[ import mx.containers.GridItem; import mx.controls.Button; import mx.core.DragSource; import mx.events.*; import mx.managers.DragManager; private function dragInit(event:MouseEvent):void { if(event.buttonDown) { var button:Button = event.currentTarget as Button; var dragSource:DragSource = new DragSource(); dragSource.addData(button, 'button'); DragManager.doDrag(button, dragSource, event); } } private function dragEnter(event:DragEvent): void { var target:GridItem = event.currentTarget as GridItem; if (event.dragSource.hasFormat('button') && target.getChildren().length == 0) { DragManager.acceptDragDrop(target); DragManager.showFeedback(DragManager.MOVE); } } private function dragDrop(event:DragEvent): void { var target:GridItem = event.currentTarget as GridItem; var button:Button = event.dragSource.dataForFormat('button') as Button; target.addChild(button); } ]]&gt; &lt;/mx:Script&gt; &lt;mx:Grid&gt; &lt;mx:GridRow width="100%" height="100%"&gt; &lt;mx:GridItem width="44" height="44" dragEnter="dragEnter(event)" dragDrop="dragDrop(event)"&gt; &lt;/mx:GridItem&gt; &lt;mx:GridItem width="44" height="44" dragEnter="dragEnter(event)" dragDrop="dragDrop(event)"&gt; &lt;/mx:GridItem&gt; &lt;mx:GridItem width="44" height="44" dragEnter="dragEnter(event)" dragDrop="dragDrop(event)"&gt; &lt;mx:Button label="A" width="40" height="40" mouseMove="dragInit(event)"/&gt; &lt;/mx:GridItem&gt; &lt;/mx:GridRow&gt; &lt;mx:GridRow width="100%" height="100%"&gt; &lt;mx:GridItem width="44" height="44" dragEnter="dragEnter(event)" dragDrop="dragDrop(event)"&gt; &lt;/mx:GridItem&gt; &lt;mx:GridItem width="44" height="44" dragEnter="dragEnter(event)" dragDrop="dragDrop(event)"&gt; &lt;mx:Button label="B" width="40" height="40" mouseMove="dragInit(event)"/&gt; &lt;/mx:GridItem&gt; &lt;mx:GridItem width="44" height="44" dragEnter="dragEnter(event)" dragDrop="dragDrop(event)"&gt; &lt;/mx:GridItem&gt; &lt;/mx:GridRow&gt; &lt;mx:GridRow width="100%" height="100%"&gt; &lt;mx:GridItem width="44" height="44" dragEnter="dragEnter(event)" dragDrop="dragDrop(event)"&gt; &lt;mx:Button label="C" width="40" height="40" mouseMove="dragInit(event)"/&gt; &lt;/mx:GridItem&gt; &lt;mx:GridItem width="44" height="44" dragEnter="dragEnter(event)" dragDrop="dragDrop(event)"&gt; &lt;/mx:GridItem&gt; &lt;mx:GridItem width="44" height="44" dragEnter="dragEnter(event)" dragDrop="dragDrop(event)"&gt; &lt;/mx:GridItem&gt; &lt;/mx:GridRow&gt; &lt;/mx:Grid&gt; &lt;mx:Style&gt; GridItem { borderColor: #A09999; borderStyle: solid; borderThickness: 2; horizontal-align: center; vertical-align: center; } Grid { borderColor: #A09999; borderStyle: solid; borderThickness: 2; horizontalGap: 0; verticalGap: 0; horizontal-align: center; vertical-align: center; } &lt;/mx:Style&gt; &lt;/mx:Application&gt; </code> </pre>
<p>It looks like each empty grid item only exists on the border you've defined (I'm not sure why this is, possibly it's a known feature of containers). If you add a backgroundColor to each GridItem then dragEnter will be triggered over the whole area rather than just that border.</p>
ASP.Net MVC: "The given key was not present in the dictionary" <p>I have a set of websites built in MVC - each, essentially, is a clone of one original site). On one of the sites I'm getting the error from the title of this post ("The given key was not present in the dictionary") - it only occurs on a single page. The code is identical across all of the sites including the one which is acting up. Each of the sites is installed with the same setup (most of them are parallel to each other on a single server). I'm unable to replicate this in my Dev environment so have no idea how to debug (our sites are compiled via a Nant build process and are all set to Release mode - so no debug info available).</p> <p>When I look into the stack trace of the error I notice that at no point does our code get called - it's all ASP.Net page-lifecycle calls (specifically, the last significant function is a method called "__RenderSearchContent" in the compiled page. So far as I can tell from digging through the relevant controller action there are no instances where the code is using a Dictionary object.</p> <p>It seems to me that I'm missing something but I'm not sure where to look - the code doesn't seem to be the problem, there <em>shouldn't</em> be any environmental differences (though, it isn't impossible - the database, for example, is a different install but has an identical schema and isn't being used yet according to the stack trace). </p> <p>One area I have suspicion of is the routing which I know uses a dictionary - but surely, if this was the case, the other sites would suffer from the same problem?</p> <p>Are there any suggestions as to where I might look to find the cause of this problem?</p> <p>Any help will be much appreciated.</p> <p>Cheers</p>
<p>Ok, so the problem was not where I was expecting it to be. If I had a dollar for every time <em>that</em> happened...</p> <p>Basically, the problem was located in the view that was throwing the error. There was a data item which was present in the other websites but not this one. I guess this type of problem is where strongly-typed objects are ideal.</p>
In Java, Prevent a field from being changed after being returned by instance method <p>In a software development class at my university, the teacher kept mentioning that on a quiz we needed to make sure that a field returned by a getter needed to be "protected." I guess she meant that nothing outside the class should be able to change it. She didn't give much more of an explanation than that.</p> <p>For instance:</p> <pre><code>class Foo { string[] bar = &lt;some array contents&gt;; public string[] getBar() { return bar; } } </code></pre> <p>Any code calling getBar would be able to modify the elements in that array. How do you prevent that from happening? I'm assuming that the object itself should be able to modify the array, just not anything outside the object.</p> <p>This isn't homework help since the quiz is a couple of weeks old. I simply want to understand Java better since my teacher didn't explain very well.</p> <p>Update: The teacher wouldn't merely allow us to use protected as the access modifier on the field.</p>
<p>You either use a collection and wrap it in Collections.unmodifiable*() or you defensively copy your array, collection or object if its <strong>mutable</strong> (which arrays always are).</p> <p>For example:</p> <pre><code>class Foo { private String[] bar = &lt;some array contents&gt;; public String[] getBar() { return bar == null ? bar : Arrays.copyOf(bar); } } </code></pre> <p>What you have to watch out for is that this is a shallow copy (so is clone). Not sure what your teacher's problem with clone was.</p>
Sending and receiving data over USB port <p>I'd like to send/receive data over a USB port to a device (from my vista pc). Is there a free/cheap library out there that can do this, and how involved would this project be (not taking into account what's being sent or received) ?</p>
<p>You don't specify what's going on here. Does the device already exist? Is it already a USB device?</p> <p>If you already have a USB device, then the manufacturer should be able to help.</p> <p>If you are building the device, then you might want to look at something like a USB to serial adapter (which generally require no special drivers at all) or something from <a href="http://www.ftdichip.com/" rel="nofollow">FTDI</a> - they make a number of easy-to-use USB chips that generally don't need, or come with appropriate drivers under windows. I've worked with their chips on a couple of occasions and they've never given me any trouble.</p>
Git hook to send email notification on repo changes <p>How do I configure the appropriate Git hook to send a summary email whenever a set of changes is pushed to the upstream repository?</p>
<p>Another, more modern way to do this is with <a href="http://git.kernel.org/cgit/git/git.git/tree/contrib/hooks/multimail/README?id=HEAD" rel="nofollow">git-multimail</a>, as suggested by <a href="http://stackoverflow.com/questions/552360/git-push-email-notification/552362?noredirect=1#comment29250514_552362">Chords</a> below.</p> <hr> <p><em>This is how you did it in 2009.</em></p> <p>You could add something like <a href="http://source.winehq.org/git/tools.git/?a=blob;f=git-notify;hb=HEAD" rel="nofollow">this</a> to your post-receive hook in $GITDIR/hooks, or use the script in the contrib directory of the source <a href="http://git.kernel.org/?p=git/git.git;a=blob;f=contrib/hooks/post-receive-email;h=60cbab65d3f8230be3041a13fac2fd9f9b3018d5;hb=HEAD" rel="nofollow">(Available here)</a></p>
Could not load file or assembly error <p>Can anyone help me figure out what the problem is. I am trying to start up a C# winformsa app in visual studio and i keep getting this error:</p> <p><strong>Could not load file or assembly, Foo.dll version1.93343 or one of its dependencies The system can't find the file specified</strong></p> <p>vs 2005, C# 2.0</p> <p>any help</p>
<p>Typically it's about one of your references' reference, possibly deep down in the dependency tree. What I usually do is, fire up Sysinternals Process Monitor (<a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx">http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx</a>), filter by process name, and run the app. It's typically fairly easy at this point to sift through the FILE NOT FOUNDs and locate the offending missing reference.</p>
Need to generate a image in ASP.Net through webservice <p>For my new asp.net application that I am developing I would like to generate an image at runtime using a webservice (return bytes), and show this as a image using Javascript (so that I can have ajax functionality.</p> <p>Any ideas how to do this?</p> <p>Or any ideas as to how I can generate an image at runtime, and show it on my webpage using Ajax (must not postback), without having to save the image to any location on the hard drive?</p> <p>Thanks!</p>
<p>Instead of having the web service put an ASHX page with the querystring parameters handling the input params. Make sure the Response.Content type is image/png </p> <p>This ASHX page will generates the image stream on the fly and send it to the requesting image object. With this there is no image file saved on the server.</p> <p><a href="http://www.developerfusion.com/code/5223/using-ashx-files-to-retrieve-db-images/" rel="nofollow">Here is a links with full code for the ASHX .</a></p> <p>After you have done this, in JavaScript access the image object via DOM and set/change the SRC property.</p> <pre><code>function ChangeImage(param1, param2) { var url = "http://someserver/somepage.ashx?param1=" + param1 + "&amp;param2=" + param2; var image1 = document.getElementById("MyImage"); image1.src = url; } </code></pre>
Why are some programs written in C++ windows-only and others are not? <p>That's something I've been wondering for a while now.</p> <p>Take Notepad++ for instace. Wikipedia tells me it was written in C++ and it's Windows-only.</p> <p>Now take PHP. Wikipedia tells me this is also written in C++, but that runs on other OS too.</p> <p>But I see more languages then just C++ for PHP... how is this done? Do they make some new code in C++, see it works and then figure out how to do it in Perl, or what happens?</p>
<p>It depends whether you are using platform specific libraries or not. Notepad++ is a desktop application and it needs a GUI toolkit. Although there are cross-platform C++ libraries like Qt and wxWidgets, Notepad++ is probably using a Microsoft's specific technology. Thus it can't be ported in other platforms.</p> <p>PHP on the other side is a WEB scripting technology so there's no need of GUI library. Also there is much more stronger interest in running PHP in many platforms than there is for Notepad++. That is an incentive for the developers to make the C++ code cross platform.</p> <p>Avoid platform specific libraries isn't the only thing needed for a C++ cross platform application. It usually means coding for the least common denominator and keeping different code branches for every platform supported. Although C++ is a cross platform language, each system has its own intricacies. In fact the code could be different in the same platform as well, if a different compiler was to be used. Try downloading the C++ source of an open source application, like PHP for example. You would notice that much of the code is the same for all platforms, but there would be different bits also. Sometimes preprocessor directives are used, elsewhere totally different source files are involved.</p> <p>So creating a true cross-platform C++ application is a hard job and it is usually created when there is a strong incentive to do so and many people are involved. An one-man application like Notepad++ really can't be cross-platform.</p>
winforms application guidelines <p>I want to start creating an application that has a menu on the left(some items in a tree) and I want to open different pages on the right on the form when I click these items. Could anybody guide me in doing this correctly pls? I dont want to have tons of data in memory and just display these pages one in top of another.</p> <p>Thanks</p>
<p>One approach is to have treeview <a href="https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6165908.html" rel="nofollow">docked</a> on the left and a panel docked to fill. Then, on the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.treeview.selectednodechanged.aspx" rel="nofollow">SelectedNodeChanged</a> event of the tree, you can load forms into the panel. Just be sure to clear out the old form every time you change nodes.</p> <p>By pages, do you mean web pages? If so, take a look at the <a href="http://frazzleddad.blogspot.com/2007/07/working-with-webbrowser-control-in.html" rel="nofollow">WebBrowser</a> control.</p>
How best to work with the Expires header in ASP.NET MVC? <p>I want to be able to set a long expires time for certain items that a user downloads via GET request.</p> <p>I want to say 'this is good for 10 minutes' (i.e. I want to set an Expires header for +10 minutes). The requests are fragments of HTML that are being displayed in the page via AJAX and they're good for the user's session. <strong>I don't want to go back to the server and get a 304</strong> if they need them again - I want the browser cache to instantly give me the same item.</p> <p>I found an article which is almost a year old about <a href="http://weblogs.asp.net/rashid/archive/2008/03/28/asp-net-mvc-action-filter-caching-and-compression.aspx">MVC Action filter caching and compression</a>. This creates a custom ActionFilter to change the expires header. I'm already using the compression filter which works great for some custom css I am generating (94% compression rate!).</p> <p>I have two main concerns :</p> <p>1) Do I really have to use this method. I'm fine with it if I do, but is there really no functionality in MVC or the OutputCache functionality to do this for me? In 'traditional' ASP.NET I've always just set the Expires header manually, but we cant do that anymore - at least not in the controller.</p> <p>2) If I do use this filter method - is it going to interfere with the OutputCache policy at all - which I want to be able to control in web.config. I'm kind of thinking the two are mutually exclusive and you wouldn't want both - but I'm not completely sure.</p>
<ol> <li><p>No, you don't <em>have</em> to use this method. However, I think it is probably the best method to choose, because it makes the controller more testable and less web-aware. The alternative would be to set the header manually in the Controller, like this:</p> <p>Response.AddHeader("Expires", "Thu, 01 Dec 1994 16:00:00 GMT"); </p></li> <li><p>Well, the OutputCache attribute controls when the action runs at all, and when it returns cached HTML instead. Expires tells the browser when to re-fetch the HTML. So I wouldn't call them mutually exclusive, but they are certainly two sides of the same coin, and you're right to think that you <em>may</em> not need both. I would suggest reviewing <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html" rel="nofollow">the HTTP spec</a> to decide what is most appropriate for your application.</p></li> </ol>
How to gain control over the construction of a WebService <p>I'd like to gain control over the construction of a WebService instance in ASP.NET.</p> <p>This is what I did so far: I created a .ASMX file and pointed it to a Class with WebServiceBinding and WebMethod attributes attached to it as usual. At the time I browse to the .ASMX file ASP.NET will automatically create an instance of the Class for me. </p> <p>Is it somehow possible to hijack into the object factory of ASP.NET and do the instance creation by my self?</p>
<p>You could write a custom handler (.ashx) and do it manually that way.</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms227675(VS.85).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms227675(VS.85).aspx</a></p>
Pushing a server by Git? <p>I have tried the following command unsuccessfully:</p> <pre><code>git push 12.12.12.123:/proj.git master </code></pre> <p>It asks my password, but each time it rejects it.</p> <p>I used the following commands to set up Git:</p> <pre><code>git --bare update-server-info chmod a+x hooks/post-update </code></pre> <p>The last command gives me this error:</p> <pre><code>chmod: Cannot access 'hooks/post-update':No such file or directory </code></pre> <p>I am reading <a href="http://www-cs-students.stanford.edu/~blynn/gitmagic/ch06.html#_git_over_ssh_http" rel="nofollow">the tutorial</a>.</p> <p><strong>[Edit]</strong></p> <p>I get the following error message after trying to push:</p> <pre><code>bash: git-receive-pack: command not found fatal: The remote end hung up unexpectedly </code></pre>
<p>you need to do git init in your repo</p> <p><a href="http://www.kernel.org/pub/software/scm/git/docs/git-init.html" rel="nofollow">http://www.kernel.org/pub/software/scm/git/docs/git-init.html</a></p> <p>Here is nice and quick tuturial: <a href="http://toolmantim.com/articles/setting_up_a_new_remote_git_repository" rel="nofollow">http://toolmantim.com/articles/setting_up_a_new_remote_git_repository</a></p> <p>This is a bit longer once </p> <p>In short to set up git:</p> <pre><code>$ ssh myserver.com Welcome to myserver.com! $ mkdir /var/git/myapp.git &amp;&amp; cd /var/git/myapp.git $ git --bare init Initialized empty Git repository in /var/git/myapp.git $ exit Bye! </code></pre> <p>and you need ssh://12.12.12.123:/proj.git master</p>
What do you think about the new Debian release cycle? <p>I was surprised to know that Lenny already promoted to "stable" - among some of my clients there is some fear that Debian would want to compete with Ubuntu for the desktop and forget its server devotion.</p> <p>"Only" 2 years between 4.0 Etch and 5.0 Lenny is unprecedented in Debian time scale. Version inflation? is it because SPARC-32 support is being dropped? otherwise the changes between 4.0 Etch and Lenny don't seem bigger than say 3.0 Woody to 3.1 Sarge (3 years apart).</p> <p>Support was longest for Woody (4 full years), then it was dropped to just under 3 years for both 3.1 and 4.0 (still pretty good, I reckon).</p> <p>It's still undecided for Lenny but I'd like to know about this before making my next server distro decision.</p> <p>What are your thoughts about this?</p> <p>Reference: - <a href="http://en.wikipedia.org/wiki/Debian#Releases" rel="nofollow">http://en.wikipedia.org/wiki/Debian#Releases</a> - <a href="http://en.wikipedia.org/wiki/File:Debian_releases.svg" rel="nofollow">http://en.wikipedia.org/wiki/File:Debian_releases.svg</a></p>
<p>Where's the problem? Etch will be supported for one year from now, and upgrading it to Lenny is a matter of typing a few commands.</p> <p>Debian seems still to be the most serious server distro. <a href="http://www.ubuntu.com/community/ubuntustory/debian" rel="nofollow">It's the rock that Ubuntu is built on</a>.</p>
Can a perceptron be used to detect hand-written digits? <p>Let's say I have a small bitmap which contains a single digit (0..9) in hand writing.</p> <p>Is it possible to detect the digit using a (two-layered) perceptron?</p> <p>Are there other possibilities to detect single digits from bitmaps besides using neural nets?</p>
<p>Here is a link to a huge database of handwritten digits. The front page also has relative performance data for many different methods including 2 layer Neural networks. This ought to give you a good start: <a href="http://yann.lecun.com/exdb/mnist/" rel="nofollow">MNIST digits database and performance</a></p> <p>You might also want to check out <a href="http://www.cs.toronto.edu/~hinton/MatlabForSciencePaper.html" rel="nofollow">Geoff Hinton's work on Restricted Boltzmann Machines</a> which he says performs fairly well, and there is a good explanatory lecture on his site (very watchable).</p>
Flex DateChooser: how to override the 'today' date? <p>By default, the Flex DateChooser highlights the 'today' date. I assume it gets this date from the OS. Is there a way to tell DateChooser what the 'today' date should be? </p>
<p>By looking at the source code of <code>mx.controls.CalendarLayout</code> (which is used internally by <code>DateChooser</code>):</p> <pre><code>// Determine whether this month contains today. var today:Date = new Date(); var currentMonthContainsToday:Boolean = (today.getFullYear() == newYear &amp;&amp; today.getMonth() == newMonth); </code></pre> <p>it seems that you have no influence on this. You could, of couse, extend/replace the <code>DateChooser</code> and <code>CalendarLayout</code> classes, and override the relevant functions.</p>
Disable IE script debugging via IE control <p>Bleh; Knowing how to ask the question is always the hardest so I explain a little more.</p> <p>I'm using CAxWindow to create an IE window internally and passing in the URL via the string class argument:</p> <pre><code>CAxWindow wnd; m_hwndWebBrowser = wnd.Create(m_hWnd, rect, m_URI, WS_CHILD|WS_DISABLED, 0); </code></pre> <p>It's part of an automated utility for anyone to get images from their "internal" javascript-based apps; the issue is that some people try getting images from their apps that have lots of errors; The errors fire off the IE debug window and my capture utility sits waiting for input.</p> <p>Initially I thought I could disable the debugging ability via IE in windows however the process that Apache runs in and hence my App is via the SYSTEM account; not sure how I'd change the debugging options without hacking the registry.</p>
<p>Would it be possible to just wrap everything in a try / catch in the javascript code that is being displayed in the CAxWindow at that URL? That would allow you to squelch all the errors, hopefully.</p>
How do I build an object that stores pictures? <p>If you were building an object to store a photo (for a program like photoshop) how would you design it? What properties would you take into account?</p>
<p>One of the major things I would consider is whether the photo actually needs to be stored in the object, or whether you just need a link to a file, URL or database. Photos tend to use a lot of memory, so keeping it out of memory until you actually need to display it is probably good design.</p> <p>Apart from that, I'd consider some sort of arbitrary tagging mechanism, and look at the tagging mechanisms that already exist in JPEG.</p> <p>You might want to look at <a href="http://en.wikipedia.org/wiki/Exchangeable_image_file_format" rel="nofollow">EXIF</a>, one of the tagging standards to get some ideas for properties. However, new ones are invented al the time, so rather than having a property for each possibility, a more general Map based structure might be better for your object.</p>
Is there any way to send a mail from within my iPhone application? <p>I want to send an email from within my iPhone application, primarily because i don't want to quit my application. Is there ANY way to do that? </p> <p>Solution:</p> <p>1) I found this open source API which does that: <a href="http://code.google.com/p/skpsmtpmessage/" rel="nofollow">http://code.google.com/p/skpsmtpmessage/</a></p> <p>Anyone can write their own smtp client for this purpose. (If you can invest that much time - that is)</p> <p>2) Use a web service to send the message details and handle message sending functionality at server end.</p> <p>Thanks.</p>
<ul> <li>Install <a href="http://subversion.tigris.org/getting.html#osx" rel="nofollow">subversion</a> on your Mac, as well as the command line tools, there are a variety of GUI wrappers available with a a little Googling.</li> <li>If you click the "source" tab on <a href="http://code.google.com/p/skpsmtpmessage/" rel="nofollow">that project</a> you'll see instructions for obtaining the source with subversion</li> </ul>
Updating WPF list when item changes <p>I have a WPF ListBox, and I've added some 'FooBar' objects as items (by code). FooBars aren't WPF objects, just dumb class with an overwritten ToString() function.</p> <p>Now, when I change a property which influences the ToString, I'd like to get the ListBox to update.</p> <ol> <li>How can I do this 'quick and dirty' (like repaint).</li> <li>Is dependency properties the way to go on this?</li> <li>Is it worth it/always advisable, to create a wpf wrapper class for my FooBars?</li> </ol> <p>Thanks...</p>
<p>Your type should implement <code>INotifyPropertyChanged</code> so that a collection can detect the changes. As Sam says, pass <code>string.Empty</code> as the argument.</p> <p>You <em>also</em> need to have the <code>ListBox</code>'s data source be a collection that provides change notification. This is done via the <code>INotifyCollectionChanged</code> interface (or the not-so-WPF <code>IBindingList</code> interface).</p> <p>Of course, you need the <code>INotifyCollectionChanged</code> interface to fire whenever one of the member <code>INotifyPropertyChanged</code> items fires its event. Thankfully there are a few types in the framework that provide this logic for you. Probably the most suitable one is <code>ObservableCollection&lt;T&gt;</code>. If you bind your <code>ListBox</code> to an <code>ObservableCollection&lt;FooBar&gt;</code> then the event chaining will happen automatically.</p> <p>On a related note, you don't have to use a <code>ToString</code> method just to get WPF to render the object in the way that you want. You can use a <code>DataTemplate</code> like this:</p> <pre><code>&lt;ListBox x:Name="listBox1"&gt; &lt;ListBox.Resources&gt; &lt;DataTemplate DataType="{x:Type local:FooBar}"&gt; &lt;TextBlock Text="{Binding Path=Property}"/&gt; &lt;/DataTemplate&gt; &lt;/ListBox.Resources&gt; &lt;/ListBox&gt; </code></pre> <p>In this way you can control the presentation of the object where it belongs -- in the XAML.</p> <p><strong>EDIT 1</strong> I noticed your comment that you're using the <code>ListBox.Items</code> collection as your collection. This won't do the binding required. You're better off doing something like:</p> <pre><code>var collection = new ObservableCollection&lt;FooBar&gt;(); collection.Add(fooBar1); _listBox.ItemsSource = collection; </code></pre> <p>I haven't checked that code for compilation accuracy, but you get the gist.</p> <p><strong>EDIT 2</strong> Using the <code>DataTemplate</code> I gave above (I edited it to fit your code) fixes the problem.</p> <p>It seems strange that firing <code>PropertyChanged</code> doesn't cause the list item to update, but then using the <code>ToString</code> method isn't the way that WPF was intended to work.</p> <p>Using this DataTemplate, the UI binds correctly to the exact property.</p> <p>I asked a question on here a while back about doing <a href="http://stackoverflow.com/questions/447035/what-is-the-wpf-xaml-data-binding-equivalent-of-string-format">string formatting in a WPF binding</a>. You might find it helpful.</p> <p><strong>EDIT 3</strong> I'm baffled as to why this is still not working for you. Here's the complete source code for the window I'm using.</p> <p>Code behind:</p> <pre><code>using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows; namespace StackOverflow.ListBoxBindingExample { public partial class Window1 { private readonly FooBar _fooBar; public Window1() { InitializeComponent(); _fooBar = new FooBar("Original value"); listBox1.ItemsSource = new ObservableCollection&lt;FooBar&gt; { _fooBar }; } private void button1_Click(object sender, RoutedEventArgs e) { _fooBar.Property = "Changed value"; } } public sealed class FooBar : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string m_Property; public FooBar(string initval) { m_Property = initval; } public string Property { get { return m_Property; } set { m_Property = value; OnPropertyChanged("Property"); } } private void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } } } </code></pre> <p>XAML:</p> <pre><code>&lt;Window x:Class="StackOverflow.ListBoxBindingExample.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:StackOverflow.ListBoxBindingExample" Title="Window1" Height="300" Width="300"&gt; &lt;DockPanel LastChildFill="True"&gt; &lt;Button Click="button1_Click" DockPanel.Dock="Top"&gt;Click Me!&lt;/Button&gt; &lt;ListBox x:Name="listBox1"&gt; &lt;ListBox.Resources&gt; &lt;DataTemplate DataType="{x:Type local:FooBar}"&gt; &lt;TextBlock Text="{Binding Path=Property}"/&gt; &lt;/DataTemplate&gt; &lt;/ListBox.Resources&gt; &lt;/ListBox&gt; &lt;/DockPanel&gt; &lt;/Window&gt; </code></pre>
Directly query TFS Warehouse using T-sql <p>Hi I'm wondering if anybody has had any experience querying a Team Foundation Server store to retrieve current work item information. It is my understanding that the information I require is stored in the TFSWarehouse Database.</p> <p>I'm well aware that there are APIs that provide this functionality and I've used them myself. However these come with the requirement to install Team Explorer on any client PC that will reference the API.</p> <p>All I want is a list of Work Items with some selected fields such as Title, State and Created By.</p> <p>Has anybody attempted this themselves, and indeed does anybody know of any pitfalls with this approach?</p> <p>---------- EDIT 16/02</p> <p>Just to add after speaking with TreeUK. What would be great is if anybody perhaps has an example query, or maybe some explanation as to the table structure?</p>
<p>If you have access to the SQL database that hosts TFS, you can write a query that pulls this information out.</p> <p>The database you want to look at is TFSWarehouse. Below is a query that gets Work Item general information.</p> <pre><code>select System_Id as WorkItemId, System_Title as Title, System_State as Status, System_Reason as Reason, System_WorkItemType as Type from [Work Item] </code></pre> <p>It's kind of clear what they all do, check that table to get any other properties of interest.</p> <p>If there's anything else you need, let me know. Otherwise, please mark this as answer :)</p>
event is not defined in mozilla firefox for javascript function? <pre><code>function onlyNumeric() { if (event.keyCode &lt; 48 || event.keyCode &gt; 57) { event.returnValue = false; } } onkeypress=onlyNumneric(); </code></pre> <p>In IE, this code is working fine. However, in Mozilla Firefox, the event is an undefined error.</p>
<p>In FF/Mozilla the event is passed to your event handler as a parameter. Use something like the following to get around the missing event argument in IE.</p> <pre><code> function onlyNumeric(e) { if (!e) { e = window.event; } ... } </code></pre> <p>You'll find that there are some other differences between the two as well. This <a href="http://www.javascriptkit.com/javatutors/javascriptkey2.shtml">link</a> has some information on how to detect which key is pressed in a cross-browser way.</p>
Delphi: How to calculate the SHA hash of a large file <p>Hi I need to generate a SHA over a 5 Gig file</p> <p>Do you know of a non string based Delphi library that can do this ?</p>
<p>You should use <a href="http://www.cityinthesky.co.uk/cryptography.html">DCPcrypt v2</a> and read your file buffered and feed the SHA hasher with the buffer until you've read the complete 5GB file.</p> <p>If you want to know how to read a large file buffered, see my answer <a href="http://stackoverflow.com/questions/438260/delphi-fast-file-copy/438323#438323">about a file copy using custom buffering</a>.</p> <p>so in concept (no real delphi code!):</p> <pre><code>function GetShaHash(const AFilename: String) begin sha := TSHAHasher.Create; SetLength(Result, sha.Size); file := OpenFile(AFilename, GENERIC_READ); while not eof file do begin BytesRead := ReadFile(file, buffer[0], 0, 1024 * 1024); sha.Update(buffer[0], BytesRead); end; sha.Final(Result[0]); CloseFile(file); end; </code></pre>
How do I use Windsor to inject dependencies into ActionFilterAttributes <p>Having seen how <a href="http://codeclimber.net.nz/archive/2009/02/10/how-to-use-ninject-to-inject-dependencies-into-asp.net-mvc.aspx">NInject can do it</a> and <a href="http://www.jeremyskinner.co.uk/2008/11/08/dependency-injection-with-aspnet-mvc-action-filters/">AutoFac can do it</a> I'm trying to figure out how to inject dependencies into MVC ActionFilters using Castle Windsor</p> <p>At the moment I'm using an ugly static IoC helper class to resolve dependencies from the constructor code like this:</p> <pre><code>public class MyFilterAttribute : ActionFilterAttribute { private readonly IUserRepository _userRepository; public MyFilterAttribute() : this(IoC.Resolve&lt;IUserRepository&gt;()) { } public MyFilterAttribute(IUserRepository userRepository) { _userRepository = userRepository; } } </code></pre> <p>I'd love to remove that static antipattern IoC thing from my filters.</p> <p>Any hints to as how I would go about doing that with Castle Windsor?</p> <p>And no, changing DI framework is not an option.</p>
<p>When I needed this, I built upon the work others have done with Ninject and Windsor to get <a href="http://weblogs.asp.net/psteele/archive/2009/11/04/using-windsor-to-inject-dependencies-into-asp-net-mvc-actionfilters.aspx">property injection dependencies on my ActionFilters</a>.</p>
Most efficient collection for this kind of LILO? <p>I am programming a list of recent network messages communicated to/from a client. Basically I just want a list that stores up to X number of my message objects. Once the list reaches the desired size, the oldest (first) item in the list should be removed. The collection needs to maintain its order, and all I will need to do is </p> <ol> <li>iterate through it,</li> <li>add an item to the end, and </li> <li>remove an item from the beginning, if #2 makes it too long.</li> </ol> <p>What is the most efficient structure/array/collection/method for doing this? Thanks!</p>
<p>You want to use a <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Queue.html" rel="nofollow">Queue</a>.</p>
Mutual exclusion: is this safe? <p>Is this pattern for mutual exclusion as safe as I think it is? If so, what do you call it?</p> <pre><code>lock (_lock) { if (_flag) return; else _flag = true; } try { //critical code... } finally { _flag = false; } </code></pre> <p>I want to ensure the critical section, but without the other threads piling up waiting to acquire the lock. Obviously I make sure the flag is set nowhere else. Is there a better way?</p>
<p>No, that is not safe. If you want to ensure mutually exclusive without blocking, you can use Monitor.TryEnter:</p> <pre><code>if (Monitor.TryEnter(lockObj, 0)) { // got the lock ! try { // code } finally { // release the lock Monitor.Exit(lockObj); } } </code></pre>
How to create duplicate allowed attributes <p>I'm using a custom attribute inherited from an attribute class. I'm using it like this:</p> <pre><code> [MyCustomAttribute("CONTROL")] [MyCustomAttribute("ALT")] [MyCustomAttribute("SHIFT")] [MyCustomAttribute("D")] public void setColor() { } </code></pre> <p>But the "Duplicate 'MyCustomAttribute' attribute" error is shown.<br> How can I create a duplicate allowed attribute?</p>
<p>Stick a <code>AttributeUsage</code> attribute onto your Attribute class (yep, that's mouthful) and set <code>AllowMultiple</code> to <code>true</code>:</p> <pre><code>[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public sealed class MyCustomAttribute: Attribute </code></pre>
How can I securely destroy some data using sql server 2008 ? (using DoD secure wipe or an equivalent) <p>One of my clients wants me to perform a periodic "real" destruction of some of his old data, and I'm evaluating the best way to do it.</p> <p>The data is in a table, and I want to destroy some of the rows contained in it.</p> <p>I could do it manually by deleting/exporting the database on another computer/degaussing the hard drive/reimporting the saved data, but I need an automatic solution.</p> <p><strong>Is there an equivalent to the delete (as in delete * from foo) command which would perform a secure destruction of the data (using DoD secure wipe, or something like that?)</strong></p> <p>Do you see other ways to perform this automatic deletion?</p> <p>Btw, I know the odds of someone retrieving some of the data I've destroyed using the sql delete command are very small, but some of my clients require it. So please don't turn this question into a global debate on the topic of data disposal procedures !</p> <p><strong>Edit</strong> : the problem I want to address is not "How should I destroy the data so it cannot be recovered" but rather "How can I convince my clients that their data cannot be recovered".</p>
<p>Use some form of encryption to store the data fields in the table.</p> <p>When you decide to "delete", re-encrypt the data you will continue to use with a new key. Discard the old key, and delete the rows encrypted with the old key. Shrink.</p> <p>Even if someone recovers the rows, w/o the old key no one will be able to restore the data. Just make sure the old key is really discarded - you can have it on a single usb stick only, and destroy the stick, etc.</p>
Read Jena OntModel with Dependencies <p>I'm new to the concept of ontology and Jena, so I'm not sure I'm phrasing this correctly..</p> <p>I need to read a series of connected owl files (by namespace dependencies?) into an in memory Jena model (OntModel?) so inference can be run. How do I do this? Does the order of the files matter? Do I need to call a specific method to "run the inference engine"?</p>
<p>This is what I did. It seems to work</p> <pre><code> OntModel model = ModelFactory.createOntologyModel(); for (OwlFile referencedOntology: referencedOntologyList) { model.getDocumentManager().addAltEntry( referencedOntology.getNamespace(), referencedOntology.getURI()); } model.read(ontology.getURI()); </code></pre> <p>The <code>OwlFile</code> object contains the URI to the ontology file as well as its namespace.</p> <p><code>referencedOntologyList</code> contains a list of referenced <code>OwlFile</code>s</p> <p><code>ontology</code> is the <code>OwlFile</code> containing the main ontology.</p>
intercepting keypresses even when the form does not have focus <p>I've built a winforms application which checks for CTR+ALT+S and CTRL+ALT+E keypresses, using by overriding the ProcessCmdKey method. This works great, but if the screensaver goes on and then goes off the form doesn't have focus and the keypresses aren't intercepted. How can I receive these even if the form does not have focus?</p>
<p>Alexander Werner has a "<a href="http://www.codeproject.com/KB/miscctrl/systemhotkey.aspx" rel="nofollow">System Hotkey Component</a>" project over at Code Project that wraps the RegisterHotkey() API into a user control that's really easy to implement.</p>
Debugging the Interwoven Worksite Web Services <p><strong><em>EDIT:</strong> Web Services being called from a windows console application at present, using VB.Net and Visual Studio 2008</em></p> <p>We are using the Interwoven Worksite Web Services and are having issues debugging them. The web service is returning the following error:</p> <blockquote> <p><em>"Unable to access the object. It may have been deleted or you may not have security access."</em></p> </blockquote> <p>However there is no more detail than this coming through from the service. I have read the official Interwoven documentation and found it to be remarkably unhelpful.</p> <p>Does anyone have any real world experience with the Worksite web services (they specifically come with the Worksite Web product, not to be confused with their COM API, which we have used within web services).</p> <p>I did a search on worksite and interwoven and didn't find anything on here so I'm not sure anyone out there will be able to help.</p>
<p>Yes - have used it and have had same issue. usually with that error you are not providing the full and/or correct moniker info, e.g. wrong dms name, wrong object id. I used fiddler to view the info being passed to/fro on the base worksite web product to see how they format those same IDs which helped alot. I hope this helps.</p>
MySql moving differences? <p>Suppose I have this code</p> <pre><code>create temporary table somedata (a integer); insert into somedata (a) values (11), (25), (62); --#these values are always increasing select * from somedata; </code></pre> <p>giving this</p> <pre><code>+--+ |a | +--+ |11| |25| |62| +--+ </code></pre> <p>How do I calculate a column of values 'b' where each one is the difference between the value of 'a' in the current row and the value of 'a' in the preceding row?</p> <pre><code>+--+--+ |a |b | +--+--+ |11| 0| # ie 11-11 since theres no preceding row |25|14| # ie 25-11 |62|37| # ie 62-25 etc +--+--+ </code></pre> <p>This is so obvious in openoffice or excel that I feel a bit silly not having yet found how to do this on MySql's site nor anywhere else.</p>
<p>It would easier if you had an auto_increment column to give each row its own id - then you could join the table against itself on (alias2.id=alias1.id+1) and calculate the diff from alias2.a-alias1.a</p> <p>As it is, I think the only way is with a subquery to obtain the largest value a less than the current row value, which will be very inefficient.</p> <p>So if you can, modify your schema!</p> <pre><code>create table somedata ( id int auto_increment not null, a integer, primary key(id) ); insert into somedata (a) values (11), (25), (62); select a2.a,ifnull(a2.a-a1.a, 0) as diff from somedata as a1 right join somedata as a2 on (a2.id=a1.id+1); +------+------+ | a | diff | +------+------+ | 11 | 0 | | 25 | 14 | | 62 | 37 | +------+------+ </code></pre> <p>Use inner join rather a right join if you don't want that first zero result.</p> <p><em>Edit: see this article for a fuller walkthrough of this idea: <a href="http://www.onlamp.com/pub/a/onlamp/excerpt/mysqlckbk/index3.html?page=2" rel="nofollow">Calculating differences between successive rows</a></em></p>
How do I declare a method using Func<T, TResult> as input argument? <p>Hy,</p> <p>I'm writing a class which should help me in unit tests. The class offers methods to perform Assertions on Exceptions. </p> <p>Until now I was able to write methods which take a function with no parameters and no return value as input. To do this I use the System.Action - delegates. My class looks like this:</p> <pre><code>internal static class ExceptionAssert { /// &lt;summary&gt; /// Checks to make sure that the input delegate throws a exception of type TException. /// &lt;para&gt; /// The input delegate must be a method with no parameters and return type void! /// &lt;/para&gt; /// &lt;/summary&gt; /// &lt;typeparam name="TException"&gt;The type of exception expected.&lt;/typeparam&gt; /// &lt;param name="methodToExecute"&gt;The method to execute.&lt;/param&gt; public static void Throws&lt;TException&gt;(Action methodToExecute) where TException : System.Exception { try { methodToExecute(); } catch (Exception e) { Assert.IsTrue(e.GetType() == typeof(TException), "Expected exception of type " + typeof(TException) + " but type of " + e.GetType() + " was thrown instead."); return; } Assert.Fail("Expected exception of type " + typeof(TException) + " but no exception was thrown."); } </code></pre> <p>In the unit test I can write now:</p> <pre><code>ExceptionAssert.Throws&lt;ArgumentNullException&gt;(theProxy.LoadProduct,productNumber); </code></pre> <p>Now I want to write more methods, which take methods as input with arguments and return values. As I understand the generic Func should serve this. And the method signature should be like this:</p> <pre><code>public static void Throws&lt;TException&gt;(Func&lt;T, TResult&gt; methodToExecute, T methodArgument) where TException : System.Exception </code></pre> <p>But this will not compile. I always have to write an explicit type like Func and not the generic. What's wrong? It should be possible to declare it the generic way, because LINQ works like this.</p> <p>EDIT:</p> <p>It is a good idea to declare everything, not just the half. The result of it:</p> <pre><code>/// &lt;summary&gt; /// Contains assertion types for exceptions that are not provided with the standard MSTest assertions. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;The type of the input arguments.&lt;/typeparam&gt; /// &lt;typeparam name="TResult"&gt;The type of the result.&lt;/typeparam&gt; /// &lt;remarks&gt; /// The standard test framework has an Attribute called &lt;see cref="ExpectedExceptionAttribute"&gt;ExpectedExceptionAttribute&lt;/see&gt;. This attribute has two /// main disadvantages: /// &lt;para&gt; /// 1. The unit test stops at the line which throws the expected exception. If you want to test a method which throws a bunch of exceptions /// you must write a test for each exception. /// 2. The attribute does not specify exactly where the exception has to be thrown. So if a method call earlier than expected throws /// suddenly the same exception, the whole test is still o.k. /// &lt;/para&gt; /// So this class can be used like the common assertions. You can test a method at a specific line in the test for a specific exception. /// &lt;/remarks&gt; internal static class ExceptionAssert&lt;T,TResult&gt; { /// &lt;summary&gt; /// Checks to make sure that the input delegate throws a exception of type TException. /// &lt;para&gt; /// The input delegate must be a method with no parameters and return type void! /// &lt;/para&gt; /// &lt;/summary&gt; /// &lt;typeparam name="TException"&gt;The type of exception expected.&lt;/typeparam&gt; /// &lt;param name="methodToExecute"&gt;The method to execute.&lt;/param&gt; public static void Throws&lt;TException&gt;(Action methodToExecute) where TException : System.Exception { try { methodToExecute(); } catch (Exception e) { Assert.IsTrue(e.GetType() == typeof(TException), "Expected exception of type " + typeof(TException) + " but type of " + e.GetType() + " was thrown instead."); return; } Assert.Fail("Expected exception of type " + typeof(TException) + " but no exception was thrown."); } /// &lt;summary&gt; /// Checks to make sure that the input delegate throws a exception of type TException with a specific exception message. /// &lt;para&gt; /// The input delegate must be a method with no parameters and return type void! /// &lt;/para&gt; /// &lt;/summary&gt; /// &lt;typeparam name="TException"&gt;The type of exception expected.&lt;/typeparam&gt; /// &lt;param name="expectedMessage"&gt;The expected exception message.&lt;/param&gt; /// &lt;param name="methodToExecute"&gt;The method to execute.&lt;/param&gt; /// &lt;remarks&gt; /// This method asserts if the given message and the message of the thrown exception are not equal! /// &lt;/remarks&gt; public static void Throws&lt;TException&gt;(string expectedMessage, Action methodToExecute) where TException : System.Exception { try { methodToExecute(); } catch (Exception e) { Assert.IsTrue(e.GetType() == typeof(TException), "Expected exception of type " + typeof(TException) + " but type of " + e.GetType() + " was thrown instead."); Assert.AreEqual(expectedMessage, e.Message, "Expected exception with a message of '" + expectedMessage + "' but exception with message of '" + e.Message + "' was thrown instead."); return; } Assert.Fail("Expected exception of type " + typeof(TException) + " but no exception was thrown."); } /// &lt;summary&gt; /// Checks to make sure that the input delegate throws a exception of type TException with a specific exception message. /// &lt;para&gt; /// The input delegate must be a method with ONE parameter and return type! /// &lt;/para&gt; /// &lt;/summary&gt; /// &lt;typeparam name="TException"&gt;The type of the exception.&lt;/typeparam&gt; /// &lt;param name="methodToExecute"&gt;The method to execute.&lt;/param&gt; /// &lt;param name="argument"&gt;The argument to input.&lt;/param&gt; public static void Throws&lt;TException&gt;(Func&lt;T,TResult&gt; methodToExecute, T argument) where TException : System.Exception { try { methodToExecute(argument); } catch (Exception e) { Assert.IsTrue(e.GetType() == typeof(TException), "Expected exception of type " + typeof(TException) + " but type of " + e.GetType() + " was thrown instead."); return; } Assert.Fail("Expected exception of type " + typeof(TException) + " but no exception was thrown."); } } </code></pre>
<p>You should "declare" T and TResult as well, e.g.</p> <pre><code>public static void Throws&lt;T, TResult, TException&gt;(Func&lt;T, TResult&gt; methodToExecute, T methodArgument) where TException : System.Exception </code></pre> <p>otherwise the compiler does not know what T and TResult are.</p>
uiwebview (mobilesafari) with static header <p>I've tried numerous methods to get a static header on a UIWebView so that it only scrolls the content below a html header. Has anyone successfully accomplished this?</p>
<p>If this needs to work only on the phone, you could just place two UIWebViews, one above the other. Display the header in one, and the content in another.</p>
How to get the actual size-on-disk of a file from PowerShell? <p>I am writing an administrative script, and I need to calculate the size of files on disk. </p> <p>These files are on a compressed NTFS volume.</p> <p>I can't use <code>FileInfo.Length</code>, because that is file size and not size on disk. For example, if I have a 100MB file, but it is only using 25MB due to NTFS compression, I need my script to return 25MB.</p> <p>Is there a way to do this in Powershell? </p> <p>(I know about the <code>GetCompressedFileSize()</code> Win32 call, but I was hoping that this is already wrappered at some level.)</p>
<p>(edit)</p> <p>I figured out how to dynamically add a property (called a "script property") to the Fileobject, so now, I can use the syntax: $theFileObject.CompressedSize to read the size.</p> <p>(end of edit)</p> <p>Read Goyuix's response, and I thought "Cool, but isn't there some kind of type-extension capability in Powershell?". So then I found this Scott Hanselman post: <a href="http://www.hanselman.com/blog/MakingJunctionsReparsePointsVisibleInPowerShell.aspx" rel="nofollow">http://www.hanselman.com/blog/MakingJunctionsReparsePointsVisibleInPowerShell.aspx</a> </p> <p>And I created a Script Property for the FileInfo object: CompressedSize.</p> <p>Here's what I did: (note: I'm quite new to Powershell, or at least I don't use it much. This could probably be made a lot better, but here's what I did:</p> <p>First, I compiled the Ntfs.ExtendedFileInfo from Goyuix's post. I put the DLL in my Powershell profile directory (Documents\WindowsPowershell)</p> <p>Next, I created a file in my profile directory named My.Types.ps1xml.</p> <p>I put the following XML into the file:</p> <pre><code>&lt;Types&gt; &lt;Type&gt; &lt;Name&gt;System.IO.FileInfo&lt;/Name&gt; &lt;Members&gt; &lt;ScriptProperty&gt; &lt;Name&gt;CompressedSize&lt;/Name&gt; &lt;GetScriptBlock&gt; [Ntfs.ExtendedFileInfo]::GetCompressedFileSize($this.FullName) &lt;/GetScriptBlock&gt; &lt;/ScriptProperty&gt; &lt;/Members&gt; &lt;/Type&gt; &lt;/Types&gt; </code></pre> <p>That code (once merged into the type system) will dynamically add a property named CompressedSize to the FileInfo objects that are returned by get-childitem/dir. But Powershell doesn't know about the code yet, and it doesn't know about my DLL yet. We handle that in the next step:</p> <p>Edit Profile.ps1. in the same directory. Now, my Profile file happens to already have some stuff in it because I have the Community Extensions for powershell installed. Hopefully, I'm including everything that you need in this next code snippet, so that it will work even on a machine that does not have the extensions. Add the following code to Profile.ps1:</p> <pre><code>#This will load the ExtendedfileInfo assembly to enable the GetCompressedFileSize method. this method is used by the #PSCompressedSize Script Property attached to the FileInfo object. $null = [System.Reflection.Assembly]::LoadFile("$ProfileDir\ntfs.extendedfileinfo.dll") #merge in my extended types $profileTypes = $ProfileDir | join-path -childpath "My.Types.ps1xml" Update-TypeData $profileTypes </code></pre> <p>Now, the $ProfileDir variable that I reference is defined earlier in my Profile.ps1 script. Just in case it's not in yours, here is the definition:</p> <pre><code>$ProfileDir = split-path $MyInvocation.MyCommand.Path -Parent </code></pre> <p>That's it. The next time that you run Powershell, you can access the CompressedSize property on the FileInfo object just as though it is any other property. Example:</p> <p>$myFile = dir c:\temp\myfile.txt </p> <p>$myFile.CompressedSize</p> <p>This works (on my machine, anyway), but I would love to hear whether it fits in with best practices. One thing I know I'm doing wrong: in the Profile.ps1 file, I return the results of LoadFile into a variable that I'm not going to use ($null = blah blah). I did that to suppress the display of result of load file to the console. There is probably a better way to do it.</p>
How to know what type is a var? <p>TypeInfo(Type) returns the info about the specified type, is there any way to know the typeinfo of a var?</p> <pre><code>var S: string; Instance: IObjectType; Obj: TDBGrid; Info: PTypeInfo; begin Info:= TypeInfo(S); Info:= TypeInfo(Instance); Info:= TypeInfo(Obj); end </code></pre> <p>This code returns:</p> <p><strong>[DCC Error] Unit1.pas(354): E2133 TYPEINFO standard function expects a type identifier</strong></p> <p>I know a non instantiated var is only a pointer address. At compile time, the compiler parses and do the type safety check. </p> <p><strong>At run time, is there any way to know a little more about a var, only passing its address?</strong></p>
<p>No.</p> <p>First, there's no such thing as a "non-instantiated variable." You instantiate it by the mere act of typing its name and type into your source file.</p> <p>Second, you already know all there is to know about a variable by looking at it in your source code. The variable <em>ceases to exist</em> once your program is compiled. After that, it's all just bits.</p> <p>A pointer only has a type at compile time. At run time, everything that can be done to that address has already been determined. The compiler checks for that, as you already noted. Checking the type of a variable at run time is only useful in languages where a variable's type could change, as in dynamic languages. The closest Delphi comes to that is with its <code>Variant</code> type. The type of the variable is always <code>Variant</code>, but you can store many types of values in it. To find out what it holds, you can use the <code>VarType</code> function.</p> <p>Any time you could want to use <code>TypeInfo</code> to get the type information of the type associated with a variable, you can also directly name the type you're interested in; if the variable is in scope, then you can go find its declaration and use the declared type in your call to <code>TypeInfo</code>.</p> <p>If you want to pass an arbitrary address to a function and have that function discover the type information for itself, you're out of luck. You will instead need to pass the <code>PTypeInfo</code> value as an additional parameter. That's what all the built-in Delphi functions do. For example, when you call <code>New</code> on a pointer variable, the compiler inserts an additional parameter that holds the <code>PTypeInfo</code> value for the type you're allocating. When you call <code>SetLength</code> on a dynamic array, the compiler inserts a <code>PTypeInfo</code> value for the array type.</p> <p><a href="http://stackoverflow.com/questions/554100/how-to-know-what-type-is-a-var/595100#595100">The answer that you gave</a> suggests that you're looking for something other than what you asked for. Given your question, I thought you were looking for a hypothetical function that could satisfy this code:</p> <pre><code>var S: string; Instance: IObjectType; Obj: TDBGrid; Info: PTypeInfo; begin Info:= GetVariableTypeInfo(@S); Assert(Info = TypeInfo(string)); Info:= GetVariableTypeInfo(@Instance); Assert(Info = TypeInfo(IObjectType)); Info:= GetVariableTypeInfo(@Obj); Assert(Info = TypeInfo(TDBGrid)); end; </code></pre> <p>Let's use the <a href="http://jcl.svn.sourceforge.net/viewvc/jcl/trunk/jcl/source/common/JclSysUtils.pas?view=markup"><code>IsClass</code> and <code>IsObject</code> functions from the JCL</a> to build that function:</p> <pre><code>function GetVariableTypeInfo(pvar: Pointer): PTypeInfo; begin if not Assigned(pvar) then Result := nil else if IsClass(PPointer(pvar)^) then Result := PClass(pvar).ClassInfo else if IsObject(PPointer(pvar)^) then Result := PObject(pvar).ClassInfo else raise EUnknownResult.Create; end; </code></pre> <p>It obviously won't work for <code>S</code> or <code>Instance</code> above, but let's see what happens with <code>Obj</code>:</p> <pre><code>Info := GetVariableTypeInfo(@Obj); </code></pre> <p>That should give an access violation. <code>Obj</code> has no value, so <code>IsClass</code> and <code>IsObject</code> both will be reading an unspecified memory address, probably not one that belongs to your process. You asked for a routine that would use a variable's address as its input, but the mere address isn't enough.</p> <p>Now let's take a closer look at how <code>IsClass</code> and <code>IsObject</code> really behave. Those functions take an arbitrary value and check whether the value <em>looks like</em> it might be a value of the given kind, either object (instance) or class. Use it like this:</p> <pre><code>// This code will yield no assertion failures. var p: Pointer; o: TObject; a: array of Integer; begin p := TDBGrid; Assert(IsClass(p)); p := TForm.Create(nil); Assert(IsObject(p)); // So far, so good. Works just as expected. // Now things get interesting: Pointer(a) := p; Assert(IsObject(a)); Pointer(a) := nil; // A dynamic array is an object? Hmm. o := nil; try IsObject(o); Assert(False); except on e: TObject do Assert(e is EAccessViolation); end; // The variable is clearly a TObject, but since it // doesn't hold a reference to an object, IsObject // can't check whether its class field looks like // a valid class reference. end; </code></pre> <p>Notice that the functions tell you <em>nothing</em> about the variables, only about the <em>values</em> they hold. I wouldn't really consider those functions, then, to answer the question of how to get type information about a variable.</p> <p>Furthermore, you said that all you know about the variable is its address. The functions you found do not take the address of a variable. They take the <em>value</em> of a variable. Here's a demonstration:</p> <pre><code>var c: TClass; begin c := TDBGrid; Assert(IsClass(c)); Assert(not IsClass(@c)); // Address of variable Assert(IsObject(@c)); // Address of variable is an object? end; </code></pre> <p>You might object to how I'm abusing these functions by passing what's obviously garbage into them. But I think that's the <em>only</em> way it makes sense to talk about this topic. If you know you'll never have garbage values, then you don't need the function you're asking for anyway because you already know enough about your program to use real types for your variables.</p> <p>Overall, you're asking the wrong question. Instead of asking how you determine the type of a variable or the type of a value in memory, <strong>you should be asking how you got yourself into the position where you don't already know the types of your variables and your data</strong>.</p>
Merge properties into a ResourceBundle from System.getProperties() <p>I'm building a ResourceBundle from a file, this bundle holds &lt; String, String> values.</p> <pre><code>InputStream in = getClass().getResourceAsStream("SQL.properties"); properties = new PropertyResourceBundle(in); in.close(); </code></pre> <p>I would like to add/<strong>replace</strong> on this bundle some properties that I'm passing from the command line using -Dsome.option.val.NAME1=HiEarth</p> <p>I don't care dumping the old bundle and creating a new one instead.</p> <p>Could you please tip?</p> <p>I think that what I need to do is :</p> <ol> <li>Create from the bundle a HashMap&lt; String, String></li> <li>Replace values.</li> <li>Transform the HashMap into a InputStream. //This is the complicated part...</li> <li>Build the new bundle from that.</li> </ol>
<p>This does some of what you want (converts the System.properties to a ResourceBundle). Better error handling is left up to you :-)</p> <pre> public static ResourceBundle createBundle() { final ResourceBundle bundle; final Properties properties; final CharArrayWriter charWriter; final PrintWriter printWriter; final CharArrayReader charReader; charWriter = new CharArrayWriter(); printWriter = new PrintWriter(charWriter); properties = System.getProperties(); properties.list(printWriter); charReader = new CharArrayReader(charWriter.toCharArray()); try { bundle = new PropertyResourceBundle(charReader); return (bundle); } catch(final IOException ex) { // cannot happen ex.printStackTrace(); } throw new Error(); } </pre>
NHibernate - map same entity to different tables within the same database <p>Lets say we have an Employee entity composed of a few other entities, such as a one-to-many addresses and contacts, and a few fields (name, age, etc). We mapped this entity out and can use it just fine, saving each piece out into "Employee", "EmployeeAddresses", and "EmployeeContacts" tables.</p> <p>However, we use pretty much all of this employee's information for a big calculation and have a separate "EmployeeInput" object composed of the same Address and Contact object lists (i.e. both the Employee and EmployeeInputs object has a list of Address and Contact entities). We need to save of this information when we preform the calculation for later auditing purposes. We'd like to save this EmployeeInput entity to an "EmployeeInput" table in the database.</p> <p>The problem we're running into is how to save the Address and Contact lists? We'd like to stick them into something like "EmployeeInputAddresses" and "EmployeeInputContacts", but the Address and Contact entites are already mapped to "EmployeeAddresses" and "EmployeeContacts", respectively. </p> <p>What's the easiest way to accomplish this without creating a new "EmployeeInputAddress" and "EmployeeInputContact" entity and separate mapping files for each (as the fields would literally be duplicated one by one). Put another way, how can we map a single entity, Address, to two different tables depending on the parent object it belongs to (EmployeeAddresses table if it's saving from an Employee object, and EmployeeInputAddresses table if it's saving from an EmployeeInput object).</p>
<p>The easiest way would be to have addresses and contacts mapped as composite elements. That way you could map your collection differently for <code>Employee</code> and for <code>EmployeeInput</code> since the mapping is owned by the container.</p> <p>For example:</p> <pre><code>public class Employee { public List&lt;Address&gt; Addresses{get; set;} } public class EmployeeInput { public List&lt;Address&gt; Addresses{get; set;} } public class Address { public string Street{get;set;} public string City{get; set;} } </code></pre> <p>Would have the folloying mapping:</p> <pre><code>&lt;class name="Employee" table="Employees"&gt; &lt;id name="id"&gt; &lt;generator class="native"/? &lt;/id&gt; &lt;list name="Addresses" table="EmployesAddresses"&gt; &lt;key column="Id" /&gt; &lt;index column="Item_Index" /&gt; &lt;composite-element class="Address"&gt; &lt;property name="Street" /&gt; &lt;property name="City" /&gt; &lt;/composite-element&gt; &lt;/list&gt; &lt;/class&gt; &lt;class name="EmployeeInput" table="EmployeesInput"&gt; &lt;id name="id"&gt; &lt;generator class="native"/? &lt;/id&gt; &lt;list name="Addresses" table="EmployeesInputAddresses"&gt; &lt;key column="Id" /&gt; &lt;index column="Item_Index" /&gt; &lt;composite-element class="Address"&gt; &lt;property name="Street" /&gt; &lt;property name="City" /&gt; &lt;/composite-element&gt; &lt;/list&gt; &lt;/class&gt; </code></pre>
Find PHP Orphan Page <p>I've inherited a PHP application that has "versions" of pages (viewacct.php, viewacct2.php, viewacct_rcw.php, etc). I want to discover which of these pages are called from other pages in the application and which are not. Is there a tool available that will help with that?</p>
<p>Using whatever tools you would like (Find/Grep/Sed on Linux, I use Visual Studio on windows), it is just a matter of crawling your source tree for references of the filenames in each file.</p>
Any mnemonic tip for boolean? <p>I guess this is trivial for most of good<sup>1</sup> programmers, but I'm so used to programming using <code>true</code> and <code>false</code><sup>2</sup> that when I encounter 0 and 1, I can never remember which one means true and which one means false. </p> <p>Any suggestions?</p> <p><sup>1</sup>Good: <a href="http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html" rel="nofollow">I mean one who knows C, of course</a> :)<br /> <sup>2</sup>I am a Java developer, as you have guessed ;)</p>
<p>The mnemonic is "how much truth is in this?" Zero integer means zero truth. Anything else is nonzero truth. :)</p>
SQL Server 2005 - Blocked Process Report <p>I need to investigate a series of blocks and deadlocks that have been occurring randomly on our SQL 2008 server. I am the main developer on the site and do not have a DBA to lean on...</p> <p>I am planning on using the Blocked Process Report in 2005 and enabling a trace.</p> <p>What performace issues can I expect? The DB server is for a website with moderate traffic and I want to minimize the impact the trace will cause.</p>
<p>use <a href="http://weblogs.sqlteam.com/mladenp/archive/2008/07/18/Immediate-deadlock-notifications-without-changing-existing-code.aspx" rel="nofollow">Event Notification</a> method. it works in 2005 and 2008. it doesn't present any perf problem for detecting deadlocks</p>
Running Cocoa app under otest causes dyld_misaligned_stack_error in Release mode <p>I have a problem which I have been struggling with for a while.</p> <p>I have a Cocoa library which acts as a wrapper for a C++ library. C++ library is tested using a set of BOOST unit tests. The tests run normally under both debug and release modes.</p> <p>In order to test the Cocoa wrapper I am using otest. Here is the strange part, the tests run normally in debug mode but fail in release mode. To make sure its not something in the code I've taken the tests content and compiled them as a separate Cocoa app which uses the wrapper code. This runs normally both under release and debug.</p> <p>When otest fails I get a stack trace which makes little sense and ends with dyld_misaligned_stack_error.</p> <p>Another strange thing that I've noticed is that when starting otest from a command line rather than from XCode if I point DYLD_LIBRARY_PATH and DYLD_FRAMEWORK_PATH to the Debug version of C++ library the tests pass. I have confirmed though that all my test code is being compiled with Release flags.</p> <p>Any help would be greatly appreciated!</p> <p>Thank you</p>
<p>Try adding flag "-mstackrealign" in C flags in the release version.</p> <blockquote> <p>-mstackrealign</p> <p>Realign the stack at entry. On the Intel x86, the -mstackrealign option will generate an alternate prologue/epilogue that realigns the runtime stack. This supports mixing legacy codes that keep a 4-byte aligned stack with modern codes that keep a 16-byte stack for SSE compatibility.</p> </blockquote> <p>See GCC's man page for reference.</p>
iPhone use of mutexes with asynchronous URL requests <p>My iPhone client has a lot of involvement with asynchronous requests, a lot of the time consistently modifying static collections of dictionaries or arrays. As a result, it's common for me to see larger data structures which take longer to retrieve from a server with the following errors:</p> <pre><code>*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection &lt;NSCFArray: 0x3777c0&gt; was mutated while being enumerated.' </code></pre> <p>This typically means that two requests to the server come back with data which are trying to modify the same collection. What I'm looking for is a tutorial/example/understanding of how to properly structure my code to avoid this detrimental error. I do believe the correct answer is mutexes, but I've never personally used them yet.</p> <p>This is the result of making asynchronous HTTP requests with NSURLConnection and then using NSNotification Center as a means of delegation once requests are complete. When firing off requests that mutate the same collection sets, we get these collisions.</p>
<p>There are several ways to do this. The simplest in your case would probably be to use the @synchronized directive. This will allow you to create a mutex on the fly using an arbitrary object as the lock.</p> <pre><code>@synchronized(sStaticData) { // Do something with sStaticData } </code></pre> <p>Another way would be to use the NSLock class. Create the lock you want to use, and then you will have a bit more flexibility when it comes to acquiring the mutex (with respect to blocking if the lock is unavailable, etc).</p> <pre><code>NSLock *lock = [[NSLock alloc] init]; // ... later ... [lock lock]; // Do something with shared data [lock unlock]; // Much later [lock release], lock = nil; </code></pre> <p>If you decide to take either of these approaches it will be necessary to acquire the lock for both reads and writes since you are using NSMutableArray/Set/whatever as a data store. As you've seen NSFastEnumeration prohibits the mutation of the object being enumerated.</p> <p>But I think another issue here is the choice of data structures in a multi-threaded environment. Is it strictly necessary to access your dictionaries/arrays from multiple threads? Or could the background threads coalesce the data they receive and then pass it to the main thread which would be the only thread allowed to access the data?</p>
How to detect which Space the user is on in Mac OS X Leopard? <p>Mac OS X Leopard has a virtual desktop implementation called <a href="http://www.apple.com/macosx/features/spaces.html" rel="nofollow">Spaces</a>. I want to <strong>programatically detect which space the user is currently on</strong>.</p> <p><strong>Cocoa is preferable</strong> but <strong>AppleScript is acceptable</strong> if there's no other way.</p> <p>I've seen a couple of AppleScript implementations, but the techniques they used seemed a bit too hacky to use in production code (one relied on causing an error and then parsing the error message to get the current space, the other interrogated the Spaces menu GUI)</p>
<p>Use HIWindowGetCGWindowID to get the CGWindowID for your WindowRef.</p> <p>Use that ID with CGWindowListCreateDescriptionFromArray from CGWindow.h to get information on your window. </p> <p>Look at the returned dictionary and extract the (optional) kCGWindowWorkspace key. That is your space ID for your window.</p>
Objective-C 2.0 and Fast Enumeration throwing exceptions <p>I have a block of code which is similar to the following:</p> <pre><code>for (NSDictionary *tmp in aCollection) { if ([[bar valueForKey:@"id"] isEqualToString:[tmp valueForKey:@"id"]]) { break; } else { [aCollection addObject:bar]; } } </code></pre> <p>Is this technically an exception in Objective-C 2.0? It appears you cannot mutate a collection with fast enumeration. This is the result of an error: </p> <pre><code>*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection &lt;NSCFArray: 0x396000&gt; was mutated while being enumerated.' </code></pre> <p>What's the best way to solve this?</p>
<p>Well the way to solve it is not to mutate the array (e.g. add an object) while enumerating it :)</p> <p>The problem here is that modifying the array by adding/removing elements could cause the enumeration values to become invalid, hence why it's a problem.</p> <p>In your case The easiest way to solve this is fixing the bug in your code. Your code is doing the "else add" clause for every item in the array and I'm quite sure that's not what you want. </p> <p>Try this;</p> <pre><code>bool found = false; for (NSDictionary *tmp in aCollection) { if ([[bar valueForKey:@"id"] isEqualToString:[tmp valueForKey:@"id"]]) { found = true; break; } } if (!found) { [aCollection addObject:bar]; } </code></pre>
Many-to-many relationship with surrogate key in Entity Framework <p>Entity Framework magically interprets the following table structure as a many-to-many relationship.</p> <pre><code>table foo (int id) table foo_bar (int foo_id, int bar_id) table bar (int id) </code></pre> <p>But if the join table has any additional fields it will instead be interpreted as two one-to-many relationships.</p> <p>I am using a database in which the join table has a surrogate key as primary key. Because of this EF interprets it as two one-to-many relationships.</p> <pre><code>table foo (int id) table foo_bar (int surrogate_pk, int foo_id, int bar_id) table bar (int id) </code></pre> <p>Is it possible to modify EF:s interpretation to make it an actual many-to-many relationship in the model? Can it be done using the designer?</p>
<p>it's possible, but it requires quite a bit of manual work in the EDMX file, and I haven't been able to make EF use the surrogate key as actual primary key on the link table. You have to make EF use a combination key of both foo_id and bar_id as primary key.</p> <p>in your storage model you have to change the EntityType of the link table from</p> <pre><code>&lt;EntityType Name="foo_bar"&gt; &lt;Key&gt; &lt;PropertyRef Name="surrogate_pk" /&gt; &lt;/Key&gt; &lt;Property Name="surrogate_pk" Type="bigint" Nullable="false" StoreGeneratedPattern="Identity" /&gt; &lt;Property Name="foo_id" Type="int" Nullable="false" StoreGeneratedPattern="None" /&gt; &lt;Property Name="bar_id" Type="int" Nullable="false" StoreGeneratedPattern="None" /&gt; &lt;/EntityType&gt; </code></pre> <p>to:</p> <pre><code>&lt;EntityType Name="foo_bar"&gt; &lt;Key&gt; &lt;PropertyRef Name="foo_id" /&gt; &lt;PropertyRef Name="bar_id" /&gt; &lt;/Key&gt; &lt;Property Name="foo_id" Type="int" Nullable="false" StoreGeneratedPattern="None" /&gt; &lt;Property Name="bar_id" Type="int" Nullable="false" StoreGeneratedPattern="None" /&gt; &lt;/EntityType&gt; </code></pre> <p>So you make the surrogate key invisible to EF, and tell it to use the combination of the two foreign keys as primary key. </p> <p>In your conceptual model, you need to have the many-many association defined:</p> <pre><code>&lt;Association Name="foo_bar_association"&gt; &lt;End Role="foo" Type="foo" Multiplicity="*" /&gt; &lt;End Role="bar" Type="bar" Multiplicity="*" /&gt; &lt;/Association&gt; </code></pre> <p>and in your mappings, an AssociationSetMapping:</p> <pre><code>&lt;AssociationSetMapping Name="foo_bar_association" TypeName="foo_bar_association" StoreEntitySet="foo_bar"&gt; &lt;EndProperty Name="foo"&gt; &lt;ScalarProperty Name="id" ColumnName="foo_id" /&gt; &lt;/EndProperty&gt; &lt;EndProperty Name="bar"&gt; &lt;ScalarProperty Name="id" ColumnName="bar_id" /&gt; &lt;/EndProperty&gt; &lt;/AssociationSetMapping&gt; </code></pre> <p>By far the easiest way to get this right, is to remove the surrogate key from the db, generate the EDMX, and then put this model on your original DB. The result will be the same. EF doesn't really need the surrogate key for anything, the table is invisible in a many-many association</p>
XML compare tool that can "Tidy" the XML and ignore differences in attributes <p>I am looking at using <strong>Beyond Compare 3</strong> with <em>XML Tidy</em> compare comparison format. <em>XML Tidy</em> formats all the nodes with <strong>proper line breaks and indentation</strong> if an XML file is all slopped onto one line. ...So I would love a tool that can do this and can <strong>ignore differences in attributes</strong>, or not even show attributes at all (this is because attributes are irrelevant to my users).</p> <p>Is there a tool that can do this?</p> <p>Thanks!</p>
<p>An XSLT identity transform that omits the attributes and sets the output to indent should work:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"&gt; &lt;xsl:output indent="yes" /&gt; &lt;xsl:template match="/"&gt; &lt;xsl:apply-templates /&gt; &lt;/xsl:template&gt; &lt;xsl:template match="node()"&gt; &lt;xsl:copy&gt; &lt;xsl:apply-templates /&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre>
Workaround for some WPF features that are missing in Silverlight <p>I’m porting a WPF app to silverlight 2, and have come across several WPF features which are presently missing from SL. Could anyone help me with equivalents or suggest workarounds.</p> <ol> <li><p>I want to handle clicks and double clicks on a textbox embedded in a list box. The WPF implementation uses PreviewMouseLeftButtonDown/Up on a listbox control. How can this be done in silverlight, it seems that PreviewMouseLeftButtonDown/Up are missing in silverlight.</p></li> <li><p>I want to handle button presses (F2/Delete) on a textbox embedded in a list box. The WPF implementation uses PreviewKeyDown on a textbox control which embedded as an item in a listbox. It seems that PreviewKeyDown is missing in silverlight. The KeyDown event handler does not seem to get invoked.</p></li> <li><p>I want to change some appearance properties of a textbox depending on the value of some custom attached properties. The WPF implementation uses a DataTrigger to do this. How can this be done in silverlight. It seems that DataTriggers are missing in silverlight.</p></li> <li><p>I want to change the width of a text box depending on the Actual Width of the listbox in which the text box is contained. The WPF implementation uses RelativeSource binding. What is the silverlight equivalent, or workaround for this.</p></li> </ol>
<p>I'm more familiar with Silverlight than the full WPF. Please considier my responses accordingly.</p> <p>For number 2. For many keys, I check on KeyUp and KeyDown. I use KeyDown while trying to watch the entire time that the key is held down and KeyUp when it was used just once. You should know this was for a game without an individual text box.</p>
jQueries equivalent to YAHOO.util.Event.addListener <p>Does jQuery have an equivalent method to YAHOO.util.Event.addListener ?</p>
<p>Yes.</p> <p>Check out <a href="http://docs.jquery.com/Events/bind#typedatafn" rel="nofollow">bind</a>. You can do something like</p> <pre><code>$("#elementID").bind("click", function(e) { // whatever you want }); </code></pre> <p>or you can call <a href="http://docs.jquery.com/Events/click#fn" rel="nofollow">click</a> directly</p> <pre><code>$("#elementID").click(function(e) { // whatever you want }); </code></pre>
How do I secure my JsonResult GET calls? <p>I know how to use MVC's AntiForgeryToken attribute and it's associated HTML helper to help XSRF-secure my application's form POSTs.</p> <p>Can something similar can be done for JsonResults that implement GET?</p> <p>For instance, my View contains an onSubmit jQuery call like such:</p> <pre><code>$.getJSON("/allowActivity/YesOrNo/" + someFormValue, "{}", function(data) { if(data.Allow) { //Do something. } }); </code></pre> <p>I want to make certain that this JsonResult is only callable from the intended page.</p> <p>EDIT:</p> <p>I found <a href="http://stackoverflow.com/questions/470011/security-and-cross-domain-with-asp-net-mvc-jsonresult-and-jquery/470039">this post</a> about a similar question, with no concrete answer.</p> <p>What is the easiest way to ensure that my GET(non-destructive) URL is consumed only by an AJAX call from my own page?</p>
<p>You may use the AntiForgeryToken combined with some custom logic. The creation of the AntiForgery token on the server is the same, but by default the value is not included in your XmlHttpRequest.</p> <p>The value of this token is in the HTTP only cookie "__RequestVerificationToken" and should also be in the form data posted to the server. So include a key/value pair in your XmlHttpRequest and use the ValidateAntiForgeryToken - attribute on your controller </p> <p>EDIT:</p> <p>Today I tried using the AntiForgeryToken for Ajax requests myself and it works fine. Just use the following javascript:</p> <pre><code>$.post('my_url', $.getAntiForgeryTokenString(), function() { ... }); $.getAntiForgeryTokenString = function() { return $(document.getElementsByName("__RequestVerificationToken")).fieldSerialize(); }; </code></pre> <p>On the server side you don't have to change your code - just use the ValidateAntiForgeryToken- attribute for your action.</p> <p>Hope this helps</p>
How to search a git repository history to find a merge error? <p>At some point in our past branches of development in git were merged. However, the wrong merge decision was made and therefore some code didn't make it into master branch that we expected would be there. (There were multiple merges of different branches before a final merge to a master branch. So the branching and merging history was fairly complex.)</p> <p>Is there an easy way to search a git repository to determine on which merge the "wrong" decision was made on?</p> <p>(I already know the answer for this particular case, but the process of finding it was a bit tedious.)</p> <p>EDIT: The reason git blame proved inadequate is that the line was touched in a commit sometime after the merge error. </p>
<p>Can <a href="http://www.kernel.org/pub/software/scm/git/docs/git-bisect.html" rel="nofollow">git-bisect</a> help in your case?</p>