input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
How to append tr to top of table <p>how can i append a new tr to the top of the table instead of under other tr.</p>
<p>Example:</p>
<pre><code><table width='100%'>
<tr><td>something</td><td>else here</td></tr>
<tr><td>something2</td><td>else here2</td></tr>
</table>
</code></pre>
<p>After a click event in jQuery, how can i place
<code><tr><td>something3</td><td>else here3</td></tr> </code>
at the top of the table so it now looks like</p>
<pre><code><table width='100%'>
<tr><td>something3</td><td>else here3</td></tr>
<tr><td>something</td><td>else here</td></tr>
<tr><td>something2</td><td>else here2</td></tr>
</table>
</code></pre>
<p>Any help on this would be greatly appreciated.</p>
| <pre><code>$('table').prepend('<tr><td>something3</td><td>else here3</td></tr>');
</code></pre>
<p>or...</p>
<pre><code>$('<tr><td>something3</td><td>else here3</td></tr>').prependTo('table');
</code></pre>
<p><hr /></p>
<p>More info on 'prepend': <strong><a href="http://docs.jquery.com/Manipulation/prepend">http://docs.jquery.com/Manipulation/prepend</a></strong></p>
<p>More info on 'prependTo': <strong><a href="http://docs.jquery.com/Manipulation/prependTo">http://docs.jquery.com/Manipulation/prependTo</a></strong></p>
|
CSS Image Caching <p>In terms of client-side image caching, is there a difference between the following:</p>
<pre><code>**Option #1**
<div style="background:url('myimage.jpg');display:none;"></div>
</code></pre>
<p>and</p>
<pre><code>**Option #2**
<div id="myimage"></div>
style.css
#myimage {
background:url('myimage.jpg');
display:none;
}
</code></pre>
<p>EDIT: I'm not sure if it matters but the above DIVs are first loaded on another page with style="display:none;" </p>
| <p>No. Client caching is controlled by headers returned from the server in the request for the image, not the css.</p>
<p>As an aside, if you're looking for image caching, I highly recommend using a CDN. <a href="http://aws.amazon.com/cloudfront/" rel="nofollow">Amazon's CloudFront</a> makes this easy and cheap.</p>
|
Effective strategies for studying frameworks/ libraries partially <p>I remember the old effective approach of studying a new framework. It was always the best way to read a good book on the subject, say MFC. When I tried to skip a lot of material to speed up coding it turned out later that it would be quicker to read the whole book first. There was no good ways to study a framework in small parts. Or at least I did not see them then.</p>
<p>The last years a lot of new things happened: improved search results from Google, programming blogs, much more people involved in Internet discussions, a lot of open source frameworks.</p>
<p>Right now when we write software we much often depend on third-party (usually open source) frameworks/ libraries. And a lot of times we need to know only a small amount of their functionality to use them. It's just about finding the simplest way of using a small subset of the library without unnecessary pessimizations.</p>
<p><strong>What do you do to study as less as possible of the framework and still use it effectively?</strong></p>
<p>For example, suppose you need to index a set of documents with <a href="http://en.wikipedia.org/wiki/Lucene" rel="nofollow">Lucene</a>. And you need to highlight search snippets. You don't care about stemmers, storing the index in one file vs. multiple files, fuzzy queries and a lot of other stuff that is going to occupy your brain if you study Lucene in depth.</p>
<p><strong>So what are your strategies, approaches, tricks to save your time?</strong></p>
<p>I will enumerate what I would do, though I feel that my process can be improved.</p>
<ul>
<li>Search "lucene tutorial", "lucene highlight example" and so on. Try to estimate trust score of unofficial articles ( blog posts ) based on publishing date, the number and the tone of the comments. If there is no a definite answer - collect new search keywords and links on the target.</li>
<li>Search for really quick tutorials/ newbie guides on official site</li>
<li>Estimate how valuable are javadocs for a newbie. (Read <a href="http://lucene.apache.org/java/2%5F4%5F1/api/org/apache/lucene/search/highlight/package-summary.html" rel="nofollow">Lucene highlight package summary</a>)</li>
<li>Search for simple examples that come with a library, related to what you need. ( Study "src/demo/org/apache/lucene/demo")</li>
<li>Ask about "simple Lucene search highlighting example" in Lucene mail list. You can get no answer or even get a bad reputation if you ask a silly question. And often you don't know whether you question is silly because you have not studied the framework in depth.</li>
<li>Ask it on Stackoverflow or other QA service "could you give me a working example of search keywords highlighting in Lucene". However this question is very specific and can gain no answers or a bad score.</li>
<li>Estimate how easy to get the answer from the framework code if it's open sourced.</li>
</ul>
<p><strong>What are your study/ search routes? Write them in priority order if possible.</strong></p>
| <p>I use a three phase technique for evaluating APIs.</p>
<p>1) Discovery - In this phase I search StackOverflow, CodeProject, Google and Newsgroups with as many different combination of search phrases as possible and add everything that might fit my needs into a huge list.</p>
<p>2) Filter/Sort - For each item I found in my gathering phase I try to find out if it suits my needs. To do this I jump right into the API documentation and make sure it has all of the features I need. The results of this go into a weighted list with the best solutions at the top and all of the cruft filtered out. </p>
<p>3) Prototype - I take the top few contenders and try to do a small implementation hitting all of the important features. Whatever fits the project best here wins. If for some reason an issue comes up with the best choice during implementation, it's possible to fall back on other implementations.</p>
<p>Of course, a huge number of factors go into choosing the best API for the project. Some important ones:</p>
<ol>
<li>How much will this increase the size of my distribution?</li>
<li>How well does the API fit with the style of my existing code?</li>
<li>Does it have high quality/any documentation?</li>
<li>Is it used by a lot of people? </li>
<li>How active is the community?</li>
<li>How active is the development team?</li>
<li>How responsive is the development team to bug patch requests?</li>
<li>Will the development team accept my patches?</li>
<li>Can I extend it to fit my needs?</li>
<li>How expensive will it be to implement overall?</li>
</ol>
<p>... And of course many more. It's all very project dependent.</p>
<p>As to saving time, I would say trying to save too much here will just come back to bite you later. The time put into selecting a good library is at least as important as the time spent implementing it. Also, think down the road, in six months would you rather be happily coding or would you rather be arguing with a xenophobic dev team :). Spending a couple of extra days now doing a thorough evaluation of your choices can save a lot of pain later.</p>
|
What is the best resource for learning C# expression trees in depth? <p>When I first typed this question, I did so in order to find the duplicate questions, feeling sure that someone must have already asked this question. My plan was to follow those dupe links instead of posting this question. But this question has not been asked before as far as I can see ... it did not turn up in the "Related Questions" list.</p>
<p><strong>What are some of the best resources you've found (articles, books, blog posts, etc.) for gaining an in-depth understanding of Expression Trees in C#?</strong> I keep getting surprised by their capabilities, and now I'm at the point where I'm saying, "OK, enough surprise. I want to stop right now and get a PhD in these things." I'm looking for material that systematically, methodically covers the capabilities and then walks through detailed examples of what you can do with them.</p>
<p>Note: I'm not talking about lambda expressions. I'm talking about Expression< T > and all the things that go with it and arise from it.</p>
<p>Thanks.</p>
| <p>Chapter 11 (Inside Expression Trees) and chapter 12 (Extending Linq) of Programming Microsoft Linq (ISBN 13: 978-0-7356-2400-9 or ISBN 10: 0-7356-2400-3) has been invaluable for me. I haven't read Jons book, but he is a quality guy and explains things well, so I assume that his coverage would also be good.</p>
<p>Another great resource is <a href="http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">Bart De Smet's blog</a> </p>
<p>Also, keep your eye on MSDN, the sample code for building a <a href="http://code.msdn.microsoft.com/SimpleLingToDatabase/Release/ProjectReleases.aspx?ReleaseId=1471">Simple Linq to Database</a> (by Pedram Rezaei) is about to get about 40 pages of Doco explaining it.</p>
<p>EDIT: (I might just keep adding resource links here over time, as it's a useful placeholder for this info.)</p>
<p>A really, really useful resource for Expression Tree's in fact I would regard it as a <em>must have</em> is the <a href="http://msdn.microsoft.com/en-us/library/bb397975.aspx">Expression Tree Visualiser</a> debugging tool.</p>
<p>You should also learn as much as you can about Expression Tree Visitors, there is a pretty good base class inplementation <a href="http://msdn.microsoft.com/en-us/library/bb882521.aspx">here</a>. </p>
<p>Here is some sample code derived from that Visitor class to do some debugging (I based this on some sample code in the book I mentioned) the prependIndent method call is just an extension method on a string to put a "--" at each indent level.</p>
<pre><code> internal class DebugDisplayTree : ExpressionVisitor
{
private int indentLevel = 0;
protected override System.Linq.Expressions.Expression Visit(Expression exp)
{
if (exp != null)
{
Trace.WriteLine(string.Format("{0} : {1} ", exp.NodeType, exp.GetType().ToString()).PrependIndent(indentLevel));
}
indentLevel++;
Expression result = base.Visit(exp);
indentLevel--;
return result;
}
...
</code></pre>
|
ejb vs hibernate <p>When is better to use hibernate and when ejb3? Aren't there any impediments with either hibernate or ejb3?</p>
| <p>I'm in the direct hibernate camp here. </p>
<p>Just think how likely it is that your going to what to change your database say from DB2 to oracle, well that is about as likely as changing from Hibernate to Toplink or eclipse it just isn't going happen that often. It's the same old thing that programmers just love to do and that is abstract any stuff so that they can in at some unforeseen point 10 years from now choose to use a different logging tool kit or what not.</p>
<p>There are I'm sure people out there that really want the vendor independence of JPA but I'm not one of them. That's not to say that Toplink or eclipse aren't any good, I just don't think you can use a product that complex and not be tied (even unintentionally) to it in some way.</p>
<p>Having said that I still follow the hibernate documentation advice and use the JPA annotations and only resort to the hibernate specific ones when I need to, not quite sure if there is a technical reason for this, but it doesn't hurt.</p>
|
How do I reorder/clear the connection history in SQL Management Studio 2008? <p>I connect to a lot of different servers in SQL Management Studio, but I find that not only is there no way to delete the old connections (dbnames, usernames, etc.), they also start to show up as duplicates.</p>
<p>Is there any way to clear them/reorder the history? I can't seem to find any easy way.</p>
<p>Thanks!
Chris</p>
| <p>I had the same issue and found the file in question is SqlStudio.bin. I'm not sure how you'd go about editing it, but if you re/move it, you get a blank slate for your SQL connections.</p>
<p>We still use XP here at work, so the file is located in the C:\Documents and Settings\%USERNAME%\Application Data\Microsoft\Microsoft SQL Server\100\Tools\Shell folder.</p>
|
distributed application model, server and multiple clients (client can run on server) <p>I've got a system i'm designing where we're using 4 specialized PC's we manufacture in house that have 16 serial ports (db-9 RS232) I need to communicate with 64 units near simultaneously (4x16) and manage the communications. <strong>Here's the model I came up with and i'm soliciting feedback</strong></p>
<p><strong>Server:</strong>
Runs on one system and coordinates client applications. Maintains a master state machine and makes sure that the clients are in lock step with that state machine. (For instance, all units do task A, when the last one reports completion, all units do task B).</p>
<p><strong>Communicates via .net remoting? WCF?</strong></p>
<p><strong>Client:</strong>
Can run on the same system as the server. Manages all the IO. Manages buisness logic for actual task execution <strong>(bad idea?)</strong> Reports status through Remoting/WCF <strong>via notification events (for instance INotifyPropertyChanged)</strong>. </p>
<p>I've never worked with .net remoting or ANY sort of distributed applications so i'm a total novice at this, but I do learn quickly. <strong>Literature and community advice would be much appreciated at this point.</strong></p>
| <p>Definitely check out the Concurrency and Coordination Runtime (CCR):</p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb648752.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb648752.aspx</a></p>
<p>EDIT:</p>
<p>Link to download: </p>
<p><a href="http://msdn.microsoft.com/en-us/robotics/aa731520.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/robotics/aa731520.aspx</a></p>
|
SQLCE - Ignoring query execution <p>Deploying database(*.sdf) to Pocket PC WM 5.0. Via C# i am attempting to DELETE records. The DELETE query returns that 5 rows are affected(there are 5 rows). However, when i view database in Pocket PC under its Query Tool the rows remain. No error or issue arise at my code level. </p>
<p>What is missing? It is the right database because if i rename or delete i get an erro on open. What's wrong?</p>
| <p>Are you doing the DELETE in a transaction, and forgetting to .Commit() it?</p>
|
How to set up properly resource pools in VMWare ESXi? <p>How to set up properly resource pools in VMWare ESXi? Does anyone have any blog entries etc.?</p>
<p>Thanks</p>
| <p>Sign up for a VMworld Account and watch the videos from <a href="http://www.vmworld.com/community/sessions/2007" rel="nofollow">VMworld 2007</a></p>
<p>Particularly IO20 and IO21. You have to have an account to view, and the direct links are a little flaky.</p>
|
Referencing Error to the AudioToolbox in Objective C <p>I'm getting the following error in a simple Roulett app where I'm trying to play some wav files. I'm not sure what the error means because no warning flags come up in the code, and I've imported </p>
<p>Here is the error:</p>
<blockquote>
<p>Undefined symbols:<br />
"_AudioServicesCreateSystemSoundID",
referenced from:
-[CustomPickerViewController playWinSound] in
CustomPickerViewController.o
-[CustomPickerViewController spin:] in CustomPickerViewController.o
"_AudioServicesPlaySystemSound",
referenced from:
-[CustomPickerViewController playWinSound] in
CustomPickerViewController.o
-[CustomPickerViewController spin:] in CustomPickerViewController.o
ld: symbol(s) not found collect2: ld
returned 1 exit status<br />
"_AudioServicesCreateSystemSoundID",
referenced from:
-[CustomPickerViewController playWinSound] in
CustomPickerViewController.o
-[CustomPickerViewController spin:] in CustomPickerViewController.o
"_AudioServicesPlaySystemSound",
referenced from:
-[CustomPickerViewController playWinSound] in
CustomPickerViewController.o
-[CustomPickerViewController spin:] in CustomPickerViewController.o
ld: symbol(s) not found collect2: ld
returned 1 exit status</p>
</blockquote>
<p>And here is the code:</p>
<pre><code>#import "CustomPickerViewController.h"
#import <AudioToolbox/AudioToolbox.h>
@implementation CustomPickerViewController
@synthesize picker;
@synthesize winLabel;
@synthesize column1;
@synthesize column2;
@synthesize column3;
@synthesize column4;
@synthesize column5;
@synthesize button;
- (void)showButton
{
button.hidden = NO;
}
-(void)playWinSound
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"win" ofType:@"wav"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID);
AudioServicesPlaySystemSound (soundID);
winLabel.text = @"WIN!";
[self performSelector:@selector(showButton) withObject:nil afterDelay:1.5];
}
-(IBAction)spin:(id)sender
{
BOOL win = NO;
int numInRow = 1;
int lastVal = -1;
for (int i = 0; i < 5; i++)
{
int newValue =random() % [self.column1 count];
if (newValue == lastVal)
numInRow++;
else
numInRow = 1;
lastVal = newValue;
[picker selectRow:newValue inComponent:i animated: YES];
[picker reloadComponent:i];
if (numInRow >= 3)
win = YES;
}
button.hidden = YES;
NSString *path = [[NSBundle mainBundle] pathForResource:@"crunch"ofType:@"wav"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((CFURLRef) [NSURL fileURLWithPath:path], &soundID);
AudioServicesPlaySystemSound(soundID);
if (win)
[self performSelector:@selector(playWinSound) withObject: nil afterDelay: .5];
else
[self performSelector:@selector(showButton) withObject: nil afterDelay: .5];
winLabel.text = @"";
}
</code></pre>
| <p>Found it. Realized I had not imported the Framework AudioToolbox.Framework in XCode. :)</p>
|
How to avoid hardcoded field names in entity framework? <p>How do i avoid using hardcoded table and field names in entity framework? For example:</p>
<pre><code> Contact contact =
contactQuery.Include("SalesOrderHeader.SalesOrderDetail")
.FirstOrDefault();
</code></pre>
<p>Is there a way to get that info from the context or metadata? I'd love to be able say SalesOrderHeader.TableName or SalesOrderHeaderFields.SalesOrderDetails.FieldName</p>
| <p>If you want to use the Entity Frameworks metadata, you need to go looking through the <code>MetadataWorkspace</code> which hangs off the <code>ObjectContext</code>.</p>
<p>The starting point is to get the EntityType for your base type, in your case Contact.</p>
<p>I have an <a href="http://blogs.msdn.com/alexj/archive/2009/03/26/index-of-tips.aspx" rel="nofollow">EF tips series</a> and in <a href="http://blogs.msdn.com/alexj/archive/2009/04/15/tip-13-how-to-attach-an-entity-the-easy-way.aspx" rel="nofollow">Tip 13</a> I show an extension method on <code>MetadataWorkspace</code> that gets the <code>EntityType</code> for a particular CLR Type:</p>
<pre><code>public static EntityType GetCSpaceEntityType<T>(
this MetadataWorkspace workspace);
</code></pre>
<p>You can use this like this:</p>
<pre><code>var contactEntity = ctx.MetadataWorkspace.GetCSpaceEntityType<Contact>();
</code></pre>
<p>Once you have this you can look at it's NavigationProperties to find the relationship's and the names you are interested in including:</p>
<p>i.e.</p>
<pre><code>foreach(var np in contactEntity.NavigationProperties)
{
Console.WriteLine("Include: {0}", np.Name);
Console.WriteLine("... Recursively include ");
EntityType relatedType =
(np.ToEndMember.TypeUsage.EdmType as RefType).ElementType;
//TODO: go repeat the same process... i.e. look at the relatedTypes
// navProps too until you decide to stop.
}
</code></pre>
<p>Of course how you decide what you want to Include is up to you.
Hope this helps</p>
<p>Alex</p>
|
use M-q in Emacs without turning all my code into comments <p>Say you write some code like this (using ruby-mode, but I've seen this happen in other modes too):</p>
<pre><code># This is a comment.
def foo
puts "foo!"
end
</code></pre>
<p>If you put the point on the first line and hit M-q, you get this:</p>
<pre><code># This is a comment. def foo puts "foo!" end
</code></pre>
<p>How do I avoid that? I'm using version 21.3.</p>
<p>Clarification: This does not happen when I add a blank line between the comment and the code. As a work-around when I want to refill my comments, I go through an annoying three step process:</p>
<ol>
<li>I add a blank line before and after
the comment paragraph</li>
<li>M-q</li>
<li>delete the blank lines</li>
</ol>
<p>It'd be much nicer if M-q handled refilling comment paragraphs without having to add and delete blank lines. Emacs already know what text is comment text, so there must be a way to do this.</p>
| <p><a href="http://www.emacswiki.org/emacs/FillAdapt">filladapt.el</a> does the trick. That with the latest version of <a href="http://www.emacswiki.org/emacs/RubyMode">RubyMode</a>.</p>
<p>Using those two packages solves the M-q problem you're seeing. (Using GNU Emacs 22.1)</p>
<p>Looking at the code for ruby-mode, it looks like it has customized the variables to control paragraph filling like so:</p>
<pre><code>(make-local-variable 'paragraph-start)
(setq paragraph-start (concat "$\\|" page-delimiter))
(make-local-variable 'paragraph-separate)
(setq paragraph-separate paragraph-start)
(make-local-variable 'paragraph-ignore-fill-prefix)
(setq paragraph-ignore-fill-prefix t)
</code></pre>
<p>Which can be added to a custom hook for your current ruby, or whatever major mode where you want fill behavior to act as you described - provided you use filladapt.el.</p>
|
What's the best way to resolve a combinatorial explosion of interactions? <p>One of the things I'm working on right now has some similarities to a game. For purposes of illustration, I'm going to explain my problem using an example drawn from a fictitious, hypothetical game.</p>
<p>Let's call it <em>DeathBlaster 4: The Deathening</em>. In DB4, you have a number of <code>Ship</code> objects which periodically and randomly encounter <code>Phenomena</code> as they travel. A given <code>Phenomenon</code> may have zero, one, or more <code>Effects</code> on a <code>Ship</code> that encounters it. For example, we might have four kinds of <code>Ships</code> and three kinds of <code>Phenomena</code>.</p>
<pre>
Phenomena
==========================================
Ships GravityWell BlackHole NebulaField
------------ ------------------------------------------
RedShip +20% speed -50% power -50% shield
BlueShip no effect invulnerable death Effects of Various
GreenShip -20% speed death +50% shield Phenomena on Ships
YellowShip death +50% power no effect
</pre>
<p>Additionally, <code>Effects</code> may interact with each other. For example, a <code>GreenShip</code> that is in both a <code>GravityWell</code> and a <code>NebulaField</code> may derive some kind of synergy between the generated <code>SpeedEffect</code> and <code>ShieldEffect</code>. In such cases, the synergistic effect is itself an <code>Effect</code> -- for example, there might be a <code>PowerLevelSynergyEffect</code> that results from this interaction. No information other than the set of <code>Effects</code> acting on a <code>Ship</code> is needed to resolve what the final result should be.</p>
<p>You may begin to see a problem emerging here. As a naive first approach, <strong>either every <code>Ship</code> will have to know how to handle every <code>Phenomenon</code>, or every <code>Phenomenon</code> will have to know about every <code>Ship</code></strong>. This is obviously unacceptable, so we would like to move these responsibilities elsewhere. Clearly there's at least one external class here, perhaps a <code>Mediator</code> or <code>Visitor</code> of some sort.</p>
<p>But what's the best way to do that? The ideal solution will probably have these properties:</p>
<ul>
<li>Just as easy to add a new <code>Ship</code> as it is to add a new <code>Phenomenon</code>. </li>
<li>Interactions that produce no effect are the default and don't require additional code to represent. Convention over configuration.</li>
<li>Understands how <code>Effects</code> interact with each other and is capable of managing these interactions to decide what the final result will be.</li>
</ul>
<p>I've already decided what my approach will be, I think, but I'm interested to hear what the best-design consensus is. Where would you start? What avenues would you explore? </p>
<p><hr/>
<hr/></p>
<p><strong>Follow-up update:</strong> Thanks for your responses, everybody. Here's what I wound up doing. My main observation was that the number of different <code>Effects</code> seems to be small relative to the number of possible <code>Phenomena</code> × <code>Ships</code> interactions. That is, although there are many possible <em>combinations</em> of interactions, the number of <em>kinds of results</em> of those interactions is a smaller number.</p>
<p>You can see that, for example, although there are 12 interaction combinations in the table, there are only five <em>kinds</em> of effects: modifications to speed, modifications to power, modifications to shield, invulnerability, death.</p>
<p>I introduced a third class, the <code>InteractionResolver</code>, to determine the result of interactions. It contains a dictionary that maps <code>Ship-Phenomenon</code> pairs to <code>Effects</code> (which are basically a delegate that performs the effect and some metadata). Each <code>Ship</code> is handed an <code>EffectStack</code> corresponding to the <code>Effects</code> it's experiencing when the result of computing the interaction is complete.</p>
<p><code>Ships</code> then use the <code>EffectStack</code> to determine the actual result of the <code>Effects</code> on them, by adding modifiers to their existing attributes and properties.</p>
<p>I like this because:</p>
<ol>
<li>Ships never need to know about Phenomena.</li>
<li>The complexity of the Ship-Phenomena relationship is abstracted into the InteractionResolver.</li>
<li>The details of how to resolve multiple and possibly complex effects is abstracted away by the <code>InteractionResolver</code>. Ships only have to apply the effects as necessary.</li>
<li>This enables additional useful refactorings. For example, the <em>way</em> in which a ship processes effects could be differentiated by making an <code>EffectProcessorStrategy</code>. The default might be to process all effects, but, say, a <code>BossShip</code> might ignore minor effects by having a different <code>EffectProcessorStrategy</code>.</li>
</ol>
| <p>An interesting potential option would be to use a variant of the <a href="http://en.wikipedia.org/wiki/Visitor%5Fpattern" rel="nofollow">Visitor Pattern</a>.</p>
<p>Judith Bishop and R. Nigel Horspool wrote a paper about <a href="http://webhome.cs.uvic.ca/~nigelh/Publications/Tools08.pdf" rel="nofollow">design pattern efficiency</a> in which they explained various variants on the classic visitor pattern using C# 3 features.</p>
<p>In particular, I would take a look at how they work with delegates to handle the visitor pattern. Using a list or stack of delegates could potentally give you an interesting way to handle multiple effects from multiple objects, and be much easier to extend either side of the class hierarchy (add ships or add effects) without huge breaking code changes.</p>
|
Windows Services and shutting down EC2 nodes <p>I've got a fairly simple Windows service running on testbed EC2 nodes right now that basically:</p>
<ul>
<li>Calls a Web Service on a machine in our local data center when the service starts (the service is set to Automatic startup, so it runs when the instance comes online).</li>
<li>Calls another Web Service once a minute as a monitoring heartbeat.</li>
<li>Calls a third Web Service when the service stops.</li>
</ul>
<p>We're using this in our Linux EC2 instances perfectly fine, and the Windows service works fine on startup, heartbeat, and manual stoppage.</p>
<p>The problem is that when terminating the node via ElasticFox, Rightscale, etc. the service never seems to be stopped, or at least, it never makes the Web Service call. Any thoughts?</p>
<p>[Note that this is copied verbatim from my post on the AWS developer forums, but that is super-low traffic compared to SO. Apologies!]</p>
<p><strong>Edit</strong>: Regarding the point about the network going down, I'm also not the most well-versed in Windows services, if I set Netman as a service dependency, would the order of service termination be guaranteed to respect that?</p>
<p>Regarding EBS, the model we've adopted for a similar system running on plain ol' Linux instances treats app servers as ephemeral, so EBS wouldn't benefit us that much. We use Rightscale on top of EC2, which makes hooking into Linux instances shutting down, so we just ship off the instance's logs elsewhere.</p>
<p><strong>Edit #2</strong>: Well, I got a reply from the AWS staff much faster than I expected:</p>
<blockquote>
<p>For windows, terminating through API (which means through elasticfox ,rightscale etc.) is a hard shutdown due to some technical limitations. It means it is like turning off your machine with power button instead of shutdown.</p>
</blockquote>
<p><em>Interesting..</em></p>
| <p>A lot of things happen when Windows shutsdown so my guess is something has already stopped that your web service call needs, first guess would be the network connection.</p>
<p>It's a bit of a tricky one since you can't keep a local log file on the C or D drives to check whether the call is at least ebing attempted since you'll never be able toa ccess them again once the instance has stopped. Do you use an EBS volume with your instances that could hold a log file?</p>
|
Synchronizing a timer to prevent overlap <p>I'm writing a Windows service that runs a variable length activity at intervals (a database scan and update). I need this task to run frequently, but the code to handle isn't safe to run multiple times concurrently.</p>
<p>How can I most simply set up a timer to run the task every 30 seconds while never overlapping executions? (I'm assuming <code>System.Threading.Timer</code> is the correct timer for this job, but could be mistaken).</p>
| <p>I'd use Monitor.TryEnter in your elapsed code:</p>
<pre><code>if (Monitor.TryEnter(lockobj))
{
try
{
// we got the lock, do your work
}
finally
{
Monitor.Exit(lockobj);
}
}
else
{
// another elapsed has the lock
}
</code></pre>
|
SSRS: ASP.NET ReportViewer parameters reset to default when clicking View Report <p>I have a SQL Reporting Services report (SQL 2008 built using Report Builder v2.0) which has a multi select integer parameter (in this case a list of stores).</p>
<p>The default value is <code>0</code> ("All Stores"). The parameter is passed to a stored procedure as a <code>varchar(1024)</code>.</p>
<p>This all works fine in Report Builder or from the Reporting Services website.</p>
<p>However from an ASP.NET website using the <code>ReportViewer</code> component the parameters are reset to the default each time you choose "View Report".</p>
<p>I've tried setting the view to non-asynchronous loading (changes the rendering container?) plus any other setting I could find, without success. Does anyone know a trick to fix this?</p>
| <p>I made a mistake. The <code>ReportViewer</code> control was inside a Master Page. Each time the "View Report" button was clicked it did a postback and reset the session.</p>
<p>I added <code>if (!IsPostBack)</code> to before the report setup method.</p>
|
Using interfaces on abstract classes in C# <p>I'm learning C# coming from C++ and have run into a wall.</p>
<p>I have an abstract class AbstractWidget, an interface IDoesCoolThings, and a class which derives from AbstractWidget called RealWidget:</p>
<pre><code>public interface IDoesCoolThings
{
void DoCool();
}
public abstract class AbstractWidget : IDoesCoolThings
{
void IDoesCoolThings.DoCool()
{
Console.Write("I did something cool.");
}
}
public class RealWidget : AbstractWidget
{
}
</code></pre>
<p>When I instantiate a RealWidget object and call DoCool() on it, the compiler gives me an error saying </p>
<blockquote>
<p>'RealWidget' does not contain a
definition for 'DoCool'</p>
</blockquote>
<p>I can cast RealWidget object to an IDoesCoolThings and then the call will work, but that seems unnecessary and I also lose polymorphism (AbstractWidget.DoCool() will always be called even if i define RealWidget.DoCool()).</p>
<p>I imagine the solution is simple, but I've tried a variety of things and for the life of me can't figure this one out.</p>
| <p>You're running into the issue because you used <strong><a href="http://msdn.microsoft.com/en-us/library/aa288461%28VS.71%29.aspx"><em>explicit interface implementation</em></a></strong> (EII). When a member is explicitly implemented, it can't be accessed through a class instance -- only through an instance of the interface. In your example, that's why you can't call <code>DoCool()</code> unless you cast your instance to <code>IDoesCoolThings</code>.</p>
<p>The solution is to make <code>DoCool()</code> public and remove the explicit interface implementation:</p>
<pre><code>public abstract class AbstractWidget : IDoesCoolThings
{
public void DoCool() // DoCool() is part of the abstract class implementation.
{
Console.Write("I did something cool.");
}
}
// ...
var rw = new RealWidget();
rw.DoCool(); // Works!
</code></pre>
<p>In general, you use EII in two cases:</p>
<ul>
<li>You have a class that must implement two interfaces, each of which contains a member that has an identical name/signature to another member in the other interface. </li>
<li>You want to <em>force</em> clients not to depend on the implementation details of your class, but rather on the interface that's being implemented by your class. (This is considered a good practice by some.)</li>
</ul>
|
Modifying look/behavior of the new Popup control (ChildWindow) in Silverlight 3 <p>I would like to remove grey header of the new Popup control in Silverlight 3.</p>
<p>Any ideas if this is possible? </p>
| <p>Pretty easy, just edit the default ChildWindow style.</p>
<ol>
<li>In Blend 3 create a new Item of type ChildWindow. (Right Click on the Project --> New Item --> Select ChildWindow from the list)</li>
<li>Right click on ChildWindow in the "Objects and Timeline" pane --> Edit Template --> Edit Copy.</li>
<li>Navigate to the element named "Chrome" inside the default template and change the Background to whatever Brush you'd like. </li>
</ol>
|
How can protocol-buffers support serialization/deserialization of std containers? <p>We plan to replace <code>Boost.serialization</code> with protocol-buffers used in distributed system design. How protocol-buffers support complicated data structures such as std containers?</p>
<p>For instance, such a class is required to be serialized/deserialized in our case:</p>
<pre><code>class Foo
{
std::vector< std::pair< unsigned int, std::vector< std::pair< int, int> > > > data;
};
</code></pre>
| <p>Protocol buffers have employ a parser which takes a .proto file and creates appropriate serialization routines. See <a href="http://code.google.com/apis/protocolbuffers/docs/overview.html" rel="nofollow">this</a>.</p>
<p>Update: You can represent a vector of strings as:</p>
<pre><code>message MyCollection {
repeated string str = 1;
}
</code></pre>
<p>in your proto file.</p>
<p>and use:</p>
<pre><code>std::vector<std::string> my_strings;
// add strings to vector MyCollection proto;
vector<string>::iterator e = my_strings.end();
for (vector<string>::iterator i = my_strings.begin();
i != e;
++i) {
*proto.add_str() = *i;
}
</code></pre>
<p>It should be easy to extend for another collection/collection of collections.</p>
|
Conditional comments not loading IE6 specific CSS file <p>I'm trying to override a few CSS selectors that are causing problems in IE6 by using the following code inside the head tag in an HTML file:</p>
<pre><code><!--[if IE 6]
<style type="text/css">
@import ("ie6.css");
</style>
<![endif]-->
</code></pre>
<p>This code comes after the main stylesheet loads, and no other stylesheets get loaded after the conditional comment. For some reason, browsing the site using IE6 doesn't load the IE6 CSS file. I've tried numerous variations on the syntax and I've also tried using a link tag instead of style import, all to no avail. </p>
<p>I do have some JavaScript that dynamically alters some style properties for the same elements that the selectors are for, but I don't think that is the problem because when I just replace the same selectors in the main CSS file, everything works as expected. So it would seem that the IE6 CSS file never loads.</p>
| <p>Actually you only left out the closing bracket for the opening conditional comment tag [if IE 6]> <----</p>
<pre><code><!--[if IE 6]>
IE6 stuff here.
<![endif]-->
</code></pre>
<p>Also, you may want to do the @import with either url("ie6.css"); or just the quotes.</p>
<pre><code>@import url("ie6.css");
@import "ie6.css";
</code></pre>
|
Make 16-bit code work in WinXP or Vista (or alternately how to find Win98 retail licenses?) <p>We have thousands of DOS programs that were all written in the 80s using 16-bit C, comprising over 1,000,000 lines of code. Many of these programs utilize libraries that directly access the screen, drive, etc. (and we don't have the sources for these libraries). Whenever we try to run them in Win2000 or above, even in compatibility mode, we get access violations and blue screens.</p>
<p>Our solution so far has been purchasing Win98SE Retail Boxes and running Win98 in a VMWare session. The problem now is that we can't find enough non-OEM licenses (we last purchased in 2006 and need another 20 or so copies). Our company is extremely careful about licensing, so they have no interest in buying the OEM copies (since we are not a system builder).</p>
<p>Our new 32-bit software won't be ready for 3 years, so unless someone knows where we can buy lots of Win98 retail boxes, I'm stuck trying to figure out how to get 16-bit software with direct system access to run in 2000/XP. Any ideas?</p>
| <p>You could see if they run in DosBox ?</p>
<p><a href="http://www.dosbox.com/" rel="nofollow">http://www.dosbox.com/</a></p>
<p><a href="http://superuser.com/questions/96812/using-a-printer-in-dosbox">Some versions of DosBox actually supports printing</a>.</p>
|
Backup and Recovery Scenario <p>Can anyone show me the step of restore and recovery of below scenario?</p>
<p>I have used the differential backup (cumulative) everyday.</p>
<pre><code>RUN {
RECOVER COPY OF DATABASE WITH TAG "whole_database_copy";
BACKUP INCREMENTAL LEVEL 1 CUMULATIVE FOR RECOVER OF COPY WITH TAG "whole_database_copy" DATABASE;
}
</code></pre>
<p>I have copies of all datafile, all backup sets, all redo log files with all archive logs on different media.</p>
<p>My system has crashed and all of my working database files are lost.</p>
<p>How can I do to recover my database to another server?</p>
<p>Regards,
Sarith</p>
| <p>Contact Oracle support right now.. Unless you can afford to lose this data, don't mess about with listening to what people on forums have to say, now is not the time to experiment.</p>
|
How can I display my SSN id in the ASP web page with PCI standards <p>In my ASP web page I am displaying SSN number </p>
<p>" name ="txtSSNID" size ="20"></p>
<p>The Fortify Developer tool detects this as error. How can I fix this issue.</p>
<p>I need to display the SSN Number but the thing is it should not caught while testing in Fortify developer tool for security violations</p>
| <p>I am not sure exactly what you want? but like Creidt card numbers cant you just show few 'X' and the last few letters?</p>
|
Advantage of using Thread.Start vs QueueUserWorkItem <p>In multithreaded .NET programming, what are the decision criteria for using ThreadPool.QueueUserWorkItem versus starting my own thread via new Thread() and Thread.Start()? </p>
<p>In a server app (let's say, an ASP.NET app or a WCF service) I think the ThreadPool is always there and available. What about in a client app, like a WinForms or WPF app? Is there a cost to spin up the thread pool? If I just want 3 or 4 threads to work for a short period on some computation, is it better to QUWI or to Thread.Start(). </p>
| <p>The ThreadPool is always there, however, there are a finite number of threads allocated to the pool based on the number of processors. For ASP.NET applications, it is generally a bad idea to use Threads unless you really are starting off an Async process and know that there won't be a large number of requests (remember that there are a finite number of threads in the ThreadPool which you share with everything running in your AppDomain and there is a realistic limit on the total number of threads you want to create using new Thread() as well).</p>
<p>For WinForms apps consider using the BackgroundWorker instead of using a Thread or the ThreadPool. It uses the ThreadPool, however, it makes communicating between threads easier on the multi-thread savvy programmer.</p>
<p><strong>Updated</strong></p>
<blockquote>
<p>Avoid using <strong><em>ThreadPool.QueueUserWorkItem</em></strong> as your app pool could disappear at any time. Move this work outside or use WebBackgrounder if you must.</p>
</blockquote>
<p>From <a href="http://www.hanselman.com/blog/ChecklistWhatNOTToDoInASPNET.aspx" rel="nofollow">Hanselman.com - "Checklist: What NOT to do in ASP.NET"</a></p>
|
Cannot Update google adwords account through API (i.e., UpdateAccount()) <p>i'm not able to pro grammatically update the google account using UpdateAccount() method in AccountService . I'm getting exception, when trying to update the address field. can some one let me know . what is the updateable fields in AccountInfo class. if possible with the source code.</p>
| <p>Both primaryAddress and billingAddress fields of AccountInfo are not updateable.</p>
<p>If you are looking an easy way to programmatically manage AdWords account and you are using .NET platform, you should take a look at GemBox.Ppc <a href="http://www.gemboxsoftware.com/Ppc/Overview.htm" rel="nofollow">AdWords API for .NET</a>.</p>
<p>It greatly simplifies management of AdWords accounts.</p>
|
Activerecord - callback after all associated objects are saved <p>I have a model and I would like to store ids of associated objects (denormalize) for performance reasons. I have a method which looks like this:</p>
<pre><code>def cache_ids
self._tag_ids = self.tag_ids
end
</code></pre>
<p>I thought I could just run it on before_save, however there is a problem - some of the associated objects might be new records, and therefore they will not have ids.</p>
<p>Then I switched to after_save, but apparently this callback is also triggered before the transaction is committed, so ids are still not set.</p>
<p>At the moment I ended up with:</p>
<pre><code>def save_with_idcache(*args)
return false unless save_without_idcache(*args)
cache_ids
return save_without_idcache(false)
end
alias_method_chain :save, :idcache
</code></pre>
<p>Which seems to work but doesn't look very elegant.</p>
<p>Is there any better way? Like, a callback after the object and associated objects are all saved?</p>
<p>Maybe I am missing something obvious.</p>
| <p>You might try it in reverse - have the associated objects update their parent's <code>_tag_ids</code> in <code>after_create</code>, <code>after_save</code> (if they are removed from the association and/or added to a new one) and <code>after_destroy</code>. </p>
<p>Whether or not this is a better solution would depend on how many of them there are, how much you're moving them around, and how careful you want to be about dirty attributes.</p>
|
How do I delete a record from a table? <p>How do I delete a record from a table?</p>
<p>For example, the table has two columns: <code>eno</code> and <code>ename</code>. I want to delete one value in ename from the table:</p>
<blockquote>
<p><strong>Eno</strong> <strong>Ename</strong></p>
<p> 1 asha</p>
<p> 2 bimal</p>
</blockquote>
<p>I want to delete the value <code>'bimal'</code>.</p>
| <p>Your question is somewhat ambiguous. </p>
<p>If, as in the title, you want to delete the <em>record</em> containing 'Bimal' then you would write something like:</p>
<pre><code>DELETE FROM [table_name] WHERE Eno = 2
</code></pre>
<p>However if, as the question body implies, you mean you want to keep the <em>record</em> but delete the <em>value</em> 'Bimal' from it, then you would write something like:</p>
<pre><code>UPDATE [table_name] SET Ename = NULL WHERE Eno = 2
</code></pre>
|
Retrieving Device Context from .NET print API <p>I am working on a .NET application to control DataCard Desktop Card printers, and I have stumbled upon a problem. In order to execute Magnetic Stripe and Chip encoding, I have to call a function in a native printer API dll to enable the printers Interactive mode.</p>
<p>I have managed to create the P/Invoke code to call this native function. But the problem is that this method takes the printer Device Context handle as a parameter, and have to be called BEFORE the Gdi32 StartDoc function is called.</p>
<p>In the .NET printing API I do have access to the hDC from the Graphics object. But as far as I can see the Graphics object is only availible AFTER the StartDoc function is invoked.</p>
<p>So my question is if anyone knows a way to retrieve the context before StartDoc is called?</p>
| <p>You can do a <code>OpenPrinter</code> to retrieve a printer handle (<code>HANDLE</code>) and then call <code>CreateDC</code> by passing in this handle to get a printer DC anytime (before <code>StartDoc</code>).</p>
|
Embedding .NET usercontrol in IE8 <p>I have a simple webpage containing a .NET usercontrol embedded using the OBJECT tag. In IE7, the page displays and I can use the usercontrol.</p>
<p>However, in IE8, the usercontrol does not even load.</p>
<p>Any thoughts / ideas? </p>
| <p>This is a change in IE8 due to a vulnerability in assembly loading. See <a href="http://blogs.msdn.com/askie/archive/2009/05/22/net-control-no-longer-loads-in-ie8-in-internet-zone.aspx" rel="nofollow">this post</a> for more details.</p>
<p>The control will load if the site is added to the Trusted Sites list. There is no way to do that from the web, so the users have to do it themselves or you can provide some kind of installer which does it. (See msdn.microsoft.com/en-us/library/ms537181(VS.85).aspx )</p>
<p>Compatibility mode or the X-UA-Compatible meta tag has no effect.</p>
|
How to detect SQL Server Express in WiX installer <p>How do I detect if Sql Server Express is installed and running on a machine in a WiX installer?</p>
<p>I want to check before installing my application and if it's not installed and running, to inform a user that it has to install it first before installing my application.</p>
| <p>Ok, I found by trial and error option that works:</p>
<pre><code><Property Id="SQLSERVER">
<RegistrySearch Id="SQLServer" Root="HKLM" Key="SOFTWARE\Microsoft\Microsoft Sql Server" Type="raw" Name="InstalledInstances"/>
</Property>
</code></pre>
<p>I define a registry search, and then check its value:</p>
<pre><code><Condition Message="You don't have SQL Server installed.">
<![CDATA[SQLSERVER >< SQLEXPRESS]]>
</Condition>
</code></pre>
|
How focus a textbox after using extjs Ext.MessageBox.alert <p>I want to validate my extjs form. When the text field is empty, there should display an alert box and after that our cursor have to focus on the text box. I tried with the coding below. Alert is working fine. but cursor is not focusing. Can you please help me anybody to focus?</p>
<pre><code>if(Ext.get('first').dom.value=='')
{
Ext.MessageBox.alert('Status', 'Enter your First Name!');
document.getElementById("first").focus();
}
</code></pre>
| <p>The <a href="http://extjs.com/deploy/dev/docs/?class=Ext.MessageBox">documentation</a> states that MessageBox is asynchronous:</p>
<blockquote>
<p>Note that the MessageBox is
asynchronous. Unlike a regular
JavaScript alert (which will halt
browser execution), showing a
MessageBox will not cause the code to
stop. For this reason, if you have
code that should only run after some
user feedback from the MessageBox, you
must use a callback function (see the
function parameter for show for more
details).</p>
</blockquote>
<p>So, your focus() is carried out immediately after the call to Ext.MessageBox.alert, not when the user dismisses it: When the user clicks to dismiss the alert, the focus will change again.</p>
<p>You could try using a regular javascript alert() instead, which is synchronous.</p>
|
Is there a standard closure interface that is Serializable? <p>If not, maybe you could tell me why.</p>
<p>I get NotSerializableException when my class is being serialized.</p>
<p>Inside the class I am passing this anonymous class to a method:</p>
<pre><code>new org.apache.commons.collections.Closure() {
...
};
</code></pre>
<p><strong>The question is still unanswered. I want to know if there is a standard Closure interface that implements Serializable</strong></p>
| <p>All references in your class must be of the type Serializable as well, even the Closure type. Is it an interface? It must extend the java.io.Serializable interface.</p>
<p>I.e:</p>
<pre><code>interface Closure extends java.io.Serializable {
...
}
class YourClass implements java.io.Serializable {
private Closure closure;
...
public void setClosure(Closure closure) {
this.closure = closure;
}
}
...
private static void main(String[] args) {
YourClass y = new YourClass();
y.setClosure(new Closure() {
...
});
...
</code></pre>
<p>Edit, clarifications. :)</p>
|
design a stack such that getMinimum( ) should be O(1) <p>This is one of an interview question. You need to design a stack which holds an integer value such that getMinimum() function should return the minimum element in the stack.</p>
<p>For example: consider the below example</p>
<pre>
case #1
5 --> TOP
1
4
6
2
When getMinimum() is called it should return 1, which is the minimum element
in the stack.
case #2
stack.pop()
stack.pop()
Note: Both 5 and 1 are poped out of the stack. So after this, the stack
looks like,
4 --> TOP
6
2
When getMinimum() is called is should return 2 which is the minimum in the
stack.
</pre>
<p><strong>Constriants:</strong></p>
<ol>
<li>getMinimum should return the minimum value in O(1)</li>
<li>Space constraint also has to be considered while designing it and if you use extra space, it should be of constant space.</li>
</ol>
| <p>EDIT: This fails the "constant space" constraint - it basically doubles the space required. I very much doubt that there's a solution which <em>doesn't</em> do that though, without wrecking the runtime complexity somewhere (e.g. making push/pop O(n)). Note that this doesn't change the <em>complexity</em> of the space required, e.g. if you've got a stack with O(n) space requirements, this will still be O(n) just with a different constant factor.</p>
<p><strong>Non-constant-space solution</strong></p>
<p>Keep a "duplicate" stack of "minimum of all values lower in the stack". When you pop the main stack, pop the min stack too. When you push the main stack, push either the new element or the current min, whichever is lower. <code>getMinimum()</code> is then implemented as just <code>minStack.peek()</code>.</p>
<p>So using your example, we'd have:</p>
<pre><code>Real stack Min stack
5 --> TOP 1
1 1
4 2
6 2
2 2
</code></pre>
<p>After popping twice you get:</p>
<pre><code>Real stack Min stack
4 2
6 2
2 2
</code></pre>
<p>Please let me know if this isn't enough information. It's simple when you grok it, but it might take a bit of head-scratching at first :)</p>
<p>(The downside of course is that it doubles the space requirement. Execution time doesn't suffer significantly though - i.e. it's still the same complexity.)</p>
<p>EDIT: There's a variation which is slightly more fiddly, but has better space in general. We still have the min stack, but we only pop from it when the value we pop from the main stack is equal to the one on the min stack. We only <em>push</em> to the min stack when the value being pushed onto the main stack is less than <em>or equal</em> to the current min value. This allows duplicate min values. <code>getMinimum()</code> is still just a peek operation. For example, taking the original version and pushing 1 again, we'd get:</p>
<pre><code>Real stack Min stack
1 --> TOP 1
5 1
1 2
4
6
2
</code></pre>
<p>Popping from the above pops from both stacks because 1 == 1, leaving:</p>
<pre><code>Real stack Min stack
5 --> TOP 1
1 2
4
6
2
</code></pre>
<p>Popping again <em>only</em> pops from the main stack, because 5 > 1:</p>
<pre><code>Real stack Min stack
1 1
4 2
6
2
</code></pre>
<p>Popping again pops both stacks because 1 == 1:</p>
<pre><code>Real stack Min stack
4 2
6
2
</code></pre>
<p>This ends up with the same worst case space complexity (double the original stack) but much better space usage if we rarely get a "new minimum or equal".</p>
<p>EDIT: Here's an implementation of Pete's evil scheme. I haven't tested it thoroughly, but I <em>think</em> it's okay :)</p>
<pre><code>using System.Collections.Generic;
public class FastMinStack<T>
{
private readonly Stack<T> stack = new Stack<T>();
// Could pass this in to the constructor
private readonly IComparer<T> comparer = Comparer<T>.Default;
private T currentMin;
public T Minimum
{
get { return currentMin; }
}
public void Push(T element)
{
if (stack.Count == 0 ||
comparer.Compare(element, currentMin) <= 0)
{
stack.Push(currentMin);
stack.Push(element);
currentMin = element;
}
else
{
stack.Push(element);
}
}
public T Pop()
{
T ret = stack.Pop();
if (comparer.Compare(ret, currentMin) == 0)
{
currentMin = stack.Pop();
}
return ret;
}
}
</code></pre>
|
Implementing run-length encoding <p>I've written a program to perform run length encoding.
In typical scenario if the text is</p>
<pre><code>AAAAAABBCDEEEEGGHJ
</code></pre>
<p>run length encoding will make it</p>
<pre><code>A6B2C1D1E4G2H1J1
</code></pre>
<p>but it was adding extra 1 for each non repeating character. Since i'm compressing BMP files with it, i went with an idea of placing a marker "$" to signify the occurance of a repeating character, (assuming that image files have huge amount of repeating text).</p>
<p>So it'd look like</p>
<pre><code>$A6$B2CD$E4$G2HJ
</code></pre>
<p>For the current example it's length is the same, but there's a noticable difference for BMP files. Now my problem is in decoding. It so happens some BMP Files have the pattern <code>$<char><num></code> i.e. <code>$I9</code> in the original file, so in the compressed file also i'd contain the same text. <code>$I9</code>, however upon decoding it'd treat it as a repeating I which repeats 9 times! So it produces wrong output. What i want to know is which symbol can i use to mark the start of a repeating character (run) so that it doesn't conflict with the original source.</p>
| <p>Why don't you encode each <code>$</code> in the original file as <code>$$</code> in the compressed file?</p>
<p>And/or use some other character instead of <code>$</code> - one that is not used much in bmp files.</p>
<p>Also note that the BMP format has RLE compression 'built-in' - look <a href="http://www.fileformat.info/format/bmp/egff.htm">here</a>, near the bottom of the page - under "Image Data and Compression". </p>
<p>I don't know what you're using your program for, or if it's just for learning, but if you used the "official" bmp method, your compressed images wouldn't need decompression before viewing.</p>
|
Flash ad network for non-games <p>I'm looking for a flash ad network which serves preloader ads for my flash application, just like <a href="http://www.mochiads.com" rel="nofollow">MochiAds</a>, <em>except</em> that my flash apps are, strictly speaking, not games, and therefore are not eligible for sign-up at MochiAds. Is there a similar network which offers me such a service?</p>
| <p>The NewGrounds API is used for anything posted in their Portal, be it apps, games or cartoons.</p>
|
Office 2007 Style UI Ribbons: DevExpress or TMS? <p>Who provides the better solution for this particular component?</p>
| <p>We have been using both. As I see it, each solution has it's pro and contra. </p>
<p><strong>DevExpress</strong></p>
<ol>
<li>Responsive (as in fast) components.</li>
<li>Adheres to the Microsoft standard.</li>
<li>Clean code.</li>
<li>Very good support</li>
<li>Expensive.</li>
</ol>
<p><strong>TMS</strong></p>
<ol>
<li>Not as snappy (as in fast) as DevExpress. </li>
<li>Looking at the code, cleaning-up things wouldn't hurt.</li>
<li>Very good support.</li>
<li>Inexpensive.</li>
</ol>
<p>In a nutshell, TMS is always very fast in releasing new components (they had a Ribbon months before DevExpress released theirs) but in my opinion at the expense of code quality.<br />
We always have been pleased with both packages. For our latest projects, we are switching to DevExpress though.</p>
|
Is there a way to override class variables in Java? <pre><code>class Dad
{
protected static String me = "dad";
public void printMe()
{
System.out.println(me);
}
}
class Son extends Dad
{
protected static String me = "son";
}
public void doIt()
{
new Son().printMe();
}
</code></pre>
<p>The function doIt will print "dad". Is there a way to make it print "son"?</p>
| <p>In short, no, there is no way to override a class variable. </p>
<p>You do not override class variables in Java you hide them. Overriding is for instance methods. Hiding is different from overriding. </p>
<p>In the example you've given, by declaring the class variable with the name 'me' in class Son you hide the class variable it would have inherited from its superclass Dad with the same name 'me'. Hiding a variable in this way does not affect the value of the class variable 'me' in the superclass Dad.</p>
<p>For the second part of your question, of how to make it print "son", I'd set the value via the constructor. Although the code below departs from your original question quite a lot, I would write it something like this;</p>
<pre><code>public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public void printName() {
System.out.println(name);
}
}
</code></pre>
<p>The JLS gives a lot more detail on hiding in section <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3">8.3 - Field Declarations</a> </p>
|
Finding a legacy firebird/Interbase database password <p>I have a customer that has an old non-existant application; he had a problem with the company that made the application and they won't disclose his database password. He realized that he signed a contract (back then) where it said that he was sort of "renting" the application and they had no right to disclose anything. This customer found out that he's not the only one with the same problem with that company. He's a Dentist and other dentists with the same old application experienced the same problems when trying to buy a new software and attempted to migrate their patients to the new system.</p>
<p>In either case, he wants to open his little firebird database, so we can at least extract some data to our SQL Servers. I have tried with the default 'masterkey' (which is, in fact, 'masterke' due to the 8 char limit) to no avail. </p>
<p>Now I know he could go legal and try to force the company to release his information, but I want to do it the short way. Does anybody know an app that can brute force/crack a legacy Firebird password?</p>
<p>Thanks.</p>
<p>EDIT: The legacy software is "STOMA-W", I cannot even find it on Internet. They are located in Asturias, Spain. </p>
| <p>Firebird does not (yet) store passwords inside the database file.<br />
With this in mind, move the database file to another server where the sysdba password is known. </p>
|
Encrypted data size using RSA encryption (RSACryptoServiceProvider) <p>I need to use some encryption mechanism in one of the project I am working on. I was exploring RSA encryption and wrote some sample programs to learn.</p>
<p>I understand that block size of RSA encryption is 16 bytes. So I gave the string "12345678" as input to below function:</p>
<pre>
public static string Encrypt (string input) {
var byteConverter = new UnicodeEncoding ();
RSACryptoServiceProvider cruptoEngine = new RSACryptoServiceProvider();
byte[] output = cruptoEngine.Encrypt (byteConverter.GetBytes (input), false);
return BytesToString (output); //BytesToString () converts the bytes to hex string
}
</pre>
<p>Now the encrypted string that I get is of 128 bytes (256 hex characters). This string is too big for me. I was kind of hoping that I would get 16 bytes of encrypted data if I give 16 bytes of plain data. Am I doing something wrong? Is this what is supposed to happen? Can I somehow shorten encrypted data?</p>
| <p>You are mistaken. RSA is not a block cipher, so you cannot really talk about the block size of it.</p>
<p>The output of a RSA encryption will have the same length as the RSA modulus. You have not indicated any RSA key in your code, so the runtime will (as far as I recall) use a default key. That key apparently has a 1024 bit modulus, which explains the output length.</p>
<p>You might want to look into AES encryption instead. For many reasons you should normally only use RSA to encrypt a key and then use AES or a similar symmetric cipher algorithm to encrypt your actual text.</p>
<p>AES is a block cipher with block size 16 bytes, so that will (depending on which padding you use and how you transport your initialization vector) encrypt 16 bytes of plain data to 16 bytes of encrypted data.</p>
|
UIAlertView inside an NSOperation is not modal in iPhone <p>So I am trying to create a check that tries to connect to the WWW. when it fails it needs to then retry several times before the application gives up and quits. Each time it retries the user is propted with an UIAlertView with the options to Retry or Cancel.</p>
<p>So here is the problem.</p>
<p>I have a chain of actions in an NSOperationQueue, all the operations should fail with no connection. I"m using the NSoperation Queue so that the UI dosn't lock and the data is being processed in the background.</p>
<p>inside an NSInvocationOperation my method will hit [AlertView show], however this is not truly modal.</p>
<p>My operation then returns and continues through the chain of NSOperations, as there seems to be no way to return them with an Error value to stop additional processing. Eventually the UI catches up, displays the Modal AlertView, but i have no context of what has happened.</p>
<p>I am sure this is a common requirement. any ideas how to achieve this?</p>
| <p>If I understand you correctly, you want a modal version of UIAlertView, but only modal within the calling thread/NSOperation? A few problems with this: </p>
<ul>
<li>You should probably only call interface operations from the main thread (easily addressed using performSelectorOnMainThread:)</li>
<li>Modal dialogs are not really part of the OS; you'll need to address this programatically.</li>
</ul>
|
Help with jQuery UI dialog <p>I am using jQuery UI.Dialog. I'm having a small problem, when I click the link to show dialog box the text from #Test disappears and the modal overlay is shown but the actual modal box is not displayed.</p>
<p>Using FireBug the dialog box is created but has Display:None so is not shown. Also, if I change this in firebug to Display:Block the dialog is shown but it is on the left hand side of my page... any suggestions?</p>
<p>My code is very simple:</p>
<pre><code><head>
<link href="Vader/jquery-ui-1.7.1.custom.css" rel="stylesheet" type="text/css">
<script src="javascripts/jquery.js" type="text/javascript"></script>
<script src="javascripts/ui.core.js" type="text/javascript"></script>
<script src="javascripts/ui.draggable.js" type="text/javascript"></script>
<script src="javascripts/ui.resizable.js" type="text/javascript"></script>
<script src="javascripts/ui.dialog.js" type="text/javascript"></script>
<script type='text/javascript'>
$(function() {
$("a").click(function(){
$('#Test').css('display','inline');
$("#Test").dialog({modal: true});
});
});
</script>
</head>
<body>
<a href="#">Test</a>
<div id="Test" title="Test Title">Bla bla bla</div>
</body>
</code></pre>
| <p>You might want to add to the click is e.preventDefault(); so it doesn't try to load the # which may refresh the page. </p>
<pre><code> $("a").click(function(e){
e.preventDefault();
$('#Test').css('display','inline');
$("#Test").dialog({modal: true});
});
</code></pre>
|
Finding the current active language on windows <p>What are the possible solutions for finding the current active language which appears on the Windows language bar ? </p>
| <p><code>CultureInfo.CurrentCulture</code>. This has information on the language and culture. If you just want the language name, try <code>CultureInfo.CurrentCulture.ThreeLetterISOLanguageName</code>.</p>
|
Why should member variables be initialized in constructors? <p>When I first started working with object-oriented programming languages, I was taught the following rule:</p>
<blockquote>
<p>When declaring a field in a class, don't initialize it yet. Do that in the constructor.</p>
</blockquote>
<p>An example in C#:</p>
<pre class="lang-cs prettyprint-override"><code>public class Test
{
private List<String> l;
public Test()
{
l = new List<String>();
}
}
</code></pre>
<p>But when someone recently asked me why to do that, I couldn't come up with a reason.
I'm not really familiar with the internal workings of C# (or other programming languages, for that matter, as I believe this can be done in all OO languages).</p>
<p>So why <em>is</em> this done? Is it security? Properties?</p>
| <ul>
<li><p>If you have multiple constructors, you might want to initialize a field to different values</p></li>
<li><p>When you initialize the field in the constructor, there can be no confusion over when exactly it is initialized in regard to the rest of the constructor. This may seem trivial with a single class, but not so much when you have an inheritance hierarchy with constructor code running at each level and accessing superclass fields.</p></li>
</ul>
|
Optimize jQuery code <p>I've written this jQuery code that fades in a overlay with some links over an image. What i found out is that it is painfully slow when I add like 10 of these images. I would really appreciate some tips and tricks on how to make this code faster.</p>
<p>If you have some tips for my HTML and CSS that would be great too ;)</p>
<p>jQuery code</p>
<pre><code>$(document).ready(function() {
var div = $(".thumb").find("div");
div.fadeTo(0, 0);
div.css("display","block");
$(".thumb").hover(
function () {
$(this).children(".download").fadeTo("fast", 1);
$(this).children(".hud").fadeTo("fast", 0.7);
},
function () {
div.fadeTo("fast", 0);
}
);
});
</code></pre>
<p>All the code</p>
<pre><code><style type="text/css">
a:active {
outline:none;
}
:focus {
-moz-outline-style:none;
}
img {
border: none;
}
#backgrounds {
font: 82.5% "Lucida Grande", Lucida, Verdana, sans-serif;
margin: 50px 0 0 0;
padding: 0;
width: 585px;
}
.thumb {
margin: 5px;
position: relative;
float: left;
}
.thumb img {
background: #fff;
border: solid 1px #ccc;
padding: 4px;
}
.thumb div {
display: none;
}
.thumb .download {
color: #fff;
position: absolute;
top: 0;
left: 0;
z-index: 999;
padding: 0 10px;
}
.thumb .download h3 {
font-size: 14px;
margin-bottom: 10px;
margin-top: 13px;
text-align: center;
}
.thumb .download a {
font-size: 11px;
color: #fff;
text-decoration: none;
font-weight: bold;
line-height: 16px;
}
.thumb .download a:hover {
text-decoration: underline;
}
.thumb .download .left, .thumb .download .right {
width: 44%;
margin: 0;
padding: 4px;
}
.thumb .download .left {
float: left;
text-align: right;
}
.thumb .download .right {
float: right;
text-align: left;
}
.thumb img, .thumb .hud {
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
.thumb .hud {
width: 100%;
height: 110px;
position: absolute;
top: 0;
left: 0;
background: #000;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var div = $(".thumb").find("div");
div.fadeTo(0, 0);
div.css("display","block");
$(".thumb").hover(
function () {
$(this).children(".download").fadeTo("fast", 1);
$(this).children(".hud").fadeTo("fast", 0.7);
},
function () {
div.fadeTo("fast", 0);
}
);
});
</script>
<div id="backgrounds">
<div class="thumb">
<div class="download">
<h3>Download wallpaper</h3>
<p class="left">
<a href="1024x768.jpg">1024x768</a>
<a href="1280x800.jpg">1280x800</a>
<a href="1280x1024.jpg">1280x1024</a>
</p>
<p class="right">
<a href="1440x900.jpg">1440x900</a>
<a href="1680x1050.jpg">1680x1050</a>
<a href="1920x1200.jpg">1920x1200</a>
</p>
</div>
<div class="hud"></div>
<img alt="image" src="thumb.jpg"/>
</div>
</div>
</code></pre>
| <p>I got it to respond a little better by simply changing the following within the hover(..):</p>
<pre><code> function () {
$(".download", this).fadeTo("fast", 1);
$(".hud", this).fadeTo("fast", 0.7);
},
function () {
$(".download, .hud", this).fadeTo("fast", 0);
}
</code></pre>
<p>The biggest difference comes from only applying the hoverout effect to the event target, no need to reapply to all your divs on the page.</p>
|
Run multiple commands in one ExecuteScalar in Oracle <p>I have a batch of sql statements such as ...</p>
<p>insert into.... ;
insert into.... ;
delete .........;</p>
<p>etc</p>
<p>When i try to execute them against oracle it gives me <a href="http://ora-00911.ora-code.com/">this</a> error (ORA-00911 Invalid Character)</p>
<p>now i can understand that this is because of the semicolon between the statements, i tried this on SQL Server and it worked but in Oracle no luck so far.</p>
<p>Is there a way to run multiple statements against oracle by using the ExecuteScalar or some other function?</p>
<p><hr /></p>
<p><strong>DUPLICATE</strong>: <a href="http://stackoverflow.com/questions/528676/how-can-i-execute-multiple-oracle-sql-statements-with-net">http://stackoverflow.com/questions/528676/how-can-i-execute-multiple-oracle-sql-statements-with-net</a></p>
| <p>Try wrapping with a <code>BEGIN..END</code></p>
<pre><code>BEGIN insert into.... ; insert into.... ; delete .........; END;
</code></pre>
|
LINQ Conflict Detection: Setting UpdateCheck attribute <p>I've been reading up on LINQ lately to start implementing it, and there's a particular thing as to how it generates UPDATE queries that bothers me.</p>
<p>Creating the entities code automatically using SQLMetal or the Object Relational Designer, apparently all fields for all tables will get attribute <strong>UpdateCheck.Always</strong>, which means that for every UPDATE and DELETE query, i'll get SQL statement like this:</p>
<pre><code>UPDATE table SET a = 'a' WHERE a='x' AND b='x' ... AND z='x', ad infinitum
</code></pre>
<p>Now, call me a purist, but this seems EXTREMELY inefficient to me, and it feels like a bad idea anyway, even if it weren't inefficient. I know the fetch will be done by the clustered primary key, so that's not slow, but SQL still needs to check every field after that to make sure it matches.</p>
<p>Granted, in some very sensitive applications something like this can be useful, but for the typical web app (think Stack Overflow), it seems like <strong>UpdateCheck.WhenChanged</strong> would be a more appropriate default, and I'd personally prefer <strong>UpdateCheck.Never</strong>, since LINQ will only update the actual fields that changed, not all fields, and in most real cases, the second person editing something wins anyway. </p>
<p>It does mean that if two people manage to edit the same field of the same row in the small time between reading that row and firing the UPDATE, then the conflict that would be found won't be fired. But in reality that's a very rare case. The one thing we may want to guard against when two people change the same thing won't be caught by this, because they won't click Submit at the exact same time anyway, so there will be no conflict at the time the second DataContext reads and updates the record (unless the DataContext is left open and stored in Session when the page is shown, or some other seriously bad idea like that). </p>
<p>However, as rare as the case is, i'd really like to not be getting exceptions in my code every now and then if this happens.</p>
<p>So my first question is, am I wrong in believing this? (again, for "typical" web apps, not for banking applications)
Am I missing some reason why having UpdateCheck.Always as default is a sane idea?</p>
<p>My second question is, can I change this civilizedly? Is there a way to tell SQLMetal or the ORD which UpdateCheck attribute to set?<br />
I'm trying to avoid the situation where I have to remember to run a tool I'll have to make that'll take some regexes and edit all the attributes in the file directly, because it's evident that at some point we'll run SQLMetal after an update to the DB, we won't run this tool, and all our code will break in very subtle ways that we probably won't find while testing in dev.</p>
<p>Any suggestions?<br />
War stories are more than welcome, i'd love to learn from other people's experiences on this.</p>
<p>Thank you very much!</p>
| <p>Well, to answer the first question - I agree with you. I'm not a big fan of this "built in" optimistic concurrency, especially if you have timestamp columns or any fields which are not guaranteed to be the same after an update occurs.</p>
<p>To address the second question - I don't know of any way to override SqlMetal's default approach (UpdateCheck = Always), we ended up writing a tool which sets UpdateCheck = Never for appropriate columns. We're using a batch file to call SqlMetal and afterwards running the tool).</p>
<p>Oh, while I think of it - it was also a treat to find that SqlMetal also models relationships to set a foreign key to null instead of "Delete On Null" (for join tables in particular). We had to use the same post-generation tool to set these appropriately too.</p>
|
What is the meaning of the default build qualities provided by TFS? <p>There is this set of default build qualities:</p>
<ul>
<li>Initial Test Passed</li>
<li>Lab Test Passed</li>
<li>Ready for Deployment</li>
<li>Ready for Initial Test</li>
<li>Rejected</li>
<li>Released</li>
<li>UAT Passed</li>
<li>Under Investigation</li>
</ul>
<p>I'm not really sure about the meaning of each entry. I lack experience in this area (and additionally, i'm not a native speaker). Is there an explanation of these values somewhere? I'm also interested in related ressources, please feel free to add links.</p>
| <p>Those are the default build qualities provided with TFS. They probably won't mean anything to you unless your organization's release process includes steps that would correspond to those qualities.</p>
<p>Resources that might help:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms181734%28VS.80%29.aspx" rel="nofollow">How to: Set Build Quality</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms181735%28VS.80%29.aspx" rel="nofollow">How to: Create Build Quality States</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms181730%28VS.80%29.aspx" rel="nofollow">Understanding the Team Foundation Build Browser</a></li>
</ul>
|
Tips on speeding up a SqlDataSource? <p>I have two SqlDataSource controls on a page. One loads high level data and the other loads more details based on which high level item you choose. It is a part of a large search that has over 900,000 records and I am looking for ways to speed it up. Whether it is options I can add onto the SqlDataSource, things I can do to the sql query, or use an alternative such as an ObjectDataSource.</p>
<p>I changed the DataSourceMode to DataReader because I heard it was faster and uses less memory. I also noticed that the paging is really slow.</p>
<p>I am doing the following from my this website, <a href="http://mosesofegypt.net/post/2008/02/Building-a-grouping-Grid-with-GridView-and-ASPNET-AJAX-toolkit-CollapsiblePanel.aspx" rel="nofollow">http://mosesofegypt.net/post/2008/02/Building-a-grouping-Grid-with-GridView-and-ASPNET-AJAX-toolkit-CollapsiblePanel.aspx</a>, but obviously with my data which is over 900,000 records and I am unsure how I can add paging to the second gridview, because right now, it is only on the top-level gridview</p>
| <p>I don't think your data source control itself would need to be the target for any optimizations. It is only going to work with the data that you get from it (meaning you should optimize your SQL) or the data put into it before sending it off to SQL (meaning you should optimize your application code).</p>
|
URL Rewriter.NET web.config node issue <p>I'm using <a href="http://urlrewriter.net/" rel="nofollow">URL Rewriter.NET</a> (which I'm liking a lot, by comparison to URL Rewriting.NET - more versitile it seems, don't get me wrong, I like URL Rewriting.NET, but it didn't seem to satisfy the need, given what I know of the tool). I'm trying to use the <a href="http://urlrewriter.net/index.php/support/reference/default-documents" rel="nofollow">default-documents</a> node to redefine the default documents for the site. I've tried adding it to the rewriter node, but I get a web.config error</p>
<pre><code>Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: The element 'default-documents' is not allowed.
Source Error:
Line 187:
Line 188: <rewriter>
Line 189: <default-documents>
Line 190: <document>default.aspx</document>
Line 191: <document>index.aspx</document>
</code></pre>
<p>Has anyone used this tool in the past, and does anyone know where to put this node (or proper usage)?</p>
<p>EDIT:</p>
<p>I tried the suggestion below, but it didn't seem to work quite right. Here is what is in my extra config file (this is the only contents in the config file)</p>
<pre><code><rewriter>
<rewrite url="^(/.+(\.gif|\.png|\.jpg|\.ico|\.pdf|\.css|\.js)(\?.+)?)$" to="$1" processing="stop" />
<default-documents>
<document>default.aspx</document>
<document>index.aspx</document>
</default-documents>
</rewriter>
</code></pre>
| <p>I've used urlrewriter before, and had some problems with actually setting a default document as well. However, eventually we got it (and other minor annoyances) to work by moving the urlrewriter config to different config file than web.config.</p>
<pre><code><rewriter configSource="urlrewriter.config"/>
</code></pre>
<p>Remember that you also have to disable default documents in IIS for the urlrewriter to work correctly. That caused a bunch of annoying problems as well.</p>
<p>EDIT: Don't forget to add this line to your config sections in web.config</p>
<pre><code><section name="rewriter" requirePermission="false" type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter"/>
</code></pre>
<p>Hope this helps.</p>
|
Asp.Net User Control Event Wireup from aspx file <p>I've got a user control that has an event that I can subscribe to. This works (ignore syntax):</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
ucControl.Event += new Event(ucControl_Event);
}
</code></pre>
<p>but if I removed this line and put the event wire up in my aspx page, it doesn't work. Ex:</p>
<pre><code><uc1:ucControl id="uc_Control1" runat="server" Event="ucControl_Event" />
</code></pre>
<p>I get compilation error when I try it without the ucControl.Event += method.</p>
<p>The error is that the page does not contain a definition for "ucControl_Event" when its obvious that it does.</p>
<p>How do I match my code behind event with the aspx file?</p>
| <p>What's the visibility of your event handler? If it's private then approach 1 works, approach 2 doesn't. If it's protected or public, both work.</p>
|
How do I install an ASP.Net MVC application on IIS 7 using Wix? <p>For IIS6 I can use the IIS helpers in Wix to install a web application like this:</p>
<pre><code><iis:WebAppPool
Id="AP_MyApp"
Name="My Application Pool"
Identity="networkService" />
<iis:WebApplication
Id="WA_MyApp"
Name="MyApp"
WebAppPool="AP_MyApp">
<iis:WebApplicationExtension
CheckPath="no"
Executable="[NETFRAMEWORK20INSTALLROOTDIR]aspnet_isapi.dll"
Verbs="GET,HEAD,POST"/>
</iis:WebApplication>
</code></pre>
<p>Unfortunately, this doesn't work for IIS7. We don't want to use the aspnet_isapi.dll mechanism, and instead want the integrated pipeline to handle the request routing. The app pool created by this script is in Classic mode not Integrated mode so none of the handlers get run correctly.</p>
<p>How can I correctly install an MVC app on IIS 7?</p>
| <p>I personally recommend using AppCmd.exe (matthewthurlow's first bullet) because you don't have to count on the legacy management components being installed, or risk modifying the configuration XML manually.</p>
<p>If you are not comfortable with AppCmd, Mike Volodarsky has a great article on <a href="http://learn.iis.net/page.aspx/114/getting-started-with-appcmdexe/" rel="nofollow">Getting Started with AppCmd.exe</a>, and the Microsoft <a href="http://www.iis.net/ConfigReference" rel="nofollow">IIS Configuration Reference</a> is excellent, offering UI, Code and AppCmd examples for modifying each of the configuration items (e.g. <a href="http://www.iis.net/ConfigReference/system.applicationHost/applicationPools" rel="nofollow">Application Pools</a> ). The <a href="http://www.iis.net/extensions/AdministrationPack" rel="nofollow">IIS7 Administration Pack</a> also includes a Configuration Editor that allows you to <a href="http://learn.iis.net/page.aspx/417/using-configuration-editor-generate-scripts/" rel="nofollow">generate AppCmd scripts</a> from any existing configuration.</p>
<p>To integrate AppCmd into WiX, you need to create and schedule two custom actions for each command. There is general information in the WiX v3 manual <a href="http://wix.sourceforge.net/manual-wix3/qtexec.htm" rel="nofollow">documenting this procedure</a>, and I've included a concrete example below.</p>
<p>First, you need to set up an immediate action to store the command line in a property:</p>
<pre><code><CustomAction
Id="CreateAppPool_Cmd"
Property="CreateAppPool"
Execute="immediate"
Value="&quot;[WindowsFolder]system32\inetsrv\APPCMD.EXE&quot; add apppool /name:&quot;[APP_POOL_NAME]&quot;" />
</code></pre>
<p>Next you set up a deferred action which references this property:</p>
<pre><code><CustomAction
Id="CreateAppPool"
BinaryKey="WixCA"
DllEntry="CAQuietExec"
Execute="deferred"
Return="ignore"
Impersonate="no"/>
</code></pre>
<p>And finally, you need to schedule these. The immediate action that sets the properties seem to work well after InstallFinalize, and the deferred action works after InstallFiles. I haven't got as far as figuring out rollback actions yet.</p>
<p>MapGuide Open Source does this method extensively; you can see the CA scheduling in our <a href="http://trac.osgeo.org/mapguide/browser/trunk/Installer/Installers/MapGuide/MapGuide.wxs#L444" rel="nofollow">MapGuide.wxs</a> file, and the CA definition in our <a href="http://trac.osgeo.org/mapguide/browser/trunk/Installer/Libraries/MapGuide%20Web%20Extensions/IIS7.wxs#L9" rel="nofollow">IIS7.wxs</a> file.</p>
|
Making an entire row clickable in a gridview <p>I have a gridview and I need to make an event fire when a row is clicked.</p>
<p>Is there an existing GridView event I need to bind to to make this happen?</p>
| <p>Here's something I prepared earlier:</p>
<pre><code>
public class RowClickableGridView : GridView
{
public Style HoverRowStyle
{
get { return ViewState["HoverRowStyle"] as Style; }
set { ViewState["HoverRowStyle"] = value; }
}
public bool EnableRowClickSelection
{
get { return ViewState["EnableRowClickSelection"] as bool? ?? true; }
set { ViewState["EnableRowClickSelection"] = value; }
}
public string RowClickCommand
{
get { return ViewState["RowClickCommand"] as string ?? "Select"; }
set { ViewState["RowClickCommand"] = value; }
}
public string RowToolTip
{
get
{
if (!RowToolTipSet) return string.Format("Click to {0} row", RowClickCommand.ToLowerInvariant());
return ViewState["RowToolTip"] as string;
}
set
{
ViewState["RowToolTip"] = value;
RowToolTipSet = true;
}
}
private bool RowToolTipSet
{
get { return ViewState["RowToolTipSet"] as bool? ?? false; }
set { ViewState["RowToolTipSet"] = value; }
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
foreach (GridViewRow row in Rows)
{
if (row.RowType != DataControlRowType.DataRow) continue;
if (EnableRowClickSelection && row.RowIndex != SelectedIndex && row.RowIndex != EditIndex)
{
if (string.IsNullOrEmpty(row.ToolTip)) row.ToolTip = RowToolTip;
row.Style[HtmlTextWriterStyle.Cursor] = "pointer";
PostBackOptions postBackOptions = new PostBackOptions(this,
string.Format("{0}${1}",
RowClickCommand,
row.RowIndex));
postBackOptions.PerformValidation = true;
row.Attributes["onclick"] = Page.ClientScript.GetPostBackEventReference(postBackOptions);
foreach (TableCell cell in row.Cells)
{
foreach (Control control in cell.Controls)
{
const string clientClick = "event.cancelBubble = true;{0}";
WebControl webControl = control as WebControl;
if (webControl == null) continue;
webControl.Style[HtmlTextWriterStyle.Cursor] = "Auto";
Button button = webControl as Button;
if (button != null)
{
button.OnClientClick = string.Format(clientClick, button.OnClientClick);
continue;
}
ImageButton imageButton = webControl as ImageButton;
if (imageButton != null)
{
imageButton.OnClientClick = string.Format(clientClick, imageButton.OnClientClick);
continue;
}
LinkButton linkButton = webControl as LinkButton;
if (linkButton != null)
{
linkButton.OnClientClick = string.Format(clientClick, linkButton.OnClientClick);
continue;
}
webControl.Attributes["onclick"] = string.Format(clientClick, string.Empty);
}
}
}
if (HoverRowStyle == null) continue;
if (row.RowIndex != SelectedIndex && row.RowIndex != EditIndex)
{
row.Attributes["onmouseover"] = string.Format("this.className='{0}';", HoverRowStyle.CssClass);
row.Attributes["onmouseout"] = string.Format("this.className='{0}';",
row.RowIndex%2 == 0
? RowStyle.CssClass
: AlternatingRowStyle.CssClass);
}
else
{
row.Attributes.Remove("onmouseover");
row.Attributes.Remove("onmouseout");
}
}
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
foreach (GridViewRow row in Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Page.ClientScript.RegisterForEventValidation(row.ClientID);
}
}
}
}
</code>
</pre>
<p>You then hook into the standard row command events...</p>
|
borrowing costructors and prototype chain <p>in many books and online tutorial there are examples on passing data to a super-class
constructor via a borrowing method pattern:</p>
<pre><code>var Parent = function(name)
{
this.name = name;
this.my_parent = "parent_property";
this.go = function()
{
alert("GO")
}
}
var Child = function(name)
{
this.name = name;
this.my_child = "child_property";
Parent.call(this);
alert(this.hasOwnProperty("go")) // HERE TRUE!!!
}
var ChildChild = function(name)
{
this.name = name;
this.su = function(){}
}
// PSEUDO CLASSICAL ECMA STANDARD
Child.prototype = new Parent("PARENT");
ChildChild.prototype = new Child("CHILD");
var c = new ChildChild("CHILDCHILD");
</code></pre>
<p>now my question is: is this correct? in that pattern the properties of the super-class
are copied into THIS but in a OOP system I think that those properties must be in its
super-class. Now BORROWING constructor is only another pattern to make a sort of inheritance so I could not use prototype and so all the chain superclass properties are
into the last child class...but I don't think it's efficient.</p>
<p>So, at end, how can I pass data to a super-class without that pattern?</p>
<p>Thanks</p>
| <p>By calling .call() you don't inherit in the classical sense of the word instead you tell Child to apply Parents prototype onto itself and thus Child.prototype has cloned properties and methods from Parent. This has no issues performance wise whatsoever though so abandoning prototype for efficiency reasons is not a valid reason. </p>
<p>If I can be honest I think enforcing OO paradigms onto javascript is the biggest mistake a javascript developer can make. Much like having to learn to deal with immutability in functional programming trying to make javascript behave like classical OO will only work against you in the long run. </p>
<p>It doesn't answer your question but there's tons of different ways to apply <a href="http://www.google.nl/search?rlz=1C1GGLS%5FenNL311NL317&sourceid=chrome&ie=UTF-8&q=javascript%2Bsuper%2BOO" rel="nofollow">a super functionality to javascript</a> none of which I can recommend though as there's no definitive version that doesn't come with a downside somewhere down the line.</p>
|
log4cpp gives `unresolved external` errors <p>I'm trying to make work the library and run the tests provided with the latest version of log4cpp on Borland Codegear 2007, in which it's included a bpr project for Borland C++ Builder 5, which is meant to be able to build and run the different tests. The problem is that I'm trying to open this project with the 2007 version, which has to carry out a project conversion. I was getting weird 'unresolved external' errors. Then I've tried to build the project myself without converting anything, but got stuck in the same point. </p>
<p>I'm trying to run the following test :</p>
<pre><code>#include <stdio.h>
#include "log4cpp/Portability.hh"
#ifdef LOG4CPP_HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <iostream>
#include "log4cpp/Category.hh"
#include "log4cpp/Appender.hh"
#include "log4cpp/FileAppender.hh"
#include "log4cpp/OstreamAppender.hh"
#ifdef LOG4CPP_HAVE_SYSLOG
#include "log4cpp/SyslogAppender.hh"
#endif
#include "log4cpp/Layout.hh"
#include "log4cpp/BasicLayout.hh"
#include "log4cpp/Priority.hh"
#include "log4cpp/NDC.hh"
int main(int argc, char** argv) {
log4cpp::Appender* appender;
#ifdef LOG4CPP_HAVE_SYSLOG
log4cpp::SyslogAppender* syslogAppender;
syslogAppender = new log4cpp::SyslogAppender("syslog", "log4cpp");
#else
log4cpp::Appender* syslogAppender;
syslogAppender = new log4cpp::OstreamAppender("syslogdummy", &std::cout);
#endif
if (argc < 2) {
appender = new log4cpp::OstreamAppender("default", &std::cout);
} else {
appender = new log4cpp::FileAppender("default", argv[1]);
}
syslogAppender->setLayout(new log4cpp::BasicLayout());
appender->setLayout(new log4cpp::BasicLayout());
log4cpp::Category& root = log4cpp::Category::getRoot();
root.addAppender(syslogAppender);
root.setPriority(log4cpp::Priority::ERROR);
log4cpp::Category& sub1 = log4cpp::Category::getInstance(std::string("sub1"));
sub1.addAppender(appender);
log4cpp::Category& sub2 = log4cpp::Category::getInstance(std::string("sub1.sub2"));
log4cpp::NDC::push(std::string("ndc1"));
std::cout << " root prio = " << root.getPriority() << std::endl;
std::cout << " sub1 prio = " << sub1.getPriority() << std::endl;
std::cout << " sub2 prio = " << sub2.getPriority() << std::endl;
root.error("root error");
root.warn("root warn");
sub1.error("sub1 error");
sub1.warn("sub1 warn");
sub2.error("sub2 error");
sub2.warn("sub2 warn");
sub1.setPriority(log4cpp::Priority::INFO);
std::cout << " root prio = " << root.getPriority() << std::endl;
std::cout << " sub1 prio = " << sub1.getPriority() << std::endl;
std::cout << " sub2 prio = " << sub2.getPriority() << std::endl;
std::cout << "priority info" << std::endl;
root.error("root error");
root.warn("root warn");
sub1.error("sub1 error");
sub1.warn("sub1 warn");
sub2.error("sub2 error");
sub2.warn("sub2 warn");
sub2.warnStream() << "streamed warn";
sub2 << log4cpp::Priority::WARN << "warn2" << " warn3"
<< log4cpp::eol << " warn4";
{
for(int i = 0; i < 10000; i++) {
char ndc2[20];
sprintf(ndc2, "i=%d", i);
log4cpp::NDC::push(ndc2);
sub1.info("%s%d", "i = ", i);
if ((i % 10) == 0) {
sub1.log(log4cpp::Priority::NOTICE, "reopen log");
if (log4cpp::Appender::reopenAll()) {
sub1.info("log reopened");
} else {
sub1.warn("could not reopen log");
}
}
#ifndef WIN32
sleep(1);
#endif
log4cpp::NDC::pop();
}
}
return 0;
}
</code></pre>
<p>The errors are all about 'unresolved external', such as:</p>
<pre><code>[ILINK32 Error] Error: Unresolved external 'log4cpp::Category::warn(const char *, ...)' referenced from C:\DOCUMENTS AND SETTINGS\MLERMA\MIS DOCUMENTOS\RAD STUDIO\PROJECTS\DEBUG\TESTMAIN.OBJ
</code></pre>
<p>I'm getting this kind of error for every single call to a log4cpp function, all referring to TESTMAIN.OBJ . </p>
<p>Any ideas on this? is there anyone out there who has worked with log4cpp on Borland ?</p>
| <p>Are you linking in the log4cpp library (.LIB)? I'm not familiar with BCB5 or Codegear but check your link libraries in your project settings and make sure the log4cpp library is included.</p>
<p>If it is, then you might have a problem with where the compiler is looking for libraries. Usually an IDE will have a project level or global setting that says where there compiler will look for .lib files. Check that setting and make sure one of those directories includes your log4cpp .lib file.</p>
<p>Mike</p>
|
SQL Inserting data from staging table to two other tables <p>I have a situation in which a CSV is uploaded to my application and each line essentially needs to be put into the database. I read each line and build a data table and then SqlBulkCopy that table up to a staging table.</p>
<p>The staging table looks like this:</p>
<pre><code>UserID, GroupID, FirstName, LastName, EmailAddress
</code></pre>
<p>I have three other relevant tables in the database. A contacts table, a groups table and a contacts to groups mapping table.</p>
<pre><code>Contacts:
ID, UserID, FirstName, LastName, EmailAddress
Groups
ID, UserID, Name, Description
ContactGroupMapping
ID, ContactID, GroupID
</code></pre>
<p>The ContactGroupMapping table simply maps contacts to groups. Hopefully the staging table now makes sense, it holds the details of each imported contact plus the group they should also be mapped to.</p>
<p>My plan was to run a query against the database after the SqlBulkCopy to move the data from the staging table to the Contacts and ContactGroupMapping tables. Currently, I have a query looking something like this:</p>
<pre><code>INSERT INTO Contacts (UserID, FirstName, LastName, EmailAddress)
SELECT DISTINCT [t1].UserID, [t1].EmailAddress, [t1].FirstName, [t1].LastName FROM ContactImportStaging as [t1]
WHERE NOT EXISTS
(
SELECT UserID, EmailAddress, FirstName, LastName FROM Contacts
WHERE UserID = [t1].UserID AND EmailAddress = [t1].EmailAddress AND FirstName = [t1].FirstName AND LastName = [t1].LastName
)
</code></pre>
<p>So, my problem is that while this inserts all the distinct contacts into my contacts table, I then have no way to add the associated row to the mapping table for each newly inserted contact. </p>
<p>The only solution (probably because I suck at SQL) I can come up with is to have an extra nullable field in the contacts table identifying the group that the contact is to be associated with and insert this too. Then I could run a second query to select all contacts with a value in this column and insert into the mappings table.</p>
<p>Any thoughts on how this sort of thing should be achieved most efficiently?</p>
<p>Thanks.</p>
<p><strong>Edit:</strong> To elaborate on the object model: There are any number of Contacts and any number of Groups. A contact can be in a group by way of an entry in the ContactGroupMapping table. One contact can be in any number of groups. At the database level, this model is the concern of the three tables <strong>Contacts</strong>, <strong>Groups</strong> and <strong>ContactGroupMapping</strong>. I'm needing to move one row from the staging table and create two rows; one in the Contacts table and one in the ContactGroupMapping table.</p>
| <p>I'd just bulk copy the CSV into a staging database table. You can delete the table later, if space is a concern.</p>
<p>After copying the CSV into, say, StagingTable, the trick is to split it into the other tables. Since your CSV can now be referenced in the database, you can join the other tables to retrieve the new table's ID:</p>
<pre><code>insert into ContactGroupMapping
select cont.ID, grp.ID
from StagingTable stag
inner join Contacts cont on cont.UserID = stag.UserID
inner join Groups grp on grp.GroupID = stag.GroupID
</code></pre>
<p>An even easier solution would be to keep the original GroupID and UserID. Filling the GroupContactMapping would then be as easy as:</p>
<pre><code>insert into ContactGroupMapping
select UserID, GroupID
from StagingTable stag
</code></pre>
|
Use GZIP to boost XML-parsing <p>I am facing the problem to handle many xml-files that are all greater than 70 MB. Validating and accessing them cost a lot of time. Now I am wondering if the following steps could increase my applications performence.</p>
<p>I can compress a 70MB xml-file in a gzip-file < 1MB.
So I could hold only gzip files.
Working with the data could be done like this:</p>
<ul>
<li>Make the gzip available with java.io.File (only the small file)</li>
<li>Using for example StringBufferInputStream and GZIPInputStream to extract the conten within the RAM</li>
<li>work with the content (RAM): Parse, Validate, ...</li>
<li>create a String in RAM that represents the new xml-content (RAM)</li>
<li>Use GZIPOutputStream to access the file system (small content again)</li>
</ul>
<p>Can I do this or id there a misapprehension in my thoughts?</p>
<p>THX in advance!
Hans</p>
| <p>Reading 70 MB from the HD should take no more than 1-2 seconds (depending on your hardware, of course), so if you're having a delay greater than, say, 4 seconds, the bottleneck is not your HD but XML processing and anything you do with that.</p>
<p>Before getting into coding your gzip idea (which sounds fine), you could hardcode a sample XML to your code (yes, insert 70 MB as a single string), run your app having a nice button saying ("do it!") - or wait for user input if you're in the terminal - and see how much XML processing takes.</p>
<p>This approach will load your 70 megs into memory (as code) before processing, so you should be able to see how much it really takes to consume it.</p>
<p>After that, if you see it's processed quickly enough, the problem is clearly the HD. If not, then you should try to optimize your XML processing.</p>
|
What is the difference among heap spraying, heap overflow, heap overrun? <p>What is the difference among heap spraying, heap overflow, heap overrun?</p>
<p>Can those terms be replaced with buffer spraying, buffer overflow, buffer overrun?</p>
<p>Do they have the same definitions as well?</p>
| <ul>
<li>Spraying is writing things to random (or at least arbitrary) addresses in the named space, thus corrupting arbitrary things in the space</li>
<li>Overflow is putting more data in the space than it will hold, thus corrupting adjacent spaces</li>
<li>Overrun is putting more data in a subset of the space (e.g. an object allocated in that space) than has been allocated for that subset, thus corrupting adjacent objects.</li>
</ul>
|
Ruby exception handling: can't suppress NoMethodError <p>I simply want my method call to suppress all "NoMethodError" exceptions that might arise in the methods it in turn calls.</p>
<pre><code>def foo
begin
bar1
bar2
rescue Exception
return '--'
end
end
</code></pre>
<p>But this doesn't work. NoMethodError keeps being raised to the top level.</p>
<p>The exact error is <code>undefined method </code>[]' for nil:NilClass' (NoMethodError)</p>
| <pre><code>class Object
def method_missing(meth,*args)
# do whatever you want here
end
end
</code></pre>
<p>If you want something less global, you can do this on an narrower class, or even a specific instance:</p>
<pre><code>class << my_object
# and so forth
</code></pre>
|
Why is my return type meaningless? <p>I am trying to use a return type of <code>const MyClass * const</code>. However, I get a warning:</p>
<blockquote>
<p>Warning: #815-D: type qualifier on return type is meaningless.</p>
</blockquote>
<p>Is this not a valid type? I want a pointer than cannot be changed, and I want the thing it points to to not be changed either.</p>
| <p>The pointer itself has value type, so it doesn't make sense to make it const. What the caller function does with the returned value can't be restricted by the called function. This is akin to trying to define something like:</p>
<pre><code>const int getInt();
</code></pre>
<p>getInt(), in this case, just returns an int value (not a reference). It goes to a register, then the caller function receives it and does whatever it wants with it.</p>
|
What are the most important infrastructure components in large-scale development? <p>What are some of the building blocks foundational to enterprise business applications? I'm thinking about re-usable components multiple applications share to:</p>
<ol>
<li>Scale up faster</li>
<li>Speed development by eliminating re-building</li>
<li>Provide a stable infrastructures by minimizing key points of failure</li>
</ol>
<p>Some examples of concepts I've seen success with centralizing/standardizing:</p>
<ul>
<li>logging</li>
<li>queueing</li>
<li>scheduling</li>
</ul>
| <p>I'd add GUI widgets that allow teams to maintain the same look and feel across the application(s).</p>
<p>As well, in a large project where multiple teams must work on sub-systems that are going to plug together at some point a set of design patterns for similar sub-systems is invaluable.</p>
<p>Additionally, creating a common set of libraries (or better yet in C++ adopting Boost) which are the place to go when a common utility is required has worked well.</p>
<p>I would also create the testing framework with samples early on. I have found that if you have a template for testing the sub-systems then people will use it. Without any testing framework early on you are bound to get all extremes of developer testing.</p>
|
Is there any use for Flex + Python/Ruby without a web framework (Django/Rails)? <p>I often hear about Flex being combined with web frameworks on the backend. The idea being that Flex serves as the presentation framework while the web framework (Django/Rails) does the database lookups and sends the data to Flex to present in the form of XML.</p>
<p>However, is there ever a situation where Flex and Python/Ruby would be combined without a web framework as an intermediary? Under what circumstances might such a combination make sense (if any)?</p>
<p>(I'm trying to think of projects where the functionality of a scripting language would be complementary with the functionality of Flex - but also whether it's possible for the two to be combined without too much high jinx).</p>
| <p>You can still code against WSGI directly in Python. If that's the route you want to go, <a href="http://www.python.org/dev/peps/pep-0333/" rel="nofollow">PEP 333</a> is about the only way to go.</p>
<p>With that said, doing so is a good learning experience, but WSGI wasn't really intended to be used directly. You don't have to use a full-stack framework like Django if you don't want to. If you want something more light-weight, might I suggest <a href="http://www.cherrypy.org/" rel="nofollow">CherryPy</a> or <a href="http://webpy.org/" rel="nofollow">web.py</a>? They're a lot more light-weight than Django is.</p>
<p>There are other options aside from WSGI, but they'll pretty much all have about the same caveats. In other words, it can be done, but usually isn't recommended.</p>
|
Flex 3 sorting object fields <p>I have an object in <strong>ActionScript3</strong> code, which I need to sort.</p>
<p>I iterate through the object and print out each value:</p>
<pre><code>for (var i:String in columnData) {
</code></pre>
<p>However I need the data I am iterating to be sorted alphabetically. Any suggestions on how to do this?</p>
| <p>You can only sort Array/Lists, not fields in an object.</p>
<p>If you want a sorted order, you first need to iterate thru the object and push the values in an array/list and <em>then</em> sort it.</p>
<p><strong>[Edit]:</strong> OK, so I assumed you just needed the data. No, flex doesn't provide a hashmap (like a TreeMap ala Java). What you could do is to store the name value pairs as objects in an array. Array provides a <code>SortOn()</code> method to let you sort on a specific field.</p>
|
"home-brew" STL for performance? <p><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html" rel="nofollow">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html</a></p>
<p>According to that article STL isn't suited for game-development.
What are your thoughts about this ?</p>
<p>My current approach is this :
use STL, if leads to performance problems exchange with homebrew container (or allocator) (didn't come to it yet, but I'm not doing a high-end 3d game ;) )</p>
| <p>Your approach is the only sane option in this case. Rule #1 for optimization is "do not optimize unless you know exactly where the bottlenecks are". </p>
<p>You should still be able to swap your container relatively easily later on, especially if you use a type defined via typedef instead of directly using the STL container. I mean something like:</p>
<pre><code>#include <vector>
typedef std::vector<int> MyIntVectorType;
int main()
{
MyIntVectorType theVector;
}
</code></pre>
|
Is there a way to define symbolic constants in Javascript? <p>I searched if JavaScript offers a mean to define symbolic constants, but didn't find anything. Did I miss something ? </p>
<p>Is it a common practices to use const var instead ? </p>
<pre><code>var const MAXIMUM_VALUE = 100;
</code></pre>
<p>Thanx.</p>
| <p><code>const</code> is not supported by IE, so if you want to support IE that is out of the question.</p>
<p>As far as I know, and the best way of doing this to keep it simple is to just have a naming convention for your constants like the ever-popular ALL UPPERCASE. There are some examples out there to force constants but they are not worth it for the most part. Alternatively, you could use a function:</p>
<pre><code>function myConst() { return 'myValue'; }
</code></pre>
<p>This can of course still be overridden but I've seen it used.</p>
<p>Also see:</p>
<blockquote>
<ul>
<li><a href="http://stackoverflow.com/questions/130396/are-there-constants-in-javascript">Are there constants in Javascript?</a> </li>
<li><a href="http://stackoverflow.com/questions/622906/is-it-possible-to-simulate-constants-in-javascript-using-closures">
Is it possible to simulate constants in Javascript using closures?
</a></li>
<li><a href="http://stackoverflow.com/questions/664829/javascript-final-immutable-global-variables">Javascript: final / immutable global variables?</a></li>
</ul>
</blockquote>
|
Static Generic Class as Dictionary <p>A static field in a generic class will have a separate value for each combination of generic parameters. It can therefore be used as a Dictionary<Type, <em>whatever</em>></p>
<p>Is this better or worse than a static Dictionary<Type, <em>whatever</em>>?</p>
<p>In other words, which of these implementations more efficient?</p>
<pre><code>public static class MethodGen<TParam> {
public static readonly Action<TParam> Method = CreateMethod();
static Action<TParam> CreateMethod() { /*...*/ }
}
</code></pre>
<p>Or,</p>
<pre><code>public static class MethodGen {
static readonly Dictionary<Type, Delegate> methods
= new Dictionary<Type, Delegate>();
public static Action<T> GetMethod<T>() {
//In production code, this would ReaderWriterLock
Delegate method;
if(!methods.TryGetValue(typeof(T), out method)
methods.Add(typeof(t), method = CreateMethod<T>());
return method;
}
static Action<T> CreateMethod<T>() { /*...*/ }
}
</code></pre>
<p>In particular, how does the CLR lookup the static fields by generic type parameter?</p>
| <p>I like using generic types this way. In particular, I often have private nested generic classes for precisely this purpose.</p>
<p>The main thing I like about it is that it's hard <em>not</em> to get the initialization right this way (in terms of thread safety), given the way type initialization works. The only problem is what to do if initialization fails - occasionally I've resorted to remembering an exception to throw on first necessary access, but that's pretty rare.</p>
<p>I wouldn't like to guess at <em>exactly</em> how the CLR looks up the type via the type arguments, but I'm pretty sure it'll be optimised to heck and back :)</p>
|
Google analytics, why have two script blocks? <p>Why does the Google Analytics script I add to my webpage need to come in two script blocks?</p>
<pre><code><script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-xxxxxxx-xx");
pageTracker._trackPageview();
} catch (err) { }
</script>
</code></pre>
| <p>The first script in your quote above writes a new <code><script></code> loading tag into the document. The second block has dependencies that are loaded by that dynamically written script tag, so the browser has to have a chance to load and parse the script before the second block runs. If everything was in one block, the script loading wouldn't take place until the first script section ended.</p>
|
Embed Python script <p>I have some Python Scripts which I would like to use from my VB.NET class library however instead of increasing the amount of files that I distribute is it possible to embed the script into my project/dll in Visual Studio and then run the script from the dll during my program runtime?</p>
<p>Thanks for any help.</p>
<p>Rob</p>
| <p><a href="http://docs.python.org/extending/embedding.html" rel="nofollow">Yes, it is possible</a>.</p>
|
Best resources for starting Jython <p>I just got my first Jython (and Python) project, and I was wondering what documentation, IDEs, etc. are best suited to a Java buff like me. </p>
<p>I know there are a lot of questions about starting out with Python, so I'm asking for things that might be specific to Jython. Where should I start? If it helps, I'm running Linux and Solaris only.</p>
| <p>For starters, I'd read <a href="http://dirtsimple.org/2004/12/python-is-not-java.html" rel="nofollow">python is not java</a>. It'll give you a good idea of some habits you may have to break to program in Python effectively. As has been mentioned, pydev is a pretty good development environment. Although I would say that you would eventually want to learn emacs (but you may just want to learn one thing at a time).</p>
|
ASP.net C# Silverlight server component and ajax modal inside firefox <p>I have a modal popup inside of an update panel with a silverlight control.
<p>The video displays fine in IE 7/8 but in firefox all I get is a white screen</p>
<p>I am using the following video skin from <a href="http://sl2videoplayer.codeplex.com/" rel="nofollow">link text</a></p>
<pre><code> <div style="height:360px;">
<asp:Silverlight
ID="myVideoPlayer"
runat="server"
Source="~/Videos/VideoPlayer.xap"
Width="640px"
Height="360px"
InitParameters="m=Efficiency.wmv"
Windowless="true" />
</div>
</code></pre>
<p>I know it works when I use the normal <object> method but that will not work as I need to set the Initparams from the code behind depending on what video category they choose.</p>
<p>I have consulted the google gods and they have been not so helpful. Hope you guys can help me with this problem. Thank you!</p>
| <p>I use Object tag, and init params injected to aspx like this : </p>
<pre><code><%= initparams %>
</code></pre>
<p>initparams is protected variable of my Page class: </p>
<pre><code>public partial class _Default : System.Web.UI.Page
{
protected string initparams;
protected void Page_Load(object sender, EventArgs e)
{
initparams = "m=video.asx";
}
</code></pre>
<p>you can also change that variable in any event, it will be injected to rendered HTML.</p>
|
Cannot see the last row in my UiTableView <p>I have a UITableView added in InterfaceBuilder. My app runs in LandScape. Because I was unable to use autorotation (still can't figure that out). I am using Transforming it for now. Having said that, I now have to place the UITableView in some weird position for it to look correct after transformation</p>
<p>My table is fine but I cannot reach to the last couple of rows in the table. It almost seems like its Cut Off.</p>
<p>What settings would be causing this?</p>
<p>Thanks very much in advance</p>
| <p>Have you tried logging your view's width and height? Maybe the view is just too big and scaling the UITableView to large?</p>
<p>I have had no problems with UITableViews and rotation so far.</p>
|
Large Object Heap Fragmentation <p>The C#/.NET application I am working on is suffering from a slow memory leak. I have used CDB with SOS to try to determine what is happening but the data does not seem to make any sense so I was hoping one of you may have experienced this before.</p>
<p>The application is running on the 64 bit framework. It is continuously calculating and serialising data to a remote host and is hitting the Large Object Heap (LOH) a fair bit. However, most of the LOH objects I expect to be transient: once the calculation is complete and has been sent to the remote host, the memory should be freed. What I am seeing, however, is a large number of (live) object arrays interleaved with free blocks of memory, e.g., taking a random segment from the LOH:</p>
<pre><code>0:000> !DumpHeap 000000005b5b1000 000000006351da10
Address MT Size
...
000000005d4f92e0 0000064280c7c970 16147872
000000005e45f880 00000000001661d0 1901752 Free
000000005e62fd38 00000642788d8ba8 1056 <--
000000005e630158 00000000001661d0 5988848 Free
000000005ebe6348 00000642788d8ba8 1056
000000005ebe6768 00000000001661d0 6481336 Free
000000005f214d20 00000642788d8ba8 1056
000000005f215140 00000000001661d0 7346016 Free
000000005f9168a0 00000642788d8ba8 1056
000000005f916cc0 00000000001661d0 7611648 Free
00000000600591c0 00000642788d8ba8 1056
00000000600595e0 00000000001661d0 264808 Free
...
</code></pre>
<p>Obviously I would expect this to be the case if my application were creating long-lived, large objects during each calculation. (It does do this and I accept there will be a degree of LOH fragmentation but that is not the problem here.) The problem is the very small (1056 byte) object arrays you can see in the above dump which I cannot see in code being created and which are remaining rooted somehow.</p>
<p>Also note that CDB is not reporting the type when the heap segment is dumped: I am not sure if this is related or not. If I dump the marked (<--) object, CDB/SOS reports it fine:</p>
<pre><code>0:015> !DumpObj 000000005e62fd38
Name: System.Object[]
MethodTable: 00000642788d8ba8
EEClass: 00000642789d7660
Size: 1056(0x420) bytes
Array: Rank 1, Number of elements 128, Type CLASS
Element Type: System.Object
Fields:
None
</code></pre>
<p>The elements of the object array are all strings and the strings are recognisable as from our application code.</p>
<p>Also, I am unable to find their GC roots as the !GCRoot command hangs and never comes back (I have even tried leaving it overnight).</p>
<p>So, I would very much appreciate it if anyone could shed any light as to why these small (<85k) object arrays are ending up on the LOH: what situations will .NET put a small object array in there? Also, does anyone happen to know of an alternative way of ascertaining the roots of these objects?</p>
<hr>
<p>Update 1</p>
<p>Another theory I came up with late yesterday is that these object arrays started out large but have been shrunk leaving the blocks of free memory that are evident in the memory dumps. What makes me suspicious is that the object arrays always appear to be 1056 bytes long (128 elements), 128 * 8 for the references and 32 bytes of overhead.</p>
<p>The idea is that perhaps some unsafe code in a library or in the CLR is corrupting the number of elements field in the array header. Bit of a long shot I know...</p>
<hr>
<p>Update 2</p>
<p>Thanks to Brian Rasmussen (see accepted answer) the problem has been identified as fragmentation of the LOH caused by the string intern table! I wrote a quick test application to confirm this:</p>
<pre><code>static void Main()
{
const int ITERATIONS = 100000;
for (int index = 0; index < ITERATIONS; ++index)
{
string str = "NonInterned" + index;
Console.Out.WriteLine(str);
}
Console.Out.WriteLine("Continue.");
Console.In.ReadLine();
for (int index = 0; index < ITERATIONS; ++index)
{
string str = string.Intern("Interned" + index);
Console.Out.WriteLine(str);
}
Console.Out.WriteLine("Continue?");
Console.In.ReadLine();
}
</code></pre>
<p>The application first creates and dereferences unique strings in a loop. This is just to prove that the memory does not leak in this scenario. Obviously it should not and it does not.</p>
<p>In the second loop, unique strings are created and interned. This action roots them in the intern table. What I did not realise is how the intern table is represented. It appears it consists of a set of pages -- object arrays of 128 string elements -- that are created in the LOH. This is more evident in CDB/SOS:</p>
<pre><code>0:000> .loadby sos mscorwks
0:000> !EEHeap -gc
Number of GC Heaps: 1
generation 0 starts at 0x00f7a9b0
generation 1 starts at 0x00e79c3c
generation 2 starts at 0x00b21000
ephemeral segment allocation context: none
segment begin allocated size
00b20000 00b21000 010029bc 0x004e19bc(5118396)
Large object heap starts at 0x01b21000
segment begin allocated size
01b20000 01b21000 01b8ade0 0x00069de0(433632)
Total Size 0x54b79c(5552028)
------------------------------
GC Heap Size 0x54b79c(5552028)
</code></pre>
<p>Taking a dump of the LOH segment reveals the pattern I saw in the leaking application:</p>
<pre><code>0:000> !DumpHeap 01b21000 01b8ade0
...
01b8a120 793040bc 528
01b8a330 00175e88 16 Free
01b8a340 793040bc 528
01b8a550 00175e88 16 Free
01b8a560 793040bc 528
01b8a770 00175e88 16 Free
01b8a780 793040bc 528
01b8a990 00175e88 16 Free
01b8a9a0 793040bc 528
01b8abb0 00175e88 16 Free
01b8abc0 793040bc 528
01b8add0 00175e88 16 Free total 1568 objects
Statistics:
MT Count TotalSize Class Name
00175e88 784 12544 Free
793040bc 784 421088 System.Object[]
Total 1568 objects
</code></pre>
<p>Note that the object array size is 528 (rather than 1056) because my workstation is 32 bit and the application server is 64 bit. The object arrays are still 128 elements long.</p>
<p>So the moral to this story is to be very careful interning. If the string you are interning is not known to be a member of a finite set then your application will leak due to fragmentation of the LOH, at least in version 2 of the CLR.</p>
<p>In our application's case, there is general code in the deserialisation code path that interns entity identifiers during unmarshalling: I now strongly suspect this is the culprit. However, the developer's intentions were obviously good as they wanted to make sure that if the same entity is deserialised multiple times then only one instance of the identifier string will be maintained in memory.</p>
| <p>Why can't Microsoft provide us with a simple API in .NET called:</p>
<pre><code>GC.CompactLargeObjectHeap()
</code></pre>
<p>even if this method causes the application to hang for 10 seconds or more -- it beats the heck out of crashing and requiring Application restart to clean up the memory!</p>
<p>There are a great many applications that use 3rdparty libraries which make allocations on the LOH. For example, even Microsoft's own XNA fragments the heck out of the LOH each time you do "new Texture2D()" or "Texture.FromFile()" without any remedy! </p>
<p>So if you are trying to create a "Game Engine" in .NET -- this is a real pain in the neck, to have our LOH leak away memory without any way to stop it. All we can do is "slow it down", unless we decide to "make our own library" and forget about XNA. Surely this is not what Microsoft wants!</p>
<p>Many months of headache would be resolved for us (and others!) if MS would simply provide us with this one method; I'll say it again:</p>
<pre><code>GC.CompactLargeObjectHeap()
</code></pre>
<p>And while I'm making this suggestion, I would suggest the MS take it one step further, and allow this command:</p>
<pre><code>GC.DoLargeObjectHeapCompactionWhenOutOfMemory = true; // would be false by default
</code></pre>
<p>So we would just set this to true for "Visual3D Game Engine" (our product), and then automatically, when the fragmentation causes the first OOM exception, .NET would automatically compact the LOH, and then retry the allocation! </p>
<p>Wow, now that would aligned with all the .NET hype about "it just works" and "easy to use"... and would only cause this "performance hit" for extreme cases, where the alternative is OOM crash, forcing a restart of the application!</p>
<p>Please Microsoft -- do this for us!</p>
<p><hr /></p>
<p>Please do not announce your ignorance by saying the trite naive advice of "just use better memory management" -- yeesh! This is very inappropriate advice! You would have to also say "write ALL your own 3rdparty libraries" (e.g. XNA)!!!!</p>
<p>Why hasn't Microsoft already provided this behavior in .NET???? What would it hurt? It would save us from these very frustrating and time-consuming band-aid solutions, which can at best "slow down the memory leaks" but never fully fix them. </p>
<p>The solution we are requesting would be harmless to those who don't want to use it, and provides a refreshing salvation to those who really do want to use it. Please, Please, Please, provide this in .NET 4.0+.</p>
|
DataTable Wrapper or How to decouple UI from Business logic <p>I am using web forms, C#, Asp.net.
As we all know, in this model UI and business logic are often mixed in. How do I separate these effectively?</p>
<p>The example I would like to use is:
I have a GridView and a DataTable (GridView binds to the DataTable and DataTable is fed from the stored procedure).</p>
<p>I would like the GridView (UI) and DataTable (business logic) to be decoupled.</p>
<p>Is it worth it to write an wrapper for DataTable? Are there practical patterns that have been proved and tested that you could recommend to be followed?</p>
<p>If someone with experience could shed some light, that would be awesome.
And, as a final note I would like to say that ASP MVC is not an option right now, so don't recommend it.</p>
<p>My database access layer returns a DataTable.
Note that I HAVE to use this database layer as this is a company policy.</p>
| <p>I went through this recently while decoupling much the same thing from our UI layer.</p>
<p>You can see my progress <a href="http://stackoverflow.com/questions/583689/dictionaryt-of-listt-and-listviews-in-asp-net">here</a> and <a href="http://stackoverflow.com/questions/609276/listview-dataitem-shows-null">here</a>.</p>
<p>In my opinion, A <code>DataTable</code> does <strong>not</strong> represent business logic. Specifically, it's data pulled directly from the database. Business logic turns that data into a truly useful business object.</p>
<p>The first step, then, is to decouple the DataTable from the Business object. </p>
<p>You can do that by creating objects and <code>List<object></code> that make up DataTables and Collections of DataTables, and then you can make a ListView that displays those Objects. I cover the latter steps in the links I posted above. And the former steps are as easy as the following:</p>
<ol>
<li>Create a class that will represent your object.</li>
<li>iterate through your DataTable (or DataSet, or however you retrieve the data) and shove those fields into properties of that object (or that <code>List<T></code>); </li>
<li>return that List to the Gridview or ListView to display. </li>
</ol>
<p>This way your ListView or Gridview won't be tightly coupled to the method that you are retrieving your data. What happens if you decide to get your data from a JSON query or a XML file later on? Then you'd have to build this into there. </p>
<h3>Step 1 - Getting Data From Database</h3>
<p>There are multiple methods to get data from a database, there's no way I can go through all of them here. I assume that you already know how to retrieve data from a database, and if you don't, there are <a href="http://www.google.com/search?hl=en&q=Get%2BData%2Bfrom%2BDatabase%2BC%23&btnG=Google%2BSearch&aq=f&oq=" rel="nofollow">quite a few links</a> to follow. Let's pretend you've connected to the database, and are using an <code>SQLDataReader</code> to retrieve data. We'll pick up there. </p>
<h3>Class Diagram</h3>
<pre><code>Foo
----
id
Name
Description
</code></pre>
<p>And here's the method:</p>
<pre><code> private void FillDefault(SqlDataReader reader, Foos foo)
{
try
{
foo.id = Convert.ToInt32(reader[Foo.Properties.ID]);
foo.Name = reader[Foo.Properties.NAME].ToString();
if (!string.IsNullOrEmpty(
reader[Foo.Properties.DESCRIPTION].ToString()))
foo.Description =
reader[Foo.Properties.DESCRIPTION].ToString();
else foo.Description = string.Empty;
}
catch (Exception ex)
{
throw new Exception(
string.Format("Invalid Query.
Column '{0}' does not exist in SqlDataReader.",
ex.Message));
}
}
</code></pre>
<p>Once that happens, you can return a list by going through that process in a <code>while</code> loop that targets the <code>SQLDataReader.Read()</code> function.</p>
<p>Once you do that, let's pretend that your <code>Foo</code> being returned is a List. If you do that, and follow the first link I gave above, you can replace <code>Dictionary<TKey, TValue></code> with <code>List<T></code> and achieve the same result (with minor differences). The <code>Properties</code> class just contains the column names in the database, so you have one place to change them (in case you were wondering).</p>
<h3>DataTable - Update Based on Comment</h3>
<p>You can always insert an intermediate object. In this instance, I'd insert a Business Layer between the DataTable and the UI, and I've discussed what I'd do above. But a DataTable is not a business object; it is a visual representation of a database. You can't transport that to the UI layer and call it de-coupled. They say you have to |
Why would AccessDataSource return different results to query in Access? <p>I have a query to return random distinct rows from an Access database. Here is the query:</p>
<pre><code>SELECT * FROM
(SELECT DISTINCT m.MemberID, m.Title, m.FullName, m.Address,
m.Phone, m.EmailAddress, m.WebsiteAddress FROM Members AS m INNER JOIN MembersForType AS t ON m.MemberID = t.MemberID WHERE
(Category = 'MemberType1' OR Category = 'MemberType2')) as Members
ORDER BY RND(members.MemberID) DESC
</code></pre>
<p>When I run this in Access it returns the rows in different order every time, as per the random sort order. When I run it through my web app however the rows return in the same order every time. Here is how I call it in my code-behind:</p>
<pre><code>private void BindData()
{
using (AccessDataSource ds = new AccessDataSource("~/App_Data/mydb.mdb", GetSQLStatement()))
{
ds.DataSourceMode = SqlDataSourceMode.DataReader;
ds.CacheDuration = 0;
ds.CacheExpirationPolicy = DataSourceCacheExpiry.Absolute;
ds.EnableCaching = false;
listing.DataSource = ds.Select(new DataSourceSelectArguments());
listing.DataBind();
if (listing.Items.Count == 0)
noResults.Visible = true;
else
noResults.Visible = false;
}
}
</code></pre>
<p>I added in all that stuff about caching because I thought maybe the query was being cached but the result was the same. I put a breakpoint in the code to make sure the query was the same as above and it was.</p>
<p>Any ideas? This is driving me nuts.</p>
| <p>When executing the ACE/Jet RND function against a new connection the same seed value is used each time. When using MS Access you are using the same connection each time, which explains why you get a different value each time.</p>
<p>Consider these VBA examples: the first uses a new connection on each iteration:</p>
<pre><code>Sub TestDiff()
Dim con As Object
Set con = CreateObject("ADODB.Connection")
With con
.ConnectionString = _
"Provider=MSDataShape;Data " & _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Tempo\Test_Access2007.accdb"
.CursorLocation = 3
Dim i As Long
For i = 0 To 2
.Open
Debug.Print .Execute("SELECT RND FROM OneRowTable;")(0)
.Close
Next
End With
End Sub
</code></pre>
<p>Output:</p>
<pre><code> 0.705547511577606
0.705547511577606
0.705547511577606
</code></pre>
<p>Note the same value each time.</p>
<p>The second example uses the same connection on each iteration (the .Open and .Close statements are relocated outside the loop):</p>
<pre><code>Sub TestSame()
Dim con As Object
Set con = CreateObject("ADODB.Connection")
With con
.ConnectionString = _
"Provider=MSDataShape;Data " & _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Tempo\Test_Access2007.accdb"
.CursorLocation = 3
.Open
Dim i As Long
For i = 0 To 2
Debug.Print .Execute("SELECT RND FROM OneRowTable;")(0)
Next
.Close
End With
End Sub
</code></pre>
<p>Output:</p>
<pre><code> 0.705547511577606
0.533424019813538
0.579518616199493
</code></pre>
<p>Note different values each time.</p>
<p>In VBA code you can use the Randomize keyword to seed the Rnd() function but I don't think this can be done in ACE/Jet. One workaround is to use the least significant decimal portion of the ACE/Jet the NOW() niladic function e.g. something like:</p>
<pre><code>SELECT CDBL(NOW()) - ROUND(CDBL(NOW()), 4) FROM OneRowTable
</code></pre>
|
Looking for MISSING records <p>I'm a bit rusty when it comes to MS Access and I am hoping someone can help me out.....</p>
<p>I have a list of all items that have been scanned (for purchase) by each store, by UPC for a one month period. I also have a particular group of UPC's that I want data for. What I want to get is the items that DIDN'T get scanned. Obviously, the items that did not get a scan will not show up in list of scanned items.</p>
<p>First, I tried doing a crosstab query...which is great, but I only want to see the '0' values. Ideally I would like to put the '0' values from the crosstab into a simple table that lists the store and the UPC. I also tried doing an unmatched query, but that only returns the UPC....I need to know which store it didn't scan in....</p>
<p>I think I may be going about this a bit wrong. Like I said, I haven't used Access in years and I apologize if I am asking an uber easy question.</p>
<p>Anyone that can offer some assistance?</p>
<p>Thank you in advance!</p>
| <p>I would use:</p>
<pre><code>SELECT ul.upc FROM upc_list ul
LEFT JOIN upc_scanned us
ON ul.upc = us.upc
WHERE us.upc Is Null
</code></pre>
<p>With your tables and fields:</p>
<pre><code>SELECT [Master UPC List].UPC
FROM [Master UPC List] LEFT JOIN [No Scans]
ON [Master UPC List].UPC = [No Scans].UPC
WHERE [No Scans].UPC Is Null;
</code></pre>
|
C#: How to access a button outside the form class <p>I want to either enable or disable a button from another file,what should I do?</p>
<p>This is the form class declaration: </p>
<pre><code>public partial class Form1 : Form
</code></pre>
<p>I tried with </p>
<pre><code>Form.btnName.enabled = false/true
</code></pre>
<p>but there's no btnName member.</p>
<p>Thanks in advance!</p>
| <p>Simply expose a public method:</p>
<pre><code>public void EnableButton(bool enable)
{
this.myButton.Enabled = enable;
}
</code></pre>
<p>Correction:</p>
<pre><code>public void EnableButton()
{
this.myButton.Enabled = true;
}
</code></pre>
|
Legacy html form in ASP .net application <p>I have an html page that I am converting over to an asp .net page. This page contained a form that accesses an external website that I have no control over. There is some sample code below:</p>
<pre><code><asp:Content ID="sample" ContentPlaceHolderID="body" Runat="Server">
<form name="Subscribe" method="post" action="http://anexternalwebsitehere.com/subscribe.asp">
<input type="text" name="email" size="45" maxlength="120" />
<input type="submit" name="submit" value="Subscribe" />
</form>
</asp:Content>
</code></pre>
<p>The form is more complicated than the example I have provided, but it gives a rough idea of what i need to convert over. Here are the problems I have encountered.</p>
<p><strong>If I leave it as is:</strong>
When you click on the submit button you have a postback to the current page and not to the external page</p>
<p><strong>If simply convert everything over to be asp form controls and change the postback url:</strong>
The id's become some convoluted "ctl00_body_ctl00" which the external page is not able to interpret.</p>
<p><em>Note: I do need the page to be an aspx page because I am using a master page for other content on the page.</em></p>
<p>Additional note: this is not Microsoft MVC.</p>
<p>What am I missing?</p>
| <p>The issue was with nested forms as others have mentioned.</p>
<p>I was able to fix all my issues by simply doing the following:</p>
<ol>
<li>Remove the extra form element i was adding.</li>
<li>Leave all controls as simply html controls, except for the submit button.</li>
<li>Replace the submit button with an asp .net button, and set the postback url.</li>
</ol>
<p>The old code is as follows:</p>
<pre><code><asp:Content ID="sample" ContentPlaceHolderID="body" Runat="Server">
<form name="Subscribe" method="post" action="http://anexternalwebsitehere.com/subscribe.asp">
<input type="text" name="email" size="45" maxlength="120" />
<input type="submit" name="submit" value="Subscribe" />
</form>
</asp:Content>
</code></pre>
<p>The new code:</p>
<pre><code><asp:Content ID="sample" ContentPlaceHolderID="body" Runat="Server">
<input type="text" name="email" size="45" maxlength="120" />
<input type="submit" name="submit" value="Subscribe" />
<asp:button postbackurl="http://anexternalwebsitehere.com/subscribe.asp" text="Subscribe" runat="server" />
</asp:Content>
</code></pre>
<p>This fixes any of the issues with invalid nested forms as there are none. It also addresses the issue of asp .net renaming the asp elements because the only control that is being renamed is the asp button control which was not necessary for the submission to succeed.</p>
|
Unable to debug ASP .NET 1.0 Application <p>When I try to debug a web site in .NET 1.0, I get the following error
"Error while trying to run project: Unable to start debugging on the web server. Could not read key from registry"</p>
<p>I was not able to find any documentation on this particular error for not not being able to read the key from registry.</p>
<p>I did look at <a href="http://support.microsoft.com/kb/306172" rel="nofollow">Microsoft KB For This</a>, but, it does not have anything for the registry read error.</p>
<p>EDIT: I found a work around for this. Add the username that aspnet_wp.exe is running under to the Administartors group on your PC. This is a very bad thing because it exposes a security hole on your machine.
But, it is still not clear what "other" rights does this account need in order to "read key from registry."</p>
| <p>Consider running the <a href="http://technet.microsoft.com/en-us/sysinternals/bb896652.aspx" rel="nofollow">RegMon</a> from SysInternals. It should show your which registry keys get denied.</p>
|
Parameterized SQL Query error <p>I have an application that builds dynamic parameterized SQL queries. The following query returns an inner exception of "syntax error at or near "="... </p>
<p>I am thinking it is in the way that I am assigning the parameter to the column name but, I'm not sure. Code follows.</p>
<pre><code>SELECT TOP 50 77 AS Repository, DocID, LastFileDate, ImageCount,
LockedUserID, DocClass, Offline, FileType, OrigFileName, C_CredCardSSN, C_CredCardName,C_CredCardDocType, C_CredCardDocDate, C_CredCardStatus
FROM D77
WHERE C_CredCardSSN
LIKE C_CredCardSSN = @sp1%
ORDER BY C_CredCardSSN,C_CredCardName
</code></pre>
<p><strong>EDIT:</strong> Thanks to everyone. All of these answers helped. =)</p>
| <p>Try just</p>
<pre><code>WHERE C_CredCardSSN LIKE @sp1
</code></pre>
<p>or </p>
<pre><code>WHERE C_CredCardSSN LIKE @sp1+'%'
</code></pre>
<p>depending on why you had a "%" there (thanks to Joel Coehoorn's comment for pointing out the "%" I'd missed).</p>
<p>Or (in response to your comment) maybe:</p>
<pre><code>WHERE C_CredCardSSN LIKE ''+@sp1
</code></pre>
|
C# Shorthand Property Question <p>So here is a bit of syntax that I have never seen before, can someone tell me what this means? Not sure if this is supposed to be some shorthand for an abstract property declaration or something or what.</p>
<pre><code>public Class1 myVar { get; set; }
</code></pre>
<p>For what its worth, Class1 is an abstract class.</p>
| <p>In C# 3.0 and later, <a href="http://msdn.microsoft.com/en-us/library/bb384054.aspx">auto-implemented properties</a> make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors. </p>
<pre><code>// Auto-Impl Properties for trivial get and set
public double TotalPurchases { get; set; }
public string Name { get; set; }
public int CustomerID { get; set; }
</code></pre>
|
How to send signed emails from java? <p>What APIs/Libraries do you recommend for sending signed emails from Java code? What are the requirements on our company's SMTP-Server to make it transport these signed mails, if any? </p>
<p>We already hava a PKI infrastructure running, so certificates are no issue here. </p>
| <p>The <a href="http://www.bouncycastle.org/java.html" rel="nofollow">BouncyCastle</a> S/MIME library is easy to use and compatible with common mail clients that support secure mail.</p>
<p>BouncyCastle also offers PGP-style email support, but this usually requires recipients to install a plug-in or find other support for signature verification.</p>
<p>In both cases, the signed messages are just MIME messages like any other email. No special treatment is required at the server.</p>
|
How do you default to Soft Tabs while programming in Textmate? <p>My "Soft Tabs" setting in TextMate is not sticky. After I restart TextMate, I often have to set the option again for the same file. How can I make this setting the sticky default across all files?</p>
| <h2>For Textmate 1</h2>
<p>After doing some research, I found that you can set TextMate 1 to default to using Soft tabs.</p>
<p>In the "Shell Variables" area of the Advanced preferences pane, add a new entry with the name <code>TM_SOFT_TABS</code> and a value of <code>YES</code>.</p>
<p>From that point on, TextMate should default to Soft tabs, though for at least one or two languages, I had to specify the number of tabs. After I did that, it seemed to stick for everything I did.</p>
|
How do I compare two git repositories? <p>I've got two different exports of our CVS repository into git. They diverge at some point, and I'm doing some investigation into why. The development line goes back several years and over tens of thousands of commits.</p>
<p>At the beginning of the development line, the SHA1 IDs for each commit are identical, telling me that git-cvsimport is very consistent about what it is doing when it reads the results of cvsps and imports.</p>
<p>But sometime between the first commit and yesterday, the SHA1 IDs begin to diverge. I'd like to find out where this is by comparing a list of commit IDs from each repository and looking to see what's missing. Are there any good tools or techniques for doing this?</p>
| <p>Since the two git repositories start out the same, you can pull both into the same working repository.</p>
<pre><code>$ git remote add cvsimport-a git://.../cvsimport-a.git
$ git remote add cvsimport-b git://.../cvsimport-b.git
$ git remote update
$ git log cvsimport-a/master..cvsimport-b/master # in B, not in A?
$ git log cvsimport-b/master..cvsimport-a/master # in A, not in B?
</code></pre>
|
How to "flatten" or "collapse" a 2D Excel table into 1D? <p>I have a two dimensional table with countries and years in Excel. eg. </p>
<pre><code> 1961 1962 1963 1964
USA a x g y
France u e h a
Germany o x n p
</code></pre>
<p>I'd like to "flatten" it, such that I have Country in the first col, Year in the second col, and then value in the third col. eg.</p>
<pre><code>Country Year Value
USA 1961 a
USA 1962 x
USA 1963 g
USA 1964 y
France 1961 u
...
</code></pre>
<p>The example I present here is only a 3x4 matrix, but the real dataset i have is significantly larger (roughly 50x40 or so).</p>
<p>Any suggestions how I can do this using Excel?</p>
| <p>You can use the excel pivot table feature to reverse a pivot table (which is essentially what you have here):</p>
<p>Good instructions here:</p>
<p><a href="http://spreadsheetpage.com/index.php/tip/creating_a_database_table_from_a_summary_table/">http://spreadsheetpage.com/index.php/tip/creating_a_database_table_from_a_summary_table/</a></p>
<p>Which links to the following VBA code (put it in a module) if you don't want to follow the instructions by hand:</p>
<pre><code>Sub ReversePivotTable()
' Before running this, make sure you have a summary table with column headers.
' The output table will have three columns.
Dim SummaryTable As Range, OutputRange As Range
Dim OutRow As Long
Dim r As Long, c As Long
On Error Resume Next
Set SummaryTable = ActiveCell.CurrentRegion
If SummaryTable.Count = 1 Or SummaryTable.Rows.Count < 3 Then
MsgBox "Select a cell within the summary table.", vbCritical
Exit Sub
End If
SummaryTable.Select
Set OutputRange = Application.InputBox(prompt:="Select a cell for the 3-column output", Type:=8)
' Convert the range
OutRow = 2
Application.ScreenUpdating = False
OutputRange.Range("A1:C3") = Array("Column1", "Column2", "Column3")
For r = 2 To SummaryTable.Rows.Count
For c = 2 To SummaryTable.Columns.Count
OutputRange.Cells(OutRow, 1) = SummaryTable.Cells(r, 1)
OutputRange.Cells(OutRow, 2) = SummaryTable.Cells(1, c)
OutputRange.Cells(OutRow, 3) = SummaryTable.Cells(r, c)
OutputRange.Cells(OutRow, 3).NumberFormat = SummaryTable.Cells(r, c).NumberFormat
OutRow = OutRow + 1
Next c
Next r
End Sub
</code></pre>
|
How do I expand a tuple into variadic template function's arguments? <p>Consider the case of a templated function with variadic template arguments:</p>
<pre><code>template<typename Tret, typename... T> Tret func(const T&... t);
</code></pre>
<p>Now, I have a tuple <code>t</code> of values. How do I call <code>func()</code> using the tuple values as arguments?
I've read about the <code>bind()</code> function object, with <code>call()</code> function, and also the <code>apply()</code> function in different some now-obsolete documents. The GNU GCC 4.4 implementation seems to have a <code>call()</code> function in the <code>bind()</code> class, but there is very little documentation on the subject.</p>
<p>Some people suggest hand-written recursive hacks, but the true value of variadic template arguments is to be able to use them in cases like above.</p>
<p>Does anyone have a solution to is, or hint on where to read about it?</p>
| <p>Here's my code if anyone is interested</p>
<p>Basically at compile time the compiler will recursively unroll all arguments in various inclusive function calls <N> -> calls <N-1> -> calls ... -> calls <0> which is the last one and the compiler will optimize away the various intermediate function calls to only keep the last one which is the equivalent of func(arg1, arg2, arg3, ...)</p>
<p>Provided are 2 versions, one for a function called on an object and the other for a static function.</p>
<pre><code>#include <tr1/tuple>
/**
* Object Function Tuple Argument Unpacking
*
* This recursive template unpacks the tuple parameters into
* variadic template arguments until we reach the count of 0 where the function
* is called with the correct parameters
*
* @tparam N Number of tuple arguments to unroll
*
* @ingroup g_util_tuple
*/
template < uint N >
struct apply_obj_func
{
template < typename T, typename... ArgsF, typename... ArgsT, typename... Args >
static void applyTuple( T* pObj,
void (T::*f)( ArgsF... ),
const std::tr1::tuple<ArgsT...>& t,
Args... args )
{
apply_obj_func<N-1>::applyTuple( pObj, f, t, std::tr1::get<N-1>( t ), args... );
}
};
//-----------------------------------------------------------------------------
/**
* Object Function Tuple Argument Unpacking End Point
*
* This recursive template unpacks the tuple parameters into
* variadic template arguments until we reach the count of 0 where the function
* is called with the correct parameters
*
* @ingroup g_util_tuple
*/
template <>
struct apply_obj_func<0>
{
template < typename T, typename... ArgsF, typename... ArgsT, typename... Args >
static void applyTuple( T* pObj,
void (T::*f)( ArgsF... ),
const std::tr1::tuple<ArgsT...>& /* t */,
Args... args )
{
(pObj->*f)( args... );
}
};
//-----------------------------------------------------------------------------
/**
* Object Function Call Forwarding Using Tuple Pack Parameters
*/
// Actual apply function
template < typename T, typename... ArgsF, typename... ArgsT >
void applyTuple( T* pObj,
void (T::*f)( ArgsF... ),
std::tr1::tuple<ArgsT...> const& t )
{
apply_obj_func<sizeof...(ArgsT)>::applyTuple( pObj, f, t );
}
//-----------------------------------------------------------------------------
/**
* Static Function Tuple Argument Unpacking
*
* This recursive template unpacks the tuple parameters into
* variadic template arguments until we reach the count of 0 where the function
* is called with the correct parameters
*
* @tparam N Number of tuple arguments to unroll
*
* @ingroup g_util_tuple
*/
template < uint N >
struct apply_func
{
template < typename... ArgsF, typename... ArgsT, typename... Args >
static void applyTuple( void (*f)( ArgsF... ),
const std::tr1::tuple<ArgsT...>& t,
Args... args )
{
apply_func<N-1>::applyTuple( f, t, std::tr1::get<N-1>( t ), args... );
}
};
//-----------------------------------------------------------------------------
/**
* Static Function Tuple Argument Unpacking End Point
*
* This recursive template unpacks the tuple parameters into
* variadic template arguments until we reach the count of 0 where the function
* is called with the correct parameters
*
* @ingroup g_util_tuple
*/
template <>
struct apply_func<0>
{
template < typename... ArgsF, typename... ArgsT, typename... Args >
static void applyTuple( void (*f)( ArgsF... ),
const std::tr1::tuple<ArgsT...>& /* t */,
Args... args )
{
f( args... );
}
};
//-----------------------------------------------------------------------------
/**
* Static Function Call Forwarding Using Tuple Pack Parameters
*/
// Actual apply function
template < typename... ArgsF, typename... ArgsT >
void applyTuple( void (*f)(ArgsF...),
std::tr1::tuple<ArgsT...> const& t )
{
apply_func<sizeof...(ArgsT)>::applyTuple( f, t );
}
// ***************************************
// Usage
// ***************************************
template < typename T, typename... Args >
class Message : public IMessage
{
typedef void (T::*F)( Args... args );
public:
Message( const std::string& name,
T& obj,
F pFunc,
Args... args );
private:
virtual void doDispatch( );
T* pObj_;
F pFunc_;
std::tr1::tuple<Args...> args_;
};
//-----------------------------------------------------------------------------
template < typename T, typename... Args >
Message<T, Args...>::Message( const std::string& name,
T& obj,
F pFunc,
Args... args )
: IMessage( name ),
pObj_( &obj ),
pFunc_( pFunc ),
args_( std::forward<Args>(args)... )
{
}
//-----------------------------------------------------------------------------
template < typename T, typename... Args >
void Message<T, Args...>::doDispatch( )
{
try
{
applyTuple( pObj_, pFunc_, args_ );
}
catch ( std::exception& e )
{
}
}
</code></pre>
|
How do you obtain the maximum possible date in Oracle? <p>Is there a function built into Oracle that will return the highest possible date that may be inserted into a date field?</p>
| <pre><code>SELECT TO_DATE('31.12.9999 23:59:59', 'dd.mm.yyyy hh24:mi:ss')
FROM dual
</code></pre>
<p>Note that minimal date is much more simple:</p>
<pre><code>SELECT TO_DATE(1, 'J')
FROM dual
</code></pre>
|
PreparedStatements and performance <p>So I keep hearing that PreparedStatements are good for performance.</p>
<p>We have a Java application in which we use the regular 'Statement' more than we use the 'PreparedStatement'. While trying to move towards using more PreparedStatements, I am trying to get a more thorough understanding of how PreparedStatements work - on the client side and the server side.</p>
<p>So if we have some typical CRUD operations and update an object repeatedly in the application, does it help to use a PS? I understand that we will have to close the PS every time otherwise it will result in a cursor leak.</p>
<p>So how does it help with performance? Does the driver cache the precompiled statement and give me a copy the next time I do connection.prepareStatement? Or does the DB server help? </p>
<p>I understand the argument about the security benefits of PreparedStatements and I appreciate the answers below which emphasize it. However I really want to keep this discussion focused on the performance benefits of PreparedStatements.</p>
<p>Update: When I say update data, I really mean more in terms of that method randomly being called several times. I understand the advantage in the answer offered below which asks to re-use the statement inside a loop.</p>
<pre><code> // some code blah blah
update();
// some more code blah blah
update();
....
public void update () throws SQLException{
try{
PreparedStatement ps = connection.prepareStatement("some sql");
ps.setString(1, "foobar1");
ps.setString(2, "foobar2");
ps.execute();
}finally {
ps.close();
}
}
</code></pre>
<p>There is no way to actually reuse the 'ps' java object and I understand that the actual connection.prepareStatement call is quite expensive. </p>
<p>Which is what brings me back to the original question. Is this "some sql" PreparedStatement still being cached and reused under the covers that I dont know about?</p>
<p>I should also mention that we support several databases.</p>
<p>Thanks in advance.</p>
| <p>The notion that prepared statements are primarily about performance is something of a misconception, although it's quite a common one.</p>
<p>Another poster mentioned that he noted a speed improvement of about 20% in Oracle and SQL Server. I've noted a similar figure with MySQL. It turns out that parsing the query just isn't such a significant part of the work involved. On a very busy database system, it's also not clear that query parsing will affect overall throughput: overall, it'll probably just be using up CPU time that would otherwise be idle while data was coming back from the disk.</p>
<p>So as a reason for using prepared statements, the <strong>protection against SQL injection attacks far outweighs</strong> the performance improvement. And if you're not worried about SQL injection attacks, you probably should be...</p>
|
3d elements as items in a WPF ListBox <p>I'm wondering if anyone knows if it's possible in XAML to have a ListBox whose DataTemplate defines the ListBoxItem as a 3d element. Something along the lines of:</p>
<pre><code> <ListBox x:Name="lst3D" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<Viewport3D>
<Viewport2DVisual3D>
<Viewport2DVisual3D.Transform>
<RotateTransform3D>
<RotateTransform3D.Rotation>
<AxisAngleRotation3D Angle="40" Axis="0, 1, 0" />
</RotateTransform3D.Rotation>
</RotateTransform3D>
</Viewport2DVisual3D.Transform>
<Viewport2DVisual3D.Geometry>
<MeshGeometry3D Positions="-1,1,0 -1,-1,0 1,-1,0 1,1,0"
TextureCoordinates="0,0 0,1 1,1 1,0"
TriangleIndices="0 1 2 0 2 3"/>
</Viewport2DVisual3D.Geometry>
<Viewport2DVisual3D.Material>
<DiffuseMaterial Viewport2DVisual3D.IsVisualHostMaterial="True" Brush="AliceBlue"/>
</Viewport2DVisual3D.Material>
<Label>Hello, 3D</Label> // we'd like to databind controls like this one
</Viewport2DVisual3D>
</Viewport3D>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBoxItem />
<ListBoxItem />
<ListBoxItem />
</ListBox>
</code></pre>
<p>Anyone seen this sort of thing done/have any advice? </p>
<p>Greatly appreciated,
bv</p>
| <p>There's a couple of ways to do this.</p>
<p>You can change the DataTemplate to a ControlTemplate, and have it apply to all the items in the ListBox. But you cannot bind it to a specific data type.</p>
<p>The other option is move the DataTemplate to a resources section, and set the DataType to the type of the item you wish to display. Then you can use binding to bind to a property of the item etc.</p>
|
Open source survey/questionnaire engine for Java <p>Is there an open source survey engine for java that will allow branching of questions? i.e. Question 1 has the options of A, B, or C and they each take you to a different set of follow-up questions.</p>
<p>I've found a couple (JSurveyLib and Socrates QE), but those seem to be very tied to a GUI.</p>
<p>The application that I'm writing has a java back-end running on glassfish, and a flex front-end. Eventually there are plans for different font-ends, so the engine needs to be very independent of the GUI.</p>
| <p>Please have a look at <a href="http://jcaif.sourceforge.net/jcaif.html" rel="nofollow">JCaiF</a> - "The Java Computer Aided Interviewing Framework (JCaiF) is a collection of Java interfaces that define the common elements of a questionnaire or survey" - so perhaps you can implement your application against these interfaces.</p>
|
documenting shell scripts' parameters <p>Is there a convention for documenting shell scripts' parameters?</p>
<p>For example:</p>
<pre><code>#!/usr/bin/env bash
# <description>
#
# Usage:
# $ ./myScript param1 [param2]
# * param1: <description>
# * param2: <description>
</code></pre>
<p>A few things I don't like about this particular template:</p>
<ul>
<li>the script's file name (<code>myScript</code>) appears within the file itself</li>
<li>parameter description seems weird</li>
<li>the leading space before <code>$</code> is visually useful, but can lead to confusion in languages with block comments, causing some validation tools to complain about mixed/inconsisent indentation (e.g. spaces in this block, tabs for code - provided one prefers tabs, of course)</li>
</ul>
<p>Are there any guidelines on this?</p>
| <p>Traditionally you document your arguments in the usage() function:</p>
<pre><code>#!/bin/bash
programname=$0
function usage {
echo "usage: $programname [-abch] [-f infile] [-o outfile]"
echo " -a turn on feature a"
echo " -b turn on feature b"
echo " -c turn on feature c"
echo " -h display help"
echo " -f infile specify input file infile"
echo " -o outfile specify output file outfile"
exit 1
}
usage
</code></pre>
|
Scheduling identical SSIS packages to run in parallel <p>We've got an architecture where we intend to use SSIS as a data-loading engine for incoming batches. The intent is to reduce the need for manual intervention & configuration and automate the function as much as possible so we're looking at setting up our "batch monitoring" package to run as scheduled SQL Server Agent jobs. </p>
<p>Is it possible to schedule several SQL Server Agent jobs using the same package, possibly looking at different folders or working on different data chunks (grouped by batch ids?</p>
<p>We might also have 3 or 4 âjobsâ all running the same package and all monitoring the same folder for incoming files, but at slightly different intervals to avoid file contention issues.</p>
| <p>I don't know of any reason you couldn't do this. You could launch the packages each with a different configuration (or configurations) pointing to different working directories, input folders, etc.</p>
|
Using Guid in ADO.Net Data Service <p>I'm pulling my hair out on this one. I'm trying to implement a ADO.Net Data Service that uses a Linq to SQL data context. I thought I had it working, but the URL for one of my tables always gets an exception.</p>
<p>The obvious difference between the table that isn't working and the ones that are, is that the one getting the exception is using a Guid, which is the primary key. The Guid is a UserID, which actually relates to the UserId used by ASP.net Membership. (I'm not exposing the ASP.net Membership tables, but I'm guessing these would break too if I were.)</p>
<p>It is a very simple table:
Name: UserDetails :: | Guid UserID | int GroupID (foreign key) | string Name |</p>
<p>Anybody know if there's a trick to getting Guids to work? Or if maybe this is an entirely different problem?</p>
<p>Here's the exception from the service:
An error occurred while processing this request.</p>
<p>InnerError: An error occurred while processing this request.</p>
<p>Type: System.InvalidOperationException</p>
<p>StackTrace:
t System.Data.Services.Serializers.SyndicationSerializer.WriteComplexObjectValue(Object element, String propertyName, ResourceType expectedType, String relativeUri, DictionaryContent content)
at System.Data.Services.Serializers.SyndicationSerializer.WriteObjectProperties(IExpandedResult expanded, Object customObject, ResourceType resourceType, Uri absoluteUri, String relativeUri, SyndicationItem item, DictionaryContent content)
at System.Data.Services.Serializers.SyndicationSerializer.WriteComplexObjectValue(Object element, String propertyName, ResourceType expectedType, String relativeUri, DictionaryContent content)
at System.Data.Services.Serializers.SyndicationSerializer.WriteObjectProperties(IExpandedResult expanded, Object customObject, ResourceType resourceType, Uri absoluteUri, String relativeUri, SyndicationItem item, DictionaryContent content)
at System.Data.Services.Serializers.SyndicationSerializer.WriteComplexObjectValue(Object element, String propertyName, ResourceType expectedType, String relativeUri, DictionaryContent content)
at System.Data.Services.Serializers.SyndicationSerializer.WriteObjectProperties(IExpandedResult expanded, Object customObject, ResourceType resourceType, Uri absoluteUri, String relativeUri, SyndicationItem item, DictionaryContent content)
at System.Data.Services.Serializers.SyndicationSerializer.WriteEntryElement(IExpandedResult expanded, Object element, Type expectedType, Uri absoluteUri, String relativeUri, SyndicationItem target)
at System.Data.Services.Serializers.SyndicationSerializer.<DeferredFeedItems>d__0.MoveNext()
at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteItems(XmlWriter writer, IEnumerable`1 items, Uri feedBaseUri)
at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteFeedTo(XmlWriter writer, SyndicationFeed feed, Boolean isSourceFeed)
at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteFeed(XmlWriter writer)
at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteTo(XmlWriter writer)
at System.Data.Services.Serializers.SyndicationSerializer.WriteTopLevelElements(IExpandedResult expanded, IEnumerator elements, Boolean hasMoved)
at System.Data.Services.Serializers.Serializer.WriteRequest(IEnumerator queryResults, Boolean hasMoved)
at System.Data.Services.ResponseBodyWriter.Write(Stream stream)</p>
| <p>That looks like a bug. I suggest you report it at <a href="http://connect.microsoft.com/visualstudio/" rel="nofollow">http://connect.microsoft.com/visualstudio/</a>, then post the URL of your bug report here, so we can vote on it.</p>
|
What applications do you use for data entry and retrieval via ODBC? <p>What apps or tools do you use for data entry into your database? I'm trying to improve our existing (cumbersome) system that uses a php web based system for entering data one ... item ... at ... a ... time.</p>
<p>My current solution to this is to use a spreadsheet. It works well with text and numbers that are human readable, but not with foreign keys that are used to join with the other table's rows.</p>
<p>Imagine that I want a row of data to include what city someone lives in. The column holding this is id_city, which is keyed to the "city" table which has two columns: id (serial) and name (text).</p>
<p>I envision being able to extend the spreadsheet capabilities to include dropdown menu's for every row of the id_city column that would allow the user to select which city (displaying the text of the city names), but actually storing the city id chosen. This way, the spreadsheet would:<br>
(1) show a great deal of data on each screen and <br>
(2) could be exported as a csv file and thrown to our existing scripts that manually insert rows into the database.</p>
<p>I have been playing around with MS Excel and Access, as well as OpenOffice's suite, but have not found something that gives me the functionality I mention above. </p>
<p>Other items on my wish-list:<br>
(1) dynamically fetch the name of cities that can be selected by the user.<br>
(2) allow the user to push the data directly into the backend (not via external files/scripts.<br>
(3) If any of the columns of the rows of data gets changed in the backend, the user could refresh the data on the screen to reflect any recent changes.</p>
<p>Do you know how I could improve the process of data entry? What tools do you use? I use PostgreSQL for the backend and have access to MS Office, OpenOffice, as well as web based solutions. I would love a solution that is flexible, powerful, and doesn't require much time to develop or deploy (I know, dream on...)</p>
<p>I know that pgAdmin3 has similar functionality, but from what I have seen, it is more of an administrative tool rather than something for users to use.</p>
| <p>As j_random_hacker noted, I've used MS Access for years (since Access 97) to connect to an ODBC Data Source.</p>
<p>You can do this via linking to external tables: (in Access 2010:)</p>
<pre><code>New -> Blank Database
External Data -> ODBC Database -> Link to Data Source
Machine Data Source -> New -> System Data Source -> Select Driver (Oracle, or whatever) -> Finish
Enter a new name for your DSN, the all of the connection parameters, then click OK
Select newly created DSN, hit ok.
</code></pre>
<p>You can do so much once Access sees your external table as a linked table, including sorting, filtering, etc. There's one caveat: as far as I can tell, ALL operations happen on the client side unless you're using a pass-through query. That's fine if you're looking at a table with 3000 records. With 2,000,000 records, that hurts. To be clear, all data in the table comes down to the workstation, for all tables being joined, and the join happens client-side, NOT server-side.</p>
|
Microsoft Message Queue - priority flag or a separate queue? <p>I've implemented a system in C# that uses the Microsoft Message Queue (<code>System.Messaging</code>) for communication between related processes. Essentially, a number of <i>Sender</i> services generate messages to put in the queue and a number of <i>Receiver</i> processes watch the queues and grab those messages when they arrive.</p>
<p>I've just been told that there are some messages that will need priority over others.</p>
<p>Messages are likely to come in waves, and there could potentially be occasions where a very large number of messages are put in the queue in one hit (say a thousand or so), so there could be a delay before the final message gets processed.</p>
<p>My original thought was to have a second <i>Priority</i> message queue which is also watched by each of the <i>Receiver</i> processes in a different thread. There'd be far fewer messages in this queue so there'd be less delay.</p>
<p>Then I stumbled across the <code>Message.Priority</code> property.</p>
<p>So:</p>
<p>Should I use this Priority flag rather than implementing another queue? Will it successfully and efficiently jump these messages ahead of the rest? If so, what conditions and side effects are there likely to be if any?</p>
<p>Or should I stick with my original plan and implement another queue for priority messages?</p>
| <p>Should I use this Priority flag rather than implementing another queue? <strong>Yes</strong>.</p>
<p>Will it successfully and efficiently jump these messages ahead of the rest? <strong>Yes</strong>.</p>
<p>If so, what conditions and side effects are there likely to be if any? <strong>None, MSMQ was designed to work this way</strong>.</p>
|
Is there any way to pass an NSArray to a method that expects a variable number of arguments, such as +stringWithFormat: <p>Some context: I'm trying to clean up some of my FMDB code. My one table has a lot of columns and the method in FMDB I need to use is one that expects a variable number of arguments, similar to NSString's class method <code>+stringWithFormat:</code>.</p>
<p>An example:</p>
<pre><code>[db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" ,
@"hi'", // look! I put in a ', and I'm not escaping it!
[NSString stringWithFormat:@"number %d", i],
[NSNumber numberWithInt:i],
[NSDate date],
[NSNumber numberWithFloat:2.2f]];
</code></pre>
<p>When a table only has 5 columns it's not that bad but when a column has 20+ it starts to get hairy.</p>
<p>What I'd like to do is create a dictionary with all db abstraction information and build these queries dynamically. My question is... How in Objective-C do I fake out that method expecting a variable number of arguments and instead perhaps hand it an NSArray?</p>
<p>Related info: </p>
<p><a href="http://developer.apple.com/qa/qa2005/qa1405.html" rel="nofollow">How can I write a method that takes a variable number of arguments, like NSString's +stringWithFormat:?</a></p>
| <p>(Edit: This worked back in the GCC days. It doesn't under Clang as of Xcode 4.6.)</p>
<hr>
<p>Get the objects in the array into a C array, then treat that as a varargs list:</p>
<pre><code>//The example input array
int i = 42;
NSArray *array = [NSArray arrayWithObjects:
[NSString stringWithFormat:@"number %d", i],
[NSNumber numberWithInt:i],
[NSDate date],
[NSNumber numberWithFloat:2.2f],
nil];
//The example destination (using NSString so anyone can test this)
NSString *string = nil;
//The intermediary C array
NSObject **arrayObjects = malloc(sizeof(NSObject *) * [array count]);
if (arrayObjects) {
//Fill out the C array.
[array getObjects:arrayObjects];
//Use the C array as a va_list.
string = [[[NSString alloc] initWithFormat:@"%@ %@ %@ %@" arguments:(va_list)arrayObjects] autorelease];
free(arrayObjects);
}
NSLog(@"string: %@", string);
</code></pre>
<p>Output:</p>
<pre><code>2009-03-26 20:10:07.128 NSArray-varargs[606:10b] string: number 42 42 2009-03-26 20:10:07 -0700 2.2
</code></pre>
<p>In your case, you'll use the <code>-[FMDatabase executeUpdate:arguments:]</code> method.</p>
|
Same rules for multiple directories in Apache? <p>I have 2 subdomains which use the same rules, as seen below:</p>
<pre><code><Directory /srv/project/sites/project.hu/htdocs/>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\?*$ index.php?route=$1 [L,QSA]
SetEnv config default,local
Order allow,deny
allow from 192.168.0.0/16
</Directory>
<Directory /srv/project/sites/admin.project.hu/htdocs/>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\?*$ index.php?route=$1 [L,QSA]
SetEnv config default,local
Order allow,deny
allow from 192.168.0.0/16
</Directory>
</code></pre>
<p>As you can see the rules are the same in both containers.
How can I specify these rules in a single container?
At first I thought about using this:</p>
<pre><code><DirectoryMatch ^/srv/project/sites/(?:(?:admin\.project\.hu)|project\.hu)/htdocs/$>
...
</DirectoryMatch>
</code></pre>
<p>But isn't there a way to do this in a more clean way that I'm missing?</p>
<p>Edit:
I dislike the DirectoryMatch way, because when when I'll have more directories, the regex will grow unmaintainable.</p>
| <p>put the rewrite rules into a separate file, eg. <code>rewrite.conf</code>, and <a href="http://httpd.apache.org/docs/2.2/mod/core.html#include">include</a> it like so</p>
<pre><code><Directory /srv/project/sites/project.hu/htdocs/>
Include rewrite.conf
</Directory>
<Directory /srv/project/sites/admin.project.hu/htdocs/>
Include rewrite.conf
</Directory>
</code></pre>
|
IDE for debugging 'C source in linux <p>Recently I am developing using 'C in Linux platforms, the tools like gcc are fast. But I wish it would be great to have an IDE like the VC++ IDE for windows.</p>
| <ul>
<li><a href="http://www.codeblocks.org/">Code::Blocks</a></li>
<li><a href="http://anjuta.sourceforge.net/">Anjuta</a></li>
<li><a href="http://www.kdevelop.org/">KDevelop</a></li>
<li>Or <a href="http://www.google.com/search?q=site:stackoverflow.com%2Bc%2Bide%2Blinux">check</a> <a href="http://stackoverflow.com/questions/579219/best-unix-linux-c-debuger-ide">on</a> <a href="http://stackoverflow.com/questions/24109/c-ide-for-linux">StackOverflow</a></li>
</ul>
|
Formula for a orthogonal projection matrix? <p>I've been looking around a bit and can't seem to find just what I"m looking for. I've found "canonical formulas," but what's the best way to use these? Do I have to scale every single vertex down? Or is there a better way?</p>
<p>A formula would really help me out, but I'm also looking for an explanation about the near and far z planes relative the viewer's position</p>
| <p>Here is a reasonable source that derives an <a href="http://www.codeguru.com/cpp/misc/misc/math/article.php/c10123__2/" rel="nofollow">orthogonal project matrix</a>:</p>
<blockquote>
<p>Consider a few points: First, in eye
space, your camera is positioned at
the origin and looking directly down
the z-axis. And second, you usually
want your field of view to extend
equally far to the left as it does to
the right, and equally far above the
z-axis as below. If that is the case,
the z-axis passes directly through the
center of your view volume, and so you
have r = âl and t = âb. In other
words, you can forget about r, l, t,
and b altogether, and simply define
your view volume in terms of a width
w, and a height h, along with your
other clipping planes f and n. If you
make those substitutions into the
orthographic projection matrix above,
you get this rather simplified
version:</p>
</blockquote>
<p>All of the above gives you a matrix that looks like this (add rotation and translation as appropriate if you'd like your resulting transformation matrix to treat an arbitrary camera position and orientation).</p>
<p><img src="http://www.codeguru.com/images/article/10123/3dproj20.gif" alt="A LaTeX rendering of the orthographic projection matrix"></p>
|
How to read integer in Erlang? <p>I'm trying to read user input of integer. (like cin >> nInput; in C++)<br>
I found io:fread bif from <a href="http://www.erlang.org/doc/man/io.html">http://www.erlang.org/doc/man/io.html</a>, so I write code like this.<br></p>
<blockquote>
<p>{ok, X} = io:fread("input : ",
"~d"),<br> io:format("~p~n", [X]).<br></p>
</blockquote>
<p>but when I input 10, the erlang terminal keep giving me "\n" not 10. I assume fread automatically read 10 and conert this into string. How can I read integer value directly? Is there any way to do this? Thank you for reading this.</p>
| <pre><code>1> {ok, [X]} = io:fread("input : ", "~d").
input : 10
{ok,"\n"}
2> X.
10
3> {ok, [A,B]} = io:fread("input : ", "~d,~d").
input : 456,26
{ok,[456,26]}
</code></pre>
<p>That's all.</p>
|
Using Winsock and C to talk with an FTP server <p>How would I go about doing this?</p>
| <p><a href="http://cs.baylor.edu/~donahoo/practical/CSockets/winsock.html" rel="nofollow">TCP/IP Sockets in C: Practical Guide for Programmers</a> has a number of C code examples using Winsock.</p>
<p>There isn't one for FTP but it will get you on your way.</p>
|
How to get the memory a function consumes <p>Our application consumes lots of memory and we need to identify which function cause the maximum usage of the memory. Is their any way or even any existing tool to do this(Windows, Native)?</p>
<p><strong>Here is the environment:</strong></p>
<p>Windows Xp</p>
<p>VS2008</p>
<p>Native C++ (MFC Based)</p>
<p>Thanks so much.</p>
| <p>If you have Visual Studio 2008 Team System you can use the <a href="http://blogs.msdn.com/buckh/archive/2007/10/09/using-vsts-2008-memory-allocation-profiling.aspx" rel="nofollow">built-in memory allocation</a> profiler. Here's a good MSDN article, <a href="http://msdn.microsoft.com/en-us/magazine/cc337887.aspx" rel="nofollow">Find Application Bottlenecks with Visual Studio Profiler</a> using VS2008. There is also a profiler <a href="http://blogs.msdn.com/profiler/" rel="nofollow">blog</a>.</p>
<p><a href="http://www.red-gate.com/products/ANTS%5FProfiler/index.htm?gclid=CMLElISKwpkCFRxNagodFBUXuQ" rel="nofollow">RedGate's ANTS</a></p>
<p><a href="http://memprofiler.com/" rel="nofollow">MemProfiler</a></p>
<p><a href="http://valgrind.org/" rel="nofollow">ValGrind</a> (free)</p>
<p>EDIT: since you updated to indicate C++, please also see this SO <a href="http://stackoverflow.com/questions/292457/profiler-for-visual-studio-2008-c">answer</a>.</p>
<p>See Also:</p>
<p><a href="http://stackoverflow.com/questions/399847/-net-memory-profiling-tools">http://stackoverflow.com/questions/399847/-net-memory-profiling-tools</a></p>
<p><a href="http://stackoverflow.com/questions/46642/does-anyone-here-have-a-favorite-memory-profiling-memory-leak-tool-they-like-to-u">http://stackoverflow.com/questions/46642/does-anyone-here-have-a-favorite-memory-profiling-memory-leak-tool-they-like-to-u</a></p>
<p><a href="http://stackoverflow.com/questions/49912/best-dotnet-memory-and-performance-profiler">http://stackoverflow.com/questions/49912/best-dotnet-memory-and-performance-profiler</a></p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.