input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Using PowerMock or How much do you let your tests affect your design? <p>I've been a fan of EasyMock for many years now, and thanks to SO I came across references to PowerMock and it's ability to mock Constructors and static methods, both of which cause problems when retrofitting tests to a legacy codebase. </p>
<p>Obviously one of the huge benefits of unit testing (and TDD) is the way it leads to (forces?) a much cleaner design, and it seems to me that the introduction of PowerMock may detract from that. I would see this mostly manifesting itself as:</p>
<ol>
<li>Going back to initialising collaborators rather than injecting them</li>
<li>Using statics rather than making the method be owned by a collaborator</li>
</ol>
<p>In addition to this, something doesn't quite sit right with me about my code being bytecode manipulated for the test. I can't really give a concrete reason for this, just that it makes me feel a little uneasy as it's just for the test and not for production.</p>
<p>At my current gig we're really pushing for the unit tests as a way for people to improve their coding practices and it feels like introducing PowerMock into the equation may let people skip that step somewhat and so I'm loathe to start using it. Having said that, I can really see where making use of it can cut down on the amount of refactoring that needs to be done to <em>start</em> testing a class.</p>
<p>I guess my question is, what are peoples experiences of using PowerMock (or any other similar library) for these features, would you make use of them and how much overall do you want your tests influencing your design?</p>
| <p>I have to strongly disagree with this question.</p>
<p>There is no justification for a mocking tool that limits design choices. It's not just static methods that are ruled out by EasyMock, EasyMock Class Extension, jMock, Mockito, and others. These tools also prevent you from declaring classes and methods <code>final</code>, and that alone is a very bad thing. (If you need one authoritative source that defends the use of <code>final</code> for classes and methods, see the "Effective Java" book, or watch this <a href="http://www.youtube.com/watch?v=aAb7hSCtvGw">presentation</a> from the author.)</p>
<p>And "initialising collaborators rather than injecting them" often is the <em>best</em> design, in my experience. If you decompose a class that solves some complex problem by creating helper classes that are instantiated from that class, you can take advantage of the ability to safely pass specific data to those child objects, while at the same time hiding them from client code (which provided the full data used in the high-level operation). Exposing such helper classes in the public API violates the principle of information hiding, breaking encapsulation and increasing the complexity of client code.</p>
<p>The abuse of DI leads to stateless objects which really should be stateful because they will <em>almost always</em> operate on data that is specific to the business operation.
This is not only true for non-public helper classes, but also for public "business service" classes called from UI/presentation objects. Such service classes are usually internal code (to a single business application) that is inherently not reusable and have only a few clients (often only one) because such code is by nature <em>domain/use-case specific</em>.
In such a case (a very common one, by the way) it makes much more sense to have the UI class directly instantiate the business service class, passing data provided by the user through a constructor.</p>
<p>Being able to easily write unit tests for code like this is precisely what led me to create the <a href="http://jmockit.org">JMockit</a> toolkit. I wasn't thinking about legacy code, but about simplicity and economy of design. The results I achieved so far convinced me that <em>testability</em> really is a function of two variables: the <em>maintainability</em> of production code, and the limitations of the mocking tool used to test that code. So, if you remove <em>all</em> limitations from the mocking tool, what do you get?</p>
|
When to use If-else if-else over switch statments and vice versa <p>Why you would want to use a switch block over a series <code>if</code> statements?</p>
<p>Switch statements seem to do the same thing but take longer to type.</p>
| <p>As with most things you should pick which to use based on the context and what is conceptually the correct way to go. A switch is really saying "pick one of these based on this variables value" but an if statement is just a series of boolean checks.</p>
<p>As an example, if you were doing:</p>
<pre><code>int value = // some value
if (value == 1) {
doThis();
} else if (value == 2) {
doThat();
} else {
doTheOther();
}
</code></pre>
<p>This would be much better represented as a switch as it then makes it immediately obviously that the choice of action is occurring based on the value of "value" and not some arbitrary test.</p>
<p>Also, if you find yourself writing switches and if-elses and using an OO language you should be considering getting rid of them and using polymorphism to achieve the same result if possible.</p>
<p>Finally, regarding switch taking longer to type, I can't remember who said it but I did once read someone ask "is your typing speed really the thing that affects how quickly you code?" (paraphrased)</p>
|
How do I configure WinCE to use wildcard SSL certificates? <p>Our Windows CE 5.0 application has a problem with our wildcard SSL certificate (*.domain.com) - it won't accept it as valid.</p>
<p>I understand that Windows Mobile 6.0 has support for wildcard certificates (earlier versions don't) and that is built on WinCE 5 which suggests it should be possible to change WinCE 5 to accept wildcard certificates (EDIT - apparently this shows my limited understanding of the environment and isn't a valid presumption!).</p>
<p>Can anyone suggest how we go about this? The change needs to be programmatic so that we can roll it out to hundreds of existing clients.</p>
<p>Help!</p>
| <p>This will accept all certs, modify as needed.</p>
<p>System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();</p>
<pre><code>public class TrustAllCertificatePolicy : System.Net.ICertificatePolicy
{
public TrustAllCertificatePolicy()
{ }
public bool CheckValidationResult(ServicePoint sp, System.Security.Cryptography.X509Certificates.X509Certificate cert, WebRequest req, int problem)
{
return true;
}
}
</code></pre>
|
Refresh problems with databinding between Listview and ComboBox <p>I am wrestling with a binding problem in WPF/Silverlight. I have a Listview witch is filled by a DataContext form an EF linq query. In the same usercontrol are textboxes. When changing their values, the listview gets refresht and the data is changed in de db bij .SaveChanges. The problem is that if I use a combobox the data is saved but de listview isn't updated.</p>
<p>Can you be of help????
Here is the xaml</p>
<pre><code> <ListView Grid.Row="1" Grid.Column="0" Margin="4,4,4,0" x:Name="controlsListBox" Grid.RowSpan="7" ItemsSource="{Binding}" SelectedValuePath="ID" LostFocus="controlsListBox_LostFocus">
<ListView.View>
<GridView>
<GridViewColumn Width="25" Header="Rw" DisplayMemberBinding="{Binding RowNr}"/>
<GridViewColumn Width="25" Header="Cl" DisplayMemberBinding="{Binding ColumnNr}"/>
<GridViewColumn Width="100" Header="Name" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Width="25" Header="Tb" DisplayMemberBinding="{Binding TabIndex}"/>
<GridViewColumn Width="100" Header="Type" DisplayMemberBinding="{Binding ControlTypes.Name}"/>
<GridViewColumn Width="100" Header="Text" DisplayMemberBinding="{Binding TextResources.Text}"/>
</GridView>
</ListView.View>
</ListView>
<Label Grid.Row="2" Grid.Column="5" Height="23" Margin="4,4,4,0" x:Name="rowSpanLabel" VerticalAlignment="Top"
Content="RowNr"/>
<TextBox Grid.Row="2" Grid.Column="6" Height="23" Margin="4,4,4,0" x:Name="rowSpanTextBox" VerticalAlignment="Top"
Text="{Binding Path=SelectedItem.RowNr, ElementName=controlsListBox}"/>
<Label Grid.Row="4" Grid.Column="1" Grid.ColumnSpan="2" Height="23" Margin="4,4,4,0" x:Name="controlTypeLabel" VerticalAlignment="Top"
Content="Type"/>
<ComboBox Grid.Row="4" Grid.Column="2" Grid.ColumnSpan="5" Height="23" Margin="4,4,4,0" x:Name="controlTypeComboBox" VerticalAlignment="Top"
DataContext="{Binding Path=ControlTypes, ElementName=controlsListBox}" IsSynchronizedWithCurrentItem="True" DisplayMemberPath="Name"
SelectedItem="{Binding Path=SelectedItem.ControlTypes, ElementName=controlsListBox, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
/>
</code></pre>
<p>And here the C# code:
_controlProperties.Clear();
var data = (from x in _dataContext.ControlProperties
where x.FormProperties.ID == 1
orderby x.RowNr, x.ColumnNr, x.Name
select x);
foreach (var item in data)
{
item.TextResourcesReference.Load();
_controlProperties.Add(item);
}
// DataContext must first be set to null for good result.
controlsListBox.DataContext = null;
controlsListBox.DataContext = _controlProperties;</p>
<pre><code> controlTypeComboBox.DataContext = (from c in _dataContext.ControlTypes
orderby c.Name
select c).ToList();
</code></pre>
| <p>You are setting the DataContext of the ComboBox, but not the ItemsSource. In code, you are overwriting that DataContext by providing a list of control types, so that part of the XAML is ignored anyway.</p>
<p>Remove the DataContext declaration and use this instead:</p>
<pre><code>ItemsSource="{Binding}"
</code></pre>
<p>That should cause the control types to appear in the combo box. When I do this, the selected control type gets displayed in the list view.</p>
<p>You might also want to look into <a href="http://codeplex.com/updatecontrols" rel="nofollow">Update Controls .NET</a>, my open-source alternative to WPF data binding. It takes some of the bookkeeping out of the bound classes.</p>
|
How to programmatically manipulate an EPS file <p>I am looking for libraries that would help in programatically manipulating EPS (Encapsulated PostScript) files. Basically, what I want to do is following:</p>
<ul>
<li>Show / Hide preexisting layers in the EPS file (toggle them on and off)</li>
<li>Fill (color) named shapes in the EPS file</li>
<li>Retrieve coordinates of named points in the EPS file</li>
<li>draw shapes on a new layer in the EPS file</li>
<li>on a server, without user interaction (scripting Adobe Illustrator won't work)</li>
</ul>
<p>I am aware of how the EPS file format is based on the PostScript language and must therefore be interpreted - for creating simple drawings from scratch this is rather easy. But for actually modifying existing files, I guess you need a library that interprets the file and provides some kind of "DOM" for manipulation.</p>
<p>Can I even have named shapes and points inside an EPS file?</p>
<p><strong>EDIT:</strong> Assuming I had the layers saved in separate EPS files. Or better still: Just the "data" part of the layers. Could I then concatenate this stuff to create a new EPS file? And append drawing commands? Fill existing named objects?</p>
| <p>This is extremely difficult and here is why: a PS file is a program whose execution results in pixels put on a page. Instruction in a PS program are at the level of "draw a line using the current pen and color" or "rotate the coordinate system by 90 degrees" but there is no notion of layers or complex objects like you would see them in a vector drawing application.</p>
<p>There are very few conventions in the structure of PS files to allow external programs to modify them: pages are marked separately, font resources, and media dimensions are spelled out in special comments. This is especially true for Embedded Postscript (EPS) which must follow these guidelines because they are meant to be read by applications but not for general PS as it is sent to a printer. A PS program is a much lower level of abstraction than what you need and there is now way to reconstruct it for arbitrary PS code. In principle could a PS file result in different output every time it is printed because it may query its execution environment and branch based on random decisions.</p>
<p>Applications like Adobe Illustrator emit PS code that follow a rigid structure. There is a chance that these could be parsed and manipulated without interpreting the code. I would stil suggest to rethink the current architecture: you are at a too low level of abstraction for what you need.</p>
|
Slow refresh on panel scrolling <p>I'm developing an user control that I need for a project, the control have around 13 rows, 7 columns of textboxes, comboboxes... everything on a form autoscrollable.
The problem is that in execution time when scrolling the content refreshing is very very slow.
Some idea?</p>
<p>Using a datagridview is not an option.</p>
<p>Edit:</p>
<p>I should be more specific, the 13 row controls are in the usercontrol.
I have changed the uc's doublebuferred property to true, I can't change the child controls because all them are standard text and comboboxes, so there isn't such property.
In the main form I'm creating around 7 of this usercontrols dynamically inside of an autoscrollable panel, the problem comes scrolling the panel, the refresh is extremely slow.
And yes, I neither can believe that the winforms could be so bad.</p>
<p>Regards.</p>
| <p>Try using <code>DoubleBuffered = true</code> within the constructor of your UserControl.</p>
|
How does object reuse work in .NET? <p>I've recently moved from VB6 to VB.NET and I am finally getting there with understanding the inner workings. I've been looking at my company's existing codebase and I am a little suprised. </p>
<p>I understand that when VB.NET creates a string it see's if the string is in memory and if not creates a new instance of that string, otherwise it points the new variable to the old . However I wonder if it does this with other objects?</p>
<p>The reason I ask is my new company has a DATABASE object which basically wraps database connection info and database connections in a object.</p>
<p>We also have a BOOK object and a PAGES object.</p>
<p>My best practice in VB6 would be to create a DATABASE object and then pass (byRef) that to the BOOK and then PAGES object, so you have one DATABASE object passed to muliple books and then PAGES.</p>
<p><em>However</em>, how they have done it is to create a new instance of the DATABASE object in each PAGE and each PAGE object, which means you could have muliple instances (thousands in fact) of objects which are in fact all the same.</p>
<p>Is this wise? Or do objects get handled like Strings?</p>
| <p>Your understanding of strings is only applicable to string constants - not strings which are created in any other way.</p>
<p>If the thousands of Database objects are all "the same" then it sounds like they should actually be passing a reference to the same object around. You need to understand <a href="http://pobox.com/~skeet/csharp/references.html" rel="nofollow">the difference between a reference and an object</a>.</p>
<p>Finally, nothing in your code should be holding onto connections, in all likelihood. It's almost always better to open the connection, do whatever you need to, and then close it again. The connection pooling system can make sure that the <em>real</em> connection to the database (which is relatively expensive to create) is reused.</p>
|
How can I replicate the trashing animation of Mail.app <p>In my iPhone app, I have put a UIBarBUtton of type UIBarButtonSystemItemTrash in my UIToolBar. When pressed, I'd like to replicate the animation of Mail.app: the bin opens, the UIView folds and flies into it.<br />
Is there a way to access this animation ithrough the iPhone SDK? </p>
<p>Presently I am using a custom made animation, but there are some limits; for example, I cannot animate the bin itself.
Do you have any suggestion? Code samples?</p>
<p>Cheers,<br />
Davide</p>
| <p>Use the suckEffect type on an animation. Also: spewEffect, genieEffect, unGenieEffect, twist, tubey, swirl, cameraIris, cameraIrisHollowClose, cameraIrisHollowOpen, rippleEffect, charminUltra, zoomyIn, and zoomyOut. Doesn't work in the simulator.</p>
<pre><code>CATransition *animation = [CATransition animation];
animation.type = @"suckEffect";
animation.duration = 2.0f;
animation.timingFunction = UIViewAnimationCurveEaseInOut;
view.opacity = 1.0f;
[view.layer addAnimation:animation forKey:@"transitionViewAnimation"];
</code></pre>
<p>Note: Code snippet was pulled from a larger codebase. I hope it works :)</p>
|
css : round cornered div on hover <p>I am trying to accomplish something that seemed quite simple... </p>
<p>I have 3 divs that contain a radiobutton and some content:</p>
<pre><code> Content of DIV1,
[] this can be as long or as tall
as wanted
[] Content of DIV2
[] Content of DIV3
</code></pre>
<p>It's easy to create rounded corners for each div using any techniques found on <a href="http://stackoverflow.com/questions/7089/what-is-the-best-way-to-create-rounded-corners-using-css">other posts</a> here. Yet, I haven't been able to do that only for the hover event, ie I would like to see the rounded box appear around the div only when the mouse hovers over it. Has anyone seen an example of this being done somewhere?</p>
<p><strong>Edit</strong>: I'm already using Prototype and Scriptaculous. I can't add jQuery just for this.</p>
| <p>this changes the CSS with jquery on the hover of a div</p>
<pre><code>print("<div id="output" class="div"></div>
<script>
jQuery(document).ready(function() {
$("#output").hover(function() {
$(this).css({ 'background-color': 'yellow', 'font-weight': 'bolder' });
}, function() {
$(this).css({ 'background-color': 'blue', 'font-weight': 'bolder' });
});
}
);
</code></pre>
<p> ");</p>
|
Select either a file or folder from the same dialog in .NET <p>Is there an "easy" way to select either a file OR a folder from the same dialog?</p>
<p>In many apps I create I allow for both files or folders as input.
Until now i always end up creating a switch to toggle between file or folder selection dialogs or stick with drag-and-drop functionality only. </p>
<p>Since this seems such a basic thing i would imagine this has been created before, but googling does not result in much information. So it looks like i would need to start from scratch and create a custom selection Dialog, but I rather not introduce any problems by reinventing the wheel for such a trivial task.</p>
<p>Anybody any tips or existing solutions?</p>
<p>To keep the UI consistent it would be nice if it is possible to extend the OpenFileDialog (or the FolderBrowserDialog).</p>
| <p>Technically, it is possible. The shell dialog used by FolderBrowseDialog has the ability to return both files and folders. Unfortunately, that capability isn't exposed in .NET. Not even reflection can poke the required option flag.</p>
<p>To make it work, you'd have to P/Invoke SHBrowseForFolder() with the BIF_BROWSEINCLUDEFILES flag turned on in BROWSEINFO.ulFlags (value = 0x4000). The P/Invoke is gritty, it is best to copy and paste the code from <a href="http://www.google.com/search?hl=en&q=shbrowseforfolder+structlayout&btnG=Google+Search&aq=f&oq=">another source</a> or the FolderBrowseDialog class itself with Reflector's help.</p>
|
Performance Point, Dashboard Designer <ol>
<li>I am brand new to this product. Microsoft has some good free videos...but I am looking for a site where I can ask question about 'how to', or post problems..any recommendations?</li>
</ol>
<p>(<a href="http://www.microsoft.com/business/performancepoint/resources/training.aspx" rel="nofollow">http://www.microsoft.com/business/performancepoint/resources/training.aspx</a>)</p>
<ol>
<li>Just in case this is a good site for that...</li>
</ol>
<p>I want to bring in a sql table to dashboard designer, and produce a scorecard based on 83 operational metrics across 12 divisions... I have a simple table schema: </p>
<p>key, metric_ID, value1, value2, value3, value4, value5, CalendarWeek, Year, Entered, Updated)</p>
<p>I have sql jobs that crawl to multiple databases and write back the base data weekly. The idea is that I would let the dashboard designer produce the actual metric, based on the metric needs. </p>
<p>eg. for hotline performance closed calls on the first call, over calls received:
(45, 16, 786, 1345,null,null,null,1,2009, 1/5/2009 6am, null) </p>
<p>786/1345 = 58% against an operational target of 50% .. so the kpi would be green.</p>
<p>my problem is;</p>
<ol>
<li><p>when I create a scorecard using the tabluar wizard, I just get a scorecard listing the fields as rows (786, 1345, blank, blank, blank); with Actual and Target as the columns... how do I do the calculation of the metric?..or do I need to expand my sql table to actually DO the math for the metric??...</p></li>
<li><p>I dont quite get the concept of dimensionality yet...the dimensions are the Entered and Updated dates...not quite what I need..i think...</p></li>
</ol>
<p>soo...how do I structure my sql table to bring in these metrics, and how do I 'dimension' the connector for dashboard designer to do the metric calculation?</p>
| <p>I would do the calculation on your database side. Then it's simple to just pull the caculated value into the dashboard. Dashboard Designer isn't the best at doing calculations (beyond normal aggregations like sum, average, etc).</p>
|
How can I hide some content from some users with PHP? <p>I have created an intranet for our company using PHP. The same menu appears on every page, and includes links to sensitive pages and documents (like Word files).</p>
<p>Currently only in-office employees have access to the site, but we'd like to open it up to some out-of-office contractors. The catch is that I'd have to restrict access for certain content.</p>
<p>I know <a href="http://www.elated.com/articles/password-protecting-your-pages-with-htaccess" rel="nofollow">how to password-protect site directories with Apache</a>, but I'd rather hide the menu options themselves.</p>
<p>How would you approach this?</p>
<p><strong>Clarification</strong>: This is in an environment where everyone is logged in to our Windows network, locally or via VPN, but currently nobody has to log in to see my intranet site. The ideal solution would not require them to do anything extra, if that's possible.</p>
| <p>If users are logging in, then you can use their login details to restrict access. You might want to look into the idea of <a href="http://en.wikipedia.org/wiki/Access_Control_Lists" rel="nofollow">Access Control Lists</a>.</p>
<p>If your users are logging in using Apache, then you can access their user name from $_SERVER['PHP_AUTH_USER']. So you might want to do something like this:</p>
<pre><code>$username = $_SERVER['PHP_AUTH_USER'];
$user_id = lookup_user_id($username); // a function you write that looks up their user id in your database of users
</code></pre>
<p>Then you can look up their access level(s) similarly -- they might have a user-status, like "Guest" or "Super-user" or "Administrator", or you might want to go so far as to have a matrix of resources and users, specifying for each user and resource whether that user can access the resource.</p>
<p>Otherwise, a framework like CakePHP will give you this kind of thing for (almost) free.</p>
|
Assigning cout to a variable name <p>In ANSI C++, how can I assign the cout stream to a variable name? What I want to do is, if the user has specified an output file name, I send output there, otherwise, send it to the screen. So something like:</p>
<pre><code>ofstream outFile;
if (outFileRequested)
outFile.open("foo.txt", ios::out);
else
outFile = cout; // Will not compile because outFile does not have an
// assignment operator
outFile << "whatever" << endl;
</code></pre>
<p>I tried doing this as a Macro function as well:</p>
<pre><code>#define OUTPUT outFileRequested?outFile:cout
OUTPUT << "whatever" << endl;
</code></pre>
<p>But that gave me a compiler error as well.</p>
<p>I supposed I could either use an IF-THEN block for every output, but I'd like to avoid that if I could. Any ideas? </p>
| <p>Use a reference. Note that the reference must be of type <code>std::ostream</code>, not <code>std::ofstream</code>, since <code>std::cout</code> is an <code>std::ostream</code>, so you must use the least common denominator.</p>
<pre><code>std::ofstream realOutFile;
if(outFileRequested)
realOutFile.open("foo.txt", std::ios::out);
std::ostream & outFile = (outFileRequested ? realOutFile : std::cout);
</code></pre>
|
Windows .Net controls - Creating property templates <p>Assume that all text box controls in my .Net Windows application created by dragging a TextBox control onto the Form editor should have the following default properties (some text box instances can override these properties) : <br></p>
<p>Text Align: Centre <br/>
Resize : As per content <br/>
Dock: Left, Top and Right<br/>
</b></p>
<p>Now, it becomes cumbersome and manually boring task to set these properties every time it is needed. Is there any way by which these properties can be defaulted at an "Assembly level".
I know that User controls will solve the problem, but that I believe that it is a costly solution, and I think that there should be a simpler and more elegant solution for this problem.
Thanks</p>
| <p>You have two options here.</p>
<p>The first is to create a method that iterates over all nested controls on a form, and picks the textboxes and change the properties, then call this property in the form's initialization code.</p>
<p>The other is to inherit the textbox control in question, and change the properties to your liking in its constructor (and maybe shadowing the properties to expose different defaultvalues to the propertygrid). To make the control available in the form designer, it must be created in a separate propject from where it is supposed to be used, and then referenced in the first project.</p>
|
Visual Studio shortcut for showing dropdown of available Enum values for function argument <p>When calling an overloaded argument in visual studio, visual studio often doesn't show the dropdown of available enumerated values available for a function argument. Is there a shortcut one can use the force the dropdown to be displayed, so one doesn't have to type the fully qualified path to the enum declaration?</p>
| <p>CTRL + SHIFT + SPACEBAR to show methods overloads</p>
<p>CTRL + SPACEBAR to show Enum values</p>
|
Pass anonymous function by value in javascript? <p>I have a function that accepts an anonymous function as an argument and sets it to a variable (scoped) for reference. I then try to execute another function with that reference but it obviously fails since that function is out of scope.</p>
<p>I was wondering if anyone knew of a simple way of passing the anonymous function straight through as an anonymous function, avoiding the scoping issue?</p>
<p><strong>EDIT</strong>: To clarify, the el element is defined after the function is isolated from the arguments list. Additionally, the el element is a part of the arguments list as well. Were this code to be used by only me, I would likely have used a two argument list with the second argument being an array or hash object but unfortunately this code is going to be used by some folks who are less familiar with JS or even coding for that matter.</p>
<p>Thanks for the help!</p>
<p>Here is the relevant portion of my code:</p>
<pre><code>locate : function(){
if ((!arguments)||(!arguments.length)) return;
arguments = [].splice.call(arguments,0); //This just converts arguments into an array
for (var i=0;i<arguments.length;i++){
if (typeof(arguments[i])=='function'){
var tf = arguments.splice(i,1);
break;
};
};
if (!tf) return;
JAS.Globals.eventListen('click',el,tf);
}
</code></pre>
<p>This is abbreviated so just trust that el is defined.
JAS.Globals.eventListen is just an intelligent addEventListener.</p>
| <pre><code> var tf = arguments.splice(i,1)
</code></pre>
<p>This returns an array into tf. Is eventListen expecting an array? If not use:-</p>
<pre><code> var tf = arguments.splice(i,1)[0]
</code></pre>
<p>Since you don't seem to have any other uses for your other arguments why are you using splice anyway?</p>
|
How can I hook into the UI rendering "engine" of ASP.NET Dynamic Data? <p>I have decorated my model using Metadata classes attached to my model classes via the MetadataType attribute. I have some use the Range attribute, Required attribute, etc. <em>and some custom attributes I have created.</em> </p>
<p>Now I want to hook into the rendering engine (or whatever it is called) of the Dynamic Data framework and be able to change the way the UI is rendered based on <em>my custom attributes</em> as well as the standard System.ComponentModel.DataAnnotations attributes.</p>
<p>Also, I might want to use ASP.NET MVC, so keep that in mind.</p>
<p>How do I do that? Pointing me to links would be great if you don't want to be verbose about explaining the nitty-gritty.</p>
<p>Thanks!</p>
| <p>There is a dynamic data project for ASP.NET MVC, but I think it is pretty much on hold:</p>
<p><a href="http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=15459" rel="nofollow">http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=15459</a></p>
<p>I looked at it a while back and it partly worked, but I don't think it works with the latest bits. I think eventually they are going to pull everything together, but it will be some time. What I do right now is I have some helper classes that read the metadata for example to show required fields, but I am not using the full blown rendering of dynamic data. You can pull the metadata like this:</p>
<pre><code>public static MetaColumn GetColumn(Type t, string columnName)
{
MetaModel model = new MetaModel();
MetaTable table = model.GetTable(t);
MetaColumn column = table.GetColumn(columnName);
return column;
}
public static string GetDisplayName(Type t, string columnName)
{
MetaColumn column = GetColumn(t, columnName);
return column.DisplayName;
}
</code></pre>
<p>For now I'm just using some of the metadata. Would like to know if you come up with anything further that this. </p>
|
What are the possibly situations that .net Viewstate could stop working? <p>Consider the following code:</p>
<pre><code> Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
If Page.IsPostBack Then
If ViewState("test") IsNot Nothing Then
Response.Write((ViewState("test").ToString))
Else
Response.Write("Viewstate is empty.")
End If
Else
ViewState("test") = "viewstate is working."
End If
End Sub
</code></pre>
<p>This code doesn't work on a particular page in my application. Viewstate is not turned off in the Page directive. I can't figure out what's going on. : \</p>
<p>Oh i just figured it out. See if you notice it.</p>
<blockquote>
<p>.<</p>
</blockquote>
| <p>Figured it out, someone had changed the Page_Load event to handle Page.Init</p>
<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
</code></pre>
|
Changing the owner of an existing process in Linux <p>I would like to start tomcat (Web Server) as a privileged user, and then bring it back to an unprivileged user once it has started. Is there a way to do this programatically, or in general with Linux?</p>
<p>Thanks.</p>
| <p>The underlying system call that you need is <code>setuid(2)</code>, but it's not exposed by any of the Java APIs.</p>
<p>It's not hard to write a JNI wrapper that would give access to it though, although even then you'd need to find a suitable place in the Tomcat startup code to invoke <code>setuid</code> after the <code>bind(2)</code> calls have been made (those being the ones that normally require the root privileges).</p>
<p>As recommended by <a href="http://stackoverflow.com/users/37507/geocar">geocar</a> you could use <code>authbind</code> so that Tomcat never needs to run as root at all.</p>
<p>Alternatively, as you've presumably got root access on the server in question, just run Tomcat on a non-privileged port and then use <code>iptables</code> tricks to forward inbound requests from the privileged port to the one that Tomcat is actually listening on. See <a href="http://stackoverflow.com/questions/277991/linux-how-to-run-a-server-on-port-80-as-normal-user">this SO post</a> for info on how to do this.</p>
|
How do I return multiple datatables from a SQL Server stored procedured? <p>I need to make two queries on two different tables and the data isn't really related. So when I call the stored proc through my code, I should be getting a DataSet with two DataTables, one DataTable for each query. How is that done in SQL Server stored procs?</p>
| <p>Simply execute two SELECT statements in the proc:</p>
<pre><code>SELECT * FROM Foo
SELECT * FROM Bla
</code></pre>
<p>when you then Fill() a dataset, you'll get two datatables, one with the first resultset, the other with the second. </p>
|
auto-detecting components using spring annotations <p>I've managed to configure to spring to auto-detect my components using the @Autowire
annotation. However the problem is that not all the components are being Auto wired.<br />
Specifically My DAO's are being bound but my service objects aren't. I have to explicitly
create a bean for my service object in the spring xml config file.</p>
<p>Any clue as to why this is happening?</p>
| <p>If spring is not complaining about anything but it's still not being wired, there are a few probable causes, from most to least likely:</p>
<ul>
<li>The service implementation is missing the proper annotation; i.e @Component, @Controller, @Service or one of the other annotations.</li>
<li>If the implementation is not annotated it has to be present as an xml bean definition.</li>
<li>The classpath-scan you have set up in the xml file does not hit the service.</li>
<li>Your jar file with services is packed without directory structure.</li>
</ul>
|
Generating absolute URLs from Seam emails <p>Is there a way to coax either the <code>h:outputLink</code> or <code>s:link</code> tags into generating absolute URLs? In a Seam email message, I want to be able to do something like</p>
<pre><code><s:link view="/someView.xhtml">
<f:param name="a" value="#{a.nastyParam}" />
<f:param name="b" value="#{b.nastyParam}" />
<h:outputText value="Come do something awesome!" />
</s:link>
</code></pre>
<p>and generate an absolute URL without the fuss of messing with URL encoding, prepending the protocol, host, context path, etc.</p>
| <p>Never mind... I should have looked more closely at my copy of "Seam in Action" before asking this one. Setting the <code>urlBase</code> attribute on the <code>m:message</code> tag did the trick.</p>
|
WPF: Best way to raise a popup window that is modal to the page? <p>I am building a WPF app using navigation style pages and not windows.
I want to show a window inside a page, this window must be modal to the page, but allow the user to go to other page, and go back to the same page with the modal window in the same state.</p>
<p>I have tried with the WPF popup control but the problem is that the control hides everytime you navigate away from the page. I guess that I can write the code to show it again, but does not seams the right way.</p>
<p>What is the best way to do this in WPF?</p>
| <p>This <a href="http://stackoverflow.com/questions/173652/how-do-i-make-modal-dialog-for-a-page-in-my-wpf-application/173769#173769">StackOverflow answer</a> may help you on your way.
I created some sample code that some other users have asked for. I have added this to a blog post <a href="http://bradleach.wordpress.com/2009/02/25/control-level-modal-dialog/">here</a>.</p>
<p>Hope this helps!</p>
|
What is the best way to implement C#'s BackgroundWorker in Delphi? <p>I use C#'s <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" rel="nofollow" title="BackgroundWorker">BackgroundWorker</a> object frequently to start a thread and perform a task. What's the easiest way to accomplish the same thing in Delphi?</p>
<p>Here's some code in C#:</p>
<pre><code>private void button1_Click(object sender, EventArgs e)
{
BackgroundWorker bg = new BackgroundWorker();
bg.DoWork += new DoWorkEventHandler(bg_DoWork);
bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);
test_number++;
object[] arguments = { "test", test_number };
bg.RunWorkerAsync(arguments);
}
void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// done.
}
void bg_DoWork(object sender, DoWorkEventArgs e)
{
// do actual work here
}
</code></pre>
| <p>Look into <a href="http://otl.17slon.com/" rel="nofollow">OmniThreadLibrary</a> by Primoz Gabrijelcic, or into <a href="http://andy.jgknet.de/blog/?page_id=100" rel="nofollow">AsyncCalls</a> by Andreas Hausladen, which should both give you similar functionality.</p>
|
How do I create a workspace window for other windows using c# in visual studio 2008? <p>I'd like to create a workspace with status bar and menu, and within this workspace container have smaller windows of various types. </p>
<p>For example, if you un-maximise a worksheet in Excel but not the main window, it becomes a window in a larger workspace.</p>
<p>I've tried searching for the result but the main problem is in knowing the right terminology.</p>
| <p>You want an MDI (Multiple Document Interface) Form</p>
<p>Just set the IsMdiContainer property of your main form to True, and you should be able to add other forms as mdi children.</p>
|
Tracking Clicks on a Flash Ad <p>When a site has third party flash ads, is it possible for the site to track clicks to the flash? As the flash files are not created by the site, they cannot be changed. But the site wants to confirm the click-through counts that the ad agency is reporting with its own click tracking.</p>
<p>JavaScript onclick (or other mouse events) attached to the object or embed tags do not work.</p>
<p>What I have tried most recently is to place a floating invisible div over the flash and attaching the click event to that. However this does not function well in IE.</p>
<p>An alternative I am thinking of is to use my own Flash loader SWF. The new SWF would load the ad SWF file as a movie it displays. Then whenever a click happens the loader flash would trigger my click tracking JS, and then allow the click event to continue on to the ad flash. Does that sound possible/feasible?</p>
<p><strong>Addendum:</strong> I have two questions about the loader method:<br />
1) Can a flash from domain example.com load a swf file from ads.mordor.com?<br />
2) Can a swf loaded within another swf both get click events?</p>
| <p>Your loader technique seems the most sane. One of the benefits is, you can make it generic so that it can load any ad you want, with as many instances on the page as you need, while always yielding the same click data. This simplifies the need to capture multiple types of click data that different Flash ads sometimes produce.</p>
<p>Here is some code I got working, sorry in advance for the large snippets.</p>
<p><strong>ImportMe.as</strong> (has a button instance on the stage named myButton)</p>
<pre><code>package
{
import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.events.MouseEvent;
public class ImportMe extends MovieClip
{
public function ImportMe()
{
myButton.addEventListener(MouseEvent.CLICK, button_OnClick);
}
private function button_OnClick(event:MouseEvent):void
{
// shifts the button right 10 pixels to prove the event fired
myButton.x += 10;
}
}
}
</code></pre>
<p><strong>Tester.as</strong> (loads the ImportMe.swf clip generated from the previous code)</p>
<pre><code>package
{
import flash.display.MovieClip;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.*;
public class Tester extends MovieClip
{
public function Tester()
{
var request:URLRequest = new URLRequest("importme.swf");
var loader:Loader = new Loader();
loader.addEventListener(Event.COMPLETE, loader_OnComplete);
loader.addEventListener(MouseEvent.CLICK, loader_OnClick);
loader.load(request);
addChild(loader);
}
private function loader_OnComplete(event:Event):void
{
trace("loaded");
}
private function loader_OnClick(event:MouseEvent):void
{
trace("clicked");
}
}
}
</code></pre>
<p>The only thing this example doesn't test is whether or not the external event will fire before the internal clip does a url redirect.</p>
|
Is there a GIS "Hello World" Equivalent? <p>Is there the equivalent of the "Hello World" program for GIS applications?</p>
<p>I am looking to become more familiar with the development of GIS applications. What are the popular (and free/low cost) tutorials and/or sample applications that would help someone get started? Are there any books that you would consider essential for beginner GIS developers?</p>
| <p>You could start with some basic desktop mapping software like <a href="http://udig.refractions.net/">uDig</a> or <a href="http://www.qgis.org">Quantum GIS</a>. And download some <a href="http://www.google.com/search?q=free+gis+data">Shape files</a>. </p>
<p>From there you might want to take a look at <a href="http://postgis.refractions.net/">PostGIS</a>. For web development start with <a href="http://mapserver.org/">MapServer</a> and <a href="http://openlayers.org/">OpenLayers</a>.</p>
<p>Would also be worth taking a look at the book <a href="http://mappinghacks.com/">Mapping Hacks</a>.</p>
|
Using XmlSerializer with private and public const properties <p>What's the simplest way to get XmlSerializer to also serialize private and "public const" properties of a class or struct? Right not all it will output for me is things that are only public. Making it private or adding const is causing the values to not be serialized.</p>
| <p><code>XmlSerializer</code> only looks at public fields and properties. If you need more control, you can implement <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx">IXmlSerializable</a> and serialize whatever you would like. Of course, serializing a constant doesn't make much sense since you can't deserialize to a constant.</p>
|
Array posting in PHP <p>I am trying to post an array full of checkboxes and to open it in the next page..</p>
<p>It only gives me the last result, anyone know why? or how to fix it?</p>
<pre><code><form name="input" action="createevent.php" method="post">
Event title:
<input type="text" name="Eventtitle" size="20">
<br>Event Description
<input type="text" name="Description" size="20">
<br>
Please select the days that you are free to arrange this meeting.<br>
Monday
<input type="checkbox" name="day" value="Monday" />
<br />
Tuesday
<input type="checkbox" name="day" value="Tuesday" />
<br />
Wednesday
<input type="checkbox" name="day" value="Wednesday" />
<br />
Thursday
<input type="checkbox" name="day" value="Thursday" />
<br />
Friday
<input type="checkbox" name="day" value="Friday" />
<br />
Saturday
<input type="checkbox" name="day" value="Saturday" />
<br />
Sunday
<input type="checkbox" name="day" value="Sunday" />
<br /><br />
<input type="submit" value="Submit">
</code></pre>
<p>and no matter how many you select it only gives a single result on the next page.
$day = sizeof($_POST['day']);</p>
<p>only ever gives '1' answer. And when I get them to the next page I will want to be able to select them separately.</p>
<p>Thanks!</p>
| <p>PHP will only automatically make a POST value into an array if it ends in <code>[]</code>.</p>
<p>So you need to have <code>name="day[]"</code> instead of just <code>name="day"</code>.</p>
<p>(Note that this works for any POST value, and also with associative arrays instead of just auto-incrementing -- you can do <code>name="foo[bar]"</code>, and you'd get <code>$_POST['foo']['bar']</code>...)</p>
|
Naming conventions for abstract classes <p>I distinctly remember that, at one time, the guideline pushed by Microsoft was to add the "Base" suffix to an abstract class to obviate the fact that it was abstract. Hence, we have classes like <code>System.Web.Hosting.VirtualFileBase</code>, <code>System.Configuration.ConfigurationValidatorBase</code>, <code>System.Windows.Forms.ButtonBase</code>, and, of course, <code>System.Collections.CollectionBase</code>.</p>
<p>But I've noticed that, of late, a lot of abstract classes in the Framework don't seem to be following this convention. For example, the following classes are all abstract but don't follow this convention:</p>
<ul>
<li><p><code>System.DirectoryServices.ActiveDirectory.DirectoryServer</code></p></li>
<li><p><code>System.Configuration.ConfigurationElement</code></p></li>
<li><p><code>System.Drawing.Brush</code></p></li>
<li><p><code>System.Windows.Forms.CommonDialog</code></p></li>
</ul>
<p>And that's just what I could drum up in a few seconds. So I went looking up what the official documentation had to say, to make sure I wasn't crazy. I found the <a href="http://msdn.microsoft.com/en-us/library/ms229040.aspx">Names of Classes, Structs, and Interfaces</a> on MSDN at <a href="http://msdn.microsoft.com/en-us/library/ms229042.aspx">Design Guidelines for Developing Class Libraries</a>. Oddly, I can find no mention of the guideline to add "Base" to the end of an abstract class's name. And the guidelines are no longer available for version 1.1 of the Framework.</p>
<p>So, am I losing it? Did this guideline ever exist? Has it just been abandoned without a word? Have I been creating long class names all by myself for the last two years for nothing? </p>
<p>Someone throw me a bone here.</p>
<p><strong>Update</strong>
I'm not crazy. The guideline existed. <a href="http://blogs.msdn.com/kcwalina/archive/2005/12/16/BaseSuffix.aspx">Krzysztof Cwalina gripes about it in 2005.</a></p>
| <p>In <a href="http://www.amazon.co.uk/Framework-Design-Guidelines-Conventions-Libraries/dp/0321246756/ref=sr_1_2?ie=UTF8&qid=1231531546&sr=8-2" rel="nofollow">Framework Design Guidelines</a> p 174 states:</p>
<blockquote>
<p><strong>Avoid</strong> naming base classes with a "Base" suffix if the class is intended for use in public APIs.</p>
</blockquote>
<p>Also : <a href="http://blogs.msdn.com/kcwalina/archive/2005/12/16/BaseSuffix.aspx" rel="nofollow">http://blogs.msdn.com/kcwalina/archive/2005/12/16/BaseSuffix.aspx</a></p>
|
MVP and UserControls and invocation <p>I'm having some fun trying to get my head around some MVP stuf, as it pertains to User Controls. I'm using .NET WinForms (or something close to it) and Supervising Controller pattern (well, I think I am :). </p>
<p>The User Control is itself part of an MVP application (its the View and has an associated Presenter etc). The Presenter is always started first, and it starts the Model(s) and then View(s). The View builds its UI, part of which will be to NEW the UC, which is the View.</p>
<p>Now the (form) Presenter needs to know about the UC Presenter, but I'm thinking that it doesn't know anything about how the View is composed. The form Presenter doesn't, for instance, know that the UC is part of the form's Controls collection, nor should it.</p>
<p>Furthermore, the design experience should not be changed; IOW the dev of the View (form) should just be able to select a User Control from the toolbox and drop it on a form.</p>
<p>So, on to my questions. Firstly, are my assumptions above correct? Somewhat misguided? Messed up? WTF are you thinking? </p>
<p>Secondly, is it right (enough?) to have the form View invoke the UC View, and the form Presenter invoke the UC Presenter and have some mechanism to tell the UC View what its Presenter is? This breaks my "Presenter first" rule, but I'm not sure how else to do it. </p>
<p>Any other thoughts, suggestions, comments gladly accepted.</p>
<p>-- nwahmaet</p>
| <p>A presenter should be thought of as "autonomous state" in the presentation tier. This means that it is responsible for ensuring that the view's presentation of the model's state is in sync. The reason I bring this up is because the "pattern" of MVP often gets lost in the dogmatic view of <em>how</em> things should be separated. It seems that this is one reason Martin Fowler decided to try to <a href="http://martinfowler.com/eaaDev/ModelViewPresenter.html">clarify the terminology around the MVP</a> pattern.</p>
<p>My favored flavor of MVP is the <a href="http://martinfowler.com/eaaDev/PassiveScreen.html">passive view</a>, so my answer is based off of that.</p>
<p>I implement composite user controls and forms very often using the passive view pattern. There are essentially 3 different configurations:</p>
<ol>
<li>One presenter for all user controls in the hierarchy. Flatten the view using an interface.</li>
<li>One presenter for each user control in the composite tree. Each parent presenter is responsible for instantiating and initializing its child presenters. The user controls are created at design time, and are able to function without a presenter (with no presentation behavior)</li>
<li>One presenter for each user control in the composite tree. All of the presenters are loosely coupled through a higher level controller class. The controller class is responsible for construcing the presenter, wiring them up, and coordinating their events.</li>
</ol>
<p>Although it is a solution of last resort for me (because of its complexity), I think that the last option is the solution that you are looking for.</p>
|
why is the iframe contents empty? <p>I'm trying to understand this bit of code:</p>
<p>in display.php:</p>
<pre><code><html>
...
<body>
<table>
<tr>
<td>
User info: <iframe id="SpControlFrame1" name="SpControlFrame1" src="javascript:'';"path_src="index.php?cmd=YYY" ></iframe>
</td>
</tr>
</table>
</body>
</html>
</code></pre>
<p>in another file, I have a switch statement:</p>
<p>main.php</p>
<pre><code>switch ("cmd") {
case ZZZ:
include("foo.php");
break;
case YYY:
include("blah.php")
break;
}
</code></pre>
<p>blah.php:</p>
<pre><code><?php
//some functions for processing
?>
<html>
<head>
...
</head>
<body>
<input type="text" size="12" name="username">
<input type="button" value="submit">
</body>
</html>
</code></pre>
<p>1) So, can some explain what is happening here? The iframe is embedded in the page and doesn't cause a reload or anything like that. </p>
<p>2) I'm trying to duplicate this functionality on another page but the iframe is always empty (I've verified this using the IE developer Toolbar)</p>
| <p>Without seeing the code in question, I couldn't really say what's happening. Your example presumes that the code in question is server-side, and when a particular variable/condition is met, then the iframe is created or populated by blah.php. </p>
<p>You would have to ensure that the same code is called when creating this other iframe. Perhaps you could expand on the code in question? Source for the original, and source for the new (not the iframe, but the containing document). </p>
|
Click Once Setup.exe returns 404 with IIS <p>Whenever I try to install a Click Once application, I always get a 404 error from the setup.exe file. I've checked the physical folder the web server points to and confirmed that setup.exe exists at the correct location.</p>
<p>The CO deployment also works fine if I open the web page using file://path/to/index.html</p>
| <p>Recording The Answer for myself so I can look it up later</p>
<p>In IIS, check to make sure that in the folder's Properties, Home Directory Tab, Application Settings section, that it is running Scripts Only and not Scripts and Executables.</p>
|
SQL Cluster - using datasource (local) <p>Using (local) in the connection string doesn't work on my cluster. I'm assuming it's looking for the default instance on the currently active node instead of the Virtual SQL name. Anyone know how to make this work? </p>
<p>edit note:
I'd like to use (local) and not localhost - I don't want to change any application generated code. </p>
| <p>The names (local) or (.) will always use the shared memory interface, rather than TCP or Named Pipes, and neither can be used against a clustered instance which requires TCP or Named Pipes over TCP. You can't use the shared memory interface against a non-local instance, which in the case of a cluster, the instance may or may not be local.</p>
|
Rails: FasterCSV - Unique Occurences <p>I have my CSV file imported as such:</p>
<pre><code>records = FasterCSV.read(path, :headers => true, :header_converters => :symbol)
</code></pre>
<p>How can I get the <strong>unique occurences</strong> of my data? For instance, here some sample data:</p>
<pre><code>ID,Timestamp
test,2008.12.03.20.26.32
test,2008.12.03.20.26.38
test,2008.12.03.20.26.41
test,2008.12.03.20.26.42
test,2008.12.03.20.26.43
test,2008.12.03.20.26.44
cnn,2008.12.03.20.30.37
cnn,2008.12.03.20.30.49
</code></pre>
<p>If I simply call <code>records[:id]</code>, I just get:</p>
<pre><code>testtesttesttesttesttestcnncnn
</code></pre>
<p>I would like to get this:</p>
<pre><code>testcnn
</code></pre>
<p>How can I do this?</p>
| <p>If your data is not <strong>masive</strong> you can use the <a href="http://www.ruby-doc.org/stdlib/libdoc/set/rdoc/index.html" rel="nofollow">Set</a> class.</p>
<p>Here's an example: </p>
<pre><code>p ['cnn','test','test','test','test','cnn','cnn'].to_set.to_a
=> ["cnn", "test"]
</code></pre>
<p>Here's a simple benchmark:</p>
<pre><code>require 'set'
require 'benchmark'
Benchmark.bm(5) do |x|
x.report("Set") do
a = []
20_000.times do |i|
a << 'cnn'<< 'test'
end
a.to_set.to_a
end
end
=>
user system total real
Set 0.110000 0.000000 0.110000 ( 0.109000)
</code></pre>
|
Why is the with() construct not included in C#, when it is really cool in VB.NET? <p>I am C# developer. I really love the curly brace because I came from C, C++ and Java background. However, I also like the other programming languages of the .NET Family such as VB.NET. Switching back and forth between C# and VB.NET is not really that big of deal if you have been programming for a while in .NET. That is very common approach in the company where I work. As C# guy, I really like the XML literal and <code>with</code> keywords provided by the VB.NET compiler. I wish Microsoft had included those features in C# also. </p>
<p>I am just curious , what other developer has to say about it!</p>
| <p>Personally I don't like WITH when it's used after construction - if you need to do several things with an object after it's initialized, usually that behaviour should be encapsulated in the type itself. If you really want to do something like WITH, it's only a matter of declaring a short variable and optionally introducing a new scope.</p>
<p>However, it <em>is</em> useful to be able to compactly initialize an object with several properties - which is precisely why C# 3 allows you to write:</p>
<pre><code>MyObject x = new MyObject { Name="Fred", Age=20, Salary=15000 };
</code></pre>
<p>There are limitations to this (which the optional and named parameters in C# 4 will help to overcome) but it's better than it was without leading to potential messes/ambiguities.</p>
<p>(On the XML literal front, I'm again with the C# team - XML is a very specific technology to put into a language. If they could come up with a <em>generalised</em> form which happened to create XML but could be used to create other trees too, that would be nice - just as query expressions aren't directly tied to IEnumerable or IQueryable.)</p>
|
What are some good resources to look into synchronizing contact data on mobile devices with a .NET application? <p>Basically we want to be able to somehow synchronize our .NET application's contacts with the contacts on a mobile device (Pocket PC, iPhone, Blackberry, etc) Preferably a one shot deal that can interface with them all but that doesn't seem likely. </p>
<p>Preferably also we're not writing applications (or at least very simple ones) for the mobile devices, but be able to sync with the built-in contacts feature of these devices, both sending from the device to our application and vice versa. For email we set up our application as an IMAP server and mobile devices can just sync that way and something like that would be ideal, but I suspect such a standard doesn't exist.</p>
<p>Are there any commercial libraries with a flexible API that allow us to do this?</p>
<p>In order of preference is PocketPC, iPhone, Blackberry, but info on any of these would be appreciated.</p>
| <p>There are API's going to/from .Net and gmail, perhaps you could use a central Google account as the conduit:</p>
<p><a href="http://code.google.com/apis/contacts/docs/2.0/developers_guide_dotnet.html" rel="nofollow">Google Account Developers Guide: .NET - Contacts</a></p>
<p>Then there are ways then to go from gMail contacts to the smartphones such as <a href="http://www.goosync.com/" rel="nofollow">Goosync</a>.</p>
<p>EDIT: Another option could be to write a syncML driver for your application using <a href="http://sourceforge.net/projects/syncmldotnet" rel="nofollow">SyncMLDotNet</a> and sync to the devices via a free server such as <a href="http://en.wikipedia.org/wiki/Funambol" rel="nofollow">Funambol</a>.</p>
|
SQL Exclude LIKE items from table <p>I'm trying to figure out how to exclude items from a select statement from table A using an exclusion list from table B. The catch is that I'm excluding based on the prefix of a field.</p>
<p>So a field value maybe "FORD Muffler" and to exclude it from a basic query I would do:</p>
<pre><code>SELECT FieldName
FROM TableName
WHERE UPPER(ColumnName) NOT LIKE 'FORD%'
</code></pre>
<p>But to use a list of values to exclude from a different tabel I would use a Subquery like:</p>
<pre><code>SELECT FieldName
FROM TableName
WHERE UPPER(ColumnName) NOT IN (Select FieldName2 FROM TableName2)
</code></pre>
<p>The problem is that it only excludes exact matches and not LIKE or Wildcards (%).</p>
<p>How can I accomplish this task? Redesigning the table isn't an option as it is an existing table in use.</p>
<p>EDIT: Sorry I am using SQL Server (2005).</p>
| <p>I think this will do it:</p>
<pre><code>SELECT FieldName
FROM TableName
LEFT JOIN TableName2 ON UPPER(ColumnName) LIKE TableName2.FieldName2 + '%'
WHERE TableName2.FieldName2 IS NULL
</code></pre>
|
Render PDF in iTextSharp from HTML with CSS <p>Any idea how to render a PDF using iTextSharp so that it renders the page using CSS. The css can either be embedded in the HTML or passed in separately, I don't really care, just want it to work. </p>
<p>Specific code examples would be <em>greatly</em> appreciated.</p>
<p>Also, I would really like to stick with iTextSharp, though if you do have suggestions for something else, it's got to be free, open source, and have a license that permits using it in commercial software.</p>
| <p>It's not possible right now but nothing stops you from starting open-source project that will do it. I might actually start one, because I need it too!</p>
<p>Basically you will need parser that will convert html and css markup into iTextSharp classes. So <code><table></code> becames <code>iTextSharp.SimpleTable</code> and so on.</p>
<p>It would be easy to come up with prototype that would be able to work with limited html and css subset.</p>
<p><strong>Update:</strong> Until the time this will be possible, this is how I temporarily resolved it for myself. Only two steps:</p>
<ul>
<li>Tell your users to download open-source app called <a href="http://www.pdfforge.org/"><strong>PDFCreator</strong></a></li>
<li><p>Make all your html reports printer friendly by providing stylesheets for print.</p>
<p><em>If some of your multi-page reports need to have headers on every page, set them up in THEAD html tag.</em></p></li>
</ul>
<p>Now users will be able to print-friendly and if they choose PDFCreator printer driver, they will even be able to get report in PDF format (there are other pdf printer drivers but this one is free and open-source).</p>
<p>Also I know HTML is not as flexible as PDF but it might be good enough. I was doing some tests with real users and they actually like it because not only they can now print anything to PDF (even beyond my app), also their workflow is faster because they don't have to download and wait until their pdf reader opens up. they just print (or export to pdf) what they see on website directly from their webbrowser... kind of makes sense.</p>
|
How does Microsoft's Entity Framework inhibit test driven development? <p>MS's entity framework is considered among developers in the agile community to inhibit test driven development. It was <a href="http://efvote.wufoo.com/forms/ado-net-entity-framework-vote-of-no-confidence/" rel="nofollow">famously attacked</a> by an influential group of .Net developers for not being a true reflection of the principles of the agile movement. </p>
<p>What are the main drawbacks that an agile developer faces when using the entity framework? </p>
| <p>It's because it has no mocks - it encourages you to base your app around objects that directly ping the database, with no way to simulate it. One of the primary tenets of agile development is that tests are <em>fast</em>, so that running them is painless and you can continually be testing your code, but with EF, your objects always ping a database and you have to do horrible hacks to get around the generated code that EF makes for you for tests.</p>
|
How to you inspect or look for .NET attributes? <p>I have an enumeration for Status for a Task. Some of the statuses are considered obsolete, and I have marked them as obsolete, as seen below:</p>
<pre><code>public enum TaskStatus
{
[Description("")]
NotSet = 0,
Pending = 1,
Ready = 2,
Open = 3,
Completed = 4,
Closed = 5,
[Description("On Hold")][Obsolete]
OnHold = 6,
[Obsolete]
Canceled = 7
}
</code></pre>
<p>In my user interface I populate a drop down with values on the enumerations, but I want to ignore ones that are marked as obsolete. How would I got about doing this?</p>
| <p>You could write a LINQ-query:</p>
<pre><code>var availableTaks = typeof (TaskStatus).GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public)
.Where(f => f.GetCustomAttributes(typeof (ObsoleteAttribute), false).Length == 0);
foreach(var task in availableTaks)
Console.WriteLine(task);
</code></pre>
|
Need a basic audio & video player library in Java <p>I need to display a series of images (perhaps BufferedImages) with variable frame rates as a video, synchronized with uncompressed audio. I also need the basic media controls of play, pause, seek, audio volume, etc.</p>
<p>Since I don't need to encode, decode, read or write video files, I would prefer to avoid large libraries such as JMF or FMJ. I just need the player. Additionally it would be best to avoid the JNI completely (rules out FMJ), and if the code is open source (rules out JMF).</p>
<p>In essence, I'm looking for the best practices of how to write a Java movie player, or for a library that has already done it. A good example might be Java-only implementation of an uncompressed AVI video player.</p>
<p>Some libraries I've looked at besides JMF and FMJ are:
Javid (<a href="http://developer.berlios.de/projects/javid/" rel="nofollow">http://developer.berlios.de/projects/javid/</a>),
javampeg1video (<a href="http://sourceforge.net/projects/javampeg1video/" rel="nofollow">http://sourceforge.net/projects/javampeg1video/</a>), java multimedia system (<a href="http://sourceforge.net/projects/jmms/" rel="nofollow">http://sourceforge.net/projects/jmms/</a>) and
javavideoplayer (<a href="http://sourceforge.net/projects/javavideoplayer/" rel="nofollow">http://sourceforge.net/projects/javavideoplayer/</a>).</p>
<p>Additional detail:
I have written a Java decoder for a unique audio/video format (Playstation 1 movies). The project is open source (GPL) and I would like it to be as simple and cross platform as possible. Before saving the decoded video with my simple AVI writer, I want to provide the user with a preview of the decoded video. Thus, as stated above, all I need is the video to sync with played audio as it is all decoded in real-time. It almost seems simple, but I'm sure there are various technical issues of real-time playback in Java that I'm not aware of.</p>
| <p>I don't know if this is what you're looking for, but have you looked at Quicktime for Java here: <a href="http://developer.apple.com/quicktime/qtjava/index.html" rel="nofollow">http://developer.apple.com/quicktime/qtjava/index.html</a></p>
<p>It says, "QuickTime for Java provides a set of cross-platform APIs which allows Java developers to build multimedia, including streaming audio and video, into applications and applets."</p>
|
Open Source HTML to PDF Renderer with Full CSS Support <p>I asked about getting iTextSharp to render a PDF from HTML and a CSS sheet before <a href="http://stackoverflow.com/questions/430280/render-pdf-in-itextsharp-from-html-with-css">here</a> but it seems like that may not be possible... So I guess I will have to try something else.</p>
<p>Is there an open source .NET/C# library out there that can take HTML <strong><em>and</em></strong> CSS as input and render it correctly? </p>
<p>I must reiterate... the library MUST be free and preferably something with a fairly liberal license. I'm working with basically no budget here.</p>
| <p>This command line tool is the business!
<a href="http://code.google.com/p/wkhtmltopdf">http://code.google.com/p/wkhtmltopdf</a></p>
<p>It uses webkit rendering engine(used in safari and KDE), I tested it on some complex sites and it was by far better than any other tool. </p>
|
PHP/Apache blocking on each request? <p>Ok, this may be a dumb question but here goes. I noticed something the other day when I was playing around with different HTML to PDF converters in PHP. One I tried (dompdf) took forever to run on my HTML. Eventually it ran out of memory and ended but while it was still running, none of my other PHP scripts were responsive at all. It was almost as if that one request was blocking the entire Webserver.</p>
<p>Now I'm assuming either that can't be right or I should be setting something somewhere to control that behaviour. Can someone please clue me in?</p>
| <p>did you had open sessions for each of the scripts?:) they might reuse the same sesion and that blocks until the session is freed by the last request...so they basically wait for each other to complete(in your case the long-running pdf generator). This only applies if you use the same browser.</p>
<p>Tip, not sure why you want html to pdf, but you may take a look at FOP <a href="http://xmlgraphics.apache.org/fop/">http://xmlgraphics.apache.org/fop/</a> to generate PDF's. I'm using it and works great..and fast:) It does have its quirks though.</p>
|
Prevent mutually recursive execution of triggers? <p>Suppose you have the tables <code>Presentations</code> and <code>Events</code>. When a presentation is saved and contains basic event information, such as location and date, an event will be created automatically using a trigger. (I'm afraid it's impossible for technical reasons to simply keep the data at one place and use a view.) In addition, when changing this information later on in the presentation, the trigger will copy the updates over to the event as well, like so:</p>
<pre><code>CREATE TRIGGER update_presentations
ON Presentations
AFTER UPDATE
AS
BEGIN
UPDATE Events
SET Events.Date = Presentations.Date,
Events.Location = Presentations.Location
FROM Presentations INNER JOIN Events ON Presentations.EventID = Events.ID
WHERE Presentations.ID IN (SELECT ID FROM inserted)
END
</code></pre>
<p>Now, the customer wants it so that, if a user ever changes the information in the <em>event</em>, it should go back to the presentation as well. For obvious reasons, I can't do the reverse:</p>
<pre><code>CREATE TRIGGER update_events
ON Events
AFTER UPDATE
AS
BEGIN
UPDATE Presentations
SET Presentations.Date = Events.Date,
Presentations.Location = Events.Location
FROM Events INNER JOIN Presentations ON Events.PresentationID = Presentations.ID
WHERE Events.ID IN (SELECT ID FROM inserted)
END
</code></pre>
<p>After all, this would cause each trigger to fire after each other. What I could do is add a column <code>last_edit_by</code> to both tables, containing a user ID. If filled by the trigger with a special invalid ID (say, by making all user IDs of actual persons positive, but user IDs of scripts negative), I could use that as an exit condition:</p>
<pre><code> AND last_edit_by >= 0
</code></pre>
<p>This might work, but what I'd like to do is indicate to the SQL server that, within a transaction, a trigger should only fire once. Is there a way to check this? Or perhaps to check that a table has already been affected by a trigger?</p>
<p><hr /></p>
<p><strong>Answer</strong> thanks to Steve Robbins:</p>
<p>Just wrap the potentially nested <code>UPDATE</code> statements in an IF condition checking for <code>trigger_nestlevel()</code>. For example:</p>
<pre><code>CREATE TRIGGER update_presentations
ON Presentations
AFTER UPDATE
AS
BEGIN
IF trigger_nestlevel() < 2
UPDATE Events
SET Events.Date = Presentations.Date,
Events.Location = Presentations.Location
FROM Presentations INNER JOIN Events ON Presentations.EventID = Events.ID
WHERE Presentations.ID IN (SELECT ID FROM inserted)
END
</code></pre>
<p>Note that <code>trigger_nestlevel()</code> appears to be 1-based, not 0-based. If you want each of the two triggers to execute once, but not more often, just check for <code>trigger_nestlevel() < 3</code> in both triggers.</p>
| <p>I'm not sure about doing it per transaction, but do you need nested triggers switched on for other parts? If you switch them off on the server then a trigger won't fire from another trigger updating a table.</p>
<p>EDIT (answer from the comments): <strong>You will need to alter trigger A to use <a href="http://msdn.microsoft.com/en-us/library/ms182737.aspx">TRIGGER_NESTLEVEL</a></strong> </p>
|
How to query (LINQ) multiple table association link? <p>I have tables association such as (CaseClient is a bridge table):</p>
<ul>
<li>Cases has many CaseClients</li>
<li>Client has many CaseClients</li>
<li>ClientType has many CaseClient</li>
</ul>
<p>The easiest way just use the view in database but I heard that with linq you can join this somehow? Or should I just created view in the database and linq query agains that view?</p>
<p>I am appreciated your comment</p>
| <p>I think you want to use the Join method, from your bridging table and resolving each of your relationships. E.g.</p>
<pre><code>// Where CaseId and TypeId are your members of CaseClient
var x = caseClients.Join( cases, cc => cc.CaseId, c => c.Id)
.Join( types, cc => cc.TypeId, t => t.Id)
.Select();
</code></pre>
<p>Above code untested (so far) and from memory. You may need to put a Select between the two joins.</p>
|
Linux system to manage configurations of servers? <p>I need a software to manage configurations of linux servers in one central location. It should be able to push changes to servers automaticly. Version control would be an advantage...</p>
| <p>I've heard good things about <a href="http://reductivelabs.com/trac/puppet/" rel="nofollow">Puppet</a> (as <a href="http://stackoverflow.com/users/23896/matli">matli</a> suggested) and <a href="http://en.wikipedia.org/wiki/Cfengine" rel="nofollow">Cfengine</a>, which are both listed at <a href="http://en.wikipedia.org/wiki/Comparison_of_open_source_configuration_management_software" rel="nofollow">http://en.wikipedia.org/wiki/Comparison_of_open_source_configuration_management_software</a></p>
|
What is the significance of trailing slashes in a namespace URI? <p>I have been studying SOAP and WSDL in preparation for implementing a web service. One thing that I have encountered that puzzles me is that some of the URIs that I have seen use a trailing slash such as:</p>
<pre><code>http://www.w3.org/some-namespace/
</code></pre>
<p>while other examples that I have studied omit this trailing slash. I really have several questions regarding this:</p>
<ul>
<li>What is the significance of the trailing slash?</li>
<li>Is the URI, http://www.w3.org/some-namespace the same as http://www.w3.org/some-namespace/?</li>
<li>If they are not the same, how do I decide when one form is warranted versus another?</li>
<li>I have read the guidelines given by w3c regarding URI's and these appear to indicate that that URI should be considered equal only if the case-sensitive comparison of the URI strings are considered equal. Is this interpretation correct?</li>
</ul>
| <p><strong>Yes, the w3c guidelines regarding URI's you have read are correct</strong>. </p>
<p><strong>The two namespaces having not equal-strings-uri's are different namespaces. Even capitalization and white-space matters</strong>. </p>
<p>A namespace-uri does not mean that issuing a request for it should produce a web-response. Therefore, any reasoning whether it should or shouldn't end with "/" is not too meaningful.</p>
<p>In fact, a namespace-uri may even not satisfy the syntax rules for an URI and it will still serve its purpose for defining a namespace. It is perfectly useful to use a namespace such as, let's say:</p>
<p><strong><code>"\/^%$#sdhfgds"</code></strong> </p>
<p>as long as it is unique (do note that in no way I am recommending such use :) ). Existing XML processors (such as parsers, XPath or XSLT processors) do not raise any errors when they encounter such namespace.</p>
|
Is there an open source C visual debugger for windows? <p>Is there an open source C visual debugger for windows?
I have heard about the visual C++ express free edition, but does it have a visual debugger?</p>
<p>Thanks.</p>
| <p>It's not open source (but then does it really need to be?) <a href="http://www.microsoft.com/express/vc/" rel="nofollow">Visual C++ 2008 Express Edition</a> is an IDE with an integrated debugger.</p>
<p>You can create a C++ project, delete the .cpp files and create/include your .c files.</p>
|
Domain Driven Design question <p>I would like to ask for a reccomended solution for this:
We have a list of Competitions.
Each competition has defined fee that a participatior has to pay
We have Participators
I have to know has a Participator that is on a Competition paid the fee or not. I am thinking about 2 solutions and the thing is it has to be the most appropriate solution in Domain Driven Design.
First is to create a Dictionary in Competition instead of a List, the dictionary would have be of type <Participator, bool>.
The secont is perhaps create a different class that has 2 fields, a participator and feePaid. And in Competiton I would have a list of object of that new class.</p>
<p>Thank you</p>
| <p>sounds like a typical many to many relationship. i would model it with an Entry association class as follows:</p>
<pre><code>class Participator {
}
class Competition {
Currency fee
}
class Entry {
Competition competition
Participator participator
Boolean feePaid
}
</code></pre>
|
C# Reflection: Getting the fields of a DataRow from a Typed DataSet <p>I am currently building a method that takes an object that is of type <code>DataRow</code> from a typed DataSet, and then returning a string in <a href="http://en.wikipedia.org/wiki/Json" rel="nofollow">JSON</a> format of the fields in the DataRow (for use in a Web Service).</p>
<p>By using <code>System.Reflection</code>, I am doing something like this : </p>
<pre><code>public string getJson(DataRow r)
{
Type controlType = r.GetType();
PropertyInfo[] props = controlType.GetProperties();
foreach (PropertyInfo controlProperty in props)
{
}
return "";
}
</code></pre>
<p>And then in the <code>foreach</code> statement, I would iterate every field and get the field name and value, and format it into JSON.</p>
<p><hr /></p>
<p>The problem is that when iterating over the <code>props</code> (of type <code>PropertyInfo[]</code>), I am getting properties that I do not want to be iterated over:</p>
<p><img src="http://img88.imageshack.us/img88/2001/datarowreflectionht0.gif" alt="alt text" /></p>
<p>As you can see from the above image, I only need the fields that range from <code>0 - 11</code> in the <code>props</code> array, because those are the 'real fields' of this particular typed row.</p>
<p>So my question is, <strong>How can I get the fields of the Typed DataRow only, and not the other 'metadata' ?</strong></p>
<p><hr /></p>
<p><strong>[UPDATE with Solution]</strong></p>
<p>As <a href="http://stackoverflow.com/questions/431050/c-reflection-getting-the-fields-of-a-datarow-from-a-typed-dataset#431058">Mehrdad Afshari</a> suggested, instead of using <code>Reflection</code>, I am using the <code>Table.Columns</code> array. </p>
<p>Here is the completed function:</p>
<pre><code>public string GetJson(DataRow r)
{
int index = 0;
StringBuilder json = new StringBuilder();
foreach (DataColumn item in r.Table.Columns)
{
json.Append(String.Format("\"{0}\" : \"{1}\"", item.ColumnName, r[item.ColumnName].ToString()));
if (index < r.Table.Columns.Count - 1)
{
json.Append(", ");
}
index++;
}
return "{" + json.ToString() + "}";
}
</code></pre>
| <p>Why don't you use <code>row.Table.Columns</code> property instead of reflection?</p>
|
Better way of returning the values of a column in Active Record? <p>Quick one, but thought I'd ask.</p>
<p>Is there a better way of getting the column values from a model's column than something like this?</p>
<pre><code>Item.count(:all, :group => 'status').reject! { |i, e| i.blank? }.collect { |i,e| i}
</code></pre>
| <pre><code>Item.find(:all, :select=>:status, :group => 'status', :conditions => "status != ''").collect{|r| r.status}
</code></pre>
|
Unexpected T_CLONE using Math_Matrix PEAR library <p>I've not used PEAR before, and so I'm probably doing something dumb. I've installed the Math_Matrix library, but when I include it I just get an error. My entire code is this:</p>
<pre><code><?php
$path = '/home/PEAR/Math_Matrix-0.8.0';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
include_once 'Matrix.php';
?>
</code></pre>
<p>The error I get is this:</p>
<pre><code>Parse error: syntax error, unexpected T_CLONE, expecting T_STRING in /home/PEAR/Math_Matrix-0.8.0/Matrix.php on line 272
</code></pre>
<p>I'm not really sure what to make of that. I guess the explanations I can think of are:</p>
<ol>
<li>I've not installed the Math_Matrix library properly (I'm on a shared server which already had PEAR installed on it) or have downloaded the wrong version of it.</li>
<li>I'm supposed to include something else before I include Matrix.php</li>
<li>I've included the wrong file (or the right filename but with the wrong path, somehow).</li>
</ol>
<p>To install it, I did the following:</p>
<pre><code>pear install --alldeps channel://pear.phpunit.de/PHPUnit
pear install --alldeps channel://pear.php.net/Math_Vector-0.6.2
pear install Math_Matrix
</code></pre>
| <p>From the Math_Matrix I can see that it was last updated in 2003. Since then, PHP has added the <a href="http://www.php.net/clone" rel="nofollow"><code>clone</code> keyword</a>, which is conflicting with the <code>clone()</code> function defined in Matrix.php.</p>
<p>You need to update Matrix.php - a search & replace on "clone" with "clone2" should do it.</p>
|
Flash upload image resize client side <p>Does anyone got an ideia on how to get client side image resize using flash.</p>
<p>Example:
Client chooses an image with 1200x800 and before it uploads it flash will turn it into half of it or something.</p>
<p>Any thoughts?</p>
| <p>Plupload is Opensource, has good documentation and supports multiple platforms, including Gears and HTML5!</p>
<p><a href="http://www.plupload.com/index.php">http://www.plupload.com/index.php</a><br>
<a href="http://www.plupload.com/example_all_runtimes.php">http://www.plupload.com/example_all_runtimes.php</a></p>
<p>Ah, yes, it supports resizing images BEFORE uploading. The closest option to aurigma, but for free :)</p>
|
Weird Behavior when using between? method for dates <p>Open up a Rails console and enter this:</p>
<pre><code>2.weeks.ago.between? 2.weeks.ago, 1.week.ago
</code></pre>
<p>Did it give you true or false? No really, try it a few more times and it will give you different answers.</p>
<p>Now, I'm thinking that because we're comparing 2.weeks.ago with 2.weeks.ago, the time between evaluating the two statements is causing this behavior.</p>
<p>I can't say for sure, but I am guessing that the between? method is not inclusive and so if a few milliseconds elapsed between the two statements, the above code will evaluate to true because it will be in between the two dates compared.</p>
<p>However, if the CPU manages to process this quickly enough such that the time elapsed is ignorable, then it will evaluate to false.</p>
<p>Can anyone shed some light on this? It is an edge case at best in a system where this might be critical, but it was giving me a headache when my tests passed and failed seemingly at random.</p>
<p>Oddly enough, this doesn't happen when doing:</p>
<pre><code> Date.yesterday.between? Date.yesterday, Date.tomorrow
</code></pre>
| <p>The cause is undoubtedly due to the resolution of the time function. Sometimes the two instances of 2.weeks.ago resolve to the same time and sometimes they don't. When you use yesterday you don't see the issue because it always resolves to zero hour instead of relative to the current time.</p>
<p>In a case like yours you probably only want to compare the date, not the date and time.</p>
|
window border width and height in Win32 - how do I get it? <pre>
::GetSystemMetrics (SM_CYBORDER)
</pre>
<p>...comes back with 1 and I know the title bar is taller than ONE pixel :/</p>
<p>I also tried:</p>
<pre>
RECT r;
r.left = r.top = 0; r.right = r.bottom = 400;
::AdjustWindowRect (& r, WS_OVERLAPPED, FALSE);
_bdW = (uword)(r.right - r.left - 400);
_bdH = (uword)(r.bottom - r.top - 400);
</pre>
<p>But border w,h came back as 0.</p>
<p>In my WM_SIZE handler, I need to make sure the window's height changes in
"steps" so, for example a whole new line of text could fit in the window
with no "junky partial line space" at the bottom.</p>
<p>But ::MoveWindow needs the dimensions WITH the border space added in.</p>
<p>SOMEbody must have done this before...
Thanks for any help :)</p>
| <p>The <a href="http://msdn.microsoft.com/en-us/library/ms633519(VS.85).aspx" rel="nofollow">GetWindowRect</a> and <a href="http://msdn.microsoft.com/en-us/library/ms633503(VS.85).aspx" rel="nofollow">GetClientRect</a> functions can be used calculate the size of all the window borders.</p>
<p>Suite101 has a article on <a href="http://suite101.com/article/client-area-size-with-movewindow-a17846" rel="nofollow">resizing a window and the keeping client area at a know size</a>. </p>
<p>Here is their sample code:</p>
<pre><code>void ClientResize(HWND hWnd, int nWidth, int nHeight)
{
RECT rcClient, rcWind;
POINT ptDiff;
GetClientRect(hWnd, &rcClient);
GetWindowRect(hWnd, &rcWind);
ptDiff.x = (rcWind.right - rcWind.left) - rcClient.right;
ptDiff.y = (rcWind.bottom - rcWind.top) - rcClient.bottom;
MoveWindow(hWnd,rcWind.left, rcWind.top, nWidth + ptDiff.x, nHeight + ptDiff.y, TRUE);
}
</code></pre>
|
ASP.net: Display PDF in a asp.net web page <p>User click on a link button and it will direct them to a url that is dynmaically generated which a pdf file. The browser will prompt the user to either save or open it.</p>
<p>I want to know if it is possible to downlaod the pdf file to the server then show the pdf file in the asp.net web page. When i google on this question, 99% of top link are some third party component. Is it a way to do this without purchase any 3rd party component?</p>
<p>thank</p>
| <p>I use <a href="http://sourceforge.net/projects/itextsharp/" rel="nofollow">itextsharp</a>, its a free open source c# port of the java itext library. </p>
<p>Makes generating dynamic pdfs in asp.net a breeze and there is lots of documentation/examples floating around.</p>
|
Storing Images to use in application <p>I would like to store some images to use in my C# application. They are png files and are currently in a folder with the dlls. Ideally I would like to have them included with the dll so i dont have to include the actual images with the installation. </p>
<p>What is the best way to do this?</p>
<p>I have though about resx but i am unsure as to the best way to go about it. Should I use create the resx file using another project, and then add it to the one I want to use it with?</p>
<p>Thanks in advance.</p>
| <p>The easiest is to just add them to your current project and then set their Build Action property to Embedded. I believe that automatically adds them to a resource file and then you can access them using reflection.</p>
<p>Here's an article on retrieving them:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa287676(VS.71).aspx" rel="nofollow">MSDN</a></p>
|
How to render decoded HTML in a (i.e. a <br>) in GridView cell <p>I'm binding a GridView to an LINQ query. Some of the fields in the objects created by the LINQ statement are strings, and need to contain new lines.</p>
<p>Apparently, GridView HTML-encodes everything in each cell, so I can't insert a <br /> to create a new line within a cell.</p>
<p>How do I tell GridView not to HTML encode the contents of cells?</p>
<p>Maybe I should use a different control instead?</p>
| <p>What about setting the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.htmlencode.aspx"><code>HtmlEncode</code> property</a> to <code>false</code>? To me, this is much simpler.</p>
<pre class="lang-asp prettyprint-override"><code><asp:BoundField DataField="MyColumn" HtmlEncode="False" />
</code></pre>
|
Is possible send a array in Obj-c for a variable arguments function? <p>In python it is easy to build a dictionary or array and pass it unpacked to a function with variable parameters</p>
<p>I have this:</p>
<pre><code>- (BOOL) executeUpdate:(NSString*)sql, ... {
</code></pre>
<p>And the manual way is this:</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>But I can't hardcode the parameters I'm calling, I want:</p>
<pre><code>NSMutableArray *values = [NSMutableArray array];
for (NSString *fieldName in props) {
..
..
[values addObject : value]
}
[db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" ,??values];
</code></pre>
| <p>Unfortunately, no. Objective-C doesn't have argument unpacking like you get in a lot of modern languages. There isn't even a good way to work around it that I've ever found.</p>
<p>Part of the problem is that Objective-C is essentially just C. It does multiple argument passing with C varargs, and there's no simple way to do this with varargs. <a href="http://stackoverflow.com/questions/280940/calling-a-c-function-with-a-varargs-argument-dynamically">A relevant SO discussion</a>.</p>
|
How to set default WPF Window Style in app.xaml? <p>I am trying to set the default Style for every window in my WPF Windows application in my app.xaml. So far i have this in app.xaml:</p>
<pre><code><Application.Resources>
<ResourceDictionary>
<Style x:Key="WindowStyle" TargetType="{x:Type Window}">
<Setter Property="Background" Value="Blue" />
</Style>
</ResourceDictionary>
</Application.Resources>
</code></pre>
<p>I can get the window to appear with this style when running the app (but not is VS designer) by specifically telling the window to use this style via:</p>
<pre><code>Style="{DynamicResource WindowStyle}
</code></pre>
<p>This works, but is not ideal. So how do I:</p>
<ol>
<li>Have all windows automatically use the style (so i don't have to specify it on every window)?</li>
<li>Have VS designer show the style?</li>
</ol>
<p>Thanks!</p>
| <p>To add on to what Ray says: </p>
<p>For the Styles, you either need to supply a Key/ID or specify a TargetType. </p>
<blockquote>
<p>If a FrameworkElement does not have an
explicitly specified Style, it will
always look for a Style resource,
using its own type as the key<br />
- Programming WPF (Sells, Griffith)</p>
</blockquote>
<p>If you supply a TargetType, all instances of that type will have the style applied. However derived types will not... it seems. <code><Style TargetType="{x:Type Window}"></code> will not work for all your custom derivations/windows. <code><Style TargetType="{x:Type local:MyWindow}"></code> will apply to only MyWindow. So the options are </p>
<ul>
<li>Use a Keyed Style that you specify as the Style property of <strong>every</strong> window you want to apply the style. The designer will show the styled window.</li>
</ul>
<p>.</p>
<pre><code> <Application.Resources>
<Style x:Key="MyWindowStyle">
<Setter Property="Control.Background" Value="PaleGreen"/>
<Setter Property="Window.Title" Value="Styled Window"/>
</Style>
</Application.Resources> ...
<Window x:Class="MyNS.MyWindow" Style="{StaticResource MyWindowStyleKey}"> ...
</code></pre>
<ul>
<li>Or you could derive from a custom BaseWindow class (which has <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/c45910f8-3619-4834-992a-19a0f042340e/">its own quirks</a>), where you set the Style property during the Ctor/Initialization/Load stage once. All Derivations would then automatically have the style applied. <strong>But the designer won't take notice of your style</strong> You need to run your app to see the style being applied.. I'm guessing the designer just runs InitializeComponent (which is auto/designer generated code) so XAML is applied but not custom code-behind.</li>
</ul>
<p>So I'd say explicitly specified styles are the least work. You can anyways change aspects of the Style centrally.</p>
|
What is Google Apps? <p>What is google apps and why are so many startup companies using it?</p>
| <p><a href="http://www.google.com/apps/intl/en/business/index.html">Google Apps</a> is a collection of business software components delivered as a service, saving you from having to install Exchange, Office and the usual business stuff. Plus Google Apps allows people to write their own apps and install them on Google's servers. A lot of companies use Google Apps for email and calendering instead of Exchange these days. It saves costs.</p>
|
3D Polygons in Python <p>As far as I am aware there is no inbuilt polygon functionality for Python. I want to create a 3D map and figured that polygons would be the best way to go about it.</p>
<p>Not wanting to reinvent the wheel I did some googling and found that there's a lot of Python stuff out there, but I couldn't find what I wanted. Thus before I reinvent the wheel (or invent it a whole), does anybody know of a Polygon system for Python?</p>
<p>Note that it does need to be 3D (I found quite a few 2D ones). Note also that I am not interested in the displaying of them but in storing them and the datastructure within Python.</p>
<p>Thanks</p>
| <p>One of the most complete geography/mapping systems available for Python that I know about is <a href="http://geodjango.org/" rel="nofollow">GeoDjango</a>. This works on top of the <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>, an MVC framework. With it comes a large collection of polygon, line and distance calculation tools that can even take into account the curvature of the earth's surface if need be.</p>
<p>With that said, the quickest way I can think of to produce a 3D map is using a height map. Create a two dimensional list of tuples containing (x, y, z) coordinates. Each tuple represents an evenly spaced point on a grid, mapped out by the dimensions of the array. This creates a simple plane along the X and Z axes; the ground plane. The polygons that make up the plane are quads, a polygon with four sides.</p>
<p>Next, to produce the three dimensional height, simply give each point a Y value. This will create peaks and valleys in your ground plane.</p>
<p>How you render this will be up to you, and converting your grid of points into a polygon format that something like OpenGL can understand may take some work, but have a look at <a href="http://vpython.org/" rel="nofollow">Visual Python</a>, its the simplest 3D library I've seen for Python.</p>
|
Correct use of Lambda query <p>Consider the following code:</p>
<pre><code> private static void WriteProcesses(StreamWriter sw, DateTime d) {
sw.WriteLine("List of processes @ " + d.ToString());
Process[] localAll = Process.GetProcesses().Where(o => o.ProcessName.ToLower() != "svchost");
if(localAll.Length > 0) {
for(int i = 0; i < localAll.Length; i++) {
sw.WriteLine(" " + localAll[i].ProcessName);
}
}
}
</code></pre>
<p>But i get a red squiggly line saying:</p>
<p>Cannot implicitly convert type System.Collections.Generic.IEnumerable' to 'System.Diagnostics.Process[]'. An explicit conversion exists (are you missing a cast?) </p>
<p>I tried changing the array to a List but didnt work.</p>
| <p>Change</p>
<pre><code>Process[] localAll = Process.GetProcesses().Where(o => o.ProcessName.ToLower() != "svchost");
</code></pre>
<p>to</p>
<pre><code>Process[] localAll = Process.GetProcesses().Where(o => o.ProcessName.ToLower() != "svchost").ToArray();
</code></pre>
<p><code>Where</code> is returning an <code>IEnumerable<Process></code> on which you can call <code>ToArray</code> to convert to an array of type <code>Process</code>.</p>
<p>Alternatively, you can enumerate through the <code>IEnumerable<Process></code> that <code>Where</code> returns.</p>
<pre><code>var processes = Process.GetProcesses().Where(o => o.ProcessName.ToLower() != "svchost");
foreach (Process process in processes) {
sw.WriteLine(" " + process.ProcessName);
}
</code></pre>
|
Dynamic Proxy generation with LinFu <p>I am trying to build a dynamic proxy for an interface with LinFu. The proxy should just implement the getter methods of the properties that are defined by the interface and return for instance a value from a dictionary, where the key is the property name.</p>
<p><a href="http://code.google.com/p/linfu/" rel="nofollow">link text</a></p>
| <p>Try:</p>
<pre><code>// The interceptor class must implement the IInterceptor interface
var yourInterceptor = new YourInterceptor();
var proxyFactory = new ProxyFactory();
IYourInterface proxy = proxyFactory.CreateProxy<IYourInterface>(yourInterceptor);
// Do something useful with the proxy here...
</code></pre>
|
How to make sure redundant data is deleted in a many-to-many relationship <p>I'm trying to make sure some data is auto-deleted when there's no more references using cascade deletes. I'll explain with a <em>fake</em> database based on Stack Overflow.</p>
<p>I have a <code>Post</code> table. Each post has zero to many Tags.</p>
<p>So it should look like:</p>
<blockquote>
<p>Post <-> PostTags <-> Tags</p>
</blockquote>
<p>eg. </p>
<blockquote>
<p>Post 1 has tags 'A', 'B', 'C' Post 2
has tags 'C', 'D'.</p>
</blockquote>
<p>now, what i'm doing is that when i delete all the tags for post 2 (eg. <code>DELETE FROM PostTags WHERE PostId = 2</code>), I would like tag 'D' to also be deleted because no one else if referencing it. I thought cascade deletes would handle this, but of course it's only if u cascade down from <code>Tag->PostTags</code> or <code>Post->PostTags</code>.</p>
<p>I'm not sure how to handle this.</p>
<p>I'm afraid that people will suggest using a trigger :( (extra complexity to the system).</p>
<p>Thoughts?</p>
<p>Note: DB is MS Sql2008.</p>
| <p>Unfortunately, you won't be able to use cascades here. Cascades don't work when you have a many-to-many relationships because you won't have a singular parent that references the child (in this case, you have multiple PostTags entries which could reference the Tags table).</p>
<p>Triggers would be a way to do this, but I wouldn't recommend it. Rather, I would suggest that in your data layer, after you deleted the entries in the PostTags table, delete the Tags which are not referenced anymore. If you have a stored procedure which does the deleting of the entry, you might want to consider doing this there (it would be relatively simple to do as well).</p>
|
Why can I assign an existing reference to a literal value in C++? <p>Consider the following:</p>
<pre><code>int ival = 1.01;
int &rval = 1.01; // error: non-const reference to a const value.
int &rval = ival;
rval = 1.01;
</code></pre>
<p>The first assignment of &rval to a literal value fails as expected. If I comment out that line the code compiles and runs. I understand why the initialization fails, but I'm confused why the assignment to rval works in the last line. I didn't think it was allowed to assign a reference to a literal value.</p>
<p><strong>EDIT:</strong> Thanks for the quick answers. I'm tempted to delete this to hide my shame, but I think I'll leave it here so everyone else can point and laugh.</p>
<p>In my own defense, I'm working through the exercises in a book (C++ Primer) and this problem is about reference <em>initialization</em>. Still, it's pretty embarrassing to have so completely overlooked the point of a reference in the first place. :)</p>
| <p><code>ival</code> isn't a literal value, <code>1.01</code> is the literal value. It's been copied to <code>ival</code> which is a variable, which most definitely can have it's references assigned to another variable.</p>
|
Data Modeling: What is a good relational design when a table has several foreign key constrainst to a single table? <p>I have 2 tables:
1. Employees
2. Vouchers</p>
<p>Employees table has a single primary key.
Vouchers table has 3 foreign key constraints referencing the Employees table.</p>
<p>The following is a sample T-SQL script (not the actual table script) to create both tables and their relationship in SQL Server:</p>
<pre><code>IF OBJECT_ID('dbo.Vouchers') IS NOT NULL
DROP TABLE dbo.Vouchers
IF OBJECT_ID('dbo.Employees') IS NOT NULL
DROP TABLE dbo.Employees
GO
CREATE TABLE Employees
(
ObjectID INT NOT NULL PRIMARY KEY IDENTITY
)
CREATE TABLE Vouchers
(
ObjectID INT NOT NULL PRIMARY KEY IDENTITY,
IssuedBy INT,
ReceivedBy INT,
ApprovedBy INT,
CONSTRAINT fk_Vouchers_Employees_IssuedBy FOREIGN KEY (IssuedBy)
REFERENCES Employees (ObjectID)
ON UPDATE CASCADE
ON DELETE NO ACTION,
CONSTRAINT fk_Vouchers_Employees_ReceivedBy FOREIGN KEY (ReceivedBy)
REFERENCES Employees (ObjectID)
ON UPDATE CASCADE
ON DELETE NO ACTION,
CONSTRAINT fk_Vouchers_Employees_ApprovedBy FOREIGN KEY (ApprovedBy)
REFERENCES Employees (ObjectID)
ON UPDATE CASCADE
ON DELETE NO ACTION
)
</code></pre>
<p>But an error is thrown:</p>
<pre><code>Msg 1785, Level 16, State 0, Line 7
Introducing FOREIGN KEY constraint 'fk_Vouchers_Employees_ReceivedBy' on table 'Vouchers' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
</code></pre>
<p>I don't have an idea of what efficient solution is available here. The requirements on the relationship is that: whenever an Employee is deleted, the Voucher that references some of its columns to the Employee does not get deleted (ON DELETE CASCADE is not an option). Instead, the values of the columns (IssuedBy, ReceivedBy and/or ApprovedBy) that are referenced to the deleted Employee should be set to NULL (since the columns are NULLABLE).</p>
<p>Many thanks!</p>
| <p>Strictly from a relational design point of view, the Vouchers table as three Foreign Keys. Whether you choose to enforce them, through CASCADE assertions or otherwise, is an implementation issue, but the relational design still exists. Presumably you want to enforce that, if one of the three fields is not NULL, then a matching record needs to exist. Or not. It's an implementation issue as to whether or not you care to enforce the design.</p>
<p>However, the violations you describe are assumed at your peril. The fact that you're asking this question suggests you may not fully appreciate all the ways these choices can lead into the swamp.</p>
<p>I think the error may be a consequence of the fact that more than one of the three might refer to the same employee.</p>
<p>BTW, I've in very few cases ever found it necessary to delete records in such a fashion that CASCADES are useful. Usually that would be used to prevent the database from being too big; and database capacity is less and less an issue over time.</p>
|
As our favorite imperative languages gain functional constructs, should loops be considered a code smell? <p>In allusion to Dare Obasanjo's impressions on Map, Reduce, Filter (<a href="http://www.25hoursaday.com/weblog/2008/06/16/FunctionalProgrammingInC30HowMapReduceFilterCanRockYourWorld.aspx" rel="nofollow">Functional Programming in C# 3.0: How Map/Reduce/Filter can Rock your World</a>) "With these three building blocks, you could replace the majority of the procedural for loops in your application with a single line of code. C# 3.0 doesn't just stop there."</p>
<p>Should we increasingly use them instead of loops? And should be having loops(instead of those three building blocks of data manipulation) be one of the metrics for coding horrors on code reviews? And why?</p>
<p>[NOTE] I'm not advocating fully functional programming on those codes that could be simply translated to loops(e.g. tail recursions)</p>
<p><em>Asking for politer term.</em> Considering that the phrase "code smell" is not so diplomatic, I posted another question <a href="http://stackoverflow.com/questions/432492/whats-the-politer-word-for-code-smell">http://stackoverflow.com/questions/432492/whats-the-politer-word-for-code-smell</a> about the right word for "code smell", er.. utterly bad code. Should that phrase have a place in our programming parlance? </p>
| <p><em>Let us change our traditional attitude to the construction of programs: Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do.</em></p>
<p>â Donald Knuth</p>
|
System Views text in SQL Server 2005 <p>I am looking for viewing the text of the system views and procedures in SQL Server 2005 using the object explorer or using sp_helptext.</p>
<p>actually i am coming from the SQL Server 2000 background, where we have the feature of retreiving the code of the view and the stored procedure using SQL Server 2000 Enterprise manager directly, but still i am unable to find this feature in the SQL Server 2005 Management Studio and still looking for the same feature for getting the view and procedure text in SQL Server 2005.</p>
<p>Kindly please help me in this.</p>
| <p>Do you have access to SQL Server Management Studio? It is now sys.sp_helptext and can be browsed at master --> Programmability --> Stored Procedures --> System Stored Procedures in the object browser and executed with</p>
<pre><code>exec sys.sp_helptext ObjectName
</code></pre>
<p>All the information you are looking for can be found in the <a href="http://msdn.microsoft.com/en-us/library/ms186293(SQL.90).aspx" rel="nofollow">syscomments</a> table which stores the definitions of all views, rules, defaults, triggers, CHECK constraints, DEFAULT constraints, and stored procedures. The SQL definition statements are stored in the "text" column.</p>
<pre><code>select text from syscomments where id =
OBJECT_id('objectname')
order by colid
</code></pre>
|
What's the best way to save a one-to-many relationship in Linq2Sql? <p>I'm trying to figure out the best way to save a simple one-to-many relationship in Linq2Sql.</p>
<p>Lets assume we have the following POCO model (pseduo code btw):</p>
<p><em>Person has zero to many Vechicles.</em></p>
<pre><code>class Person
{
IList<Vehicle> Vehicle;
}
class Vehicle
{
string Name;
string Colour;
}
</code></pre>
<p>Now, when i save a Person, i pass that poco object to the repository code (which happens to be L2S). I can save the person object fine. I usually do this.</p>
<pre><code>using (Db db = new Db())
{
var newPerson = db.People.SingleOrDefault(p => p.Id == person.Id) ?? new SqlContext.Person();
// Left to right stuff.
newPerson.Name = person.Name;
newPerson.Age = person.Age;
if (newPerson.Id <= 0)
db.People.InsertOnSubmit(newPerson);
db.SubmitChanges();
}
</code></pre>
<p>i'm not sure where and how i should handle the list of vehicles the person might have? any suggestions?</p>
| <pre><code>using (Db db = new Db())
{
var newPerson = db.People.SingleOrDefault(p => p.Id == person.Id) ?? new SqlContext.Person();
// Left to right stuff.
newPerson.Name = person.Name;
newPerson.Age = person.Age;
// add vehicles.
Vehicle firstV = new Vehicle();
firstV.Name = "some name";
firstV.Person = newPerson; // need to do this to set the person Id on the vehicle.
newPerson.Vehicle.Add(firstV);
// now when you save the Person it should save the Vehicle list
// if you set Cascade save update on the list. (not sure how to do that in L2S
if (newPerson.Id <= 0)
db.People.InsertOnSubmit(newPerson);
db.SubmitChanges();
}
</code></pre>
<p>Now you may choose to construct the list of vehicles at another level , with the data that's coming from the interface. </p>
<p>But you need to remember that it's not enough to add the Vehicle to the list on the Person object , you also need to set the vehicles Person property to the person that has the vehicles.</p>
<p><strike><strong>Observation</strong> I'm not sure about this but when you do <em>db.People.SingleOrDefault</em> you might be loading the whole People table in memory . That's not something you want to do.</strike> Corrected by Slace in the comments.</p>
|
Is there a O(1) way in windows api to concatenate 2 files? <p>Is there a O(1) way in windows API to concatenate 2 files?</p>
<p>O(1) with respect to not having to read in the entire second file and write it out to the file you want to append to. So as opposed to O(n) bytes processed. </p>
<p>I think this should be possible at the file system driver level, and I don't think there is a user mode API available for this, but I thought I'd ask. </p>
| <p>If the "new file" is only going to be read by your application, then you can get away without actually concatenating them on disk.</p>
<p>You can just implement a stream interface that behaves as if the two files have been concatenated, and then use that stream as opposed to what ever the default filestream implementation used by your app framework is.</p>
<p>If that won't work for you, and you are using windows, you could always create a re parse point and a file system filter. I believe if you create a "mini filter" that it will run in user mode, but I'm not sure.</p>
<p>You can probably find more information about it here:</p>
<p><a href="http://www.microsoft.com/whdc/driver/filterdrv/default.mspx" rel="nofollow">http://www.microsoft.com/whdc/driver/filterdrv/default.mspx</a></p>
|
Animate a StackPanel when the property Visibility changes <p>In WPF 3.5 (with SP1), I have simply <strong>StackPanel that I would like to animate when I change the property Visibility</strong>. I have no idea of the height of this StackPanel since its content determines its height. So when I change the property of my StackPanel to Visible (progressPanel.Visibility = Visibility.Visible;) I would like to see an animation (probably an DoubleAnimationUsingKeyFrames from 0 to X). </p>
<p>Moreover, I have multiple StackPanel that I would like to see with this behavior (so in the best case, I need something generic). <strong>Does anybody have an idea on how to do that?</strong> </p>
<p>Thanks!</p>
| <p>You can create and reuse custom StackPanel style that triggers animation when Visibility changes:</p>
<pre><code><Style x:Key="MyStyle" TargetType="{x:Type StackPanel}">
<Style.Triggers>
<Trigger Property="Visibility" Value="Visible">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard >
<DoubleAnimation .../>
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
</Trigger>
</Style.Triggers>
</Style>
</code></pre>
|
How to get a user token from Logonuser for a user account with no password? <p>How can you get a user token from Logonuser for a user account with no password?</p>
<p>In particular Logonuser will fail for accounts that do not have passwords.<br />
You can validate an account by checking for a blank password + checking for GetLastError() == ERROR_ACCOUNT_RESTRICTION. </p>
<p>But I need to actually get a token returned, so I need this function to succeed. </p>
| <p>This will fail if the registry setting LimitBlankPasswordUse is enabled, which it is by default. In order to disable this change the LimitBlankPasswordUse value under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa to zero. Or change the group policy setting under Security Options. </p>
<p>Be aware that this creates a security hole since it allows remote logons for accounts with null passwords.</p>
|
Naming: What would you call a rich API that wraps around a thin API <p>I have a "thin" (SOAP) API that only knows how to set and get entities in the underlying system.</p>
<p>I am about to to create a "rich" API that encapsulates the "thin" API and implements the logic that is required for complex operations that entail getting and setting several entities in specific order.</p>
<p>Example: The rich API will be responsible for creating a new user account by creating a "Lead" entity that's linked to an "Account" entity via the thin API.</p>
<p>I'm stuck in a naming block so I turn to SO ;) What name would you give my rich API? "xxxRichAPI"? "xxxHelper"? "xxxService"? </p>
| <p>Isn't the point of an API that it hides it's implementation? As such, the fact that your API calls a thinner API is irrelevant. Name your API appropriately for what it does, regardless of how it does it.</p>
|
Writing custom IEnumerator<T> with iterators <p>How can I write a custom <code>IEnumerator<T></code> implementation which needs to maintain some state and still get to use iterator blocks to simplify it? The best I can come up with is something like this:</p>
<pre><code>public class MyEnumerator<T> : IEnumerator<T> {
private IEnumerator<T> _enumerator;
public int Position {get; private set;} // or some other custom properties
public MyEnumerator() {
Position = 0;
_enumerator = MakeEnumerator();
}
private IEnumerator<T> MakeEnumerator() {
// yield return something depending on Position
}
public bool MoveNext() {
bool res = _enumerator.MoveNext();
if (res) Position++;
return res;
}
// delegate Reset and Current to _enumerator as well
}
public class MyCollection<T> : IEnumerable<T> {
IEnumerator<T> IEnumerable<T>.GetEnumerator() {
return GetEnumerator();
}
public MyEnumerator<T> GetEnumerator() {
return new MyEnumerator<T>();
}
...
}
</code></pre>
| <p>Why do you want to write an iterator class? The whole point of an iterator block is so you don't have to...</p>
<p>i.e.</p>
<pre><code>public IEnumerator<T> GetEnumerator() {
int position = 0; // state
while(whatever) {
position++;
yield return ...something...;
}
}
</code></pre>
<p>If you add more context (i,e, why the above can't work), we can probably help more.</p>
<p>But if possible, avoid writing an iterator class. They are lots of work, and easy to get wrong.</p>
<p>By the way, you don't really have to bother with <code>Reset</code> - it is largely deprecated, and shouldn't really ever be used (since it can't be relied to work for an arbitrary enumerator).</p>
<p>If you want to consume an inner iterator, that is fine too:</p>
<pre><code>int position = 0;
foreach(var item in source) {
position++;
yield return position;
}
</code></pre>
<p>or if you only have an enumerator:</p>
<pre><code>while(iter.MoveNext()) {
position++;
yield return iter.Current;
}
</code></pre>
<p>You might also consider adding the state (as a tuple) to the thing you yield:</p>
<pre><code>class MyState<T> {
public int Position {get;private set;}
public T Current {get;private set;}
public MyState(int position, T current) {...} // assign
}
...
yield return new MyState<Foo>(position, item);
</code></pre>
<p>Finally, you could use a LINQ-style extension/delegate approach, with an <code>Action<int,T></code> to supply the position and value to the caller:</p>
<pre><code> static void Main() {
var values = new[] { "a", "b", "c" };
values.ForEach((pos, s) => Console.WriteLine("{0}: {1}", pos, s));
}
static void ForEach<T>(
this IEnumerable<T> source,
Action<int, T> action) {
if (source == null) throw new ArgumentNullException("source");
if (action == null) throw new ArgumentNullException("action");
int position = 0;
foreach (T item in source) {
action(position++, item);
}
}
</code></pre>
<p>Outputs:</p>
<pre><code>0: a
1: b
2: c
</code></pre>
|
System.Net's Webclient in C# won't connect to server <p>Is there something I need to do to get System.Net working with Microsoft Visual C# 2008 Express Edition? I can't seem to get any web type controls or classes to work at all.. the below WebClient example always throws the exception "<strong>Unable to connect to the remote server</strong>".. and consequently I can't get the WebBrowser control to load a page either.</p>
<p>Here is the code (Edited):</p>
<pre><code>using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
using (WebClient client = new WebClient()) {
string s = client.DownloadString("http://www.google.com");
this.textBox1.Text = s;
}
}
}
}
</code></pre>
<p>This is in a simple form with only a textbox control (with multiline set to true) in it. The exception gets thrown on the <code>DownloadString(...)</code> line. I also tried using <code>WebRequest</code>.. same exception!</p>
<p>EDIT:</p>
<p>I am connected to a Linksys WRT54G Router that connects directly to my cable modem. I am not behind a proxy server, although I did run <code>proxycfg -u</code> and I got:</p>
<pre><code>Updated proxy settings
Current WinHTTP proxy settings under:
HKEY_LOCAL_MACHINE\
SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections\
WinHttpSettings :
Direct access (no proxy server).
</code></pre>
<p>I am using Windows XP and not running any kind of firewall. Only AVG at the moment. I'm pretty sure I shouldn't have to forward any ports or anything, but I did try forwarding port 80 to my workstation on my router. Didn't help.</p>
| <p>(<strong>update</strong> - I meant <code>proxycfg</code>, not <code>httpcfg</code>; <code>proxycfg -u</code> will do the import)</p>
<p>First, there is nothing special about "express" here. Second, contoso is a dummy url.</p>
<p>What OS are you on? And do you go through a proxy server? If so, you might need to configure the OS's http stack - <code>proxycfg</code> will do the job on XP, and can be used to import the user's IE settings.</p>
<p>The sample is fine, although it doesn't correctly handle the multiple <code>IDisposable</code> objects - the following is much simpler:</p>
<pre><code> using (WebClient client = new WebClient()) {
string s = client.DownloadString("http://www.google.com");
// do something with s
}
</code></pre>
|
How can I call an executable to run on a separate machine within a program on my own machine (win xp)? <p>My objective is to write a program which will call another executable on a separate computer(all with win xp) with parameters determined at run-time, then repeat for several more computers, and then collect the results. In short, I'm working on a grid-computing project. The algorithm itself being used is already coded in FORTRAN, but we are looking for an efficient way to run it on many computers at once.</p>
<p>I suppose one way to accomplish this would be to upload a script to each computer and then run said script on each computer, all automatically and dependent on my own parameters. But how can I write a program which will write to, upload, and run a script on a separate computer?</p>
<p>I had considered GridGain, but the algorithm is already coded and in a different language, so that is ruled out.</p>
<p>My current guess at accomplishing this task is using Expect (<a href="http://en.wikipedia.org/wiki/Expect" rel="nofollow">wiki/Expect</a>), but I have no knowledge of the tool.</p>
<p>Any advice appreciated.</p>
| <p>You can use PsExec for this:</p>
<p><a href="http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx" rel="nofollow">http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx</a></p>
<p>You could also look at the open source alternative RemCom:</p>
<p><a href="http://rce.sourceforge.net/" rel="nofollow">http://rce.sourceforge.net/</a></p>
<p>It's actually pretty simple to write your own as well but RCE will show you how to do it if you want. Although, using PsExec may just suffice your needs.</p>
|
Bi-Directionnal Replication With SQL Server <p>Is there a way to make a bi-directionnal Replication with SQL Server ?</p>
<p>(BDD 1) Table 1 <=> (BDD 2) Table 1</p>
<p>Thanks.</p>
| <p>There are a few solutions that might suit your need. </p>
<ol>
<li><a href="http://msdn.microsoft.com/en-us/library/ms151329.aspx" rel="nofollow">Merge replication</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms151196.aspx" rel="nofollow">Peer to peer transactional replication</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/bb934127.aspx" rel="nofollow">Database mirroring</a></li>
</ol>
<p>Each of them has its own advantages and disadvantages. Choosing one depends on the nature of your scenario.</p>
|
Hyperlinks within "about" text for iphone application <p>I'm on the final stretch of my first simple iPhone application. I'm building an "about" view, with credits/info/etc.</p>
<p>I am failing on the simplest thing: how can I embed hyperlinks into the text? I'm current using a UIView with a UILabel for the text.</p>
<p>I've looked on here, and the sample apps, but not got anywhere. Should I use a UIWebView? </p>
<p>Thx.</p>
| <p>Yep, use a UIWebView and put static HTML in it.</p>
<p>Like so:</p>
<pre><code>[myWebView loadHTMLString:@"<html><head></head><body style=\"font-family: sans-serif;\"> .... </body></html>" baseURL:nil];
</code></pre>
|
Automatic .toString() when calling a method? <p>I got the code of a former employee. There are many calls to methods like:</p>
<pre><code>foo(val,...);
</code></pre>
<p>where </p>
<pre><code>void foo(String s,...) {
...
}
</code></pre>
<p>and val is an int.</p>
<p>Of course, I get an error.</p>
<p>As a workaround I pass ""+val to foo. I wonder if there is a better way.</p>
| <p>depending on the different types that are supposed to be passed as parameter, you could either accept an object and call .toString()</p>
<pre><code>void foo(Object o){
String s=o.toString();
...
}
</code></pre>
<p>or overload foo for specific types</p>
<pre><code>void foo(String s) {
...
}
void foo(int i){
foo(Integer.toString(i);
}
</code></pre>
|
Recommendations of a high volume log event viewer in a Java enviroment <p>I am in a situation where I would like to accept a LOT of log events controlled by me - notably the logging agent I am preparing for slf4j - and then analyze them interactively.</p>
<p>I am not as such interested in a facility that presents formatted log files, but one that can accept log events as objects and allow me to sort and display on e.g. threads and timelines etc.</p>
<p>Chainsaw could maybe be an option but is currently not compatible with logback which I use for technical reasons.</p>
<p>Is there any project with stand alone viewers or embedded in an IDE which would be suitable for this kind of log handling. I am aware that I am approaching what might be suitable for a profiler, so if there is a profiler projekt suitable for this kind of data acquisition and display where I can feed the event pipe, I would like to hear about it).</p>
<p>Thanks for all feedback</p>
<p><hr /></p>
<p>Update 2009-03-19: I have found that there is not a log viewer which allows me to see what I would like (a visual display of events with coordinates determined by day and time, etc), so I have decided to create a very terse XML format derived from the log4j XMLLayout adapted to be as readable as possible while still being valid XML-snippets, and then use the Microsoft LogParser to extract the information I need for postprocessing in other tools.</p>
| <p>You might implement a adapter for logback to send log4j events to a log4j receiver. This would enable you to use chainsaw. Or build an adapter which receives logback network events and exposes them for log4j.</p>
|
QNX c++ thread question <p>I have a question concerning this code which I want to run on QNX:</p>
<pre><code>class ConcreteThread : public Thread
{
public:
ConcreteThread(int test)
{
testNumber = test;
}
void *start_routine()
{
for(int i = 0; i < 10; i++)
{
sleep(1);
cout << testNumber << endl;
}
}
private:
int testNumber;
};
class Thread
{
public:
Thread(){};
int Create()
{
pthread_t m_id;
return pthread_create(&m_id, NULL, &(this->start_routine_trampoline), this);
}
protected:
virtual void *start_routine() = 0;
private:
static void *start_routine_trampoline(void *p)
{
Thread *pThis = (Thread *)p;
return pThis->start_routine();
}
};
</code></pre>
<p>Now, when I run this code without the sleep in *start_routine, it will simply print the number 10 times, before continuing on to the next line of code (sequential instead of parallel). However, when I use a sleep like in the code, it doesn't print any numbers at all and simply goes on to the next line of code. Why doesn't sleep work and how can I make a thread like this work, instead of running sequential?</p>
| <p>Note 1: If you only have 1 processor the code can only be done sequentially no matter how many threads you create. Each thread is given a slice of processor time before it is swapped out for the next threads.</p>
<p>Note 2: If the main thread exits pthreads will kill all child threads before they have a chance to execute.</p>
<p>Now to answer you questions:</p>
<p>Without the sleep. The thread once started has enough time in the single slice it was given to execute the loop 10 times completely.</p>
<p>With the sleep: Your worker thread is going to sleep for a full second. So your main thread has time to do a lot of work. If the main thread exits in this time the worker will be killed.</p>
<p>I would make the following changes:</p>
<pre><code>// Remove the Create() method
// Put thread creation in the constructor.
// Make the thread variable part of the object
pthread_t m_id;
Thread()
{
if (pthread_create(&m_id, NULL, &(this->start_routine_trampoline), this) != 0)
{
throw std::runtime_error("Thread was not created");
}
}
// Make sure the destructor waits for the thread to exit.
~Thread()
{
pthread_join(m_id);
}
</code></pre>
<p>If you go and look at <b>boost threading</b> library. you will find that all the little mistakes like this have already been taken care of; Thus making threading easier to use.</p>
<p>Also note. That using a static may work but it is non portable. This is because pthread's is a C library and is thus expecting a function pointer with a C ABI. You are just getting lucky for your platform here. You need to define this as a function and declare the ABI by using extern "C"</p>
<pre><code>// This needs to be a standard function with C Interface.
extern "C" void *start_routine_trampoline(void *p)
{
}
</code></pre>
|
Paletted textures with 8-bit alpha channel in OpenGL ES <p>Can I get paletted textures with RGB palette and 8-bit alpha channel in OpenGLÂ ES? (I am targetting the iPhone OpenGL ES implementation.) After peeking into the OpenGL documentation it seems to me that there is support for paletted textures with alpha in the palette, ie. the texture contains 8-bit indexes into a palette with 256 RGBA colors. I would like a texture that contains 8-bit indexes into an RGB palette <em>and</em> a standalone 8-bit alpha channel. (IÂ am trying to save memory and 32-bit RGBA textures are quite a luxury.) Or is this supposed to be done by hand, ie. by creating two independent textures, one for the colors and one for the alpha map, and combining them manually?</p>
| <p>No. In general, graphics chips really don't like palletized textures (why? because reading any texel from it requires two memory reads, one of the index and another into the palette. Double the latency of a normal read).</p>
<p>If you're only after saving memory, then look into compressed texture formats. In iPhone specifically, it supports PVRTC compressed formats with 2 bits/pixel and 4 bits/pixel. The compression is lossy (just like palette compression is often lossy), but memory and bandwidth savings are substantial.</p>
|
Fluent interfaces and leaky abstractions <p>What is a fluent interface? I can't find a good definition of this, but all I get are long code examples in a language I am not very familiar with (e.g. C++).</p>
<p>Also, what is a leaky abstraction?</p>
<p>Thanks</p>
| <p>A fluent interface is an API that allows you to write code that reads more or less like normal English. For example:</p>
<pre><code>Find.All.Questions(Where.IsAnswered == true);
</code></pre>
<p>Method-chaining is usually used as part of the implementation, but there is more to it than that. To quote <a href="http://martinfowler.com/bliki/FluentInterface.html">Fowler</a>:</p>
<blockquote>
<p>I've also noticed a common misconception - many people seem to equate fluent interfaces with Method Chaining. Certainly chaining is a common technique to use with fluent interfaces, but true fluency is much more than that.</p>
</blockquote>
<p>It is also often called an internal <a href="http://www.martinfowler.com/bliki/DomainSpecificLanguage.html">DSL</a>, since the syntax resembles that of a DSL, but it is implemented inside the host language instead of being processed by a parser.</p>
|
Lookup Tables Best Practices: DB Tables... or Enumerations <p>If we have to store the available positions at a company (i.e. Manager, Team Lead, ... etc). What are the best practices for storing it? I have two opinions with comments... "sure, welcoming yours"<br/>
<b></p>
<ol>
<li>Storing it as DB table with columns ID and Name, and deal with it using queries and joins.</li>
<li>Storing it as Enum and forget about the DB table.</li>
</ol>
<p></b>
In my opinion, I will choose the first solution if I have changing items. So that I won't hard code these options as Enum.<br/>
I may choose the Enum solution, if I have no doubt that data won't change (for example, Gender: Male, Female). <br/><br/>
<b>NOTE:</b> I code in English, and the UI Culture may be Arabic. If I will work with the Enum Solution, I will hard code the culture-based strings in the presentation layer, is it okay from the best practices perspective!!!! <br/><br/>
I would like to know your opinions and if my thoughts correspond to what is most recommended "Best Practices"?? </p>
| <p>Generally you should only use enumeration where the is a clear set of items that will not change. Male/Female is a good example, otherwise lookup tables, with appropriately implemented foreign keys are pretty much always the best option.</p>
<p>There is a possible variation on the lookup table option where you potentially have a large number of lookup tables for simple id/value relationships. A domain/lookup table pair can dramatically reduce this the number of tables required, albeit with some additional coding complexity. In this case you'd have a domain table</p>
<pre>
DomainID int identity
Domain varchar(255)
</pre>
<p>and a key/value table</p>
<pre>
DomainID int
ID int identity
Value varchar(255)
</pre>
<p>Hence a row is added to the Domain table corresponding to each lookup table that you would otherwise use, and all (key-domain)/value pairs added to the value table. Apart from simplifying the database structure this approach also has the advantage that 'lookup tables' can be created in the application code dynamically, which in some applications can be extremely useful. </p>
|
Entity Framework query with grouping (many to many) <p>I have a classical many to many scenario with three tables (students, courses, and third StudentsCourses assignment table).</p>
<p>I'm using EF in my new project and EF designer doesn't create third table.
I need to select all cources along with number of students assigned to it.
Using plain SQL is very straightforward:</p>
<pre><code>select c.Id, c.Name, Count(sc.*) as StudentCount
from Courses c left join StudentCourses sc on(c.Id=sc.CourseId)
group by c.Id, c.Name
</code></pre>
<p>But I can't figure out how to translate this query to Linq to SQL.
Please advice.</p>
<p>Thank you.</p>
| <p>The EF designer hides the table. It's still there, but it just creates the assocation for you, so you can just reference students from courses or vice versa.</p>
|
Is WPF production ready? <p>I'm wondering if there are people out there with experience of WPF application development - and maybe more interesting - running WPF in production.</p>
<p>Is it mature enough to use in larger projects? What are the obvious pitfalls? Any best practices? (Databinding in WPF seems pretty nifty but does it work in 'real' projects?)</p>
<p>Thanks in advance!</p>
| <p>WPF came out with .NET 3.0. We're on 3.5 sp1, so if its not production ready MS has got a lot of essplainin' to do. Frankly, it was production ready when 3.0 came out.</p>
<p>I'm currently working on a project that uses WPF for templating and databinding (not for UI display, but I use UI classes to define templates). I've also used WPF for personal stuff. And, quite frankly, I'd have to be beaten severely to even consider using windows forms for UI. WPF is beautiful in its simplicity and flexibility. Its databinding facilities are spectacular compared to the hacked-together windows forms binding models. And XAML is a revolutionary step in software design, imho. </p>
<p>Databinding in WPF is not just nifty, it also allows you to implement some pretty good architectural designs. <a href="http://blogs.sqlxml.org/bryantlikes/archive/2006/09/27/WPF-Patterns.aspx">This is a good post that covers some of the more popular ones.</a> Think of it like MVC/MVP on steroids. </p>
<p>Long story short, run. Don't walk. </p>
|
Where do you download Linux source code? <p>Say I'm interested in the source for one particular Linux utility, like <code>factor</code>. Where can I find the source code for that utility?</p>
| <p>You can also find out which package the binary comes from an download that packages source code.</p>
<p>On Debian (and Ubuntu and anything else that's based on Debian) you do that like this:</p>
<pre>
$ dpkg -S /usr/bin/factor
coreutils: /usr/bin/factor
$ apt-get source coreutils
</pre>
<p>The first command will check which package contains the file you are searching for (use "<code>which factor</code>" to find out which binary is executed when you just type "<code>factor</code>").</p>
<p>The second command will download and unpack the sources (including the patches applied to build the package) to the current directory, so it should be executed in a dedicated or temporary directory.</p>
<p>I'm pretty sure <code>rpm</code>-based distributions have a similar mechanism, but I don't know their commands.</p>
|
Segfault from adding a variable <p>I'm admittedly a straight-C newbie, but this has got me stumped. I'm working on a linked list implementation for practice, and I'm getting a segfault by simply adding a variable to the split_node function:</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Node {
struct Node *child;
char *content;
};
void print_list(struct Node node);
void split_node(struct Node *node, int position);
int main() {
struct Node head, second, third;
head.content = "first";
second.content = "second";
third.content = "i'm third";
head.child = &second;
second.child = &third;
print_list(head);
split_node(&head, 3);
print_list(head);
return 0;
}
void print_list(struct Node node) {
printf("%s\n", node.content);
if(node.child) print_list(*node.child);
}
/*
Split node into two nodes, with the first position characters of the node's content remaining with node, and the remainder being copied to the new node. (It doesn't yet truncate the first node's string, but does do the copy.)
*/
void split_node(struct Node *node, int position) {
if(position >= strlen((*node).content)) return;
struct Node newNode;
newNode.child = (*node).child;
(*node).child = &newNode;
int length = (strlen((*node).content) - position);
newNode.content = malloc(sizeof(char) * (length + 1));
strncpy(newNode.content, (*node).content + sizeof(char) * position, length);
newNode.content[length] = '\0';
//int foo;
}
</code></pre>
<p>This code compiles (gcc -Wall -o list list.c) and runs fine:</p>
<pre><code>$ ./list
first
second
i'm third
first
st
second
i'm third
</code></pre>
<p>But if I uncomment <code>int foo</code> at the end of <code>split_node</code>, compile and run, I get:</p>
<pre><code>$ ./list
first
second
i'm third
first
st
Segmentation fault
</code></pre>
<p>gdb gives me this backtrace:</p>
<pre><code>#0 0x91d6ae70 in strlen ()
#1 0x91dd3126 in puts ()
#2 0x00001f21 in print_list (node={child = 0xbcec815b, content = 0x8b000000 <Address 0x8b000000 out of bounds>}) at list.c:41
#3 0x00001f3c in print_list (node={child = 0x8fe0154b, content = 0x1ff6 "i'm third"}) at list.c:42
#4 0x00001f3c in print_list (node={child = 0xbffff568, content = 0x1fef "second"}) at list.c:42
#5 0x00001f3c in print_list (node={child = 0xbffff570, content = 0x1fe9 "first"}) at list.c:42
#6 0x00001ee0 in main () at list.c:33
</code></pre>
<p>Why would adding a variable definition cause a segfault? It appears to be smashing the content pointer of the newly created node. I'm confused; any help?</p>
| <p>You need to dynamically allocate your nodes (using malloc).</p>
<p>As you have it, your new node is declared on the stack. When the split function returns, that new node is no longer valid memory.</p>
<p>Adding a variable causes a segfault because that variable changes the layout of the stack causing slightly different behavior when the function returns.</p>
|
Two basic C++ questions about string literals and dynamic allocation <p>Are these two equivalent?</p>
<p>char * aString = "This is a string.";</p>
<p>char aString[] = "This is a string.";</p>
<p>From my understanding, C++ stores strings by their addresses, so the pointer is getting a valid address. I assume the strings are also stored as type char? But how does it know how much memory to allocate for the string? Normally, char arrays need their array size preset. I believe the [] type arrays are counted by the compiler before compilation. Is this what happens for the string literal pointer as well?</p>
<p>On to my second question, what is the difference between these two:</p>
<p>int someNumber;</p>
<p>int * someNumber = new int;</p>
<p>The second is supposed to be dynamic allocation. If I understand the concept right, it allocates the memory as soon as it reads the declaration. But what happens in the standard declaration? Basically, I need to understand how dynamic allocation is advantageous over standard declarations.</p>
| <pre><code>char * aString = "This is a string.";
</code></pre>
<p>It's making a pointer <code>aString</code> point to a statically allocated char array containing <code>"This is a string."</code>. The string is <em>not</em> writable, even though the type of the pointer might suggest you could write to it. See the answer in the link below, for reasons to avoid it and how you can do better. </p>
<pre><code>char aString[] = "This is a string.";
</code></pre>
<p>It's creating an array having the type <code>char[18]</code>. Even though you tell it with the declarator that <code>aString</code> has a type <code>char[]</code>, it's really defining an array with a complete type - that is, with a defined length for that array. That's because it's directly initialized, and the compiler can deduce the size of the array. The array <em>is</em> writable. You can freely change characters in it. I tried to make the difference clear in this answer: <a href="http://stackoverflow.com/questions/308279/c-vs#308724">http://stackoverflow.com/questions/308279/c-vs#308724</a></p>
<pre><code>int someNumber;
</code></pre>
<p>It's an integer variable created on the stack. It's <em>not</em> initialized. It has automatic storage duration: Going out of scope (returning from the function, breaking out of the loop...) will free the memory of it. You can of course write to it as much as you want. </p>
<pre><code>int * someNumber = new int;
</code></pre>
<p>It's a pointer which will point to an integer that's dynamically allocated. The int is <em>not</em> initialized. And the memory is <em>not</em> freed when the pointer goes out of scope. That is, when your function returns, the memory will still be there.</p>
|
Rails: how do you access RESTful helpers? <p>I'm trying to work through this <a href="http://guides.rubyonrails.org/routing_outside_in.html">guide to Rails routing</a>, but I got stuck in section <a href="http://guides.rubyonrails.org/routing_outside_in.html#_urls_and_paths">3.3</a>:</p>
<blockquote>
<p>Creating a RESTful route will also make available a pile of helpers within your application</p>
</blockquote>
<p>and then they list some helpers like <code>photos_url</code>, <code>photos_path</code>, etc.</p>
<p>My questions:</p>
<p>Where can I find the complete list of helpers that is "made available?"</p>
<p>Is there a way to call the helpers in the console? I created an app, then opened up the console with <code>script/console</code>. I tried to call one of the helpers on the console like this:</p>
<pre><code>>> entries_url
</code></pre>
<p>But got:</p>
<pre><code>NameError: undefined local variable or method `entries_url' for #<Object:0x349a4>
from (irb):8
</code></pre>
| <p>You have several questions in there, most of which have already been answered by people below.</p>
<p>The answer to one that wasn't fully addressed however, is: yes you can use the script/console to see where your routes go. Just type in <code>app.[route_helper]</code> and it will respond with the path. For example <code>app.users_path</code> will return <code>/users/</code></p>
<p>So for your example type <code>app.entries_url</code> for the full URL - or <code>app.entries_path</code> for its relative path within the console.</p>
|
Mongrel hangs <p>I'm running into a problem in a Rails application.
After some hours, the application seems to start hanging, and I wasn't able to find where the problem was. There was nothing relevant in the log files, but when I tried to get the url from a browser nothing happened (like mongrel accept the request but wasn't able to respond).</p>
<p>What do you think I can test to understand where the problem is? </p>
<p>Thanks for your help!</p>
| <p>I might get voted down for dodging the question, but I recently moved from nginx + mongrel to mod_rails and have been really impressed. Moving to a much simpler setup will undoubtedly save me headaches in the future. </p>
<p>It was a really easy transition, I'd highly recommend it.</p>
|
mysql select - how to retrieve a result for threaded/nested messages? <p>I'm creating a threaded message board and I'm trying to keep it simple. There's a message table, and then a replies table that has an 'reply_id' field that can be null to indicate a top level response, or a value that indicates a threaded response.</p>
<p>I'm a bit confused on how to do a SELECT call on this type of table though? </p>
<pre><code>Reply
-id (every reply gets a unique id)
-message_id (the message it is replying to)
-reply_id (the id of the reply it may be replying to - for threading)
-reply
</code></pre>
<p>I know this can be a complex problem, especially for performance, but I'm really just looking for the most basic solution to this.</p>
<p>thanks...</p>
| <p>You're using the naive "textbook" way of storing trees, i.e. store a reference to the immediate parent. This design is called <strong>Adjacency List</strong>. There are other solutions:</p>
<ul>
<li><strong>Path Enumeration</strong>, where you store in each node of the tree a string encoding all its direct ancestors.</li>
<li><strong>Nested Sets</strong>, a clever approach by Joe Celko where you use two numeric values per node to bound all its descendants.</li>
<li><strong>Closure Table</strong> (or Adjacency Relation), where you use a separate table to list every ancestor-descendant pair.</li>
</ul>
<p>See my response to "<a href="http://stackoverflow.com/questions/192220/what-is-the-most-efficient-elegant-way-to-parse-a-flat-table-into-a-tree#192462">What is the most efficient/elegant way to parse a flat table into a tree?</a>" for references and examples of the Closure Table design.</p>
|
Array of structs and new / delete <p>I have a struct like this:</p>
<pre><code>class Items
{
private:
struct item
{
unsigned int a, b, c;
};
item* items[MAX_ITEMS];
}
</code></pre>
<p>Say I wanted to 'delete' an item, like so:</p>
<pre><code>items[5] = NULL;
</code></pre>
<p>And I created a new item on that same spot later:</p>
<pre><code>items[5] = new item;
</code></pre>
<p>Would I still need to call <code>delete[]</code> to clean this up? Or won't this be needed since bounds of array <code>items[]</code> are known before compiling? </p>
<p>Is setting that pointer to NULL valid or should I be calling delete there?</p>
| <p>You need to call <code>delete</code> before setting it to NULL. (Setting it to NULL isn't required, it just helps reduce bugs if you accidentally try to dereference the pointer after deleting it.)</p>
<p>Remember that every time you use <code>new</code>, you will need to use <code>delete</code> later on the same pointer. Never use one without the other.</p>
<p>Also, <code>new []</code> and <code>delete []</code> go together in the same way, but you should never mix <code>new []</code> with <code>delete</code> or <code>new</code> with <code>delete []</code>. In your example, since you created the object with <code>new</code> (rather than <code>new []</code> which would create an array of objects) you must delete the object with <code>delete</code> (rather than <code>delete []</code>).</p>
|
How to reverse a Unicode string <p>It was hinted in a <a href="http://stackoverflow.com/questions/433525/choosing-asp-net-over-php-or-perl#433610">comment to an answer to this question</a> that PHP can not reverse Unicode strings. </p>
<blockquote>
<p>As for Unicode, it works in PHP
because most apps process it as
binary. Yes, PHP is 8-bit clean. Try
the equivalent of this in PHP: perl
-Mutf8 -e 'print scalar reverse("ã»ãã»ã")' You will get garbage,
not "ãã»ãã»". â jrockway</p>
</blockquote>
<p>And unfortunately it is correct that PHPs unicode support atm is at best "lacking". This will <a href="http://74.125.77.132/search?q=cache:X3t6LgxXRa0J:derickrethans.nl/files/php6-unicode.pdf+php6+unicode">hopefully change drastically with PHP6</a>. </p>
<p>PHPs <a href="http://no2.php.net/manual/en/ref.mbstring.php">MultiByte functions</a> does provide the basic functionality you need to deal with unicode, but it is inconsistent and does lack a lot of functions. One of these is a function to reverse a string.</p>
<p>I of course wanted to reverse this text for no other reason then to figure out if it was possible. And I made a function to accomplish this enormous complex task of reversing this Unicode text, so you can relax a bit longer until PHP6.</p>
<p>Test code:</p>
<pre><code>$enc = 'UTF-8';
$text = "ã»ãã»ã";
$defaultEnc = mb_internal_encoding();
echo "Showing results with encoding $defaultEnc.\n\n";
$revNormal = strrev($text);
$revInt = mb_strrev($text);
$revEnc = mb_strrev($text, $enc);
echo "Original text is: $text .\n";
echo "Normal strrev output: " . $revNormal . ".\n";
echo "mb_strrev without encoding output: $revInt.\n";
echo "mb_strrev with encoding $enc output: $revEnc.\n";
if (mb_internal_encoding($enc)) {
echo "\nSetting internal encoding to $enc from $defaultEnc.\n\n";
$revNormal = strrev($text);
$revInt = mb_strrev($text);
$revEnc = mb_strrev($text, $enc);
echo "Original text is: $text .\n";
echo "Normal strrev output: " . $revNormal . ".\n";
echo "mb_strrev without encoding output: $revInt.\n";
echo "mb_strrev with encoding $enc output: $revEnc.\n";
} else {
echo "\nCould not set internal encoding to $enc!\n";
}
</code></pre>
| <p>here's another approach using regex:</p>
<pre><code>function utf8_strrev($str){
preg_match_all('/./us', $str, $ar);
return implode(array_reverse($ar[0]));
}
</code></pre>
|
Extending XHTML <p>I'm playing around with writing a jQuery plugin that uses an attribute to define form validation behavior (yes, I'm aware there's already a validation plugin; this is as much a learning exercise as something I'll be using). Ideally, I'd like to have something like this:</p>
<p>Example 1 - input:</p>
<pre><code><input id="name" type="text" v:onvalidate="return this.value.length > 0;" />
</code></pre>
<p>Example 2 - wrapper:</p>
<pre><code><div v:onvalidate="return $(this).find('[value]').length > 0;">
<input id="field1" type="text" />
<input id="field2" type="text" />
<input id="field3" type="text" />
</div>
</code></pre>
<p>Example 3 - predefined:</p>
<pre><code><input id="name" type="text" v:validation="not empty" />
</code></pre>
<p>The goal here is to allow my jQuery code to figure out which elements need to be validated (this is already done) and still have the markup be valid XHTML, which is what I'm having a problem with. I'm fairly sure this will require a combination of both DTD and XML Schema, but I'm not really quite sure how exactly to execute.</p>
<p>Based on <a href="http://www.w3.org/TR/xhtml-modularization/dtd_developing.html#s_dev_attrs" rel="nofollow">this article</a>, I've created the following DTD:</p>
<pre><code><!ENTITY % XHTML1-formvalidation1
PUBLIC "-//W3C//DTD XHTML 1.1 +FormValidation 1.0//EN"
"http://new.dandoes.net/DTD/FormValidation1.dtd" >
%XHTML1-formvalidation1;
<!ENTITY % Inlspecial.extra
"%div.qname; " >
<!ENTITY % xhmtl-model.mod
SYSTEM "formvalidation-model-1.mod" >
<!ENTITY % xhtml11.dtd
PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd" >
%xhtml11.dtd;
</code></pre>
<p>And here is "formvalidation-model-1":</p>
<pre><code><!ATTLIST %div.qname;
%onvalidation CDATA #IMPLIED
%XHTML1-formvalidation1.xmlns.extra.attrib;
>
</code></pre>
<p>I've never done DTD before, so I'm not even really exactly sure what I'm doing. When I run my page through the W3 XHTML validator, I get 80+ errors because it's getting duplicate definitions of all the XHTML elements. Am I at least on the right track? Any suggestions?</p>
<hr>
<p><strong>EDIT:</strong>
I removed this section from my custom DTD, because it turned out that it was actually self-referencing, and the code I got the template from was really for combining two DTDs into one, not appending specific items to one:</p>
<pre><code><!ENTITY % XHTML1-formvalidation1
PUBLIC "-//W3C//DTD XHTML 1.1 +FormValidation 1.0//EN"
"http://new.dandoes.net/DTD/FormValidation1.dtd" >
%XHTML1-formvalidation1;
</code></pre>
<p>I also removed this, because it wasn't validating, and didn't seem to be doing anything:</p>
<pre><code><!ENTITY % Inlspecial.extra
"%div.qname; " >
</code></pre>
<p>Additionally, I decided that since I'm only adding a handful of additional items, the separate files model recommended by W3 doesn't really seem that helpful, so I've put everything into the dtd file, the content of which is now this:</p>
<pre><code><!ATTLIST div onvalidate CDATA #IMPLIED>
<!ENTITY % xhtml11.dtd
PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd" >
%xhtml11.dtd;
</code></pre>
<p>So now, I'm not getting any DTD-related validation errors, but the onvalidate attribute still is not valid.</p>
<p><strong>Update:</strong> I've ditched the DTD and added a schema: <a href="http://schema.dandoes.net/FormValidation/1.0.xsd" rel="nofollow">http://schema.dandoes.net/FormValidation/1.0.xsd</a></p>
<p>Using v:onvalidate appears to validate in Visual Studio, but the W3C service still doesn't like it.</p>
<p>Here's a page where I'm using it so you can look at the source:</p>
<p><a href="http://new.dandoes.net/auth" rel="nofollow">http://new.dandoes.net/auth</a></p>
<p>And here's the link to the w3c validation result:</p>
<p><a href="http://validator.w3.org/check?uri=http://new.dandoes.net/auth&charset=%28detect+automatically%29&doctype=Inline&group=0" rel="nofollow">http://validator.w3.org/check?uri=http://new.dandoes.net/auth&charset=(detect+automatically)&doctype=Inline&group=0</a></p>
<p>Is this about as close as I'll be able to get with this, or am I still doing something wrong?</p>
| <p>If you want the result to be valid XHTML, I believe you'll need to use <a href="http://www.w3.org/TR/xml-names11" rel="nofollow">XML namespaces</a> rather than a custom DTD. Not only does the DTD <em>define</em> the language (and thus, a custom DTD isn't "really" XHTML), but it will throw any browsers that read it into <a href="http://en.wikipedia.org/wiki/Quirks_mode" rel="nofollow">quirks mode</a>, even if they don't choke on the file.</p>
<p>Using a namespace, on the other hand, will produce perfectly valid XHTML (though not all validators are namespace-aware and may not validate it correctly) and allow browsers to work in (near-)standards mode.</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="http://example.com/ns/validation" xml:lang="en">
<head><title>Validation Example</title></head>
<body>
<input id="name1" type="text" v:onvalidate="return this.value.length &gt; 0;"/>
<input id="name2" type="text" v:validation="not empty"/>
</body>
</html>
</code></pre>
|
In LINQ to SQL, how do you pass parts of a LINQ query into a function <p>Is it possible to pass parts of a linq Query into a function?
I want create a common interface for my DAL that always uses the same query interface. For example, </p>
<pre><code>List<T> Get(Join j, Where w, Select s){
return currentDataContext<T>.Join(j).Where(w).Select(s).ToList();
}
</code></pre>
<p>Is this sort of thing possible? I'm thinking it would be done with expression trees, but I haven't been able to find examples of it.</p>
| <p>Well, the "join" is tricky, because it is very hard to express a join - but things like where / select / orderby are pretty easy...</p>
<p>Really, it is just a case of combining the various LINQ methods on <code>IQueryable<T></code>, which generally accept <code>Expression<Func<...>></code> for some combination. So a basic select with an optional predicate would be:</p>
<pre><code> public IQueryable<T> Get<T>(
Expression<Func<T,bool>> predicate
) where T : class
{
IQueryable<T> query = (IQueryable<T>)GetTable(typeof(T));
if (predicate != null) query = query.Where(predicate);
return query;
}
</code></pre>
<p>I would tend to return <code>IQueryable<T></code> too, since that is fully composable. If the caller wants a list, they can always use <code>ToList()</code> on it... or (for example):</p>
<pre><code> using(var ctx = new MyDataContext(CONN))
{
ctx.Log = Console.Out;
int frCount = ctx.Get<Customer>(c => c.Country == "France").Count();
}
</code></pre>
<p>which (using Northwind) does the query:</p>
<pre><code>SELECT COUNT(*) AS [value]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[Country] = @p0
</code></pre>
<p>The problem with including the "select" (projection) in the query is that you would end up with multiple generic types. Since you often want the projection the be an anonymous type, it would then be pretty impossible to specify the projection type (anonymous) <strong>and</strong> the table-type, and it would not be callable.</p>
<p>In reality, I wonder if there is much benefit writing such a method at all. I might just stick with a base method:</p>
<pre><code> public IQueryable<T> Get<T>() where T : class
{
return (IQueryable<T>)GetTable(typeof(T));
}
</code></pre>
<p>And let the caller compose it in their preferred way - perhaps with query syntax:</p>
<pre><code> var list = (from cust in ctx.Get<Customer>()
where cust.Country == "France"
select cust.CompanyName).Take(10).ToList();
</code></pre>
<p>Which uses:</p>
<pre><code>SELECT TOP (10) [t0].[CompanyName]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[Country] = @p0
</code></pre>
<p><hr /></p>
<p>Alternatively, if you really do want to include the order by and projection, then an extension method is the most practical approach; then you don't need to specify the original (source) T (which is what makes it uncallable when mixed with anon-types):</p>
<pre><code>public static class QueryExtension
{
public static IQueryable<TProjection>
Get<TSource, TProjection, TOrderKey>(
this IQueryable<TSource> source,
Expression<Func<TSource, bool>> where, // optional
Expression<Func<TSource, TProjection>> select,
Expression<Func<TProjection, TOrderKey>> orderBy)
{
if (where != null) source = source.Where(where);
return source.Select(select).OrderBy(orderBy);
}
}
</code></pre>
<p>Then consider a DAL method such as:</p>
<pre><code> public List<string> Countries()
{
return Customers.Get(
x=>x.CompanyName != "",
x=>x.Country,
x=>x).Distinct().ToList();
}
</code></pre>
<p>Which uses (again, with Northwind):</p>
<pre><code>SELECT DISTINCT [t0].[Country]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[CompanyName] <> @p0
</code></pre>
|
For Python support, what company would be best to get hosting from? <p>I want to be able to run WSGI apps but my current hosting restricts it. Does anybody know a company that can accommodate my requirements?</p>
| <p>My automatic response would be <a href="http://www.webfaction.com/">WebFaction</a>. </p>
<p>I haven't personally hosted with them, but they are primarily Python-oriented (founded by the guy who wrote CherryPy, for example, and as far as I know they were the first to roll out <a href="http://blog.webfaction.com/python-3-0-is-here">Python 3.0 support</a>).</p>
|
Should I create a interface and mock this class <p>I have this class called Table:</p>
<pre><code>class Table
{
public string Name
{
get
{
return this.wrapper.Eval(//some command);
//wrapper is pass in by the ctor and is a COM object.
}
}
}
</code></pre>
<p>which is used in this class:</p>
<pre><code>class Map
{
public Map MapTable(Table table)
{
return new Map(table.Name);
}
}
</code></pre>
<p>I want to test MapTable command, should I be mocking Table or should I mock the wrapper object that is used by the table object.</p>
<p>I was thinking something like this</p>
<pre><code> Test()
{
Mock<ITable> mocktable = new Mock<ITable>(//pass in the wrapper object);
mocktable.ExpectGet(n => n.Name).Returns("Hello World");
ITable table = mocktable.object;
Map mymap = Map.MapTable(table);
}
</code></pre>
<p>Would that be correct?</p>
| <p>Beyond the fact that there is usually no <em>one</em> perfect testing solution, I'd first go for mocking the COM object: there should be a interface available and you'll probably want to test everything "above" it.</p>
<p>If the <code>Table</code> contains non-trivial code (e.g. within the <code>Eval()</code>; anything with conditionals; or e.g. parsing using a <code>Culture</code>) you might want to have a mock of it as you show in your example.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.