instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>Any idea how I express 'implements' in UML?
I'm trying to write some actionscript classes in starUML with the help of this handy little template tool:
<a href="http://blog.flashmech.net/2008/09/generate-actionscript-3-with-staruml/" rel="nofollow noreferrer">http://blog.flashmech.net/2008/09/generate-actionscript-3-with-staruml/</a>
I want the tool to generate 'implements Iblah' in the classes but am not sure what connector to use, Aggregation? Dependecy?</p>
<p>Any help much appreciated.</p>
|
<p>Here is a starUML tutorial that should help - <a href="http://cnx.org/content/m15092/latest/" rel="nofollow noreferrer"><a href="http://cnx.org/content/m15092/latest/" rel="nofollow noreferrer">http://cnx.org/content/m15092/latest/</a></a></p>
|
<p>Here is a starUML tutorial that should help - <a href="http://cnx.org/content/m15092/latest/" rel="nofollow noreferrer"><a href="http://cnx.org/content/m15092/latest/" rel="nofollow noreferrer">http://cnx.org/content/m15092/latest/</a></a></p>
| 44,405
|
<p>I have data loaded and various transformations on the data complete, the problem is there is a parent/child relationship managed in the data - best explained by an example</p>
<p>each row has (column names are made up)</p>
<pre><code>row_key parent_row_key row_name parent_row_name
</code></pre>
<p>some rows have row_key == parent_row_key (their own parent)
some rows relate to another row
(row 25 is the parent to row 44 for example).</p>
<p>In this case, row 25 is parent to row 44. I need to put row 25's row_name in row 44's parent_row_name. How do I query the data in the pipeline for the value?</p>
|
<p>Can you not just split the data using a multicast and then do a merge-join against itself?</p>
|
<p>You could write your data to a temp table in your database, a raw file destination or recordset destination (depending on the size of your dataset). Then you could run through you data again and query your temp data and find the correct parent.</p>
| 22,129
|
<p>What is the difference between a <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.group.aspx" rel="nofollow noreferrer">Group</a> and a <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.match.aspx" rel="nofollow noreferrer">Match</a> in .NET's RegEx?</p>
|
<p>A <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.match.aspx" rel="noreferrer">Match</a> is an object that indicates a particular regular expression matched (a portion of) the target text. A <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.group.aspx" rel="noreferrer">Group</a> indicates a portion of a match, if the original regular expression contained group markers (basically a pattern in parentheses). For example, with the following code:</p>
<pre><code>string text = "One car red car blue car";
string pat = @"(\w+)\s+(car)";
Match m = r.Match(text);
</code></pre>
<p><code>m</code> would be match object that contains two groups - group 1, from <code>(\w+)</code>, and that captured "One", and group 2 (from <code>(car)</code>) that matched, well, "car".</p>
|
<p>A Match is a part of a string that matches the regular expression, and there could therefore be multiple matches within a string.</p>
<p>Inside a Match you can define groups, either anonymous or named, to make it easier to split up a match. A simple example is to create a regex to search for URLs, and then use groups inside to find the protocol (http), domain (www.web.com), path (/lol/cats.html) and arguments and what not. </p>
<pre><code>// Example I made up on the spot, probably doesn't work very well
"(?<protocol>\w+)://(?<domain>[^/]+)(?<path>/[^?])"
</code></pre>
<p>A single pattern can be found multiple times inside a string, as I said, so if you use Regex.Matches(string text) you will get back multiple matches, each consisting of zero, one or more groups.</p>
<p>Those named groups can be found by either indexing by number, or with a string. The example above can be used like this:</p>
<pre><code>Match match = pattern.Match(urls);
if (!match.Success)
continue;
string protocol = match.Groups["protocol"].Value;
string domain = match.Groups[1].Value;
</code></pre>
<p>To make things even more interesting, one group could be matched multiple times, but then I recommend start reading the <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.group.captures.aspx" rel="nofollow noreferrer">documentation</a>.</p>
<p>You can also use groups to generate back references, and to do partial search and replace, but read more of that on <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchcollection.aspx" rel="nofollow noreferrer">MSDN</a>.</p>
| 4,875
|
<p>What is the best way to create a fixed width file in C#. I have a bunch of fields with lengths to write out. Say 20,80.10,2 etc all left aligned. Is there an easy way to do this? </p>
|
<p>You can use string.Format to easily pad a value with spaces
e.g.</p>
<pre><code>string a = String.Format("|{0,5}|{1,5}|{2,5}", 1, 20, 300);
string b = String.Format("|{0,-5}|{1,-5}|{2,-5}", 1, 20, 300);
// 'a' will be equal to "| 1| 20| 300|"
// 'b' will be equal to "|1 |20 |300 |"
</code></pre>
|
<p>Can't you use standard text file? You can read back data line by line.</p>
| 11,190
|
<p>I want to plan a data access layer and I thought to use Linq.
I read that linq has its problems with performance and that you could use stored procedures with linq.
Should I use stored procedures with linq when planning my data access layer? Is it crucial for the performance? When should I use them?
I know that stored procedures are essential for security but linq uses type safe queries so the only reason for stored procedures is performance.</p>
<p>Thanks,</p>
<p>Omri</p>
|
<p>From what I have read, the server caches execution plans of queries generated through LinqToSql, so these queries will perform roughly the same way as would equivalent stored procedures. And if you use stored procedures, then you lose the advantages that you get by using LinqToSql, since your query logic will stay in the DB.</p>
<p>See Rico Mariani's <a href="http://blogs.msdn.com/ricom/archive/2007/06/22/dlinq-linq-to-sql-performance-part-1.aspx" rel="nofollow noreferrer">blog series</a> on LinqToSql performance for more, as well as <a href="http://dotnet.org.za/hiltong/archive/2008/02/01/why-use-linq-to-sql-part-1-performance-considerations.aspx" rel="nofollow noreferrer">this blog post</a>.</p>
|
<p>I would recommend going with LINQ or stored procedures, but not both - there is no real reason to combine the two and you won't win in terms of performance. LINQ would be useful for smaller-scale web apps, stored procedures for a larger scale web-app or for better scaleability</p>
<p>The problem is not only performance as a web app grows in terms of number of users, pages served, etc... it becomes a problem of maintenace as well. If your queries become more complex over time, your LINQ code could become a nightmare to maintain. Stored procedures remain nicely hidden away in the database layer. And... no matter what anyone says, a query that executes at the database level will ALWAYS execute faster. </p>
| 43,665
|
<p>I do some minor programming and web work for a local community college. Work that includes maintaining a very large and soul destroying website that consists of a hodge podge of VBScript, javascript, Dreamweaver generated cruft and a collection of add-ons that various conmen have convinced them to buy over the years. </p>
<p>A few days ago I got a call "The website is locking up for people using Safari!" Okay, step one download Safari(v3.1.2), step two surf to the site. Everything appears to work fine.</p>
<p>Long story short I finally isolated the problem and it relates to Safari's back button. The website uses a fancy-pants javascript menu that works in every browser I've tried including Safari, the first time around. But in Safari if you follow a link off the page and then hit the back button the menu no longer works.</p>
<p>I made a pared down webpage to illustrate the principle.</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><title>Safari Back Button Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body onload="alert('Hello');">
<a href="http://www.codinghorror.com">Coding Horror</a>
</body>
</html>
</code></pre>
<p>Load the page and you see the alert box. Then follow the link off the page and hit the back button. In IE and Firefox you see the alert box again, in Safari you do not.</p>
<p>After a vigorous googling I've discovered others with similar problems but no really satisfactory answers. So my question is how can I make my pages work the same way in Safari after the user hits the back button as they do in other browsers?</p>
<p>If this is a stupid question please be gentle, javascript is somewhat new to me.</p>
|
<p>Stefan's iframe solution works, but if that's not elegant enough, I find the following JavaScript also solves it:</p>
<pre><code>window.onunload = function(){};
</code></pre>
<p>That is, if your menu is JavaScript, then you might prefer to solve this issue with JavaScript too.</p>
<p>The unload event handler definition idea came from this Firefox 1.5 article: <a href="https://developer.mozilla.org/en/Using_Firefox_1.5_caching" rel="noreferrer">https://developer.mozilla.org/en/Using_Firefox_1.5_caching</a>.</p>
|
<p>Had the same problem on iPad.</p>
<p>Not that beautiful but it works :). How it works.</p>
<p>I realised that on iPad Safari, the page was not reloaded when the back button was pressed. I put a counter every second on the page and I save the current timestamp.</p>
<p>When the page is loaded the counter and time are synchronized. On back button, counter continue where it stopped and there is a gap between timestamp and counter. If the gap is grater than 500ms, force reload the page.</p>
<p>In the file action.js</p>
<pre><code>var showLoadingBoxSetIntervalVar;
var showLoadingBoxCount = 0;
var showLoadingBoxLoadedTimestamp = 0
function showLoadingBox(text) {
var showLoadingBoxSetIntervalVar=self.setInterval(function(){showLoadingBoxIpadRelaod()},1000);
showLoadingBoxCount = 0
showLoadingBoxLoadedTimestamp = new Date().getTime();
//Here load the spinner
}
function showLoadingBoxIpadRelaod()
{
//Calculate difference between now and page loaded time minus threshold 500ms
var diffTime = ( (new Date().getTime()) - showLoadingBoxLoadedTimestamp - 500)/1000;
showLoadingBoxCount = showLoadingBoxCount + 1;
var isiPad = navigator.userAgent.match(/iPad/i) != null;
if(diffTime > showLoadingBoxCount && isiPad){
location.reload();
}
}
</code></pre>
| 4,384
|
<p>I create a web application (WAR) and deploy it on Tomcat. In the <em>webapp</em> there is a page with a form where an administrator can enter some configuration data. I don't want to store this data in an DBMS, but just in an XML file on the file system. Where to put it?</p>
<p>I would like to put the file somewhere in the directory tree where the application itself is deployed. Should my configuration file be in the <em>WEB-INF</em> directory? Or put it somewhere else? </p>
<p>And what is the Java code to use in a servlet to find the absolute path of the directory? Or can it be accessed with a relative path?</p>
|
<p>What we do is to put it in a separate directory on the server (you could use something like /config, /opt/config, /root/config, /home/username/config, or anything you want). When our servlets start up, they read the XML file, get a few things out of it (most importantly DB connection information), and that's it.</p>
<p>I asked about why we did this once.</p>
<p>It would be nice to store everything in the DB, but obviously you can't store DB connection information in the DB.</p>
<p>You could hardcode things in the code, but that's ugly for many reasons. If the info ever has to change you have to rebuild the code and redeploy. If someone gets a copy of your code or your WAR file they would then get that information.</p>
<p>Putting things in the WAR file seems nice, but if you want to change things much it could be a bad idea. The problem is that if you have to change the information, then next time you redeploy it will overwrite the file so anything you didn't remember to change in the version getting built into the WAR gets forgotten.</p>
<p>The file in a special place on the file system thing works quite well for us. It doesn't have any big downsides. You know where it is, it's stored seperatly, makes deploying to multiple machines easy if they all need different config values (since it's not part of the WAR).</p>
<p>The only other solution I can think of that would work well would be keeping everything in the DB except the DB login info. That would come from Java system properties that are retrieved through the JVM. This the Preferences API thing mentioned by Hans Doggen above. I don't think it was around when our application was first developed, if it was it wasn't used.</p>
<p>As for the path for accessing the configuration file, it's just a file on the filesystem. You don't need to worry about the web path. So when your servlet starts up it just opens the file at "/config/myapp/config.xml" (or whatever) and it will find the right thing. Just hardcodeing the path in for this one seems pretty harmless to me.</p>
|
<p>If it is your custom config WEB-INF is a good place for it. But some libraries may require configs to reside in WEB-INF/classes.</p>
| 12,182
|
<p>In ASP.NET, if I databind a gridview with a array of objects lets say , how can I retrieve and use foo(index) when the user selects the row?</p>
<p>i.e.</p>
<pre><code>dim fooArr() as foo;
gv1.datasource = fooArr;
gv1.databind();
</code></pre>
<p>On Row Select</p>
<pre><code>Private Sub gv1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv1.RowCommand
If e.CommandName = "Select" Then
'get and use foo(index)
End If
End Sub
</code></pre>
|
<p>If you can be sure the order of items in your data source has not changed, you can use the CommandArgument property of the CommandEventArgs.</p>
<p>A more robust method, however,is to use the DataKeys/SelectedDataKey properties of the GridView. The only caveat is that your command must be of type "Select" (so, by default RowCommand will not have access to the DataKey).</p>
<p>Assuming you have some uniqueness in the entities comprising your list, you can set one or more key property names in the GridView's DataKeys property. When the selected item in the GridView is set, you can retrieve your key value(s) and locate the item in your bound list. This method gets you out of the problem of having the ordinal position in the GridView not matching the ordinal position of your element in the data source.</p>
<p>Example:</p>
<pre><code><asp:GridView ID="GridView1" runat="server" AutoGenerateSelectButton="True"
DataKeyNames="Name" onrowcommand="GridView1_RowCommand1"
onselectedindexchanged="GridView1_SelectedIndexChanged">
</asp:GridView>
</code></pre>
<p>Then the code-behind (or inline) for the Page would be something like:</p>
<pre><code>protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
// Value is the Name property of the selected row's bound object.
string foo = GridView1.SelectedDataKey.Value as string;
}
</code></pre>
<p>Another choice would be to go spelunking in the Rows collection of the GridView, fetching values a column at a time by getting control values, but that's not recommended unless you have to.</p>
<p>Hope this helps.</p>
|
<p>in theory the index of the row, should be the index of foo (maybe +1 for header row, you'll need to test). so, you should be able to do something along these lines</p>
<pre><code>dim x as object = foo(e.row.selectedIndex)
</code></pre>
<p>The other alternative is to find a way to databind the index to the commandArgument attribute of the button. </p>
| 15,464
|
<p>I want to learn how to create <strong>truly</strong> robust applications in .net - ones that are fault tolerant and are capable of withstanding unexpected situations. Where can I find literature/guidance on this subject? So far, I am not having much luck.</p>
|
<p>I'm aware of at least a couple resources. First, there's a very useful article on MSDN titled <a href="http://msdn.microsoft.com/en-us/magazine/cc163716.aspx" rel="nofollow noreferrer">Keep Your Code Running with the Reliability Features of the .NET Framework</a>.</p>
<p>Chris Brumme also had a <a href="http://blogs.msdn.com/cbrumme/archive/2004/02/21/77595.aspx" rel="nofollow noreferrer">post on hosting</a> when the reliability features were being designed. This can provide some useful background information</p>
<p>Search terms that you may find useful include "High Availability" "CER" and "Constrained Execution Regions".</p>
<p>Good luck! Truly available code is pretty tricky stuff. :)</p>
|
<p>If you are looking from a software implementation perspective, then it may be worth looking into <a href="http://en.wikipedia.org/wiki/Design_by_contract" rel="nofollow noreferrer">Design by Contract (DbC)</a></p>
<p>According to <a href="http://archive.eiffel.com/doc/manuals/technology/contract/" rel="nofollow noreferrer">this source</a>, the benefits of Design by Contract include the following:</p>
<ul>
<li>A better understanding of the object-oriented method and, more generally, of software construction.</li>
<li>A systematic approach to building bug-free object-oriented systems.</li>
<li>An effective framework for debugging, testing and, more generally, quality assurance.</li>
<li>A method for documenting software components.</li>
<li>Better understanding and control of the inheritance mechanism.</li>
<li>A technique for dealing with abnormal cases, leading to a safe and effective language construct for exception handling. </li>
</ul>
<p>In addition, I would advocate looking into a <a href="http://en.wikipedia.org/wiki/Test-driven_development" rel="nofollow noreferrer">Test Driven Development (TDD)</a> approach, which should help drive out a more robust design.</p>
| 46,042
|
<p>This error message appears on a colleague's machine when he tries to launch a Windows application he's working on:</p>
<blockquote>
<p>An unhandled non-continuable exception was thrown during process load</p>
</blockquote>
<p>What does this mean, and how does one go about investigating what is causing it?</p>
<p>I have Googled it, but haven't found a clear answer. It seems to have something to do with problems loading DLLs.</p>
|
<p>Is there more information in the error message, maybe in the debug console? If there's a stack trace available, it might point you to the problem application, or better yet, the DLL that's causing the problem. The next step would be to see if there's an update available for that DLL.</p>
|
<p>I had the same issue and it turned out that a DLL compiled for x64 in a x86 project was the culprit. Replacing the DLL with the x86 version resolved the issue.</p>
| 28,942
|
<p>I've been developing Winforms applications in C# for a few years now and have been interested in moving future development toward WPF, mainly because of the positive things I've been hearing about it. But, I'm wondering what sort of hurdles others have had to overcome as they migrated to WPF. Was there a significant hit to your productivity or any particular issues which you found challenging?</p>
|
<p>I'm not sure I can give you just one hurdle, because it is a complete departure from WinForms. My suggestion is get Adam Nathan's WPF Unleashed, forget everything you know about building UI's with any previous technology (Winforms, MFC, Java) and begin again at square one. </p>
<p>If you try and do it any other way it will cause utter frustration.</p>
<p>ETA: the reason I say to just start from scratch is because sometimes it's easier to learn new concepts if you go in with a clean slate. In the past, I've discovered that I can be my own worst enemy when it comes to learning something new if I try to carry knowledge from technology to technology (e.g. thinking that doing asmx web services for years precludes me from reading the first couple chapters of a WCF book).</p>
|
<p>Well, for me it was the fact that controls in WPF behave rather different from those in WPF (for example, when it comes to positioning in the form). You have to understand the difference as soon as possible to use it successfully and productively.</p>
| 13,486
|
<p>How can I get rid of: </p>
<pre><code><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="..."/>
</code></pre>
<p>Completely !</p>
|
<p>You need to add the EnableViewState="false" to the @Page directive in the Default.aspx file.</p>
<pre><code><%@ Page Language="C#" AutoEventWireup="true"
Codebehind="Default.aspx.cs" Inherits="Sample._Default"
EnableViewState="false" %>
</code></pre>
<p>Then, add the following code to the Default.aspx.cs file. This removes the hidden field from the generated HTML.</p>
<pre><code> #region Disable ViewState
protected override void SavePageStateToPersistenceMedium(object state)
{
}
protected override object LoadPageStateFromPersistenceMedium()
{
return null;
}
#endregion
</code></pre>
|
<pre><code>#region Disable ViewState
protected override void SavePageStateToPersistenceMedium(object state)
{
}
protected override object LoadPageStateFromPersistenceMedium()
{
return null;
}
#endregion
</code></pre>
<p>This is awesome.However, just to let everyone know it's still rendering an empty viewstate hidden field</p>
<pre><code><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="" />
</code></pre>
| 37,077
|
<p>i want the result of an equation rounded to the nearest integer.
e.g. </p>
<pre><code>137 * (3/4) = 103
</code></pre>
<p>Consider the following incorrect code. </p>
<pre><code>int width1 = 4;
int height1 = 3;
int width2 = 137;
int height2 = width2 * (height1 / width1);
</code></pre>
<p>What is the proper way to perform "integer" math in C#?</p>
<p>Do i really have to do:</p>
<pre><code>int height2 = (int)Math.Round(
(float)width2 * ((float)height1 / (float)width1)
);
</code></pre>
|
<p>As said above, you should do the multiplication before the division.
Anyway you could write your expression with casting only the divisor:</p>
<pre><code>int height2 = (int)Math.Round(width2 * (height1 / (float)width1));
</code></pre>
|
<p>The elaborate on Jeffery's message, since you generally a better chance of truncated needed decimals than you have of overflowing a 32-bit integer (and because multiplication & division is commutative), you should generally do multiplication before division.</p>
| 38,300
|
<p>I am using Eclipse 3.3 ("Europa"). Periodically, Eclipse takes an inordinately long time (perhaps forever) to start up. The only thing I can see in the Eclipse log is:</p>
<pre>
!ENTRY org.eclipse.core.resources 2 10035 2008-10-16 09:47:34.801
!MESSAGE The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes.
</pre>
<p>Googling reveals <a href="http://dev.zhourenjian.com/blog/2007/11/07/eclipse-freezing-on-start.html" rel="noreferrer">someone's suggestion</a> that I remove the folder:</p>
<pre><code>workspace\.metadata\.plugins\org.eclipse.core.resources\.root\.indexes
</code></pre>
<p>This does not appear to have helped.</p>
<p>Short of starting with a new workspace (something which I am not keen to do, as it takes me hours to set up all my projects again properly), is there a way to make Eclipse start up properly?</p>
|
<p>This may not be an exact solution for your issue, but in my case, I tracked the files that Eclipse was polling against with <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="noreferrer">SysInternals Procmon</a>, and found that Eclipse was constantly polling a fairly large snapshot file for one of my projects. Removed that, and everything started up fine (albeit with the workspace in the state it was at the previous launch).</p>
<p>The file removed was:</p>
<pre><code><workspace>\.metadata\.plugins\org.eclipse.core.resources\.projects\<project>\.markers.snap
</code></pre>
|
<p>I had no snap files. Going through the help menu installation list, at least 90% of my plugins had the uninstall button deactivated so I could not handle it through there. Under startup/shutdown most of plugins were not listed. Instead, I had to manually remove items from my plugins folder. Wow, the startup time is much faster for me now. So if everything else does not work and you have plugins that are disposable, this could be the ultimate solution to use.</p>
| 25,478
|
<p>I have a small web application which uses themes. The themes work on host, so on preinit, if the host = a, load x theme, if the host = b, load y theme. </p>
<p>In my code this looks like: </p>
<p>If request.url.host.contains("a") Then
Page.Theme = x
Else
request.url.host.contains("b") Then
Page.Theme = y </p>
<p>I have a url which is a.abc.com and another which is b.abc.com (well it is this structure, but the letters are meaningful/company names). Problem is (and I have done host == ""), when I debug my site on localhost (another clause in the above if block where host = localhost), the style renders perfectly. Alignment of elements are perfect as I expect with the numerical values I have provided for width, margins, etc in the css. But when I use the publish tool of VS2008 (with updatable ticked), and upload to a.abc.com, which has the same stylesheet as localhost (a copy in its own folder), there are all sorts of alignment issues as if I have done no work. Why do my styles render incorrectly @ runtime? If it helps, I am using VS2008 Pro Edition, IIS6 and Windows Server 2003.</p>
<p>What is frustrating is that the page source indicates the theme is loading ok, as it is referenced in HTML head. So when I publish, the theme for a.abc.com is loaded and referenced. Other than all this information, there is no obvious sign of what the problem is. I haven't tried to conventionally reference a single CSS file in the ASPX markup, but if I did and this worked, then it doesn't explain the problem either, anyway.</p>
<p>Thanks</p>
|
<p>Are you setting the Theme early enough in your code? A Theme must be applied to a page very early in the request lifecycle, in the PreInit event, if you do it in code-behind.</p>
|
<p>Yep, it is on page preinit.</p>
<p>I think it is to do with forms authentication. If I view (not debug) the login page, it picks up the localhost theme and everything is displayed correctly. The login control is in the middle of the page, as it should be, etc.</p>
<p>But if I debug the page and, as you'd expect, the login page is the start/default page, the login control appears to the left as it does when I deploy and the source indicates the css for the appropriate host has been picked up - only when I debug, there is no style applied until I login.</p>
| 40,771
|
<p>It is not uncommon for me (or likely anyone else) to have a list of objects I need to iterate through and then interact with a list of properties. I use a nested loop, like this:</p>
<pre><code>IList<T> listOfObjects;
IList<TProperty> listOfProperties;
foreach (T dataObject in listOfObjects)
{
foreach (TProperty property in listOfProperties)
{
//do something clever and extremely useful here
}
}
</code></pre>
<p>Is this the time and performance tested pattern for this problem? Or is there something more performant, more elegant, or just plain fun (while still being readable and maintainable of course)?</p>
<p>The code above doesn't make me smile. Can someone please help bring some joy to my loop?</p>
<p>Thank you!</p>
<p>Update: I use the term "nerd" in a most positive sense. As part of the wikipedia definition puts it "that refers to a person who passionately pursues intellectual activities". By "code nerd" I mean someone who is concerned about continually improving oneself as a programmer, finding new, novel, and elegant ways of coding that are fast, maintainable, and beautiful! They rejoice to move out of VB6 and want smart people to critique their code and help them smartify themselves. (Note: they also like to make new words that end in -ify).</p>
<p>Final note:</p>
<p>Thank you to Dave R, Earwicker, and TheSoftwareJedi for sending me down the Linq path. It is just the sort of happy code I was looking for!</p>
|
<p>Looks like you are trying to cartesian join two lists, and apply a where clause. Here's a simple example showing the Linq syntax for doing this, which I think is what you are looking for. list1 and list2 can be any IEnumerable, your where clause can contain more detailed logic, and in your select clause you can yank out what you need.</p>
<pre><code> var list1 = Enumerable.Range(1, 100);
var list2 = Enumerable.Range(1, 100);
foreach (var item in from a in list1
from b in list2
where a % b == 0
select new { a, b })
{
Console.WriteLine(item);
};
</code></pre>
<p>Performance will be identical to what you posted though - no desire to mislead on that respect. I do prefer this Linq syntax.</p>
|
<p>In such a scenario, we often start by filtering the pieces we're interested in.
your block dosomethingclever() usually starts in</p>
<pre><code>foreach (T dataObject in listOfObjects)
{
foreach (TProperty property in listOfProperties)
{
if (property.something == "blah")
{ // OK, we found the piece we're interested in...
// do something clever...
}
}
}
</code></pre>
<p>This is where LINQ is your friend, allowing your to replace your loops by a select statement. Of course you may still need to iterate on the results set.</p>
<p><a href="http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx" rel="nofollow noreferrer">Tons of samples here</a>.</p>
| 47,697
|
<p>Is there a utility that will generate html or css for blocks of code (.net c#) when you post it on a website? </p>
<p>I have seen several websites with very nicely formatted code and I dont believe they do this manually.</p>
|
<p>Google prettify -</p>
<p><a href="http://code.google.com/p/google-code-prettify/" rel="noreferrer">http://code.google.com/p/google-code-prettify/</a></p>
|
<p>An even better solution, if you don't want to bother installing anything, is to just use the little web app I wrote called BlogTrog CodeWindow:</p>
<p><a href="http://www.blogtrog.com" rel="nofollow noreferrer">http://www.blogtrog.com</a></p>
<p>It's easy to use. Just paste your code and embed the results.</p>
| 20,904
|
<p>I'm implementing a comment control that uses an ASP.Repeater to display each comment. The comment itself is currently displayed using a table to divide up some images to display the comment in a bubble.</p>
<p>I know that tables are supposed to be the epitome of evil for design layout, and really expensive to display for the browser, but I'm not exactly sure how to put my rounded corners in the correct location and make sure everything lines up.</p>
<p>Does anyone have any suggestions, examples, hacks for the HTML/CSS required, or should I just stick with tables and hope for the best?</p>
|
<p>The best resource I've seen for creating rounded corners using DIV elements was an article on "A List Apart" - see <a href="http://alistapart.com/articles/customcorners/" rel="nofollow noreferrer">http://alistapart.com/articles/customcorners/</a>. If you're looking to use DIV elements to layout your entire site, there are several other relevant articles on that site. See:</p>
<p><a href="http://alistapart.com/articles/slidingdoors/" rel="nofollow noreferrer">http://alistapart.com/articles/slidingdoors/</a><br>
<a href="http://www.alistapart.com/articles/slidingdoors2/" rel="nofollow noreferrer">http://www.alistapart.com/articles/slidingdoors2/</a><br>
<a href="http://www.alistapart.com/articles/negativemargins/" rel="nofollow noreferrer">http://www.alistapart.com/articles/negativemargins/</a></p>
|
<p>In short you would want something like this:</p>
<pre><code><style>
.start { background-image: url("topofbubble.png"); height: <heightofimage>; }
.end { background-image: url("bottomofbubble.png"); height: <heightofimage>; }
.body {background-image: url("sliceofbubblemiddle.png"); }
</style>
...
<div class="comment">
<span class="start"></span>
<span class="body">I would like to say that div layouts are far better than table layouts.</span>
<span class="end"></style>
</div>
</code></pre>
<p>That should get you started. I did not try the code specifically and can make a complete example if necessary.</p>
| 11,834
|
<p>ASP.NET 1.1 - I have a DataGrid on an ASPX page that is databound and displays a value within a textbox. The user is able to change this value, then click on a button where the code behind basically iterates through each DataGridItem in the grid, does a FindControl for the ID of the textbox then assigns the .Text value to a variable which is then used to update the database. The DataGrid is rebound with the new values.</p>
<p>The issue I'm having is that when assigning the .Text value to the variable, the value being retrieved is the original databound value and not the newly entered user value. Any ideas as to what may be causing this behaviour?</p>
<p>Code sample:</p>
<pre><code>foreach(DataGridItem dgi in exGrid.Items)
{
TextBox Text1 = (TextBox)dgi.FindControl("TextID");
string exValue = Text1.Text; //This is retrieving the original bound value not the newly entered value
// do stuff with the new value
}
</code></pre>
|
<p>Are you able to manage permissions on this database? Would adding a separate user who only has read access to a database be sufficient for this type of scenario? This could be a read-only user on the main database, but is only effectively used on the snapshot db.</p>
<p>i.e. Add a new user, readerMan5000 who is only given select access, to the database in question. Then require users to authenticate through that new credential.</p>
<p>Note to future commenters, you may want to read:
<a href="http://www.simple-talk.com/sql/database-administration/sql-server-2005-snapshots/" rel="nofollow noreferrer">http://www.simple-talk.com/sql/database-administration/sql-server-2005-snapshots/</a>
or
<a href="http://msdn.microsoft.com/en-us/library/ms187054(SQL.90).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms187054(SQL.90).aspx</a>
before you open your big mouth like me. :)</p>
|
<p>You can't change permissions after you take the snapshot, but here's one workaround: instead of having them access the tables directly, require them to use views instead. If the views are used only for reporting, then you can set tight security on them in the original database, and then have the users hit those views in the snapshot. You'll need to restrict access on the underlying tables though if you want it to be effective.</p>
| 10,426
|
<p>I am using sfOpenID plugin for Symfony, which doesn't support OpenID 2.0. That means, for example, that people using Yahoo! OpenID can't login to my site.</p>
<p>There is an OpenID 2.0 plugin that works with sfGuard, but I am not using nor planning to use sfGuard. Plus, it requires to install Zend framework, too, which is an overkill in my scenario.</p>
<p>So I've got two questions, really:</p>
<ul>
<li>is there another OpenID plugin for Symfony supporting OpenID 2.0?</li>
<li>what would be the hack required to make sfOpenID support OpenID 2.0?</li>
</ul>
<p>I suppose I could study OpenID specs and hack it myself, but then, I am a lazy programmer :)</p>
|
<p>I think you've covered all your options with sfOpenID and taOpenIDsfGuardPlugin for Symfony's plugins.</p>
<p>Without studying OpenID's specs in detail though, you could try one of those PHP libraries (<a href="http://wiki.openid.net/Libraries" rel="noreferrer">http://wiki.openid.net/Libraries</a>) by dropping it in your lib and connecting to a <code>sfUser</code>, or whatever you're using for authentication. There is also the OpenID Enabled library (<a href="http://openidenabled.com/php-openid/" rel="noreferrer">http://openidenabled.com/php-openid/</a>) which still uses PHP4 although compatible with PHP5 if you <a href="http://www.php.net/manual/en/errorfunc.configuration.php" rel="noreferrer">tweak the error reporting level</a> to exclude some warnings.</p>
<p>There are a few tutorials out there that explains how to enable OpenID on your site with PHP: <a href="http://www.saeven.net/openid.htm" rel="noreferrer">http://www.saeven.net/openid.htm</a> or <a href="http://www.plaxo.com/api/openid_recipe" rel="noreferrer">http://www.plaxo.com/api/openid_recipe</a>. </p>
<p>And better yet, use this knowledge to <a href="http://www.symfony-project.org/book/1_1/17-Extending-Symfony#How%20to%20Write%20a%20Plug-In" rel="noreferrer">make a sfPlugin out of it</a> afterwards.</p>
|
<p>There is an easier way. JanRain offers OpenID (and facebook) as a service <a href="http://rpxnow.com" rel="nofollow noreferrer">http://rpxnow.com</a> . Vastly easier/quicker than going native with the libraries.</p>
| 34,840
|
<p>I'm developing a Linux application that has its own file format. I want my app to open when you double-click on those files.</p>
<p>How can I register a file extension and associate it with my application on Linux? I'm looking for a way that is standard (works with GNOME and KDE based systems) and can be done automatic when my program is installed or run for the first time.</p>
|
<p>Use <code>xdg-utils</code> from <a href="http://portland.freedesktop.org/wiki/" rel="noreferrer">freedesktop.org Portland</a>.</p>
<p>Register the icon for the MIME type:</p>
<pre class="lang-sh prettyprint-override"><code>xdg-icon-resource install --context mimetypes --size 48 myicon-file-type.png x-application-mytype
</code></pre>
<p>Create a configuration file (<a href="http://standards.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html" rel="noreferrer">freedesktop Shared MIME documentation</a>):</p>
<pre><code><?xml version="1.0"?>
<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'>
<mime-type type="application/x-mytype">
<comment>A witty comment</comment>
<comment xml:lang="it">Uno Commento</comment>
<glob pattern="*.myapp"/>
</mime-type>
</mime-info>
</code></pre>
<p>Install the configuration file:</p>
<pre class="lang-sh prettyprint-override"><code>xdg-mime install mytype-mime.xml
</code></pre>
<p>This gets your files recognized and associated with an icon. <a href="http://portland.freedesktop.org/xdg-utils-1.0/xdg-mime.html" rel="noreferrer"><code>xdg-mime default</code></a> can be used for associating an application with the MIME type after you get a <a href="http://portland.freedesktop.org/xdg-utils-1.0/xdg-desktop-menu.html" rel="noreferrer"><code>.desktop</code></a> file installed.</p>
|
<p>This is all existing answers combined, completed and corrected into a single bash script.</p>
<pre class="lang-bash prettyprint-override"><code>#!/bin/bash
set -e # stop on error
APP=my-app
EXT=my-app
COMMENT=Comment
EXEC=/usr/bin/my-app
LOGO=./logo.png
xdg-icon-resource install --context mimetypes --size 48 $LOGO application-x-$APP
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">
<mime-type type=\"application/x-$APP\">
<comment>$COMMENT</comment>
<icon name=\"application-x-$APP\"/>
<glob pattern=\"*.$EXT\"/>
</mime-type>
</mime-info>" > $APP-mime.xml
xdg-mime install $APP-mime.xml
rm $APP-mime.xml
update-mime-database $HOME/.local/share/mime
echo "[Desktop Entry]
Name=$APP
Exec=$EXEC %U
MimeType=application/x-$APP
Icon=application-x-$APP
Terminal=false
Type=Application
Categories=
Comment=$COMMENT
"> $APP.desktop
desktop-file-install --dir=$HOME/.local/share/applications $APP.desktop
rm $APP.desktop
update-desktop-database $HOME/.local/share/applications
xdg-mime default $APP.desktop application/x-$APP
</code></pre>
| 5,078
|
<p>I understand that a hxs file is a compiled help file, a replacement for .chm files, but I can't seem to open them.</p>
<p>I've read that you read them with the help explorer, dexplore.exe found here:
C:\Program Files\Common Files\microsoft shared\Help 9\dexplore.exe</p>
<p>When I try opening the file with dexplore, it asks me to save the file to disk, or open with another program.</p>
<p>Any ideas?</p>
|
<p>Not sure if you want to look through them programmatically or with some tool, but Help Explorer can open hxs files and extract contents. CHM files (the precursor to hxs) were a custom binary format with indexing and other data at the beginning of the file, and a zip archive in the rest. </p>
<p>You can also decompile hxs using HxComp.exe</p>
<p>EDIT: That link appears to be broken/down or something, but your answer did lead me to find <a href="http://download.cnet.com/Help-Explorer-Viewer/3000-6675_4-10666661.html" rel="nofollow noreferrer">Help Explorer Viewer</a>, which may or may not be the same program, but it does the job.</p>
<p>Edit: I've deleted all broken links to spare confusion.</p>
|
<p>After a bit more research, it looks like these files must be installed into the IDE when you install 3rd party tools. There is a diagnostic tool called Namespace#. You can see details about it here:</p>
<p><a href="http://code.msdn.microsoft.com/NamespaceSharp" rel="nofollow noreferrer">http://code.msdn.microsoft.com/NamespaceSharp</a></p>
| 21,757
|
<p>What is the simplest way (least error-prone, least lines of code, however you want to interpret it) to open a file in C and read its contents into a string (char*, char[], whatever)?</p>
|
<p>I tend to just load the entire buffer as a raw memory chunk into memory and do the parsing on my own. That way I have best control over what the standard lib does on multiple platforms.</p>
<p>This is a stub I use for this. you may also want to check the error-codes for fseek, ftell and fread. (omitted for clarity).</p>
<pre><code>char * buffer = 0;
long length;
FILE * f = fopen (filename, "rb");
if (f)
{
fseek (f, 0, SEEK_END);
length = ftell (f);
fseek (f, 0, SEEK_SET);
buffer = malloc (length);
if (buffer)
{
fread (buffer, 1, length, f);
}
fclose (f);
}
if (buffer)
{
// start to process your data / extract strings here...
}
</code></pre>
|
<p>easy and neat(assuming contents in the file are less than 10000):</p>
<pre><code>void read_whole_file(char fileName[1000], char buffer[10000])
{
FILE * file = fopen(fileName, "r");
if(file == NULL)
{
puts("File not found");
exit(1);
}
char c;
int idx=0;
while (fscanf(file , "%c" ,&c) == 1)
{
buffer[idx] = c;
idx++;
}
buffer[idx] = 0;
}
</code></pre>
| 21,036
|
<p>What is the largest heap you have personally used in a managed environment such as Java or .NET? What were some of the performance issues you ran into, and did you end up getting a diminishing returns the larger the heap was? </p>
|
<p>I work on a 64-bit .Net system that typically uses 9-12 GB, and sometimes as much as 20GB. I have not seen any performance problems even while garbage collecting, and I have been looking hard as I was not expecting it to work so well.</p>
<p>An earlier version hung on to some objects for too long resulting in occasional GCs that freed up 3GB+. Even then, there was no noticeable impact on performance. The system is running on a 16-core server with 32GB RAM, which probably helps...</p>
|
<p>I am unsure what you mean by heap, but if you mean memory used, I have used quite a bit, 2GB+. I have a web app that does image processing and it requires loading 2 large scan files into memory to do analysis.</p>
<p>There were performance issues. Windows would swap out lots of ram, and then that would create a lot of page faults. There was never any need for anymore than 2 images at a time as all requests were gainst those images (I only allowed 1 session per image set at a time)</p>
<p>For instance, to setup the files for initial viewing would take about 5 seconds. Doing simple analysis and zooming would be fairly fast once in memory, in the order of .1 to .5 seconds.</p>
<p>I still had to optimize, so I ended up preparsung the files and chopping into smaller peices and worked only with the peices that were required by the user at the time.</p>
| 22,442
|
<p>I would like to know if it is possible, to select certain columns from one table, and another column from a second table, which would relate to a non imported column in the first table. I have to obtain this data from access, and do not know if this is possible with Access, or SQL in general.</p>
|
<p>Assuming the following table structure:</p>
<pre><code>CREATE TABLE tbl_1 (
pk_1 int,
field_1 varchar(25),
field_2 varchar(25)
);
CREATE TABLE tbl_2 (
pk_2 int,
fk_1 int,
field_3 varchar(25),
field_4 varchar(25)
);
</code></pre>
<p>You could use the following:</p>
<pre><code>SELECT t1.field_1, t2.field_3
FROM tbl_1 t1
INNER JOIN tbl_2 t2 ON t1.pk_1 = t2.fk_1
WHERE t2.field_3 = "Some String"
</code></pre>
<p>In regard to Bill's post, there are two ways to create JOIN's within SQL queries:</p>
<ul>
<li><p>Implicit - The join is created using
the WHERE clause of the query with multiple tables being specified in the FROM clause</p></li>
<li><p>Explicit - The join is created using
the appropriate type of JOIN clause
(INNER, LEFT, RIGHT, FULL)</p></li>
</ul>
<p>It is always recommended that you use the explicit JOIN syntax as implicit joins can present problems once the query becomes more complex. </p>
<p>For example, if you later add an explicit join to a query that already uses an implicit join with multiple tables referenced in the FROM clause, the first table referenced in the FROM clause will not be visible to the explicitly joined table.</p>
|
<p>I'm not 100% sure I understand your question.</p>
<p>Is the following true:</p>
<p>Your first table is imported from somewhere else.
You are only importing some columns.
You want to build a query which references a column which you haven't imported.</p>
<p>If this is true, it's just not possible. As far as the Access query engine in concerned the non-imported columns don't exist.</p>
<p>Why not just import them as well?</p>
| 35,522
|
<p>I'm looking at stdint.h and given that it has uint16_t and uint_fast16_t, what is the use for uint_least16_t what might you want that couldn't be done equally well with one of the other two?</p>
|
<p>Say you're working on a compiler with:</p>
<ul>
<li><code>unsigned char</code> is 8 bits</li>
<li><code>unsigned short</code> is 32 bits</li>
<li><code>unsigned int</code> is 64 bits</li>
</ul>
<p>And unsigned int is the 'fastest'. On that platform:</p>
<ul>
<li><code>uint16_t</code> would <em>not</em> be available</li>
<li><code>uint_least16_t</code> would be a 32 bit value</li>
<li><code>uint_fast16_t</code> would be a 64 bit value</li>
</ul>
<p>A bit arcane, but that's what it's for.</p>
<p>How useful they are is another story - I see the exact size variants all the time. That's what people want. The 'least' and 'fast' versions I've seen used pretty close to never (it's possible that it was only in example code - I'm really not sure).</p>
|
<p>It's part of the c standard. It doesn't need a good use case. :P</p>
<p>See <a href="http://www.opengroup.org/onlinepubs/009695399/basedefs/stdint.h.html" rel="nofollow noreferrer">this</a> page and look for the section titled "Minimum-width integer types".</p>
| 31,017
|
<p>There are several very high quality web frameworks out there today, and everyone seems to be able to find one that becomes their favorite. Then, they have nothing but good things to say about the framework in question, and they relate their personal experiences on how the framework has made web development more enjoyable for them.</p>
<p>That's excellent, and the web framework-related questions I've seen on stackoverflow have been answered in helpful ways while avoiding flame wars and so on - that says a lot about the people who participate here and it's a pleasure to read quality content.</p>
<p>So here's my question: sure, there are 99 reasons to love your favorite web framework, but what is that 1 extra feature that you wish it had? Or that 1 area that you think could use some improvement?</p>
<p>Hopefully we've moved past the "my framework is better than your framework" pointless discussions, and we've also realized that all frameworks have their sweet spots. I
certainly respect people who can admit that their favorite framework is not perfect, and I'd like to read about the types of features that people find are missing or could be improved. Who knows, the developers of those frameworks might hear you and implement/improve those features!</p>
<p>Thanks in advance for your responses.</p>
|
<p>With ASP.NET the only thing I dislike is that MS often encourages quick and dirty style development with too many drag and drop controls and datasets over better thought through not so quick, but much less dirty, solutions.</p>
|
<p>I'll post an answer to my own question by admitting that my favorite framework, <a href="http://www.stripesframework.org" rel="nofollow noreferrer">Stripes</a>, <em>could</em> use some improvement in the flexibility of its localization mechanism. While the mechanism is quite useable, it should be easier for developers to customize which resource bundles are dynamically used and which are the lookup keys for field names and error messages.</p>
<p>But hey, we're working on it!</p>
| 26,729
|
<p>I am looking to determine from a large code base, what files are actually being used over a period of time. I need to know about CFM pages and CFCs as well as any included CFM files etc. </p>
<p>I know I can get <em>some</em> of this info using logging in application.cfm, or by using IIS, but I will still be missing any include files and any CFCs used. </p>
<p>Is there any way to get CF to log every file it executes? Ideally I would like to keep any new coding to a minimum or just in one place. </p>
<p>Thanks,
Ciarán </p>
|
<p>Hmmm, I think you'll need to turn on debugging and create a custom debug template.</p>
<p>The debug templates are in: [coldfusiondir]/wwwroot/WEB-INF/debug</p>
<p>Have a look at the code which <code>classic.cfm</code> uses to display Templates to screen, and then create some similar code which logs each template run to a suitable data store.</p>
<p>Note: there is a performance issue (in CFMX6/7) with Report Execution Times and CFCs, so make sure you have that setting disabled, and any related code removed.</p>
<p>Infact, if this is to be running in a Live environment (not ideal), then make sure you strip down your custom template to the minimum necessary code to perform just this logging.</p>
|
<p>The approach using the debug templates will work, but will only work if you have debugging enabled. If the code base is large an unwieldy and the only place you have to collect this info is live then make sure those templates aren't outputting anything.</p>
<p>Additionally your CFC calls will slow down quite a bit. Be very careful to see how this destroys your servers. </p>
<p>Personally I would just have it updating a server level structure with nothing more than the filename. </p>
<pre><code><cfparam name="server.st_FileLog" default="#structNew()#">
<cfparam name="server.st_FileLog[thisFile]" default="1">
</code></pre>
<p>Those two lines in Application.cfc or Application.cfm might just do it.</p>
<p>Then just have a separate piece of code that dumps out the code.</p>
<pre><code><cfoutput><code>#structKeyList(server.st_FileLog,chr(13))#</code></cfoutput>
</code></pre>
| 48,110
|
<p>I have read that to send email in Java I need to obtain my ISP's SMTP address, but if I am intending to host my web app online, will this be my hosts ISP SMTP address?</p>
<p>EDIT: So I need to find out my clients ISP's SMTP address and send via this?</p>
|
<p>No, unless your webhost is the same as your ISP or your webhost also offers SMTP services.</p>
<p>In response to your edit, yes you need your ISP's SMTP address by the sound of things.</p>
|
<p>It will be the SMTP address you want to forward email through.</p>
<p>If you want to send email through your ISP account then it will be that SMTP.</p>
| 38,542
|
<p>I want to use the standard ADO connection string dialog box in MS Access.
How can I do that?</p>
|
<p>If not already selected, check the following references in the References dialog:</p>
<p>Microsoft OLE DB Service Component 1.0 Type Library</p>
<p>Microsoft ActiveX Data Objects 2.7 Library</p>
<p>The following code will open the dialog box and set a connection object to the parameters provided in the Data Link Properties dialog box:</p>
<pre><code>Dim dl As MSDASC.DataLinks
Dim cn As ADODB.Connection
Set dl = New MSDASC.DataLinks
Set cn = New ADODB.Connection
Set cn = dl.PromptNew
cn.Open
</code></pre>
<p>You can then open an ADODB recordset with the connection or retrieve properties about the connection and proceed as needed.</p>
|
<p>See <a href="http://support.microsoft.com/kb/281998" rel="nofollow noreferrer">How to bind Microsoft Access forms to ADO recordsets</a></p>
| 45,866
|
<p>I am preparing a project proposal for a client who wants to publish video in his website. I need to define which video formats will be allowed, which video sizes, as well as the necessary tools for conversion and preparation. </p>
<p>I have no experience with embedding video in websites so which markup do I need to play video online?</p>
|
<p>You could embed them using a flash player, like Youtube for example.</p>
<p>A quick way to do this is using some already made player, like the excellent <a href="http://www.jeroenwijering.com/?item=JW_FLV_Player" rel="nofollow noreferrer">JW FLV Player</a>, free for non-commercial projects and very cheap for commercial ones.</p>
<p>It supports FLV and MP4 video files, you can convert your videos in this formats in a lot of ways, for example using <a href="http://www.ffmpegx.com/" rel="nofollow noreferrer">ffmpegx</a>.</p>
|
<p>For what it's worth here is a example of embedding video using the media player plugin.</p>
<p><code><embed src="http://aaa/bbb/ccc/myVideo.wmv" type="application/x-mplayer2" pluginspage="http://www.microsoft.com/Windows/MediaPlayer/" name="MediaPlayer" autostart="1" showcontrols="1" showstatusbar="0" autorewind="1" showdisplay="0" height="256" width="320"></code></p>
| 37,859
|
<p>Currently running Server 2003 but am looking at reinstalling in the near future due to a change of direction with the domains. Should I take this opportunity to install Windows Server 2008 instead?
I would love to play with new technology and the server is only for a small home business so downtime/performance issues aren't really a concern.</p>
|
<p>I am no expert on Windows server revisions, but the only new feature of Server 2008 I can think of is Hyper-V. But I would try Server 2008 just for Hyper-V, as this VM hypervisor is supposedly much faster than VMware and Virtual PC, and is compatible with Virtual PC virtual disks.</p>
|
<p>There is no Exchange Server 2008. Exchange has always been tightly integrated with IIS which tends to bind it to a specific version of Windows. However, Exchange Server 2007 SP1 can be installed on Windows Server 2008.</p>
<p>Exchange Server 2003, however, cannot run on Windows Server 2008 and I do not believe there are any plans to do so in a future service pack.</p>
<p>Note that Exchange Server 2007 <em>requires</em> x64 architecture, running the 64-bit OS, on a production system. The days of booting <code>/3GB</code> are past - it simply does not provide enough virtual address space for current large databases. Exchange's long-running virtual memory fragmentation problem has not been fixed, it has just been given more virtual address space to work in.</p>
| 19,467
|
<p>I am migrating an application from .NET 1.1 to .NET 2.0. Should I remove all uses of CollectionBase? If so, what is the best strategy for migration?</p>
|
<p>Yes, the best classes to look at are in System.Collections.Generic.<br>
I usually use List.</p>
<p>There are two approaches you can use either:</p>
<p><strong>A</strong></p>
<pre><code>public class MyClass
{
public List<MyItem> Items;
}
</code></pre>
<p><strong>B</strong></p>
<pre><code>public class MyItemCollection : List<MyItem>
{
}
public class MyClass
{
public MyItemCollection Items;
}
</code></pre>
<p>The two approaches only differ very slightly and you only need to use method (B) if you plan on extending the functionality of List.</p>
<p>Here's a link with more info:<br>
<a href="http://msdn.microsoft.com/en-us/library/6sh2ey19(VS.80).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/6sh2ey19(VS.80).aspx</a></p>
<p>With regards to the classes that you've already implemented, you can remove all of the functions which are specified in the IList interface. e.g.</p>
<pre><code>public int Add(InstrumentTradeDataRow instTrade) { return List.Add(instTrade); }
</code></pre>
<p>This can be removed because List already implements a type safe Add function for you.</p>
<p>See this link for more information:<br>
<a href="http://msdn.microsoft.com/en-us/library/3wcytfd1(VS.80).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/3wcytfd1(VS.80).aspx</a></p>
|
<p>I prefer Mark Ingrams A) approach, possibly with a base class you write yourself.</p>
<p>There is another issue with migrating to generics; converting has a tendency to have a certain viral effect. You may find it impossible to stop before you're all the way through. If you THOUGHT you were going to spend a couple of hours doing SOME generics, you'll often find yourself spending several days doing ALL the generics.</p>
<p>You can/should avoid this by giving your new classes operator overloads to/from list</p>
<pre><code>public static implicit operator MyClass(List m)
{
// code to convert from m to MyClass
}
public static explicit operator List(MyClass m)
{
// code to convert from MyClass list
}
</code></pre>
<p>These are really just stopgaps. You can use "find usages" on these at any later stage to determine which places have not been fully converted. When all usages are removed, you can delete the casts.</p>
<p>I generally perfer to make the cast from MyClass to List explicit (this is the way you dont want to go) and the other implicit.</p>
<p>The best approach would then normally be to start at the TOP of your layers, close to the presentation layer and work downwards. (This is opposite of what you might think. If you make the cast from MyClass to List implicit it doesnt matter which end you start)</p>
| 40,104
|
<p>I have a website where we use Javascript to submit the login form. On Firefox it prompts the user to remember their password, when they login, but on IE7 it doesn't.</p>
<p>After doing some research it looks like the user is only prompted in IE7 when the form is submitted via a Submit control. I've created some sample html to prove this is the case.</p>
<pre><code><html>
<head>
<title>test autocomplete</title>
<script type="text/javascript">
function submitForm()
{
return document.forms[0].submit();
}
</script>
</head>
<body>
<form method="GET" action="test_autocomplete.html">
<input type="text" id="username" name="username">
<br>
<input type="password" id="password" name="password"/>
<br>
<a href="javascript:submitForm();">Submit</a>
<br>
<input type="submit"/>
</form>
</body>
</html>
</code></pre>
<p>The href link doesn't get the prompt but the submit button will in IE7. Both work in Firefox.</p>
<p>I can't get the style of my site to look the same with a submit button, Does anyone know how to get the remember password prompt to show up when submitting via Javascript?</p>
|
<p>Why not try hooking the form submission this way?</p>
<pre><code><html>
<head>
<title>test autocomplete</title>
<script type="text/javascript">
function submitForm()
{
return true;
}
</script>
</head>
<body>
<form method="GET" action="test_autocomplete.html" onsubmit="return submitForm();">
<input type="text" id="username" name="username">
<br>
<input type="password" id="password" name="password"/>
<br>
<a href="#" onclick="document.getElementById('FORMBUTTON').click();">Submit</a>
<br>
<input id="FORMBUTTON" type="submit"/>
</form>
</body>
</html>
</code></pre>
<p>That way your function will be called whether the link is clicked or the submit button is pushed (or the enter key is pressed) and you can cancel the submission by returning false. This may affect the way IE7 interprets the form's submission. </p>
<p>Edit: I would recommend always hooking form submission this way rather than calling submit() on the form object. If you call submit() then it will not trigger the form object's onsubmit.</p>
|
<p>Did you try putting in url in the href and attaching a click event handler to submit the form and returning false from the click handler so that the url does not get navigates to.</p>
<p>Alternatively hidden submit button triggered via javascript?</p>
| 19,161
|
<p>We have an issue using the <code>PEAR</code> libraries on <code>Windows</code> from <code>PHP</code>.</p>
<p>Pear contains many classes, we are making use of a fair few, one of which is the Mail class found in <code>Mail.php</code>. We use PEAR on the path, rather than providing the full explicit path to individual PEAR files:</p>
<pre><code>require_once('Mail.php');
</code></pre>
<p>Rather than:</p>
<pre><code>require_once('/path/to/pear/Mail.php');
</code></pre>
<p>This causes issues in the administration module of the site, where there is a <code>mail.php</code> file (used to send mails to users). If we are in an administrative screen that sends an email (such as the user administration screen that can generate and email new random passwords to users when they are approved from the moderation queue) and we attempt to include <code>Mail.php</code> we "accidentally" include mail.php.</p>
<p>Without changing to prepend the full path to the PEAR install explicitly requiring the PEAR modules (non-standard, typically you install PEAR to your path...) is there a way to enforce PHP on Windows to require files case-sensitively?</p>
<p>We are adding the PEAR path to the include path ourselves, so have control over the path order. We also recognize that we should avoid using filenames that clash with PEAR names regardless of case, and in the future will do so. This page however (which is not an include file, but a controller), has been in the repository for some years, and plugins specifically generate URLS to provide links/redirects to this page in their processing.</p>
<blockquote>
<p>(We support Apache, Microsoft IIS, LightHTTPD and Zeus, using PHP 4.3 or later (including PHP5))</p>
</blockquote>
|
<p>As it's an OS level thing, I don't believe there's an easy way of doing this.</p>
<p>You could try changing your include from <code>include('Mail.php');</code> to <code>include('./Mail.php');</code>, but I'm not certain if that'll work on a Windows box (not having one with PHP to test on).</p>
|
<p>If you are using PHP 4, you can take advantage of <a href="http://bugs.php.net/bug.php?id=43821" rel="nofollow noreferrer">this</a> bug. Off course that is a messy solution...</p>
<p>Or you could just rename your mail.php file to something else...</p>
| 8,902
|
<p>I need my code to do different things based on the operating system on which it gets compiled. I'm looking for something like this:</p>
<pre><code>#ifdef OSisWindows
// do Windows-specific stuff
#else
// do Unix-specific stuff
#endif
</code></pre>
<p>Is there a way to do this? Is there a better way to do the same thing?</p>
|
<p>The <strong><a href="https://sourceforge.net/p/predef/wiki/OperatingSystems/" rel="noreferrer">Predefined Macros for OS</a></strong> site has a very complete list of checks. Here are a few of them, with links to where they're found:</p>
<h2><a href="http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx" rel="noreferrer">Windows</a></h2>
<p><code>_WIN32</code> Both 32 bit and 64 bit<br/>
<code>_WIN64</code> 64 bit only<br/>
<code>__CYGWIN__</code></p>
<h2>Unix (Linux, *BSD, but not Mac OS X)</h2>
<p>See this <a href="https://stackoverflow.com/questions/7063303/">related question</a> on some of the pitfalls of using this check.</p>
<p><code>unix</code><br/>
<code>__unix</code><br/>
<code>__unix__</code></p>
<h2>Mac OS X</h2>
<p><code>__APPLE__</code> Also used for classic<br/>
<code>__MACH__</code></p>
<p>Both are defined; checking for either should work.</p>
<h2><a href="http://www.faqs.org/docs/Linux-HOWTO/GCC-HOWTO.html" rel="noreferrer">Linux</a></h2>
<p><code>__linux__</code><br>
<code>linux</code> Obsolete (not POSIX compliant)<br>
<code>__linux</code> Obsolete (not POSIX compliant)</p>
<h2><a href="http://www.freebsd.org/doc/en/books/porters-handbook/porting-versions.html" rel="noreferrer">FreeBSD</a></h2>
<p><code>__FreeBSD__</code></p>
<h2>Android</h2>
<p><code>__ANDROID__</code></p>
|
<p>I wrote an <a href="https://github.com/abranhe/os.c" rel="nofollow noreferrer">small library</a> to get the operating system you are on, it can be installed using <a href="https://clibs.org" rel="nofollow noreferrer">clib</a> (The C package manager), so it is really simple to use it as a dependency for your projects.</p>
<h3>Install</h3>
<pre><code>$ clib install abranhe/os.c
</code></pre>
<h3>Usage</h3>
<pre><code>#include <stdio.h>
#include "os.h"
int main()
{
printf("%s\n", operating_system());
// macOS
return 0;
}
</code></pre>
<p>It returns a string (<code>char*</code>) with the name of the operating system you are using, for further information about this project check it out <a href="https://github.com/abranhe/os.c/blob/master/readme.md#api" rel="nofollow noreferrer">the documentation on Github</a>.</p>
| 17,224
|
<p>I've never used CI tools before, but from what I've read, I'm not sure it would provide any benefit to a solo developer that isn't writing code every day.</p>
<p>First - what benefits does CI provide to any project?</p>
<p>Second - who should use CI? Does it benefit all developers?</p>
|
<p>The basic concept of CI is that you have a system that builds the code and runs automated tests everytime someone makes a commit to the version control system. These tests would include unit and functional tests, or even behavior driven tests.</p>
<p>The benefit is that you know - immediately - when someone has broken the build.<br>
This means either:</p>
<p><strong>A</strong>. They committed code that prevents compilation, which would screw any one up </p>
<p><strong>B</strong>. They committed code that broke some tests, which either means they introduced a bug that needs to be fixed, or the tests need to be updated to reflect the change in the code.</p>
<p>If you are a solo developer, CI isn't <em>quite</em> as useful if you are in a good habit of running your tests before a commit, which is what you <em>should</em> be doing. That being said, you could develop a bad habit of letting the CI do your tests for you. </p>
<p>As a solo programmer, it mainly comes down to discipline. Using CI is a useful skill to have, but you want to avoid developing any bad habits that wouldn't translate to a team environment.</p>
|
<p>CI benefits a solo developer in the sense that you're aware if you forgot to check something in (because the build will be broken). The integration value of it is diminished when there are no other developers, though.</p>
| 15,860
|
<p>I would like to be able to add custom commands/script to be executed during a print.</p>
<p>For example I would like to write some software to take a picture check the print hasn't moved off the bead between layers. </p>
<p>Does anyone know if any of the available software/firmware allows custom scripts or calling back to the computer before continuing printing?</p>
<p>I am happy to build/buy a new printer if anyone knows a control board that has this sort of feature. </p>
|
<p>One of the solutions could be adding a layer change script (simplifi3d has that out of the box) and then using marlin firmware you could set a value to digital pin that could triger external actions.</p>
<blockquote>
<p><a href="https://forum.simplify3d.com/viewtopic.php?t=1959" rel="nofollow noreferrer">Layer Change G-Code</a>: I personally haven't had to use this, but I'm
sure that there are some excellent reasons/ideas to use for this. If
you'd like for a G-Code script to be inserted in-between each layer,
than you can simply place it in this tab. One interesting use of this,
is for the FlashForge Dreamer, to have the lights blink in between
each layer, however that can be a bit too much at times! </p>
</blockquote>
<p>The syntax for the M42 command is: M42 S(value to be written to pin) P (pin number) e.g. To set digital pin 30 high, you would use M42 S1 P30</p>
<blockquote>
<p><a href="http://forums.reprap.org/read.php?146,168237,173098" rel="nofollow noreferrer">The MARLIN firmware will</a> not enable you to change the status / write
values to any of the pins in use for things such as the heaters,
thermistors, end stops etc. The command will let you send values other
than 0 and 1 to any pins which can output analogue values. (0-255)</p>
</blockquote>
|
<p>I saw this 3 years ago, this is a <a href="https://www.youtube.com/watch?time_continue=33&v=L-_5KsAOVko" rel="nofollow noreferrer">closed loop control</a>, I think is better that taking a photo then analyze it with a kind of optical recognition software which needs some of possible failures.</p>
<p>The video has also the link for the <a href="https://www.youmagine.com/designs/dc-motor-closed-loop-control-software" rel="nofollow noreferrer">additional resources</a> the 3d printer will need according his author.</p>
| 877
|
<p>Does anyone have an idea how long it will take before "almost all" widely used Python libraries work with Python 3.0?</p>
<p>I am planning to stay on 2.X for a while because I don't want to start porting stuff over and then find that some library I already rely on or a new library I might start using doesn't work yet with py3k.</p>
<p>My understanding is that the py3k beta process was drawn out specifically to give library developers time to move their stuff over. Has this been happening?</p>
<p>Examples of the sorts of libraries I am talking about would be PIL, numpy/ scipy, SQLAlchemy, BeautifulSoup, CherryPy...</p>
|
<p>The examples you have listed will probably be ported very quickly, as they are so widely used.</p>
<p>I would be surprised if BeautifulSoup takes more than a month (In fact, I'm surprised it hasn't been ported already using the py3k betas), more complex things like numpy may take a big longer, especially because 2to3 only works on python sources, not C modules..</p>
<p>It's hard to generalise - some modules may never be ported, some may take days, others may take years. It could end up being a situation along the lines of "well I'm not porting my library to Python3, no one is using it!"/"Well I'm not porting my project to python3, no libraries have been updated yet!", but I hope not!</p>
|
<p>The libraries you mention will be ported once someone puts some serious time into porting them.</p>
<p>In the specific case of NumPy/SciPy, a large part of the code is written as C extensions. There is no 2to3 tool for C extensions and so it will take a large amount of man hours to port the code over to the format that cPython3 C extensions need to use.</p>
| 20,577
|
<p>I want to move a legacy Java web application (J2EE) to a scripting language - any scripting language - in order to improve programming efficiency.</p>
<p>What is the easiest way to do this? Are there any automated tools that can convert the bulk of the business logic?</p>
|
<p>Here's what you have to do.</p>
<p>First, be sure you can walk before you run. Build something simple, possibly tangentially related to your main project.</p>
<p><strong>DO NOT</strong> build a piece of the final project and hope it will "evolve" into the final project. This never works out well. Why? You'll make dumb mistakes. But you can't delete or rework them because you're supposed to evolve that mistake into the final project.</p>
<p>Next, pick a a framework. What? Second? Yes. Second. Until you actually do something with some scripting languages and frameworks, you have no real useful concept of what you're doing. Once you've built something, you now have an informed opinion.</p>
<p>"Wait," you say. "To do step 1 I had to pick a framework." True. Step 1, however, contains decisions you're allowed to revoke. Pick the wrong framework for step 1 has no long-term bad effects. It was just learning.</p>
<p>Third, with your strategic framework, and some experience, break down your existing site into pieces you can build with your new framework. Prioritize those pieces from most important to least important. </p>
<p><strong>DO NOT</strong> plan the entire conversion as one massive project. It never works. It makes a big job more complex than necessary.</p>
<p>We'll use Django as the example framework. You'll have templates, view functions, model definitions, URL mapping and other details.</p>
<p>For each build, do the following:</p>
<ol>
<li><p>Convert your existing model to a Django model. This won't ever fit your legacy SQL. You'll have to rethink your model, fix old mistakes, correct old bugs that you've always wanted to correct.</p></li>
<li><p>Write unit tests.</p></li>
<li><p>Build a conversion utility to export old data and import into the new model.</p></li>
<li><p>Build Django admin pages to touch and feel the new data.</p></li>
<li><p>Pick representative pages and rework them into the appropriate templates. You might make use of some legacy JSP pages. However, don't waste too much time with this. Use the HTML to create Django templates.</p></li>
<li><p>Plan your URL's and view functions. Sometimes, these view functions will leverage legacy action classes. Don't "convert". Rewrite from scratch. Use your new language and framework.</p></li>
</ol>
<p>The only thing that's worth preserving is the data and the operational concept. Don't try to preserve or convert the code. It's misleading. You might convert unittests from JUnit to Python unittest. </p>
<hr>
<p>I gave this advice a few months ago. I had to do some coaching and review during the processing. The revised site is up and running. No conversion from the old technology; they did the suggested rewrite from scratch. Developer happy. Site works well.</p>
|
<p>A lot of the recommendations being given here are assuming you -- and just you -- are doing a full rewrite of the application. This is probably not the case, and it changes the answer quite a bit</p>
<p>If you've already got J2EE kicking around, the correct answer is Grails. It simply is: you probably already have Hibernate and Spring kicking around, and you're going to want the ability to flip back and forth between your old code and your new with a minimum amount of pain. That's exactly Groovy's forte, and it is even smoother than JRuby in this regards.</p>
<p>Also, if you've already got a J2EE app kicking around, you've already got Java developers kicking around. In that case, learning Groovy is like falling off a ladder -- literally. With the exception of anonymous inner classes, Groovy is a pure superset of Java, which means that you can write Java code, call it Groovy, and be done with it. As you become increasingly comfortable with the nicities of Groovy, you can integrate them into your Java-ish Groovy code. Before too long, you'll be writing very Groovy code, and not even really have realized the transition.</p>
| 24,324
|
<p>I'm building a function to extend the <code>Enum.Parse</code> concept that</p>
<ul>
<li>Allows a default value to be parsed in case that an Enum value is not found</li>
<li>Is case insensitive</li>
</ul>
<p>So I wrote the following:</p>
<pre><code>public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
{
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
</code></pre>
<p>I am getting a Error Constraint cannot be special class <code>System.Enum</code>.</p>
<p>Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the <code>Parse</code> function and pass a type as an attribute, which forces the ugly boxing requirement to your code.</p>
<p><strong>EDIT</strong> All suggestions below have been greatly appreciated, thanks.</p>
<p>Have settled on (I've left the loop to maintain case insensitivity - I am using this when parsing XML)</p>
<pre><code>public static class EnumUtils
{
public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible
{
if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
}
</code></pre>
<p><strong>EDIT:</strong> (16th Feb 2015) Christopher Currens has posted <a href="https://stackoverflow.com/a/8086788">a compiler enforced type-safe generic solution in MSIL or F#</a> below, which is well worth a look, and an upvote. I will remove this edit if the solution bubbles further up the page.</p>
<p><strong>EDIT 2:</strong> (13th Apr 2021) As this has now been addressed, and supported, since C# 7.3, I have changed the accepted answer, though full perusal of the top answers is worth it for academic, and historical, interest :)</p>
|
<h2>This feature is finally supported in C# 7.3!</h2>
<p>The following snippet (from <a href="https://github.com/dotnet/samples/blob/3ee82879284e3f4755251fd33c3b3e533f7b3485/snippets/csharp/keywords/GenericWhereConstraints.cs#L180-L190" rel="noreferrer">the dotnet samples</a>) demonstrates how:</p>
<pre><code>public static Dictionary<int, string> EnumNamedValues<T>() where T : System.Enum
{
var result = new Dictionary<int, string>();
var values = Enum.GetValues(typeof(T));
foreach (int item in values)
result.Add(item, Enum.GetName(typeof(T), item));
return result;
}
</code></pre>
<p>Be sure to set your language version in your C# project to version 7.3.</p>
<hr />
<p>Original Answer below:</p>
<p>I'm late to the game, but I took it as a challenge to see how it could be done. It's not possible in C# (or VB.NET, but scroll down for F#), but <em>is possible</em> in MSIL. I wrote this little....thing</p>
<pre><code>// license: http://www.apache.org/licenses/LICENSE-2.0.html
.assembly MyThing{}
.class public abstract sealed MyThing.Thing
extends [mscorlib]System.Object
{
.method public static !!T GetEnumFromString<valuetype .ctor ([mscorlib]System.Enum) T>(string strValue,
!!T defaultValue) cil managed
{
.maxstack 2
.locals init ([0] !!T temp,
[1] !!T return_value,
[2] class [mscorlib]System.Collections.IEnumerator enumerator,
[3] class [mscorlib]System.IDisposable disposer)
// if(string.IsNullOrEmpty(strValue)) return defaultValue;
ldarg strValue
call bool [mscorlib]System.String::IsNullOrEmpty(string)
brfalse.s HASVALUE
br RETURNDEF // return default it empty
// foreach (T item in Enum.GetValues(typeof(T)))
HASVALUE:
// Enum.GetValues.GetEnumerator()
ldtoken !!T
call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
call class [mscorlib]System.Array [mscorlib]System.Enum::GetValues(class [mscorlib]System.Type)
callvirt instance class [mscorlib]System.Collections.IEnumerator [mscorlib]System.Array::GetEnumerator()
stloc enumerator
.try
{
CONDITION:
ldloc enumerator
callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()
brfalse.s LEAVE
STATEMENTS:
// T item = (T)Enumerator.Current
ldloc enumerator
callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current()
unbox.any !!T
stloc temp
ldloca.s temp
constrained. !!T
// if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
callvirt instance string [mscorlib]System.Object::ToString()
callvirt instance string [mscorlib]System.String::ToLower()
ldarg strValue
callvirt instance string [mscorlib]System.String::Trim()
callvirt instance string [mscorlib]System.String::ToLower()
callvirt instance bool [mscorlib]System.String::Equals(string)
brfalse.s CONDITION
ldloc temp
stloc return_value
leave.s RETURNVAL
LEAVE:
leave.s RETURNDEF
}
finally
{
// ArrayList's Enumerator may or may not inherit from IDisposable
ldloc enumerator
isinst [mscorlib]System.IDisposable
stloc.s disposer
ldloc.s disposer
ldnull
ceq
brtrue.s LEAVEFINALLY
ldloc.s disposer
callvirt instance void [mscorlib]System.IDisposable::Dispose()
LEAVEFINALLY:
endfinally
}
RETURNDEF:
ldarg defaultValue
stloc return_value
RETURNVAL:
ldloc return_value
ret
}
}
</code></pre>
<p>Which generates a function that <strong>would</strong> look like this, if it were valid C#:</p>
<pre><code>T GetEnumFromString<T>(string valueString, T defaultValue) where T : Enum
</code></pre>
<p>Then with the following C# code:</p>
<pre><code>using MyThing;
// stuff...
private enum MyEnum { Yes, No, Okay }
static void Main(string[] args)
{
Thing.GetEnumFromString("No", MyEnum.Yes); // returns MyEnum.No
Thing.GetEnumFromString("Invalid", MyEnum.Okay); // returns MyEnum.Okay
Thing.GetEnumFromString("AnotherInvalid", 0); // compiler error, not an Enum
}
</code></pre>
<p>Unfortunately, this means having this part of your code written in MSIL instead of C#, with the only added benefit being that you're able to constrain this method by <code>System.Enum</code>. It's also kind of a bummer, because it gets compiled into a separate assembly. However, it doesn't mean you have to deploy it that way.</p>
<p>By removing the line <code>.assembly MyThing{}</code> and invoking ilasm as follows:</p>
<pre><code>ilasm.exe /DLL /OUTPUT=MyThing.netmodule
</code></pre>
<p>you get a netmodule instead of an assembly.</p>
<p>Unfortunately, VS2010 (and earlier, obviously) does not support adding netmodule references, which means you'd have to leave it in 2 separate assemblies when you're debugging. The only way you can add them as part of your assembly would be to run csc.exe yourself using the <code>/addmodule:{files}</code> command line argument. It wouldn't be <em>too</em> painful in an MSBuild script. Of course, if you're brave or stupid, you can run csc yourself manually each time. And it certainly gets more complicated as multiple assemblies need access to it.</p>
<p>So, it CAN be done in .Net. Is it worth the extra effort? Um, well, I guess I'll let you decide on that one.</p>
<hr />
<h3>F# Solution as alternative</h3>
<p>Extra Credit: It turns out that a generic restriction on <code>enum</code> is possible in at least one other .NET language besides MSIL: F#.</p>
<pre class="lang-ml prettyprint-override"><code>type MyThing =
static member GetEnumFromString<'T when 'T :> Enum> str defaultValue: 'T =
/// protect for null (only required in interop with C#)
let str = if isNull str then String.Empty else str
Enum.GetValues(typedefof<'T>)
|> Seq.cast<_>
|> Seq.tryFind(fun v -> String.Compare(v.ToString(), str.Trim(), true) = 0)
|> function Some x -> x | None -> defaultValue
</code></pre>
<p>This one is easier to maintain since it's a well-known language with full Visual Studio IDE support, but you still need a separate project in your solution for it. However, it naturally produces considerably different IL (the code <em>is</em> very different) and it relies on the <code>FSharp.Core</code> library, which, just like any other external library, needs to become part of your distribution.</p>
<p>Here's how you can use it (basically the same as the MSIL solution), and to show that it correctly fails on otherwise synonymous structs:</p>
<pre><code>// works, result is inferred to have type StringComparison
var result = MyThing.GetEnumFromString("OrdinalIgnoreCase", StringComparison.Ordinal);
// type restriction is recognized by C#, this fails at compile time
var result = MyThing.GetEnumFromString("OrdinalIgnoreCase", 42);
</code></pre>
|
<p>Just for completeness, the following is a Java solution. I am certain the same could be done in C# as well. It avoids having to specify the type anywhere in code - instead, you specify it in the strings you are trying to parse.</p>
<p>The problem is that there isn't any way to know which enumeration the String might match - so the answer is to solve that problem.</p>
<p>Instead of accepting just the string value, accept a String that has both the enumeration and the value in the form "enumeration.value". Working code is below - requires Java 1.8 or later. This would also make the XML more precise as in you would see something like color="Color.red" instead of just color="red".</p>
<p>You would call the acceptEnumeratedValue() method with a string containing the enum name dot value name. </p>
<p>The method returns the formal enumerated value.</p>
<pre><code>import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
public class EnumFromString {
enum NumberEnum {One, Two, Three};
enum LetterEnum {A, B, C};
Map<String, Function<String, ? extends Enum>> enumsByName = new HashMap<>();
public static void main(String[] args) {
EnumFromString efs = new EnumFromString();
System.out.print("\nFirst string is NumberEnum.Two - enum is " + efs.acceptEnumeratedValue("NumberEnum.Two").name());
System.out.print("\nSecond string is LetterEnum.B - enum is " + efs.acceptEnumeratedValue("LetterEnum.B").name());
}
public EnumFromString() {
enumsByName.put("NumberEnum", s -> {return NumberEnum.valueOf(s);});
enumsByName.put("LetterEnum", s -> {return LetterEnum.valueOf(s);});
}
public Enum acceptEnumeratedValue(String enumDotValue) {
int pos = enumDotValue.indexOf(".");
String enumName = enumDotValue.substring(0, pos);
String value = enumDotValue.substring(pos + 1);
Enum enumeratedValue = enumsByName.get(enumName).apply(value);
return enumeratedValue;
}
}
</code></pre>
| 10,450
|
<p>I'm an avid vim user and have started to write some SQL code recently. I like to write my SQL statements in CAPS and sometimes forget to switch <kbd>CapsLock</kbd> 'off' and I then quickly wreak havoc on my code before I realise what's happening.</p>
<p>I have so far not found any way to tell whether the <kbd>CapsLock</kbd> key is on other than looking at my keyboard (which requires me to look away from the screen which I consider a big delay). </p>
<p>Ideally I would like vim to automatically change my background colour whenever <kbd>CapsLock</kbd> is 'on' but I'd be willing to settle for some other on-screen indicator of <kbd>CapsLock</kbd> status as a compromise.</p>
|
<p><s>The best I can give you is to have vim toggle the background color whenever the CAPSLOCK
key is hit in vim.</s></p>
<p>Vim can't detect the CAPSLOCK key alone. What I can give you is a mapping so you can use some other key (in this example, F3) to act like the CAPSLOCK key for insert mode, and change the background color when all-caps is on. Hopefully this will give you the functionality you need.</p>
<p>Put the following in your ~/.vimrc or in the appropriate ~/.vim/ftplugin/<strong><filetype></strong>.vim :</p>
<pre><code> " let the case be toggled in normal mode
map <expr> <F3> ToggleInsertCase()
" let the case be toggled in insert mode
imap <expr> <F3> ToggleInsertCase()
let toUpper = 0
func! ToggleInsertCase()
let g:toUpper = 1 - g:toUpper
if (g:toUpper == 1)
highlight Normal ctermbg=Blue " the background color you want when uppercased
" convert all the letters to uppercase in insert mode
let i = char2nr('a')
while i <= char2nr('z')
let c = nr2char(i)
exe 'inoremap' c toupper(c)
let i = i + 1
endwhile
else
highlight Normal ctermbg=Black " the background color you want normally
" let letters be as normal in insert mode
let i = char2nr('a')
while i <= char2nr('z')
let c = nr2char(i)
exe 'iunmap' c
let i = i + 1
endwhile
endif
" don't insert anything when this function is called in normal mode
return ""
endfunc
</code></pre>
<p>This borrows some from <a href="http://www.vim.org/scripts/script.php?script_id=1725" rel="nofollow noreferrer">Tim Pope's capslock.vim</a>.</p>
<p>If you really want to use the CAPSLOCK key for this, depending on your platform, there's a bunch of free apps that let you remap
your CAPSLOCK key to something else, so you could set it up so that when you hit CAPSLOCK, vim (and everything else) got F3. Or whatever.
This would interfere with other apps getting the CAPSLOCK key though (unless the key-remapper app is clever), so that could be troublesome.</p>
|
<p>Why not have a filetype plugin for .sql files that contain imap commands to convert all your keystrokes to caps. That way, you never have to toggle the actual capslock key on the keyboard and things will be fine when you go back to code.</p>
<p>Add the following in the file $VIM/vimfiles/ftplugin/sql_too.vim :</p>
<pre><code>imap a A
imap b B
imap c C
imap d D
imap e E
imap f F
imap g G
imap h H
imap i I
imap j J
imap k K
imap l L
imap m M
imap n N
imap o O
imap p P
imap q Q
imap r R
imap s S
imap t T
imap u U
imap v V
imap w W
imap x X
imap y Y
imap z Z
</code></pre>
| 36,892
|
<p>I have a C/C++ source file with conditional compilation. Before I ship it to customers I want to remove most of the #if statements, so that my customers do not need to worry about passing the right -D options to the compiler.</p>
<p>I have this implemented and working in Python, but it only handles #ifdef and #ifndef statements properly. I need to add support for #if statements, but the syntax of #if is much more complex. (E.g. you can use &&, ||, !, brackets, relational operators, arithmetic, etc).</p>
<p>Is there any existing open-source code to parse and evaluate #if statements? (Preferably in Python).</p>
<p>The only implementation I know of is GCC, and that's much too complex for this task.</p>
|
<p>As <a href="https://stackoverflow.com/questions/287379/parsing-c-preprocessor-if-statements#287405">KeithB said</a>, you could just let the preprocessor do this for you. </p>
<p>But if you're not trying to hide things (ie., there may be stuff in the conditionally compiled code that you don't want or aren't permitted to give to some one else) a much simpler option would be to just put the proper <code>#define</code> directives in a header that's globally included.</p>
<ul>
<li>your clients don't need to worry about <code>-D</code> options</li>
<li>you don't have to have some custom step in your build process</li>
<li>the code you give your clients isn't potentially semi-obfuscated</li>
<li>you don't introduce bugs because the tool does things subtly different from the C preprocessor</li>
<li>you don't have to maintain some custom tool</li>
</ul>
|
<p>The GCC preprocessor is typicallly a stand-alone program, typically called <code>cpp</code>. That will probably also strip off your comments, of course.</p>
| 36,555
|
<p>How do I make a GUI for my python program because now it only runs in Idle and a command line and what software packages can I use and where can I get them? Thanks.</p>
|
<p>The <a href="http://wiki.python.org/moin/GuiProgramming" rel="nofollow noreferrer">GuiProgramming</a> page in the Python wiki has a good overview of the different options you have.</p>
|
<p>We started down the path of wxPython a few years ago and found it to be quite easy to do for simple, quick and dirty app. However, you are not going to get something you can put on the modern desktop. So we switched to WinForms and Python.Net and haven't looked back since. It's fairly easy to get going and you get all the power and support of rich windows UI with .NET.</p>
| 35,358
|
<p>I am trying to find all matches in a string that begins with <code>| |</code>. </p>
<p>I have tried: <code>if ($line =~ m/^\\\|\s\\\|/)</code> which didn't work. </p>
<p>Any ideas?</p>
|
<p>You are escaping the pipe one time too many, effectively escaping the backslash instead.</p>
<pre><code>print "YES!" if ($line =~ m/^\|\s\|/);
</code></pre>
|
<p>What about:</p>
<pre><code>m/^\|\s*\|/
</code></pre>
| 22,074
|
<p>If you're using Opera 9.5x you may notice that our client-side <a href="http://docs.jquery.com/Plugins/Validation" rel="noreferrer">JQuery.Validate</a> code is disabled here at Stack Overflow.</p>
<pre><code>function initValidation() {
if (navigator.userAgent.indexOf("Opera") != -1) return;
$("#post-text").rules("add", { required: true, minlength: 5 });
}
</code></pre>
<p>That's because it generates an exception in Opera! Of course it works in every other browser we've tried. I'm starting to seriously, seriously hate Opera.</p>
<p>This is kind of a bummer because without proper client-side validation some of our requests will fail. We haven't had time to put in complete server-side messaging when data is incomplete, so <strong>you may see the YSOD on Opera much more than other browsers</strong>, if you forget to fill out all the fields on the form.</p>
<p>Any Opera-ites want to uncomment those lines (they're on core Ask & Answer pages like this one -- just View Source and search for <code>"Opera"</code>) and give it a go?</p>
|
<p>turns out the problem was in the</p>
<pre><code>{ debug : true }
</code></pre>
<p>option for the JQuery.Validate initializer. <strong>With this removed, things work fine in Opera.</strong> Thanks to Jörn Zaefferer for helping us figure this out!</p>
<p>Oh, and the $50 will be donated to the JQuery project. :)</p>
|
<p>I can't seem to reproduce this bug. Can you give more details?</p>
<p>I have my copy of Opera masquerading as Firefox so the validation should be executing:</p>
<pre><code>>>> $.browser.opera
false
</code></pre>
<p>When I go to the edit profile page and enter a malformed date, the red text comes up and says "Please enter a valid date". That's jQuery.Validate working, right? Does it only fail on certain forms/fields?</p>
<p>This is Opera 9.51 on WinXP.</p>
<p>Edit: testing editing on Opera.</p>
<p>Edit: It also works when I comment out the "if ($.browser.opera) return;" line on a copy of the edit profile page I saved locally. I really can't reproduce this bug. What is your environment like? (Vista? Opera plugins?)</p>
| 3,014
|
<p>What's the easiest way to increase or decrease indentation for a large block of code in vi?</p>
|
<p>In vim (not sure if this applies to you too), you use <code>>></code> to indent one line. As with nearly every command in vim, type in a number before the command to perform is multiple times. So to indent the next 50 lines, type <code>50>></code>.</p>
|
<p>use two angle-brackets ("<<" or ">>") for one line left or right by shiftwidth characters. You can do this with the common line-range indicators - ":m,n", brace/bracket/paren matching, etc.</p>
<p>Or "<", then a motion indicator, then another "<".</p>
<p>Or "<12<" shifts the next 12 lines left.</p>
| 31,446
|
<p>For a university project I programmed a Internet Explorer Browser Helper Object to process web document information while browsing. It were running successful on Windows XP with IE6 and IE7.</p>
<p>Now I have the issue that under Windows Vista the same BHO needs administrator rights to run. Browser and BHO running if you start the IE as administrator but if you start as normal user it crashes.</p>
<p>The BHO is of course registered on the system and activated in the browser.</p>
<p>What can I do that a user with non-admin rights can run the registered and activated BHO? Or is maybe something else the reason and I totally miss it?</p>
<p>Thank you very much for your help!</p>
|
<p>Not sure if your problem is related to custom actions in your installer but the following two links should help you.</p>
<ul>
<li><p>Building a BHO with the UAC in mind - <a href="http://simonguest.com/2006/11/20/building-browser-helper-objects-using-managed-code/" rel="nofollow noreferrer">http://simonguest.com/blogs/smguest/archive/2006/11/19/Building-Browser-Helper-Objects-using-Managed-Code.aspx</a> (a little over half way down)</p></li>
<li><p>Using the NoImpersonate script - <a href="http://blogs.msdn.com/astebner/archive/2007/05/28/2958062.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/astebner/archive/2007/05/28/2958062.aspx</a> </p></li>
</ul>
|
<p>You should use a debugger to determine <em>why</em> the addon is crashing. Chances are good that you're attempting to write to a protected location, and when that fails, your code fails to check for an error result.</p>
<p>Using Process Monitor and watching for Access_Denied returns is often helpful, but using a full-debugger is the right way to go.</p>
| 19,074
|
<p>Why does the SQLite C/C++ API return <code>unsigned char *</code>s for text values as opposed to the more de-facto <code>char *</code> type?</p>
<p>This is somewhat related to <a href="https://stackoverflow.com/questions/75191/unsigned-char">the unsigned char</a> question, except that the SQLite API's decision seems opposite of the conventional <code>char *</code> advice given for string-like values.</p>
<p>For example:</p>
<pre><code>const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
</code></pre>
|
<p>From the <a href="http://www.sqlite.org/capi3ref.html#sqlite3_column_blob" rel="noreferrer">SQLite documentation</a>:</p>
<blockquote>
<p>(H13821) The sqlite3_column_text(S,N) interface converts the Nth column in the current row of the result set for the prepared statement S into a zero-terminated UTF-8 string and returns a pointer to that string.</p>
</blockquote>
<p>UTF-8 wants byte values ranging from 0x00 to 0xFF. char can range from -0x80 to 0x7F (signed) or 0x00 to 0xFF (unsigned). Forcing unsigned allows the proper encoding of a UTF-8 string.</p>
|
<p>At a wild guess I'd say that it has something to do with supporting UTF-8 encoding. Signed char values only make sense in a 7-bit ASCII environment where everything above 0x7f is open to interpretation. In UTF-8 everything between 0x00 and 0xFF can be used equally.</p>
| 41,356
|
<p>In php I need to get the contents of a url (source) search for a string "maybe baby love you" and if it does not contain this then do x.</p>
|
<p>Just read the contents of the page as you would read a file. PHP does the connection stuff for you. Then just look for the string via regex or simple string comparison.</p>
<pre><code>$url = 'http://my.url.com/';
$data = file_get_contents( $url );
if ( strpos( 'maybe baby love you', $data ) === false )
{
// do something
}
</code></pre>
|
<p>Assuming fopen URL Wrappers are on ...</p>
<pre><code>$string = file_get_contents('http://example.com/file.html');
if(strpos ('maybe baby love you', $string) === false){
//do X
}
</code></pre>
| 34,880
|
<p>When I call CreateProcess in Windows, the new process doesn't seem to inherit the console of the calling process. I made a test program that runs "ruby xtest", xtest being a script that writes "hello" to standard output. I ran this test program from Emacs, and get no output. I also tried the following code calling GetStdHandle, but again, no output. Then I tried passing CREATE_NEW_CONSOLE in dwCreationFlags to CreateProcess, which made a whole new window with the Ruby output. Finally, I made a simple fork/exec
test program and compiled it using Cygwin's GCC. This program worked: the Ruby output showed up in Emacs as expected. I tried to decipher the Cygwin source code in <a href="http://cygwin.com/cgi-bin/cvsweb.cgi/src/winsup/cygwin/spawn.cc?rev=1.268&content-type=text/x-cvsweb-markup&cvsroot=src" rel="noreferrer">http://cygwin.com/cgi-bin/cvsweb.cgi/src/winsup/cygwin/spawn.cc?rev=1.268&content-type=text/x-cvsweb-markup&cvsroot=src</a> but failed. So, how do you make the new process inherit the console of the parent process such that the output from the child shows up as expected?</p>
<pre><code>STARTUPINFO si;
PROCESS_INFORMATION pi;
memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
si.dwFlags |= STARTF_USESTDHANDLES;
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
if(!CreateProcess(0, "ruby xtest", 0, 0, 1, 0, 0, 0, &si, &pi)) die("CreateProcess");
</code></pre>
|
<p>I know, this thread is rather old, however, I just ran into the same problem.</p>
<p>Just as for the TS, the console handle was inherited and working fine under Cygwin, but not on a Windows console. Instead, the output on stdout was neither shown, nor any error was reported. Inherited Pipe handles worked still fine.</p>
<p>I took me some time to identify the (now obvious) problem: CreateProcess() was called with CREATE_NO_WINDOW. Dropping this flag, console output is fine. (Though, according to the code of the TS, they never set this flag in the first place.)</p>
<p>Hope this might be helpful for people who also stumble across this thread, like myself.</p>
|
<p>I've done this by passing in pipes for <code>hStdInput</code>, <code>hStdOutput</code>, and <code>hStdError</code> and manually routing data from the <code>hStdOutput</code> and <code>hStdError</code> pipes to the console.</p>
| 44,221
|
<p>We're developing an EPiServer-based website and trying to deploy our latest build onto a WinXP IIS6 box.</p>
<p>When browsing to site, we're getting the following stack trace</p>
<pre><code>[ClassFactoryException: ClassFactory not initialized]
EPiServer.BaseLibrary.ClassFactory.get_Instance() +123
EPiServer.BaseLibrary.Context.get_Repository() +14
EPiServer.WorkflowFoundation.StorageProviders.ObjectStoreStorageProvider.VerifyCommonSchemas() +15
EPiServer.WorkflowFoundation.AspNetWorkflowManager.get_StorageProvider() +44
EPiServer.WorkflowFoundation.AspNetWorkflowManager.Initialize(Boolean lazyLoading) +589
EPiServer.WorkflowFoundation.AspNetWorkflowManager.get_InstanceHandler() +16
EPiServer.WorkflowFoundation.Workflows.ApprovalService..ctor() +93
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +103
System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +261
System.Activator.CreateInstance(Type type, Boolean nonPublic) +66
EPiServer.WorkflowFoundation.WorkflowSystem.RegisterServices(IWorkflowManager manager, WorkflowSettingsElement configuration) +338
EPiServer.WorkflowFoundation.WorkflowSystem.Init(HttpApplication context) +240
System.Web.HttpApplication.InitModules() +267
System.Web.HttpApplication.InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers) +1251
System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext context) +243
System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context) +106
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +214
</code></pre>
<p>I've googled it, and visited the EPiServer forums, but I've not found any concrete suggestions or solutions. Has anyone else out there run into this?</p>
<p>Ross</p>
|
<p>The configuration file is written for IIS7 but you build in webserver in Studio want a IIS6 sonfig file.
I have wrote abut this in ny EPiServer notes
<a href="http://epiwiki.se/troubleshooting/classfactory-not-initialized" rel="nofollow noreferrer">http://epiwiki.se/troubleshooting/classfactory-not-initialized</a> </p>
|
<p>I am going out on a limb and guessing here, but did you by chance do development on EPiServer 5 SP 2 and deploy on EPiServer 5 SP 3?</p>
<p>In EPiServer 5 SP3 there was some remodelling in how a EPiServer handles the initialization of the application. These changes made it so that it's not possible to hook into the datafactory events in Application_Start. Instead you need to first hook into Application_FirstBeginRequest and then we have a instance of the DataFactory to work with.</p>
<p><a href="http://world.episerver.com/Forum/Pages/Thread.aspx?id=23087&epslanguage=en" rel="nofollow noreferrer">Suggested reading</a></p>
| 25,014
|
<p>When objects from a CallList intersect the near plane I get a flicker..., what can I do?</p>
<p>Im using OpenGL and SDL.</p>
<p>Yes it is double buffered.</p>
|
<p>It sounds like you're getting z-fighting.</p>
<p>"Z-fighting is a phenomenon in 3D rendering that occurs when two or more primitives have similar values in the z-buffer, and is particularly prevalent with coplanar polygons. The effect causes pseudo-random pixels to be rendered with the color of one polygon or another in a non-deterministic manner, varying as the scene is animated, causing one polygon to "win" the z test, then another, and so on."
(From <a href="http://en.wikipedia.org/wiki/Z-fighting" rel="noreferrer">wikipedia</a>)</p>
<p>You can get more information about the problem in the <a href="http://www.opengl.org/resources/faq/technical/depthbuffer.htm" rel="noreferrer">OpenGL FAQ</a>.</p>
<p>glPolygonOffset might help, but you can also get yourself into trouble with it. Tom Forsyth has a good explanation in his <a href="http://tomsdxfaq.blogspot.com/2002_07_01_archive.html#79344425#79344425" rel="noreferrer">FAQ</a> Note: It talks about ZBIAS, but that's just the DirectX equivilent.</p>
|
<p>Ah, you meant the <em>near</em> plane. :)</p>
<p>Well...another thing when drawing polygons in the same plane is to use <a href="http://www.cs.sfu.ca/~haoz/teaching/htmlman/polygonoffset.html" rel="nofollow noreferrer">glPolygonOffset</a></p>
<p>From the description</p>
<pre><code> glPolygonOffset is useful for rendering hidden-line images,
for applying decals to surfaces, and for rendering solids
with highlighted edges.
</code></pre>
| 7,903
|
<p>I have a Excel macro that generates a this error whenever it gets input of a specific format. Does anyone knows <strong>in general</strong> what an <em>advise flag</em> is OR where can I find information on this type of error? Thanks</p>
<blockquote>
<p>Runtime error -2147221503
(80040001): Automation error, Invalid
advise flags</p>
</blockquote>
|
<p>I don't put in comments like that, the source control system already maintains that history and I am already able to log the history of a file.</p>
<p>I do put in comments that describe why something non-obvious is being done though. So if the bug fix makes the code less predictable and clear, then I explain why.</p>
|
<p>To locate ones specific comment we use <strong>DKBUGBUG</strong> - which means David Kelley's fix and reviewer can easily identity, Ofcourse we will add Date and other VSTS bug tracking number etc along with this. </p>
| 15,075
|
<p>There's this program, pdftotext, that can convert a pdf file to a text file. To use it directly on the linux console:</p>
<pre><code>pdftotext file.pdf
</code></pre>
<p>That will generate a file.txt on the same directory as the pdf file. I was looking for a way to do it from inside a php program, and after some googling I ended with two commands that should work for me: <em>system()</em> and <em>exec()</em>. So I made a php file with this:</p>
<pre><code><?php
system('pdftotext file.pdf');
?>
</code></pre>
<p>But when I run this code, it doesn't work. No txt file is created.
So I tried to create a test file with another command:</p>
<pre><code><?php
system('touch test.txt');
?>
</code></pre>
<p>This worked fine. I've also used exec() and the results were the same. Why doesn't it work?</p>
<p><strong>EDIT:</strong> following RoBorg advice, i added the 2>&1 argument to the command, so:</p>
<pre><code><?php
system('pdftotext file.pdf 2>&1');
?>
</code></pre>
<p>it printed a error message:</p>
<blockquote>
<p>pdftotext: error while loading shared
libraries: libfontconfig.so.1: cannot
open shared object file: No such file
or directory</p>
</blockquote>
<p>Seems like something is missing on the server.</p>
|
<p>It's probably a permissions issue, but try this instead:</p>
<pre><code><?php
system('pdftotext file.pdf 2>&1');
?>
</code></pre>
<p>The <code>2>&1</code> redirects stderr to stdout, so any error messages will be printed. It should be pretty easy to fix from then on.</p>
|
<p>PHP has a build in PDF function library, that should be able to give you what you need:<br>
<a href="http://nl3.php.net/pdf" rel="nofollow noreferrer">http://nl3.php.net/pdf</a></p>
| 42,013
|
<p>The website works with Wemf and Google Analytics, but they are giving me very different results; WEMF counts 10 - 30 % more page views than Google Analytics... Why can this be?</p>
<p>Google Analytics works only with JavaScript enabled, yes - but I don't think that's the reason for this difference. The site which should be counted is a famous newspaper in Switzerland.</p>
<p>Any suggestions?</p>
|
<p>Don't know much about WEMF. Could it be that Google Analytics does a better job at detecting and not counting search engine spider traffic?</p>
|
<p>Yes!!! I googled a little bit for "Google Analytics search engine spider" and it really seems as Google Analytics doesn't count those...</p>
<p>Thank you very much for that info, helped a lot!</p>
| 24,027
|
<p>I'm not entirely sure if this is possible in Ruby, but hopefully there's an easy way to do this. I want to declare a variable and later find out the name of the variable. That is, for this simple snippet:</p>
<pre><code>foo = ["goo", "baz"]
</code></pre>
<p>How can I get the name of the array (here, "foo") back? If it is indeed possible, does this work on any variable (e.g., scalars, hashes, etc.)?</p>
<p>Edit: Here's what I'm basically trying to do. I'm writing a SOAP server that wraps around a class with three important variables, and the validation code is essentially this:</p>
<pre><code> [foo, goo, bar].each { |param|
if param.class != Array
puts "param_name wasn't an Array. It was a/an #{param.class}"
return "Error: param_name wasn't an Array"
end
}
</code></pre>
<p>My question is then: Can I replace the instances of 'param_name' with foo, goo, or bar? These objects are all Arrays, so the answers I've received so far don't seem to work (with the exception of re-engineering the whole thing ala <a href="https://stackoverflow.com/questions/58482/ruby-get-a-variables-name#58870">dbr's answer</a>) </p>
|
<p>What if you turn your problem around? Instead of trying to get names from variables, get the variables from the names:</p>
<pre><code>["foo", "goo", "bar"].each { |param_name|
param = eval(param_name)
if param.class != Array
puts "#{param_name} wasn't an Array. It was a/an #{param.class}"
return "Error: #{param_name} wasn't an Array"
end
}
</code></pre>
<p>If there were a chance of one the variables not being defined at all (as opposed to not being an array), you would want to add "rescue nil" to the end of the "param = ..." line to keep the eval from throwing an exception...</p>
|
<p>You can't, you need to go back to the drawing board and re-engineer your solution.</p>
| 8,282
|
<p>I recently ran across some 3rd party C# code which does the following:</p>
<pre><code>public int RecvByteDataFromPrinter(ref byte[] byteData)
{
byte[] recvdata = new byte[1024];
///...fills recvdata array...
byteData = recvdata;
return SUCCESS;
}
</code></pre>
<p>What does the line "<code>byteData = recvdata</code>" actually do in this case?</p>
<p>It appears that the goal is to have byteData contain the contents of the recvdata array. However, I was under the impression that you would need to do an <code>Array.Copy(...)</code> operation in order for that to happen. </p>
<p>Is this actually modifying the byteData reference to point to the newly allocated array? If so, is that array guaranteed to stick around?</p>
|
<p>Yes, because of ref - it does modify the reference passed.
Stick around? you mean - not destroyed? Yes, it will not be GC'd because of a new reference. The old array (passed) might be GC'd though after this assignment if no more references...</p>
<p>Array.Copy will actually copy elements, then you don't need "ref", but this will be more time-consuming</p>
|
<p>The byteData reference will now be pointing at the recvdata array, giving it a root. It will "stick around" until all of its roots are gone (i.e. the called gets rid of the byteData object passed in) and it becomes a collection candidate. The original array object passed is is a candidate for collection as soon as the method returns.</p>
| 38,937
|
<p>Typical scenario. We use old-school XML Web Services <em><code>internally</code></em> for communicating between a server farm and several distributed <em>and</em> local clients. No third parties involved, only our applications used by ourselves and our customers.</p>
<p>We're currently pondering moving from <code>XML</code> <code>WS</code> to a <code>WCF/object-based</code> model and have been experimenting with various approaches. One of them involves transferring the domain objects/aggregates directly over the wire, possibly invoking DataContract attributes on them.</p>
<p>By using <code>IExtensibleDataObject</code> and a <code>DataContract</code> using the Order property on the <code>DataMembers</code>, we should be able to cope with simple property versioning issues (remember, we control all clients and can easily force-update them).</p>
<p>I keep hearing that we should use dedicated, transfer-only Data Transfer Objects (<code>DTOs</code>) over the wire.</p>
<p>Why? Is there still a reason to do so? We use the same domain model on the server side and client side, of course, prefilling collections, etc. only when deemed right and "necessary." Collection properties utilize the service locator principle and IoC to invoke either an <code>NHibernate-based</code> "service" to fetch data directly (on the server side), and a <code>WCF</code> "service" client on the client side to talk to the <code>WCF</code> server farm.</p>
<p>So - why do we need to use <code>DTOs</code>?</p>
|
<p>In my experience DTOs are most useful for:</p>
<ol>
<li>Strictly defining what will be sent over the wire and having a type specifically devoted to that definition.</li>
<li>Isolating the rest of your application, client and server, from future changes.</li>
<li>Interoperability with non-.Net systems. DTOs certainly aren't a requirement, but they make it easier to design "safe" types.</li>
</ol>
<p>In your scenario these design features may not matter that much. I've used WCF with both strict DTOs and shared Domain Objects and in both scenarios it worked great. The only thing I noticed when sending Domain Objects over the wire was that I tended to send more data (and in unexpected ways) then I needed to. This was likely more due to my lack of experience with WCF than anything else; but it's something you should definitely be wary of should you choose to go that route. </p>
|
<p>Having worked with both approaches (shared domain objects and DTOs) I'd say the big problem with shared domain objects is when you don't control all clients, but from my past experiences I'd usually use DTOs unless it development speed were of the essence.</p>
<p>If there's any chance that you won't always be in control of the clients then I'd definately recommend DTOs, because as soon as you share your domain objects with someone else's client application you start tying your internals to someone else's dev cycle.</p>
<p>I've also found DTOs useful when working in a versioned service environment, which allowed us to radically change the internals of our app but still accept calls to the old versions of our service interfaces. </p>
<p>Finally, if you have a lot of client applications it might also be beneficial to use DTOs as you're then protected with an easily versionable service.</p>
| 4,496
|
<p>If I can do this, how do I call Java code (methods for instance) from within JavaScript code, in Wicket. </p>
|
<p>erk. The correct answer would be ajax call backs. You can either manually code the js to hook into the wicket js, or you can setup the callbacks from wicket components in java.
For example, from AjaxLazyLoadPanel:</p>
<pre><code> component.add( new AbstractDefaultAjaxBehavior() {
@Override
protected void respond(AjaxRequestTarget target) {
// your code here
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead( response );
response.renderOnDomReadyJavascript( getCallbackScript().toString() );
}
}
</code></pre>
<p>This example shows how to add call back code to any Component in Wicket. After the OnDomReady event fires in your browser, when loading a page, Wicket will cause it's js enging, to call back into your code, using Ajax, to the 'respond' method shown above, at which point you can execute Java code on the server, and potentially add components to the ajax target to be re-rendered.</p>
<p>To do it manually, from js, you can hook into wicket's system by printing out getCallbackScript().toString() to a attribute on a wicket component, which you'll then be able to access from js. Calling this url from js manually with wicket's wicketAjaxGet from wicket-ajax.js.</p>
<p>Check out the mailing list for lot's of conversation on this topic:
<a href="http://www.nabble.com/Wicket-and-javascript-ts24336438.html#a24336438" rel="noreferrer">http://www.nabble.com/Wicket-and-javascript-ts24336438.html#a24336438</a></p>
|
<p>Assuming you mean JavaScript running on the client - you cause an HTTP redirect to be made to the server, and have your servlet react to the request for the given URL.</p>
<p>This is known as <a href="http://www.jibbering.com/2002/4/httprequest.html" rel="nofollow noreferrer">Ajax</a>, and there are a <a href="http://developer.yahoo.com/yui/connection/" rel="nofollow noreferrer">number</a> of <a href="http://docs.jquery.com/Ajax" rel="nofollow noreferrer">libraries</a> that help you do it..</p>
| 19,699
|
<p>My mouse, in my virtual server virtual machine is all jittery, and not working smoothly.<br>
Outside the virtual machine it is fine.</p>
<p>My mouse is set to use the VMWare Pointing Device, which it says is working properly.
I've tried the sample rate in 100 and 200 reports/second and it makes no difference.</p>
<p>Any ideas?</p>
|
<p>Install VMware Tools and enable Full Acceleration in Display Properties -> Advanced -> Troubleshoot Tab on the VMware machine.</p>
|
<p>Also, make sure the mouse is using VMware drivers. Sometimes it reverts to general PS/2 drivers, which can cause very irritating lag.</p>
| 23,293
|
<p>I have a K280 3D printer with a MKS V1.5 and Repetier firmware.</p>
<p><a href="https://i.stack.imgur.com/yCoXM.jpg" rel="nofollow noreferrer" title="Damaged transistor associated with E0 (3rd one on the right)"><img src="https://i.stack.imgur.com/yCoXM.jpg" alt="Damaged transistor associated with E0 (3rd one on the right)" title="Damaged transistor associated with E0 (3rd one on the right)"></a></p>
<p>I’ve damaged the transistor associated with E0 (3rd one on the right) and so that means I need to avoid that. I’ve decided to switch to E1 for the extruder but I have a feeling I need to go in the firmware or Repetier host and manipulate that. </p>
<p>I don’t know how and any help would be great. </p>
<p>The only info I can access for the firmware is the EEPROM and it seems that I can’t edit the pins. Also, do I need to edit the pin for the sensor or just where the extruder goes?</p>
|
<p>If you go through the <a href="https://www.repetier.com/firmware/v100/index.php" rel="nofollow noreferrer">Repetier-Firmware configuration tool for version 1.0.2</a> you can select the E1 stepper for the E0 extruder (or whatever stepper you want to use for it) in the tools tab sheet. I'm not familiar with Repetier, but if that does not work you would have to switch pin numbers. </p>
<p>If you already have a Configuration.h, you can use that one (by loading it into the configuration tool) and alter the E1 afterwards so that you do not have to enter all the other options by yourself.</p>
<p><strong>Edit:</strong> After some investigation, you can find your configuration file <a href="https://www.facebook.com/groups/1787070361537465/" rel="nofollow noreferrer">here</a> as described <a href="http://he3d-delta-printer-owners.wikia.com/wiki/Configuring_the_Repetier_Software_for_the_first_time" rel="nofollow noreferrer">here</a>, so the only thing you would have to do is to load the file in the online tool and adjust the E1 stepper for E0 extruder.</p>
|
<p>You can try editing the gcodes by searching and replacing E0 for E1, so this way the extruder E1 will be enabled.</p>
<p>Other way is setting the Slicer to use 2 extruders but everything for printing on E1 like: Perimeter, Infill, Solid, Support/raft/skirt, Support / raft interface.</p>
<p>The third one, Switch the transistor from E1 to E0 (your Q2 for Q1) or Q3 if you are not using the FAN output.</p>
| 771
|
<p>How to check if a folder (directory) exists in Cocoa using Objective-C?</p>
|
<p>Use <code>NSFileManager</code>'s <code>fileExistsAtPath:isDirectory:</code> method. See Apple's docs <a href="https://developer.apple.com/documentation/foundation/nsfilemanager/1410277-fileexistsatpath?language=objc" rel="nofollow noreferrer">here</a>.</p>
|
<p>If your have a <code>NSURL</code> object as <code>path</code>, it's better to use path to convert it into <code>NSString</code>.</p>
<pre><code>NSFileManager*fm = [NSFileManager defaultManager];
NSURL* path = [[[fm URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] objectAtIndex:0]
URLByAppendingPathComponent:@"photos"];
NSError *theError = nil;
if(![fm fileExistsAtPath:[path path]]){
NSLog(@"dir doesn't exists");
}else
NSLog(@"dir exists");
</code></pre>
| 12,462
|
<p>Say I have the following string:</p>
<pre><code>"I am the most foo h4ck3r ever!!"
</code></pre>
<p>I'm trying to write a makeSpecial(foo) function where the foo substring would be wrapped in a new span element, resulting in:</p>
<pre><code>"I am the most <span class="special">foo></span> h4ck3r ever!!"
</code></pre>
<p>BeautifulSoup seemed like the way to go, but I haven't been able to make it work.</p>
<p>I could also pass this to the browser and do it with javascript, but that doesn't seem like a great idea.</p>
<p>Some advice for this would be really useful, especially in python. </p>
|
<p>How about this:</p>
<pre><code>Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def makeSpecial(mystring, special_substr):
... return mystring.replace(special_substr, '<span class="special">%s</span>
' % special_substr)
...
>>> makeSpecial("I am the most foo h4ck3r ever!!", "foo")
'I am the most <span class="special">foo</span> h4ck3r ever!!'
>>>
</code></pre>
|
<p>If you wanted to do it with javascript/jQuery, take a look at this question: <a href="https://stackoverflow.com/questions/119441/highlight-a-word-with-jquery">Highlight a word with jQuery</a></p>
| 15,207
|
<p>Maybe this is a dumb question, but I have the following behavior in Visual Studio 2005 while designing forms:</p>
<p>1 - Drop a control onto the form (suppose it's a Label, just for discussion)</p>
<p>2 - Drag that label to a specific location (aligning w/other controls, whatever)</p>
<p>3 - Release the mouse button</p>
<p>4 - The control is still stuck to the mouse!!!</p>
<p>To get it un-stuck from the mouse, I have to hit ESC, which restores the Label to it's original location.</p>
<p>This is driving me nuts. I literally have to use the arrow keys to move each control into place, pixel-by-pixel. I don't observe this behavior anywhere else in VS2005, nor do I observe it in the OS in general.</p>
<p>I am running on Windows XP inside a Parallels Virtual Machine, hosted on OS X. I don't think there is a driver problem though, b/c as I already said, no other apps demonstrate anything like this.</p>
<p>Please tell me there is some tiny checkbox buried somewhere that will turn off this behavior.</p>
|
<p>Depends what language you're using, but an IP address is usually stored as a 32-bit unsigned integer, at least at the network layer, making comparisons quite fast. Even if it's not, unless you're designing a high performance packet switching application it's not likely to be a performance bottleneck. Avoid premature optimization - design your program for testability and scalability and if you have performance problems then you can use a profiler to see where the bottlenecks are.</p>
<p>Edit: to clarify, IPv4 addresses are stored as 32-bit integers, plus a netmask (which is not necessary for IP address comparisons). If you're using the newer and currently more rare IPv6, then the addresses will be 128 bits long.</p>
|
<p>if you receive the IP address as a string, comparing it to a string may be more efficient than converting it to integer representation</p>
<p>but i'd profile both solutions to be certain, if a few milliseconds (nanoseconds!) are going to matter on this operation ;-)</p>
| 19,431
|
<p>I am extending Alfresco Web Client and in one page while expanding panels I get this error. I do not get it always.</p>
<pre><code>JSF : java.lang.IllegalStateException: Client-id : _idJsp35 is duplicated in the faces tree in Alfresco Web Client
</code></pre>
<p>I tried to give every component possible unique id, but error still shows up. How can I find source of that error?</p>
|
<p>Whenever I have seen this it has been due to duplicate ids in your JSP.</p>
|
<p>Aren't you better off not specifying ids, and let JSF do the work for you?</p>
| 42,044
|
<p>When I need some complex algorithm I first check if there's anything relevant already published on the Internet. 10 times out of 10 I'll find that someone already have figured out a solution much smarter than what I would have thought of.</p>
<p>Apart from a generic Google search, I use:</p>
<ul>
<li><strong><a href="http://citeseerx.ist.psu.edu/" rel="nofollow noreferrer">Citeseer</a></strong> That has a lot of good theoric reports from Universities</li>
<li><strong><a href="http://www.ddj.com" rel="nofollow noreferrer">Dr Dobb's Portal</a></strong> More practical than Citeseer but very often too specific to a particular technology or language</li>
<li><strong><a href="http://arxiv.org/" rel="nofollow noreferrer">Arxiv</a></strong> Even more theoretic contains draft and pre-prints (just in case I'm desperate :) )</li>
</ul>
<p>I've also found the <strong><a href="http://www.jucs.org/" rel="nofollow noreferrer">J.UCS</a></strong> (Journal of Universal Computer Science) containing some interesting articles (but i've not really used any of the info I found there).</p>
<p>Do you know of any other place where good CS articles can be searched and read for free?</p>
|
<p>Google’s <a href="http://code.google.com/edu/curriculumsearch/" rel="nofollow noreferrer">CS Curriculum Search</a> might be useful. It's a Google web search restricted to the CS departments of universities. It categorises the results into “Lectures”, “Assignments” and “Reference”.</p>
<p>Also <a href="http://www.scholarpedia.org/" rel="nofollow noreferrer">Scholarpedia</a>, which is like Wikipedia but with standards.</p>
|
<p>There are fantastic mathematical libraries around for which you pay modest cost and get the <em>whole</em> library, in executable form, already ported to your platform. NAG - Numerical Algorithms Group, is by far the best well known, but there are others.</p>
| 22,824
|
<p>How would I return multiple values (say, a number and a string) from a user-defined function in SQL Server?</p>
|
<p>Change it to a table-valued function</p>
<p>Please refer to the following <a href="http://technet.microsoft.com/en-us/library/ms191165.aspx" rel="noreferrer">link</a>, for example.</p>
|
<h3>Example of using a stored procedure with multiple out parameters</h3>
<p>As User <code>Mr. Brownstone</code> suggested you can use a <a href="http://msdn.microsoft.com/en-us/library/ms345415.aspx" rel="nofollow noreferrer">stored procedure</a>; to make it easy for all i created a minimalist example. First <a href="http://msdn.microsoft.com/en-us/library/ms187926.aspx" rel="nofollow noreferrer">create a stored procedure</a>:</p>
<pre><code>Create PROCEDURE MultipleOutParameter
@Input int,
@Out1 int OUTPUT,
@Out2 int OUTPUT
AS
BEGIN
Select @Out1 = @Input + 1
Select @Out2 = @Input + 2
Select 'this returns your normal Select-Statement' as Foo
, 'amazing is it not?' as Bar
-- Return can be used to get even more (afaik only int) values
Return(@Out1+@Out2+@Input)
END
</code></pre>
<h3>Calling the stored procedure</h3>
<p>To <a href="http://msdn.microsoft.com/en-us/library/ms189915.aspx" rel="nofollow noreferrer">execute the stored procedure</a> a few <a href="http://msdn.microsoft.com/en-us/library/ms188927.aspx" rel="nofollow noreferrer">local variables</a> are needed to receive the value:</p>
<pre><code>DECLARE @GetReturnResult int, @GetOut1 int, @GetOut2 int
EXEC @GetReturnResult = MultipleOutParameter
@Input = 1,
@Out1 = @GetOut1 OUTPUT,
@Out2 = @GetOut2 OUTPUT
</code></pre>
<p>To see the values content you can do the following</p>
<pre><code>Select @GetReturnResult as ReturnResult, @GetOut1 as Out_1, @GetOut2 as Out_2
</code></pre>
<p>This will be the result:</p>
<p><img src="https://i.stack.imgur.com/fjX9E.png" alt="Result of Stored Procedure Call with multiple out parameters"></p>
| 35,238
|
<p>I'd like to build a query string based on values taken from 5 groups of radio buttons.</p>
<p>Selecting any of the groups is optional so you could pick set A or B or both. How would I build the querystring based on this? I'm using VB.NET 1.1</p>
<p>The asp:Radiobuttonlist control does not like null values so I'm resorting to normal html radio buttons. My question is how do I string up the selected values into a querystring</p>
<p>I have something like this right now:</p>
<p>HTML:</p>
<pre><code><input type="radio" name="apBoat" id="Apb1" value="1" /> detail1
<input type="radio" name="apBoat" id="Apb2" value="2" /> detail2
<input type="radio" name="cBoat" id="Cb1" value="1" /> detail1
<input type="radio" name="cBoat" id="Cb2" value="2" /> detail2
</code></pre>
<p>VB.NET</p>
<pre><code>Public Sub btnSubmit_click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim queryString As String = "nextpage.aspx?"
Dim aBoat, bBoat, cBoat bas String
aBoat = "apb=" & Request("aBoat")
bBoat = "bBoat=" & Request("bBoat")
cBoat = "cBoat=" & Request("cBoat ")
queryString += aBoat & bBoat & cBoat
Response.Redirect(queryString)
End Sub
</code></pre>
<p>Is this the best way to build the query string or should I take a different approach altogether? Appreciate all the help I can get. Thanks much.</p>
|
<p>The easiest way would be to use a non-server-side <form> tag with the method="get" then when the form was submitted you would automatically get the querystring you are after (and don't forget to add <label> tags and associate them with your radio buttons):</p>
<pre><code><form action="..." method="get">
<input type="radio" name="apBoat" id="Apb1" value="1" /> <label for="Apb1">detail1</label>
<input type="radio" name="apBoat" id="Apb2" value="2" /> <label for="Apb2">detail2</label>
<input type="radio" name="cBoat" id="Cb1" value="1" /> <label for="Cb1">detail1</label>
<input type="radio" name="cBoat" id="Cb2" value="2" /> <label for="Cb2">detail2</label>
</form>
</code></pre>
|
<p>You could use StringBuilder instead of creating those three different strings. You can help it out by preallocating about how much memory you need to store your string. You could also use String.Format instead.</p>
<p>If this is all your submit button is doing why make it a .Net page at all and instead just have a GET form go to nextpage.aspx for processing?</p>
| 10,735
|
<p>I'm binding a datatable to a gridview control, and when I format each column I need to format the data based on whether that column has a particular custom attribute. In this case, a column can represent:</p>
<ul>
<li>a text box (in which case I just display the text from the textbox in the gridview), </li>
<li>a checkbox (in which case I display "Checked" or "Unchecked" based on whether the column's underlying data value is 1 or 0), </li>
<li>a radio button (in which case I display "On" or "Off" based on whether the column's underlying data value is 1 or 0).</li>
</ul>
<p>The problem is that the column data types are all strings in the untyped data table being bound to the grid, currently. And the binding uses autoGenerateColumns. So:</p>
<ol>
<li>How do I flag a column as being either a radio, a textbox, or a checkbox?</li>
<li>How do I access that "flag" while binding to the grid to show the text, "Checked/Unchecked", or "On/Off"?</li>
</ol>
<p>I hope I asked this right. Phew!</p>
|
<p>Okay- I added extended properties to the DataTable columns with the proper data type and checked them on the GridView's RowDataBound event in a loop from 1..numColumns:</p>
<p>myProperty=e.Row.DataItem.dataview.table.columns(i).extendedproperties("TYPE")</p>
<p>and set the value (e.Row.Cells(i).Text) based on the type.</p>
|
<p>I'm okay with templatefields; what I don't know is how to add metadata to my datatable columns that I can read during GridView databinding. E.g. when I'm binding to a column that has checkbox data, I want to put the word "Checked" or "Unchecked" in the column, but I need to somehow annotate my data table so it contains the column data type.</p>
| 34,324
|
<p>I'd like to slice and dice large datafiles, up to a gig, in a fairly quick and efficient manner. If I use something like UNIX's "CUT", it's extremely fast, even in a CYGWIN environment. </p>
<p>I've tried developing and benchmarking various Ruby scripts to process these files, and always end up with glacial results. </p>
<p>What would you do in Ruby to make this not so dog slow?</p>
|
<p>This question reminds me of Tim Bray's <a href="http://www.tbray.org/ongoing/When/200x/2007/09/20/Wide-Finder" rel="nofollow noreferrer">Wide Finder project</a>. The fastest way he could read an Apache logfile using Ruby and figure out which articles have been fetched the most was with this script:</p>
<pre><code>counts = {}
counts.default = 0
ARGF.each_line do |line|
if line =~ %r{GET /ongoing/When/\d\d\dx/(\d\d\d\d/\d\d/\d\d/[^ .]+) }
counts[$1] += 1
end
end
keys_by_count = counts.keys.sort { |a, b| counts[b] <=> counts[a] }
keys_by_count[0 .. 9].each do |key|
puts "#{counts[key]}: #{key}"
end
</code></pre>
<blockquote>
<p>It took this code 7½ seconds of CPU, 13½ seconds elapsed, to process a million and change records, a quarter-gig or so, on last year’s 1.67Ghz PowerBook. </p>
</blockquote>
|
<p>I doubt the problem is that ruby is reading the whole file in memory. Look at the memory and disk usage while running the command to verify.</p>
<p>I'd guess the main reason is because cut is written in C and is only doing one thing, so it has probably be compiled down to the very metal. It's probably not doing a lot more than calling the system calls.</p>
<p>However the ruby version is doing many things at once. Calling a method is much slower in ruby than C function calls.</p>
<p>Remember old age and trechery beat youth and skill in unix: <a href="http://ridiculousfish.com/blog/archives/2006/05/30/old-age-and-treachery/" rel="nofollow noreferrer">http://ridiculousfish.com/blog/archives/2006/05/30/old-age-and-treachery/</a></p>
| 15,092
|
<p>I'll try to explain my scenario as best i can;</p>
<p>At each application <em>tick</em> I query the current state of the keyboard and mouse and wrap them in individual classes and data structures. For the keyboard it's an array of my <em>Keys</em> enum (one item for each of the keys that are currently pressed) and for the mouse it's a class containing coordinate delta's and bools for each buttons pressed.</p>
<p>I also have a rudimentary state machine managed via a state manager class which maintains the stack and marshalls the states.</p>
<p>All I want to know is, how best to pass the input (snapshots) to the individual states my app can be in at any one time?</p>
<p>I would like to process as much of the input as possible away from the individual states, so as to reduce repeating logic within the states.</p>
<p>Or would it be better to keep the input snapshots as pure as possible and pass them to the states so they can keep they're input-specific-logic hidden?</p>
<p><strong>Note</strong><br/>
This structure is similiar to how I imagine a game would work, and although this application is not a game it does need to be processed as quickly as possible.</p>
|
<p>Why are you querying the state of the keyboard and mouse with each tick? A much better and traditional solution would be to capture events fired from the keyboard and mouse. That way you only need to update the state when you HAVE to.</p>
|
<p>You should fire events and capture the arguments. That would be the easiest, and most efficient way to handle this.</p>
<pre><code>class YourClass
{
//data members ...
public void OnKeyboardPress(object sender, EventArgs args)
{
//handle your logic capturing the state here
}
}
//elsewhere
someControl.KeyPress += new KeyPressDelegate(yourClassInstance.OnKeyboardPress);
</code></pre>
| 30,119
|
<p>I have a threading issue,</p>
<p>I'm setting the <code>ThreadPool.SetMaxThreads(maxThreads, System.Environment.ProcessorCount)</code> to 10.</p>
<p>But when I check how many are avaliable <code>ThreadPool.GetAvailableThreads()</code> it says there are (maxThreads - 1) so 9, but then goes on to use 10 threads.</p>
<p>Any ideas why this is?</p>
<p>Thanks for the help.</p>
|
<p>In an ideal world, we would have 1 thread/physical core. That way, we would no longer have context switches, which are rather costly operations. But until we have processors with hundreds of cores, that won't be practical. </p>
<p>Anyway, as Marc suggested, you shouldn't mess with the ThreadPool parameters unless you REALLY know what you are doing. The logic behind the .Net implementation of the ThreadPool is rather good, and it can successfully handle most scenarios. </p>
|
<p>One of the threadpool threads is monitoring the wait operations of the other threads in the thread pool. That should explain the maxthreads - 1 result.</p>
<p>I am not sure why it would appear to use all 10 threads then. It might be that it is using 9 for your work, 1 for monitoring and queuing the other.</p>
| 41,455
|
<p>I have a few controls that inherit from <code>ASP.NET buttons</code> and use <code>onserverclick</code>.</p>
<p>If the user clicks twice, the button fires two server side events. How can I prevent this?</p>
<p>I tried setting <code>this.disabled='true'</code> after the click (in the <code>onclick</code> attribute) via javascript, but that blocks the first postback as well.</p>
|
<p>See this example for disabling control on postback. It should help you do what you're trying to achieve.</p>
<p><a href="http://encosia.com/2007/04/17/disable-a-button-control-during-postback/" rel="noreferrer">http://encosia.com/2007/04/17/disable-a-button-control-during-postback/</a></p>
|
<p>You can also try for example btnSave.Enable = false; when the button is hit and before the processing for the button is done in the Click Event routine. If you need it to be reset to allow it to be enabled have a separate button that resets the button for reuse. </p>
<p>Another method is to set the button with verification so that the user is asked if they want to Save, it should pop up both times.</p>
<p>Yet another method would be to flag the first occurrence then set a popup for the second to verify a second or subsequent usage.</p>
| 7,323
|
<p>I've problem with sending HTML mails with <a href="http://phpmailer.worxware.com/index.php?pg=phpmailer" rel="nofollow noreferrer">PHPMailer</a>. I make a <a href="http://en.wikipedia.org/wiki/Smarty" rel="nofollow noreferrer">Smarty</a> template and I got all the HTML code from it. But when I send mail, I got the mail without included CSS (it's only background-color, font or something like that). In PHPMailer I set that the mail is HTML.</p>
<p>Is there any way to send HTML mail with included CSS?</p>
|
<p>There's is a way...</p>
<pre><code> $body = <<< YOUR_HTML_WITH_CSS_STYLE_TAGS
<html>
<head>
<style>
body * {width:1px;}
#adiv {padding:2px;}
.aclass {margin:3px;}
</style>
</head>
<body>
<div>
some html
</div>
<div id="adiv">
<p class="aclass">
</p>
</div>
</body>
</html>
YOUR_HTML_WITH_CSS_STYLE_TAGS;
$doc = new DOMDocument();
@$doc->loadHTML($body);
$xpd = new DOMXPath($doc);
0&&$node = new DOMElement();
$result = $xpd->query('//img');
foreach($result as $node){
$attr = $node->getAttribute('src');
$re = '/(http:\/\/.*?)?(\/.*+)/i';
if(preg_match_all($re, $attr, $matches)){
if(!empty($matches[1][0])&&0)
continue;
$attr = 'http://'.$_SERVER['HTTP_HOST'].$matches[2][0];
}
$node->setAttribute('src',$attr);
}
false&&$node=new DOMElement()&&$child=new DOMElement();
$result = $xpd->query('//style/..');
foreach($result as $node){
foreach($node->childNodes as $child){
if(strtolower($child->nodeName)=='style'){
$node->removeChild($child);
$css = $child->textContent;
$re = '/(.*?)\{([^}]+)\}/';
if(preg_match_all($re, $css, $matches)){
foreach($matches[1] as $idx=>$css_selector){
$css_text = $matches[2][$idx];
$css_text = preg_replace('/\s+/',' ',$css_text);
$css = new CSSQuery($doc);
foreach($css->query($css_selector) as $selected_node){
$style = $selected_node->getAttribute('style');
$selected_node->setAttribute('style', $style?$css_text:$style.';'.$css_text);
}
}
}
}
}
}
$body = $doc->saveHTML();
</code></pre>
<p>That code will generate an HTML output in $body like this:</p>
<pre><code><html>
<head>
</head>
<body>
<div style="width:1px;">
some html
</div>
<div id="adiv" style="width:1px;padding:2px;">
<p class="aclass" style="width:1px;margin:3px;">
</p>
</div>
</body>
</html>
</code></pre>
<p>The <code>CSSQuery</code> class can be found at <a href="http://www.phpclasses.org/" rel="noreferrer">phpclasses.org</a>.
This implementation is based on the fact that most webmails will only allow to add style by an inline tag attribute style and not through style tags or link tags.</p>
<p>It's pretty much limited and with a restricted syntax because of the regular expression it's kind of simple, but it's still better than write by your own the inline style attributes in each HTML tag.</p>
|
<p>How is your stylesheet referenced?</p>
<p>For email you will either have to provide an absolute path to your stylesheet or include the styles in the head of the template</p>
| 46,786
|
<p>On large files (~200+ MB), I get the 503 error when I read the stream.</p>
<pre><code>ftp = (FtpWebRequest)WebRequest.Create(new Uri(address.AbsoluteUri + @"/" + file.Name));
ftp.Credentials = new NetworkCredential(username, password);
ftp.Method = WebRequestMethods.Ftp.DownloadFile;
response = (FtpWebResponse)ftp.GetResponse();
</code></pre>
<p>Any clues on what I'm doing wrong or a better practice for larger files?</p>
|
<p>Do you receive the 503 after every attempt or only subsequent attempts?</p>
<p>Have you tried setting the disabling KeepAlive?</p>
<pre><code>ftp.KeepAlive = false;
</code></pre>
<p>I would try a more rubust ftp client library, a basic free one can be at <a href="http://sourceforge.net/projects/dotnetftpclient/" rel="nofollow noreferrer">sourceforge</a>.</p>
|
<p>In my case, the server (belonging to a client) had been changed to only accept TLS (SSL) requests. They didn't tell us this of course and the 503 error message was not helpful!</p>
<p>So we needed to use <code>.EnableSsl</code> like this:</p>
<pre><code> var ftp = WebRequest.Create(uri) as FtpWebRequest;
if (ftp != null) {
ftp.EnableSsl = true; // <- the new bit
ftp.Credentials = myCredentials;
ftp.KeepAlive = false; // <- you may or may not want this
}
return ftp;
</code></pre>
<p>In order to ignore certificate errors, I also needed to add this: </p>
<pre><code>System.Net.ServicePointManager.ServerCertificateValidationCallback +=
(sender, certificate, chain, sslPolicyErrors) => true;
</code></pre>
<p>It's my understanding that this line has a global effect, so just need to call it when your application starts.</p>
<p>:o)</p>
| 31,467
|
<p>I'm looking at building basic CMS functionality into our web product and am researching tips and design ideas for versioning content. I'm specifically looking for database schemas in use today.</p>
<p>What are you using for content versioning? What patterns apply if you have different types of content that need versions stored? How is question versioning handled on Stack Overflow?</p>
<p>Thanks</p>
|
<p>Literature uses a 5 dimensional model for this:</p>
<ul>
<li>version (wanting to change)</li>
<li>status (life cycle: creating, testing, deploy, retire)</li>
<li>view (html, pdf, file system, derivability)</li>
<li>hierarchy (page, section, paragraph)</li>
<li>variant (largely similar, describing the differences, product families)</li>
</ul>
<p>Most systems only handle a few of these dimensions. To handle all five, you have to describe (fix) your development process.</p>
<p>The reference:</p>
<p><em>Managing design data: the five dimensions of CAD frameworks, configuration management, and product data management.</em><br>
van den Hamer, P. Lepoeter, K.<br>
Philips Res., Eindhoven; </p>
<p>This paper appears in: <em>Proceedings of the IEEE</em><br>
Publication Date: Jan 1996<br>
Volume: 84, Issue: 1<br>
On page(s): 42-56<br>
ISSN: 0018-9219<br>
References Cited: 26<br>
CODEN: IEEPAD<br>
INSPEC Accession Number: 5175049<br>
Digital Object Identifier: 10.1109/5.476025<br>
Current Version Published: 2002-08-06 </p>
|
<p>My gut instinct is that the best thing for this is (in order of bestitude):</p>
<ol>
<li>A ready version control system. <a href="http://en.wikipedia.org/wiki/List_of_revision_control_software" rel="nofollow noreferrer">A nice list here.</a></li>
<li>Storing diffs. <a href="http://en.wikipedia.org/wiki/Diff" rel="nofollow noreferrer">What is a diff here.</a></li>
<li>I guess the obvious database solution of having a "ContentVersion" table, where you have multiple "Versions" per unique "Content".</li>
</ol>
| 34,027
|
<p>I find it annoying that I can't clear a list. In this example:</p>
<pre><code>a = []
a.append(1)
a.append(2)
a = []
</code></pre>
<p>The second time I initialize a to a blank list, it creates a new instance of a list, which is in a different place in memory, so I can't use it to reference the first, not to mention it's inefficient.</p>
<p>The only way I can see of retaining the same pointer is doing something like the following:</p>
<pre><code>for i in range(len(a)):
a.pop()
</code></pre>
<p>This seems pretty long-winded though, is there a better way of solving this?</p>
|
<p>You are looking for:</p>
<pre><code>del L[:]
</code></pre>
|
<p><strong><em>this can help you::)</em></strong></p>
<pre><code>L[:] = []
</code></pre>
| 20,103
|
<p>Found some old code, circa VS 2003. Now I have just VS 2008 (SP1) installed. When I try opening the *.sln file, it tries converting the projects. The report notifies me it was done successfully, but the solution is empty, marked with "project file was unloaded".
VS 2008 doesn't even include opening a *.vcproj file.</p>
<p>Does anyone have any idea how I can convert my solution?</p>
<p>PS: I found several conversion tools that convert from VS 2005 to 2008 and vice versa - no one looks back to 2003 :(</p>
<p>As always, thanks for your assistance and time!</p>
|
<p>I suggest manually converting the project by creating a new proj. If you are having trouble now then there will be no way that you can be certain later by trying some other import method.</p>
<p>On a side note- I am on vs2005 and I often get 2008 projects handed to me. I go into the sln and proj files and rename the version numbers and it works perfectly. Hope that works for you!</p>
|
<p>Maybe you could first convert your solution from VS2003 to VS2005 and then do one more conversion from VS2005 to VS2008 ??? </p>
| 37,302
|
<p>I have no frame of reference in terms of what's considered "fast"; I'd always wondered this but have never found a straight answer...</p>
|
<p>OpenStreetMap seems to have <a href="http://munin.openstreetmap.org/openstreetmap/puff.openstreetmap-lighttpd_accesses.html" rel="noreferrer">10-20 per second</a></p>
<p>Wikipedia seems to be <a href="http://toolserver.org/~leon/stats/reqstats/reqstats-weekly.png" rel="noreferrer">30000 to 70000 per second</a> spread over <a href="http://meta.wikimedia.org/wiki/Wikimedia_servers" rel="noreferrer">300 servers</a> (100 to 200 requests per second per machine, most of which is caches)</p>
<p>Geograph is getting <a href="http://www.geograph.org.uk/statistics.php" rel="noreferrer">7000 images per week</a> (1 upload per 95 seconds)</p>
|
<p>I have a customer that uses our software on a commercial web app servers. The software runs on 40 servers. The software is a 10 year old Java API.</p>
<p>4000 TPS.</p>
| 48,788
|
<p>I'm starting a project that will be public facing using asp.net mvc. I know there are about a billion php, python, and ruby html sanitizers out there, but does anyone have some pointers to anything good in .net? What are your experiences with what is out there? I know stackoverflow is a site done in asp.net that allows freeform HTML, what does it use?</p>
|
<h3><a href="http://www.nuget.org/packages/HtmlSanitizer/" rel="noreferrer">HtmlSanitizer</a></h3>
<p>Source: <a href="https://github.com/mganss/HtmlSanitizer" rel="noreferrer">https://github.com/mganss/HtmlSanitizer</a></p>
<p>A fairly robust sanitizer. It understands and can clean inline styles, but doesn't have a parser that can deal with <style> blocks, so it strips them. It's certainly up to and probably beyond the level that Microsoft's AntiXSS was at, before it was abandoned.</p>
|
<p>We can also use</p>
<p>AntiXss.GetSafeHtmlFragments </p>
<p>sanitize input by parsing the HTML fragment,to use this sanitizer for rich content to ensure that it does not content any harmful script and it is safe to be displayed on the browser.For the text input(not rich content) to use AntiXss.HtmlEncode or any other equivalent html encoder.Here is the Sample for rich content.</p>
<pre><code> string mal = "<IMG NAME = 'myPic' SRC = 'images / myPic.gif' onerror='alert(1)' onerror='alert(1) ><div bottommargin = 150 ondblclick = 'alert('double clicked!')' >< p > Double - click anywhere in the page.</p> </div> ";
var cleanHtml = Sanitizer.GetSafeHtmlFragment(mal);
Console.Write(cleanHtml);
Console.Read();
</code></pre>
<p><strong>Note: Download AntiXSS library fron nugetpackage manager and include this namesapce</strong>
<strong>Microsoft.Security.Application in the souce code</strong>;</p>
| 44,434
|
<p>Looking for a toolkit/SDK for general Blackberry development or application toolkits. Anything like an MVC framework?</p>
|
<p>My understanding is that blackberry's OS is Java ME - based, and that there's a decent development kit for them. I presume you have already <a href="http://na.blackberry.com/eng/developers/" rel="noreferrer">looked over everything here</a>... you can find a lot of information, including the development kit download link. <br />
Regarding model-view-controller, there's no particular framework to my knowledge, but I don't see why you wouldn't be able to take MVC as an approach in the paradigmatic sense. Google has resources out there on java developers working with MVC.</p>
|
<p>I'm not sure exactly what you are looking for beyond the standard SDKs, but you could check out Plazmic's Content Developer Kit:</p>
<p><a href="http://www.plazmic.com/en/index.shtml" rel="nofollow noreferrer">http://www.plazmic.com/en/index.shtml</a></p>
| 24,265
|
<p>Just after a bit of confirmation really:</p>
<p>Does XP SP3 implement the User Interface Privilege Isolation (UIPI) mechanism found in Vista?</p>
<p>Back story for human interest :)
I've recently been handed the C++ source to a fairly large application. Sadly the sole developer of this application, since its inception back in the mid 90's, passed away recently leaving us in a pretty tight spot until we can hire a new developer.</p>
<p>Recently users have reported that the application has randomly stopped working and/or certain features that previously worked don't seem to fire at all "although nothing has changed my end!". The "nothing changed" turned out to be SP3 :)</p>
<p>Knowing this, and although I'm not a C/C++ guy, I thought I'd take a look at the source to see if I could find out anything (having spent a great deal of time looking at firewalls, virus scanners and other external factors).</p>
<p>I traced one error to a call to an Api function, SendMessage, and went to the MSDN docs to take a look. It clearly states <strong>"Microsoft Windows Vista and later. Message sending is subject to User Interface Privilege Isolation (UIPI). The thread of a process can send messages only to message queues of threads in processes of lesser or equal integrity level."</strong> Whilst I'm not 100% sure, this does seem to be a probable cause.</p>
<p>Cheers!</p>
<p>Lenny. </p>
|
<p>No, XP SP3 doesn't implement any of the Vista security changes, at least not any related to the window manager. You don't really give much background to help, but what sort of error do you get that's associated with SendMessage()?</p>
<p>SendMessage() is a very widely used routine that simply dispatches a Windows message to a window, so I'd expect that the error is associated with how the recipient window handles the incoming message (or not) rather than with SendMessage() itself. Rather than thinking of SendMessage() as being just a Windows function, you've got to think of it as a function that will end up calling further application code in whatever application owns the window that you sent the message to - in particular, the return code from SendMessage() tells you how the window's application got on trying to process the message.</p>
|
<p>UIPI doesn't report errors on SendMessage - if you're getting an error returned, then it's something else. And the other commenters are right, UIPI is on Vista only, and you wouldn't get bit by this <em>anyways</em> unless you were trying to send a message to a service, for example.</p>
| 34,244
|
<p>I've been reading some tutorials on how to get started using Rails 2.0.</p>
<p>(Time out: genius website name idea conceived from a typo I just made: "tutoRAILS." Sorry, back to my question.)</p>
<p>In most of the tutorials I've been reading, it seems to encourage using MySQL instead of sqlite3. Is there a reason for this, like, performance-wise or anything? I'm just testing out Rails on my PC using InstantRails at the moment, and they're nice enough to include MySQL in their setup, but I've been making my experimental applications using sqlite3. Am I missing some major caveat of sqlite3, or is this just a general preference that others have for MySQL?</p>
|
<p>SQLite is a good engine, but it's still an <em>in process</em> (or desktop) style engine. In process engines have inherent weaknesses in terms of concurrency that make them a fundamentally poor choice over server-based engines like MySQL for web sites or other scenarios with the potential for a lot of simultaneous write access.</p>
<p>See this page on the SQLite web site:<br>
<a href="http://www.sqlite.org/whentouse.html" rel="nofollow noreferrer">http://www.sqlite.org/whentouse.html</a></p>
<blockquote>
<p>SQLite usually will work great as the database engine for low to medium traffic websites </p>
</blockquote>
<p>and </p>
<blockquote>
<p>if ... you are thinking of splitting the database component off onto a separate machine, then you should definitely consider using an enterprise-class client/server database engine instead of SQLite.</p>
</blockquote>
|
<p>Note that Sqlite is the default engine for the <a href="http://redhanded.hobix.com/bits/campingAMicroframework.html" rel="nofollow noreferrer">Camping</a> framework. Makes sense since both are aimed at small and fast, not big and enterprisey</p>
| 46,564
|
<p>Is there an IDE that I can load on a Blackberry, E71, or an iPhone?</p>
|
<p>Apple released iPhone SDK for XCode a while back, check out developer.apple.com and Nokia also release their own SDK check out forum.nokia.com</p>
<p>But for pure Java Midlet goodness, i would recommend Netbeans (netbeans.org) their netbeans mobile application editor is a gem, second to none.</p>
<p>To answer your question, i don't think any phone is powerful enough to compile and test the code on themselves, so no ...</p>
|
<p>Not that I know of, typically you'll develop apps on a desktop machine (PC/MAC whatever) and download/control the application on the phone. Also I don't think Java is available on a standard (non-cracked) iPhone.</p>
| 6,213
|
<p>i am working on a simple web app which has a user model and role model (among others), and an admin section that contains many controllers. i would like to use a before_filter to check that the user of the user in the session has a 'can_access_admin' flag.</p>
<p>i have this code in the application.rb:</p>
<p>def check_role
@user = session[:user]</p>
<p>if @user.role.can_access_admin.nil? || !@user.role.can_access_admin
render :text => "your current role does not allow access to the administration area."
return
end
end</p>
<p>and then i have this code inside one of the admin controllers:</p>
<p>class Admin::BlogsController < ApplicationController
before_filter :check_role</p>
<p>def list
@blogList = Blog.find(:all)
end
end</p>
<p>and when i try to view the list action i get this error:</p>
<p>undefined method 'role' for user...</p>
<p>anyone know what i have to do to get the role association to be recognized in the application.rb? (note that the associations are configured correctly and the @user.role is working fine everywhere else i've tried to use it)</p>
|
<p>just a guess but it seems that your session[:user] is just storing the id, you need to do:</p>
<pre><code>@user = User.find(session[:user])
</code></pre>
<p>or something along those lines to fetch the user from the database (along with its associations). </p>
<p>It's good to do the above in a before filter too.</p>
|
<p>Is session[:user] holding the user? or the user_id? You may need a lookup before you call .role.</p>
| 17,116
|
<p>The project I am working on were are trying to come up with a solution for having the database and code be agile and be able to be built and deployed together.</p>
<p>Since the application is a combination of code plus the database schema, and database code tables, you can not truly have a full build of the application unless you have a database that is versioned along with the code.</p>
<p>We have not yet been able to come up with a good agile method of doing the database development along with the code in an agile/scrum environment.</p>
<p>Here are some of my requirements:</p>
<ol>
<li>I want to be able to have a svn revision # that corresponds to a complete build of the system.</li>
<li>I do not want to check in binary files into source control for the database.</li>
<li>Developers need to be able to commit code to the continuous integration server and build the entire system and database together.</li>
<li>Must be able to automate deployment to different environments without doing a rebuild other than the original build on the build server.</li>
</ol>
<p>(Update)
I'll add some more info here to explain a bit further.</p>
<p>No OR/M tool, since its a legacy project with a huge amount of code.
I have read the agile database design information, and that process in isolation seems to work, but I am talking about combining it with active code development.</p>
<p>Here are two scenario's</p>
<ol>
<li><p>Developer checks in a code change, that requires a database change. The developer should be able to check in a database change at the same time, so that the automated build doesn't fail.</p></li>
<li><p>Developer checks in a DB change, that should break code. The automated build needs to run and fail.</p></li>
</ol>
<p>The biggest problem is, how do these things synch up. There is no such thing as "checking in a database change". Right now the application of the DB changes is a manual process someone has to do, while code change are constantly being made. They need to be made together and checked together, the build system needs to be able to build the entire system.</p>
<p>(Update 2)
One more add here:</p>
<p>You can't bring down production, you must patch it. Its not acceptable to rebuild the entire production database.</p>
|
<p>You need a build process that constructs the database schema and adds any necessary bootstrapping data. If you're using an O/R tool that supports schema generation, most of that work is done for you. Whatever is not tool-generated, keep in scripts.</p>
<p>For continuous integration, ideally a "build" should include a complete rebuild of the database and a reload of static testing data.</p>
<p>I just saw that you have no ORM tool... here's what we had at a company I used to work for</p>
<pre><code>db/
db/Makefile (run `make` to rebuild db from scratch, `make clean` to close db)
db/01_type.sql
db/02_table.sql
db/03_function.sql
db/04_view.sql
db/05_index.sql
db/06_data.sql
</code></pre>
<p>Arrange however necessary... each of those <code>*.sql</code> scripts would be run in order to generate the structure. Developers each had local copies of the DB, and any DB change was just another code change, nothing special.</p>
<p>If you're working on a project that already has a build process (Java, C, C++), this is second nature. If you're using scripts in such a way that there is no build process at all, this'll be a bit of extra work.</p>
|
<p>Make sure that your O/R-Mapping tool is able to build the necessary tables out of the default configuration it has and also add missing columns. This should cover 90% of your cases.</p>
<p>The other 10% are</p>
<ul>
<li>coping with missing values for columns that where added after the data was inserted</li>
<li>write data-migration scripts for the rare case where you need to do more fundamental changes between versions</li>
</ul>
| 47,574
|
<p>I came across a controller in an older set of code (Rails 1.2.3) that had the following in a controller:</p>
<pre><code>class GenericController > ApplicationController
# filters and such
model :some_model
</code></pre>
<p>Although the name of the model does not match the name of the model, is there any reason to specify this? Or is this something that has disappeared from later versions of Rails?</p>
|
<p>This had to do with dependency injection. I don't recall the details.</p>
<p>By now it's just a glorified <code>require</code>, which you don't need because rails auto-requires files for missing constants.</p>
|
<p>Yes, that is something that has disappeared in later versions of Rails. There is no need to specify it.</p>
| 11,965
|
<p>I can't be sure if my code is sucking, or if it's just that the browsers haven't caught up with the spec yet.</p>
<p>My goal is to simulate list markers using generated content, so as to get e.g. continuation of the counters from list to list in pure CSS.</p>
<p>So the code below, which I <em>think</em> is correct according to <a href="http://www.w3.org/TR/CSS2/generate.html#markers" rel="nofollow noreferrer">the spec</a>, is like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
counter-reset: myCounter;
}
li {
counter-increment: myCounter;
}
li:before {
content: counter(myCounter)". ";
display: marker;
width: 5em;
text-align: right;
marker-offset: 1em;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
<li>The<li>
<li>quick</li>
<li>brown</li>
</ol>
<ol>
<li>fox</li>
<li>jumped</li>
<li>over</li>
</ol></code></pre>
</div>
</div>
</p>
<p>But this doesn't seem to generate markers, in either FF3, Chrome, or IE8 beta 2, and if I recall correctly not Opera either (although I've since uninstalled Opera).</p>
<p>So, does anyone know if markers are <em>supposed</em> to work? Quirksmode.org isn't being its usual helpful self in this regard :(.</p>
|
<p>Apparently marker was introduced as a value in CSS 2 but did not make it to CSS 2.1 because of lacking browser support.
I suppose that didn’t help its popularity …</p>
<p>Source: <a href="http://de.selfhtml.org/css/eigenschaften/positionierung.htm#display" rel="nofollow noreferrer">http://de.selfhtml.org/css/eigenschaften/positionierung.htm#display</a> (German)</p>
|
<p>Oh ouch, did not know that :-|. That probably seals its case, then. Because mostly I was under the assumption that such a basic CSS2 property should definitely be supported in modern browsers, but if it didn't make it into CSS 2.1, then it makes a lot more sense that it isn't.</p>
<p>For future reference, it doesn't show up <a href="http://developer.mozilla.org/en/CSS/display" rel="nofollow noreferrer">in the Mozilla Development Center</a>, so presumably Firefox doesn't support it at all.</p>
<p>Also for future reference, I got my original example to work with <code>inline-block</code> instead:</p>
<pre><code>li:before
{
content: counter(myCounter)". ";
display: inline-block;
width: 2em;
padding-right: 0.3em;
text-align: right;
}
</code></pre>
| 7,289
|
<p>Is there a way of getting all required assemblies (excluding the .net framework) for a .net project into a folder ready to be packaged into an <a href="http://nsis.sourceforge.net/Main_Page" rel="nofollow noreferrer">nsis</a> as setup file?</p>
<p>I've tried writing a small console app that uses reflection to get a list of dlls but have got stuck with finding a foolproof way of determining if a dll is from the .net framework or not.</p>
<p>The answer could be a simple switch in Visual Studio to output all dependencies, or a standalone app that can do it, or a plugin for Nsis, or some information on reflection that I've missed.</p>
|
<p>In Visual Studio (2005 at least - what I'm using right now), each reference that you have associated to a project has a property called "Copy Local", this can be set to true/false. When true it will copy the dll's for you into the current configuration directory.</p>
|
<p><a href="http://www.dependencywalker.com" rel="nofollow noreferrer">Dependency Walker</a> is what you need. Or maybe <a href="http://www.netomatix.com/Development/DependsNet.aspx" rel="nofollow noreferrer">Depends.Net</a></p>
| 7,525
|
<p>I have some products that belongs to the some category.</p>
<p>Each category can have different properties.</p>
<p>For example, </p>
<ul>
<li>category <em>cars</em> has properties <em>color</em>,
power, ... </li>
<li>category <em>pets</em> have properties <em>weight</em>, <em>age</em>, ...</li>
</ul>
<p>Number of categories is about 10-15.
Number of properties in each category is 3-15.
Number of products is very big.</p>
<p>Main requirement for this app is very good search. We will select category, and enter criteria for each property in this category.</p>
<p>Have to design database for this scenario. (SQL Server 2005)</p>
|
<p>The classic design approach would be (the star denotes the primary key column):</p>
<pre><code>Product
ProductId*
CategoryId: FK to Category.CategroyId
Name
Category
CategoryId*
Name
Property
PropertyId*
Name
Type
CategoryProperty
CategoryId*: FK to Category.CategoryId
PropertyId*: FK to Property.PropertyId
ProductProperty
ProductId*: FK to Product.ProductId
PropertyId*: FK to Property.PropertyId
ValueAsString
</code></pre>
<p>If you can live with the fact that every property value would go to the DB as a string and type conversion info is stored in the Property table, this layout would be enough.</p>
<p>The query would go something like this:</p>
<pre><code>SELECT
Product.ProductId,
Product.Name AS ProductName,
Category.CategoryId,
Category.Name AS CategoryName,
Property.PropertyId,
Property.Name AS PropertyName,
Property.Type AS PropertyType,
ProductProperty.ValueAsString
FROM
Product
INNER JOIN Category ON Category.CategoryId = Product.CategoryId
INENR JOIN CategoryProperty ON CategoryProperty.CategoryId = Category.CategoryId
INNER JOIN Property ON Property.PropertyId = CategoryProperty.PropertyId
INNER JOIN ProductProperty ON ProductProperty.PropertyId = Property.PropertyId
AND ProductProperty.ProductId = Product.ProductId
WHERE
Product.ProductId = 1
</code></pre>
<p>The more WHERE conditions you supply (conjunctively, e.g. using AND), the faster the query will be. If you have properly indexed your tables, that is. </p>
<p>As it is, the solution is not ideal for a full text indexing situation. An additional table that stores all the text associated with a ProductId in a more denormalized way could help here. This table would need updating through triggers that listen for changes in the ProductProperty table.</p>
|
<p>If you want to be flexible on your categories and properties, you should create following tables:</p>
<ul>
<li>product: ProductID</li>
<li>category: CategoryID, ProductID</li>
<li>property: PropertyID, CategoryID</li>
</ul>
<p>when you want to share a category over mroe than one product, you have to create a link table for the n:m join:</p>
<ul>
<li>productCategoryPointer: ProdCatID, ProductID, CategoryID.</li>
</ul>
<p>You will have to to some joins in your queries, but with the right indexes, you shoulb be able to query your data fast.</p>
| 27,319
|
<p>Currently Tomcat's login support redirects users back to where they initially were when the application figured out they weren't logged in.</p>
<p>For this particular application I need to force them to always go back to <code>index.jsp</code>.</p>
<p>I'm pretty sure this is a simple configuration option in the WAR's <code>web.xml</code>, but I haven't found the answer in google.</p>
|
<p>A better solution would probably be to use a servlet filter.
You could then check for j_username / j_password, and a successful login and redirect them where you wanted them to go.</p>
|
<p>It's something you can't configure in web.xml as it is not part of the standard. For Tomcat (tested on version 6.0.14) you can force users back to index.jsp by adding the next code on top of your login.jsp. It redirects every request that does not have a parameter with the name 'login' in the url to the /index.jsp?login page. Because the redirect does have the 'login' parameter the user will be presented the login page.</p>
<p>It's not a secure solution. If someone requests for a page and adds the login parameter, he will be redirected. So:</p>
<p>/showPerson?id=1234 will redirect to /index.jsp?login</p>
<p>/showPerson?id=1234?login will NOT redirect to /index.jsp?login</p>
<p>The code that goes on top of your login.jsp:</p>
<pre><code><%
if (request.getParameter("login") == null) {
response.sendRedirect(request.getContextPath() + "/index.jsp?login");
return;
}
%>
</code></pre>
<p>Instead of using the 'login' parameter you probably could use a cookie. You can make it more secure by creating a random value for the login parameter (login=randomvalue) and store the value in the session object for comparison.</p>
| 16,254
|
<p>If I have .Net Form with a component/object such as a textbox that I need to access from a parent or other form I obviously need to "upgrade" the modifier to this component to an Internal or Public level variable.</p>
<p>Now, if I were providing a public variable of an int or string type etc. in my form class I wouldn't think twice about using Getters and (maybe) Setters around this, even if they didn't do anything other than provide direct access to the variable.</p>
<p>However, the VS designer doesn't seem to implement such Getters/Setters for those public objects that are components on a form (and therefore does not comply with good programming practice).</p>
<p>So, the question is; In order to do the "right thing" should I wrap such VS designer components or objects in a Getter and/or Setter?</p>
|
<p>"<em>However, the VS designer doesn't seem to implement such Getters/Setters for those public objects that are components on a form (and therefore does not comply with good programming practice).</em>"</p>
<p>If you mean the controls you're dragging and dropping onto the form, these are marked as private instance members and are added to the form's Controls collection. Why would they be otherwise? A form could have forty or fifty controls, it'd be somewhat unnecessary and unwieldy to provide a getter/setter for every control on the form. The designer leaves it up to you to provide delegated access to specific controls via public getter/setters.</p>
<p>The designer does the right thing here.</p>
|
<p>I always do that, and if you ARE following an MVP design creating getter/setters for your view components would be a design requirement.</p>
<p>I do not understand what you mean by "does not comply with good programming practice". Microsoft violates <em>a lot</em> of good programming practices to make it easier to create stuff on Visual Studio (for the sake of rapid app development) and I do not see the lack of getters/setters for controls as evidence of violating any such best practices.</p>
| 2,785
|
<p>I would like to programatically shutdown a Windows Mobile device using Compact framework 2.0, Windows mobile 5.0 SDK.</p>
<p>Regards,</p>
|
<p>It probably not a great idea to do it from your app - the device has a power button for a reason and shutting down the app can cause user confusion and frustration.</p>
<p>If you must do it, and you are using Windows Mobile 5.0 or later, you can P/Invoke <a href="http://msdn.microsoft.com/en-us/library/bb416523.aspx" rel="nofollow noreferrer">ExitWindowsEx</a> like this:</p>
<pre><code>[Flags]
public enum ExitFlags
{
Reboot = 0x02,
PowerOff = 0x08
}
[DllImport("coredll")]
public static extern int ExitWindowsEx(ExitFlags flags, int reserved);
...
ExitWindowsEx(ExitFlags.PowerOff, 0);
</code></pre>
|
<p>The "normal" Windows API has ExitWindowsEx() function. You might want to check this out.
It appears however that it is <a href="http://www.themssforum.com/Compact/ExitWindowsEx/" rel="nofollow noreferrer">OEM dependant</a>.</p>
| 25,431
|
<p>I know how to set up a local webserver using xampp on windows... I enter my alias and target on the hosts file (c:\windows\system32\drivers\etc\hosts) and then add a respective entry on my apache vhosts config file. This way, assuming that my webserver is listening to port 80, I can for example map <code>example.com</code> to my local webserver.</p>
<p>I've always entered the whole domain name (that is e.g. example.com) in my hosts file and any requests on that name would be directed to localhost.</p>
<p>Now I was wondering if there's a way to <strong>only forward example.com on a certain port</strong> (for example only example.com:8080) to the local webserver, and leave example.com (on the default port 80) alone, so that it would still go to my live production website.</p>
<p>As far as I understand this might not be possible using only the hosts file (I tried adding the port :8080 to my domain names - didn't seem work ;-) )...</p>
<p>I really don't know much on this topic so any ideas, insights, links, reading material, tools are welcome. </p>
<p>Edit:
Arnout's reply answers the question I've asked above but doesn't solve my actual problem. Rerouting example.com:8080 to localhost:80 does work and if I access example.com it loads up the frontpage of my local version, but all links on that page of course don't know about the port number and therefore point to the production version... The actual solution to my problem seems to be to bite into the sour apple and <em>fix</em> my application (following Rob's suggestion) and remove all hardcoded urls, so that it works on any domain...</p>
|
<p>Internet Junkbuster (a proxy server) can do this using its <a href="http://www.junkbuster.com/ijbman.html#o_f" rel="nofollow noreferrer">forwarding</a> functionality.</p>
<p>Just add a line like</p>
<pre><code>example.com:8080 localhost:80 . .
</code></pre>
<p>to <code>sforward.ini</code>, and uncomment the <code>forwardfile</code> line in <code>junkbstr.ini</code>. Now configure your browser to use a proxyserver running at port 8000 of localhost, and you're set.</p>
<p>I'm sure other proxy servers have a similar feature — I just like Junkbuster since it's a simple standalone executable.</p>
|
<p>Can you confirm if 8080 port is listening on webserver? use the command "netstat -na" to see if the port 8080 is listening.</p>
<p>Did you add 8080 port on apache config file as the same as the default 80 port?</p>
<p>Once you add port 8080 on apache config file to make it listen and double check if 8080 port is listening on webserver, then you will be able to access the page using port 8080. like <a href="http://mytestwebserver:8080/index.html" rel="nofollow noreferrer">http://mytestwebserver:8080/index.html</a> or something like this....</p>
| 43,099
|
<p>I'm writing a website in JSP using Struts and Hibernate. I'm looking for a way to implement a rich UI where you can have more than just buttons. For examples, drag and drops, drop down lists that updates itself in real time as you type more letters out etc. Is there a way to use something like Swing with Struts and Hibernate? Or are there any other options available for making a rich UI?? (I'm open to abandon Struts and/or Hibernate if there are better alternatives)</p>
<p><strong>Fundamental problem:</strong> The organization I work for have strict rules about what development tools and open source libraries we can or cannot use, and is pretty slow on updating their approval list. None of the AJAX things (e.g. GWT, dojo) are on the list yet. </p>
<p><em>Thank you for taking the time to read this post!</em></p>
|
<p>As far as I know, there's not going to be a 100% foolproof solution, as not all email clients or gateways preserve or respect all headers.</p>
<p>However, you'll get a pretty high hit rate with the following:</p>
<ul>
<li><p>Every email message should have a unique "Message-ID" field. Find this, and keep a record of it as a part of the case. (See <a href="https://www.rfc-editor.org/rfc/rfc822" rel="nofollow noreferrer">RFC-822</a>)</p>
</li>
<li><p>If you receive two messages with the same Message-ID, discard the second one as it's a duplicate.</p>
</li>
<li><p>Check for the "In-Reply-To" field, if the ID shown matches a known Message-ID then you know the email is related.</p>
</li>
<li><p>The "References" and "Original-Message-ID" headers have similar meanings.</p>
</li>
</ul>
<p>If your system ever generates emails, include a CaseID# in the subject line in a way that you can search for it if you get an email back (eg: [Case#20081114-01]); most people don't edit subject lines when replying.</p>
<p>The internet standards <a href="https://www.rfc-editor.org/rfc/rfc822" rel="nofollow noreferrer">RFC-822</a>, <a href="https://www.rfc-editor.org/rfc/rfc2076" rel="nofollow noreferrer">RFC-2076</a> and <a href="https://www.rfc-editor.org/rfc/rfc4021" rel="nofollow noreferrer">RFC-4021</a> may be useful further reading.</p>
<p>Given that there will always be messages that are missed (for whatever reason), you'll also probably want related features in your case management system - say, "Close as Duplicate Case" or "Merge with Duplicate Case", along with tools to make it easier to find duplicates.</p>
|
<p>As far as I know, there's not going to be a 100% foolproof solution, as not all email clients or gateways preserve or respect all headers.</p>
<p>However, you'll get a pretty high hit rate with the following:</p>
<ul>
<li><p>Every email message should have a unique "Message-ID" field. Find this, and keep a record of it as a part of the case. (See <a href="https://www.rfc-editor.org/rfc/rfc822" rel="nofollow noreferrer">RFC-822</a>)</p>
</li>
<li><p>If you receive two messages with the same Message-ID, discard the second one as it's a duplicate.</p>
</li>
<li><p>Check for the "In-Reply-To" field, if the ID shown matches a known Message-ID then you know the email is related.</p>
</li>
<li><p>The "References" and "Original-Message-ID" headers have similar meanings.</p>
</li>
</ul>
<p>If your system ever generates emails, include a CaseID# in the subject line in a way that you can search for it if you get an email back (eg: [Case#20081114-01]); most people don't edit subject lines when replying.</p>
<p>The internet standards <a href="https://www.rfc-editor.org/rfc/rfc822" rel="nofollow noreferrer">RFC-822</a>, <a href="https://www.rfc-editor.org/rfc/rfc2076" rel="nofollow noreferrer">RFC-2076</a> and <a href="https://www.rfc-editor.org/rfc/rfc4021" rel="nofollow noreferrer">RFC-4021</a> may be useful further reading.</p>
<p>Given that there will always be messages that are missed (for whatever reason), you'll also probably want related features in your case management system - say, "Close as Duplicate Case" or "Merge with Duplicate Case", along with tools to make it easier to find duplicates.</p>
| 36,763
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/255470/what-are-the-different-doctypes-in-html-and-what-do-they-mean">What are the different doctypes in html and what do they mean?</a> </p>
</blockquote>
<p>Being fairly inexperienced with certain aspects of web development (I've always concentrated more on the back-end than the front), can anyone give me their thoughts on whether I should worry about the DOCTYPE declaration made at the beginning of web pages?</p>
<p>Is the most common HTML 4.01 and should I build my web apps to conform to this standard?</p>
|
<p>John Resig (jQuery) <a href="http://ejohn.org/blog/html5-doctype/" rel="nofollow noreferrer">has a say</a> in that matter. Additionally, a DocType helps make MSIE6 <a href="http://msdn.microsoft.com/en-us/library/bb250395.aspx#cssenhancements_topic2" rel="nofollow noreferrer">use the right box model</a>, and it also eases the pain of validating your site (this is a <strong>good</strong> thing for development; think of it as debugging).</p>
|
<p>Disregarding all good practices, the biggest reason people use a DOCTYPE such as XHTML 1.0 Transitional is to switch the CSS box model in IE to be the same as the rest of the browsers. This circumvents much frustration with CSS layout. It is explained here in more detail: <a href="http://css.maxdesign.com.au/listamatic/about-boxmodel.htm" rel="nofollow noreferrer">http://css.maxdesign.com.au/listamatic/about-boxmodel.htm</a></p>
| 33,418
|
<p>In other languages you can use strings as keys -</p>
<p>PHP:</p>
<pre><code>$array['string'] = 50;
$array['anotherstring'] = 150;
</code></pre>
<p>Is this possible in VBA?</p>
|
<p>In VBA you can create a Collection object. Items in the collection can be accessed by index (Long integer) or by a string key.</p>
|
<p>I haven't used VBA in a long time, but those are not arrays, they are <a href="http://www.perl.com/pub/a/2006/11/02/all-about-hashes.html" rel="nofollow noreferrer">hashes</a> (in perl) and <a href="http://www.onlamp.com/pub/a/php/2001/06/21/php_foundations.html" rel="nofollow noreferrer">associative arrays</a> (in PHP). If you are looking for an answer, you might get better results searching for one of those terms and VBA instead of just "array". </p>
<p>As far as I know, there is no native hash table type in VBA, but like I said, it has been a while since I used it, so I may be wrong. </p>
| 41,161
|
<p>I find System.Monitor very confusing, although I understand threading, locks, deadlocks, race conditions, dining philosophers and all that jazz. Normally I use a ManualResetEvent() to do inter-thread co-ordination, but I know that that's a heavyweight kernel object, and that System.Monitor (Enter/Pulse, etc.) is much more efficient. I've Googled and Googled but cannot find a sensible example.</p>
<p>I would be most grateful if the SO crew could explain this potentially wonderful construct to me :-)</p>
|
<p>Here's a very simple example; the call to <code>Wait</code> releases the lock (allowing <code>Worker</code> to obtain it) and adds the <code>Main</code> thread to the lock-object's pending queue. <code>Worker</code> then obtains the lock, and calls <code>Pulse</code>: this moves the <code>Main</code> thread into the lock-object's ready queue. When <code>Worker</code> <em>releases</em> the lock, <code>Main</code> can resume work.</p>
<p>Note that <code>lock(obj) {...}</code> is just compiler-candy for <code>Monitor.Enter</code>/<code>Monitor.Exit</code> in a try/finally block.</p>
<p>[edit: I changed the sample to move <code>lock(sync)</code> earlier, to avoid the (unlikely) risk of a missed Pulse] </p>
<pre><code> static void Main()
{
object sync = new object();
lock (sync)
{
ThreadPool.QueueUserWorkItem(Worker, sync);
Console.WriteLine("Main sleeping");
// wait for the worker to tell us it is ready
Monitor.Wait(sync);
Console.WriteLine("Main woke up!");
}
Console.WriteLine("Press any key...");
Console.ReadKey();
}
static void Worker(object sync)
{
Console.WriteLine("Worker started; about to sleep");
Thread.Sleep(5000);
Console.WriteLine("Worker about pulse");
lock (sync)
{ // notify Main that we did something interesting
Monitor.Pulse(sync);
Console.WriteLine("Worker pulsed; about to release lock");
}
Console.WriteLine("Worker all done");
}
</code></pre>
|
<p>See if <a href="http://pobox.com/~skeet/csharp/threads/deadlocks.shtml" rel="nofollow noreferrer">this part of my threading article</a> helps... (the second half of that page). It implements a producer/consumer queue: when the producer produces something in the queue (and finds it was empty - as an optimisation), it pulses the monitor to wake up any waiting threads. When a consumer tries to consume from the queue but finds it empty, it waits for a pulse before trying again.</p>
<p>Alternatively, <a href="http://www.albahari.com/threading/part4.aspx#_Wait_and_Pulse" rel="nofollow noreferrer">Joe Albahari's threading tutorial</a> has a section on Wait/Pulse too.</p>
<p>It's quite similar to the WaitHandle stuff you're used to - although frankly I find it easier to get my head round than WaitHandles, mostly because it's so similar to the Java wait/notify that I "grew up" with :)</p>
| 28,335
|
<p>Is it possible to create a multithreading application in VC6 with boost library?
If it is possible, what are some relevant tutorials.</p>
|
<p>Yes, I have done this successfully, but with Boost v1.30.0. So if you have trouble with the latest versions of the Boost libraries, you might want to go back a year or five. I recall I started getting all sorts of internal compiler errors, <em>et al.</em>, when trying to upgrade Boost -- so I didn't, but rather went on using v1.30.0 until I was able to upgrade Visual C++ as well. Even the old versions of Boost are very stable and useful, they just have less features.</p>
|
<p>A quick google for "boost thread example" turns up lots of good hits.</p>
| 35,425
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.