instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p><a href="https://stackoverflow.com/questions/20702/whats-youra-good-limit-for-cyclomatic-complexity">This question</a> on <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity" rel="nofollow noreferrer">Cyclomatic Complexity</a> made me think more about <a href="http://en.wikipedia.org/wiki/Static_code_analysis" rel="nofollow noreferrer">static code analysis</a>. Analyzing code complexity and consistency is occasionally useful, and I'd like to start doing it more. What tools do you recommend (per language) for such analysis? <a href="http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis" rel="nofollow noreferrer">Wikipedia</a> has a large list of tools, but which ones have people tried before?</p> <p><strong>Edit:</strong> As David points out, this is not a completely unasked question when it comes to <a href="https://stackoverflow.com/questions/2873/choosing-a-static-code-analysis-tool">C/UNIX based tools</a>.</p>
<p>I have been setting up a Hudson continuous integration (CI) build system for my Objective-C iPhone projects (iOS apps), and have compiled a varied list of tools that can be used to analyze my projects during a build:</p> <ul> <li><p><strong>Clang static analyzer</strong>: free, up-to-date stand-alone tool that catches more issues than the version of Clang included with Xcode 4. Active project. -- visit <a href="http://clang-analyzer.llvm.org" rel="nofollow noreferrer">http://clang-analyzer.llvm.org</a></p></li> <li><p><strong>Doxygen</strong>: free documentation generation tool that also generates class dependency diagrams. Active project -- visit <a href="http://www.doxygen.nl" rel="nofollow noreferrer">http://www.doxygen.nl</a></p></li> <li><p><strong>HFCCA</strong> (header-free cyclomatic complexity analyzer): free Python script to calculate code complexity, but without header files and pre-processors. Supports output in XML format for Hudson/Jenkins builds. Active project. -- visit <a href="http://code.google.com/p/headerfile-free-cyclomatic-complexity-analyzer" rel="nofollow noreferrer">http://code.google.com/p/headerfile-free-cyclomatic-complexity-analyzer</a></p></li> <li><p><strong>CLOC</strong> (count lines of code): free tool to count files, lines of code, comments, and blank lines. Supports diffing, so you can see the differences between builds. Active project. -- visit <a href="http://cloc.sourceforge.net" rel="nofollow noreferrer">http://cloc.sourceforge.net</a></p></li> <li><p><strong>SLOCcount</strong> (source lines of code count): a free tool to count lines of code and estimate the costs and time associated with a project. Does not appear to be active. -- visit <a href="http://sourceforge.net/projects/sloccount" rel="nofollow noreferrer">http://sourceforge.net/projects/sloccount</a> and <a href="http://www.dwheeler.com/sloccount" rel="nofollow noreferrer">http://www.dwheeler.com/sloccount</a></p></li> <li><p><strong>AnalysisTool</strong>: free code analysis tool that measures code complexity and also generates dependency diagrams. Not active. Does not seem to work with Xcode 4, but I would love to get it working. -- visit <a href="http://www.karppinen.fi/analysistool" rel="nofollow noreferrer">http://www.karppinen.fi/analysistool</a></p></li> </ul>
<p>The only time I've ever used one of those tools is Split (C programming language). I thought it was helpful, but I was by no means a power user and I think I barely scratched the surface of what it could do.</p>
4,113
<p>I am working on a silverlight app that you need to enter information into a textbox and then just hit enter. Well there is no onclick event, that I could find, so what I did was use the onkeypressup event and check if it was the enter key that was pressed if so do "blah".</p> <p>It just feels like there is a better way to do this. So the question is, is there?</p>
<p>I thinks that's the way to catch Key.Enter.</p> <p>Also, you're code will be more readable if you use the KeyDown event instead of the KeyUp event.</p> <p>If you only care about catching Key.Enter for a single control then your approach is correct.</p> <p>You can also catch the Key.Enter for a group of related controls by using the KeyDown event of their container ("Event Bubbling").</p>
<p>Well, Im preaty new to Silverlight and I created HitEnter beahaviour for button which have one DependencyProperty Button.</p> <p>And I manulay wire up Button and Behavior (in code behind) and then when enter is hit I inovke the command on the button.</p>
40,331
<p>I need to style a table to have rounded corners.</p> <p>I'm just looking at how best to go about it:</p> <p>Normally when I style a div to have rounded corners, I use 2 divs with empty comments at the top and bottom, and apply sizing &amp; background image CSS to them.</p> <p>The table, however, has internal borders, so I'd have to carefully align the vertical lines in the corner bg images, to match with the true cell borders. </p> <p>Is this clear so far?</p> <p>So I was wondering how others would approach this. I think the best thing I can do is to just use one complete fixed size background image, borders and all, and overlay a borderless table on top. The table will always be the same size after all.</p> <p>Can anyone think of a better way? </p>
<p>You better make a background image with just the corners, and not the borders. Apply a class to the top left, top right, bottom left and bottom right cell, to define that the corners-background image should be used.</p> <p>And style the borders with css. Don't put them in the background image.</p> <p>In your approach, you'll always gonna end up having the vertical lines in your background image not match the borders of the actual table cells.</p>
<p><strike>A better way would be a 9-grid where you have the background corners, and top, bottom, left and right backgrounds repeating</p> <p>Your table goes in cell 5 </strike></p> <h1>Edit</h1> <p>As some posted in the comments you can not achieve the effect with a 9-grid. You have to do a 12-grid-system (made up by me right now :) </p> <h2><a href="http://www.bizcacha.com/public/twelve-grid/roundedtable.htm" rel="nofollow noreferrer">Live demo</a></h2> <p>. </p> <h2>Code:</h2> <p><i>Warning: it's not pretty, but works</i></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style&gt; .cell1 {background: #f8f8f8 url(images/cell1.gif) no-repeat left top; height: 10px; font-size: 1px;} .cell2 {background: #f8f8f8 url(images/cell2.gif) repeat-x top; height: 10px; font-size: 1px; border-right: solid 1px #c3c2c2; font-weight:bold; } .cell3 {background: #f8f8f8 url(images/cell3.gif) no-repeat right top; height: 10px; font-size: 1px;} .cell4 {background: white url(images/cell4.gif) repeat-y left; border-bottom: solid 1px #c3c2c2; width: 13px; } .cell5 {background-color: #f8f8f8; padding: 5px; border-right: solid 1px #c3c2c2; font-weight:bold; border-bottom: solid 1px #c3c2c2; } .cell6 {background: white url(images/cell6.gif) repeat-y right; border-bottom: solid 1px #c3c2c2; width: 18px; } .cell7 {background: white url(images/cell7.gif) repeat-y left; width: 13px;} .cell8 {background-color: white; padding: 5px; border-right: solid 1px #c3c2c2; font-weight:normal; } .cell9 {background: white url(images/cell9.gif) repeat-y right; width: 18px;} .cell10 {background: white url(images/cell10.gif) no-repeat left bottom; height: 17px;font-size: 1px; } .cell11 {background: white url(images/cell11.gif) repeat-x bottom; border-right: solid 1px #c3c2c2; height: 17px; font-size: 1px; } .cell12 {background: white url(images/cell12.gif) no-repeat right bottom; height: 17px;font-size: 1px; } .lastcolumn, th.lastcolumn, td.lastcolumn {border-right: solid 0px #c3c2c2; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;table id="pricing" border="0" cellpadding="0" cellspacing="0"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th class="cell1"&gt;&lt;/th&gt; &lt;th class="cell2"&gt;&amp;nbsp;&lt;/th&gt; &lt;th class="cell2"&gt;&amp;nbsp;&lt;/th&gt; &lt;th class="cell2"&gt;&amp;nbsp;&lt;/th&gt; &lt;th class="cell2"&gt;&amp;nbsp;&lt;/th&gt; &lt;th class="cell2"&gt;&amp;nbsp;&lt;/th&gt; &lt;th class="cell2 lastcolumn"&gt;&amp;nbsp;&lt;/th&gt; &lt;th class="cell3"&gt;&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th class="cell4"&gt;&amp;nbsp;&lt;/th&gt; &lt;th class="cell5"&gt;Incoming calls&lt;/th&gt; &lt;th class="cell5"&gt;National calls&lt;/th&gt; &lt;th class="cell5"&gt;Calls to US &amp;amp; Canada&lt;/th&gt; &lt;th class="cell5"&gt;Calls to other Phones&lt;/th&gt; &lt;th class="cell5"&gt;Calls to other Countries&lt;/th&gt; &lt;th class="cell5 lastcolumn"&gt;SMS text messages&lt;/th&gt; &lt;th class="cell6"&gt;&amp;nbsp;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td class="cell7"&gt;&lt;/td&gt; &lt;td class="cell8"&gt;Select&lt;/td&gt; &lt;td class="cell8"&gt;country&lt;/td&gt; &lt;td class="cell8"&gt;from&lt;/td&gt; &lt;td class="cell8"&gt;dropdown&lt;/td&gt; &lt;td class="cell8"&gt;list&lt;/td&gt; &lt;td class="cell8 lastcolumn"&gt;above&lt;/td&gt; &lt;td class="cell9"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="cell10"&gt;&lt;/td&gt; &lt;td class="cell11"&gt;&amp;nbsp;&lt;/td&gt; &lt;td class="cell11"&gt;&amp;nbsp;&lt;/td&gt; &lt;td class="cell11"&gt;&amp;nbsp;&lt;/td&gt; &lt;td class="cell11"&gt;&amp;nbsp;&lt;/td&gt; &lt;td class="cell11"&gt;&amp;nbsp;&lt;/td&gt; &lt;td class="cell11 lastcolumn"&gt;&amp;nbsp;&lt;/td&gt; &lt;td class="cell12"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><i>Note: there are some non-breaking spaces that SO strips from the code. Check out the living demo for more info</i></p> <p>Enjoy!</p>
36,095
<p>I need to add a tooltip/alt to a "td" element inside of my tables with jquery.</p> <p>Can someone help me out?</p> <p>I tried:</p> <pre><code>var tTip ="Hello world"; $(this).attr("onmouseover", tip(tTip)); </code></pre> <p>where I have verified that I am using the "td" as "this".</p> <p>**Edit:**I am able to capture the "td" element through using the "alert" command and it worked. So for some reason the "tip" function doesn't work. Anyone know why this would be?</p>
<pre><code>$(this).mouseover(function() { tip(tTip); }); </code></pre> <p>a better way might be to put <code>title</code> attributes in your HTML. That way, if someone has javascript turned off, they'll still get a tool tip (albeit not as pretty/flexible as you can do with jQuery).</p> <pre><code>&lt;table id="myTable"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td title="Tip 1"&gt;Cell 1&lt;/td&gt; &lt;td title="Tip 2"&gt;Cell 2&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>and then use this code:</p> <pre><code>$('#myTable td[title]') .hover(function() { showTooltip($(this)); }, function() { hideTooltip(); }) ; function showTooltip($el) { // insert code here to position your tooltip element (which i'll call $tip) $tip.html($el.attr('title')); } function hideTooltip() { $tip.hide(); } </code></pre>
<p>If you really do want to put those tooltips on your table cells and not your table headers--where they'd make much more sense--please consider putting them on the content INSIDE the table cells, where it's much more meaningful.</p>
20,006
<p>I’m getting nothing but jams with a new BCN3D Sigma R19 printer, printing PLA at 195 °C, two brands (BCN’s own brand and Monoprice orange). 6.5 mm retraction, as used in BCN’s PLA profile. Using their fork of Cura. Full enclosure, but it gets maybe to 32 °C inside, just warm. It prints fine for a few layers, then it jams, usually partially-I caught it in the act and the extruder (the Bondtech dual gear Bowden extruder they switched to on this model) would make knocking sounds as it skipped steps, and the plastic under extrudes in spider webs. It would valiantly try to keep going, and just chew up the filament a little, then extrude, then skip, etc.</p> <p>After thinking the problem was the extruder, taking it apart, cleaning, trying a few different tensions on the hobbed gears, my attention shifted to the hotend. I did some cold pulls with nylon, and each time the nylon would come out with this frayed ring of plastic about 15 mm above the cone from the nozzle tip. It’s like it was a separate piece of plastic from the filament, but it seems like it constricts the path. <strong>This ring is about the depth where the heat break screws into the heat block.</strong> I supposed it could have started higher in the cool end and gotten pushed down? I suspect the grooves pressed into the filament by the Bondtech might be prone to hang up on this plastic gunk ring.</p> <p>Their hotend design is all metal, similar to the V6 (and apparently manufactured custom for them by E3D). Different, taller nozzle. It has a 30 mm fan blowing on the fins. There is no shroud on the fan, like the blue thing on the V6. The heat block is halfway up into the enclosed part with the cool end and fan. The fan blows on the heat break and the block.</p> <p>One of my cold pulls shows a little bulge, right about where I think the brass nozzle butts into the heat break steel piece. I’m wondering if there is a gap there that plastic melts into? They do an inconvenient thing where they sell the hotend as a whole piece for $125, and apparently you can’t unscrew the nozzle like a V6, people report the threads get ripped out of the heat block. All to say, it isn’t advised to completely disassemble the hotend.</p> <p>I thought the little fan might not be moving enough air across the cooling fins, so I tried to replace it with a new fan that moves more CFM, but it just screeches, it seems the fan isn’t really driven by 12 V, but maybe a PWM thing at 24 V. It was fine on 12 V DC when I bench tested it.</p> <p>I disassembled the cold end from the heat break, and verified it had thermal paste on the threads.</p> <p>My question is if anyone has experience with the gunk ring? Is my heat break getting cooled down into the heat block, or is heat creep getting up into the cool end? Or is the little gap or chamfer where the heat break meets the nozzle causing clogs? I can work on more cooling (faster fan), or design a shroud for the existing fan so it doesn’t cool the heat break+heater block), to just not sure which.</p> <p><a href="https://i.stack.imgur.com/eVGNx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eVGNx.jpg" alt="enter image description here" /></a></p> <p>EDIT: The filament partially jams (the extruder skips steps an knocks) even without printing, while just loading and purging over empty space, no retractions.</p>
<p>My first thought is heat creep. I've never seen a heatsink on the hot-end that couldn't use more air and a lower temperature. IF not heat creep, then perahps under-temperature.</p> <p>But, since you've worked on this issue without success, and the extruder skipping happens even wit a steady flow and no backpressure against the bed or part, perhaps we should look elsewhere.</p> <p>First thing to check would be the friction of the filament through the Bowden tube, and the attachment points. First, I would back off the extruder pressure, remove the nozzle, and see if you can easily and without jerks or hangups slide fresh filament past the extruder gears all the way through the hot end and out where the nozzle would be. You'll be doing this cold with the printer off. That should feel slick and easy. If you need to push with any significant force, find where the friction is happening and fix it.</p> <p>If it flow smoothly, try checking the extruder motor, the extruder gear, and if it is a dual gear system, check both of them. Try running the extruder (you'll need to hear the hot end) with no filament. Does everything turn easily? Try inserting filament in the extruder, pulling back on the filament, and extruding forward. Is the motion smooth? If not, check the gearing to see if a piece of filament or anything else if interfering with the motion.</p> <p>If you can check the motor current, see if it is running to spec on both coils, in all directions. You could have a problem with one half of one H-bridge.</p> <p>If you have two extruders, does the problem happen with both, or only one?</p> <p>I would still mostly suspect that heat creep, or under-temperature. 195 °C may be a little cool. My Prusa prints PLA at 215 °C. I have had heat creep problems with the Prusa, which I addressed by directing more air through the heat sink fins -- too much was passing around the sides of the heat sink without actually cooling it.</p>
<p>Is this what your hotends look like? <a href="https://i.stack.imgur.com/R6FKi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R6FKi.jpg" alt="enter image description here" /></a></p> <p>They look like Bowden tube extruders. Your images are consistent with heat creek for Bowden tub extruders. Can you print with the enclosure open to see if the problem is at least less?</p> <p>Here is a full discussion on heat creep.<br /> <a href="https://3dprinting.stackexchange.com/questions/15629/what-are-ways-to-avoid-heat-creep">What are ways to avoid heat creep?</a></p>
1,972
<p>The RefEdit control that comes as part of VBA is a little buggy, but it's good for putting on a form when you want people to specify one or more ranges of cells (i.e. <code>Excel.Range</code> objects).</p> <p>The main problem is that you can only use the RefEdit control on a VBA UserForm (<a href="http://support.microsoft.com/kb/q281542/" rel="nofollow noreferrer">Microsoft states this</a>, and my tests confirm it too). I'm making an Excel add-in using <strong>Delphi</strong>, and I'm looking for an <strong>alternative to the RefEdit control</strong>.</p> <p><code>Excel.Application.InputBox Type:=8</code> is one alternative way of selecting a range of cells, but it's not very user-friendly when you need people to select <em>multiple</em> ranges of cells on a single form. The best real alternative I have at the moment is to call a VBA form from my Delphi add-in, but that's far from ideal.</p> <p>So ideally I could do with a <em>drop-in replacement for RefEdit</em> - one that I can use on a Delphi form. If there is one, it's not easy to find (I've been searching pretty hard, and I've not been able to find a drop-in RefEdit replacement for Delphi, VB6, or .NET).</p> <p>Failing a drop-in replacement I might try cobbling together my own alternative, but I suspect it would be difficult if not impossible to make one that works as well as RefEdit. RefEdit lets you "select" cells without actually selecting them: it uses marching ants around the cells that you choose instead of highlighting them and changing the <code>Excel.Application.Selection</code>. I don't know of a way to do that by manipulating the Excel object model through VBA, Delphi, or whatever.</p> <p>Any tips, tricks, hacks, or, if I'm really lucky, pointers to drop-in RefEdit replacements would be most welcome.</p>
<p>I came across <a href="http://www.oraxcel.com/cgi-bin/yabb2/YaBB.pl?num=1208162527" rel="nofollow noreferrer">this RefEdit control replacement</a> when looking for workarounds to RefEdit's bugs. A third party control wasn't an option for me at the time but it might help you out.</p>
<p>Not sure from your question: Have you tried to import RefEdit into Delphi?</p> <p>You can import it as an ActiveX control from RefEdit.dll, then drop a TRefEdit control in any Delphi form. and you have the very same RefEdit as in your VBA apps.</p> <p>Or is it what you tried and it does not work because RefEdit needs some VBA woodoo...?</p>
12,714
<p>I know that the .NET framework looks for referenced DLLs in several locations</p> <ul> <li>Global assembly cache (GAC)</li> <li>Any private paths added to the AppDomain</li> <li>The current directory of the executing assembly</li> </ul> <p>What order are those locations searched? Is the search for a DLL ceased if a match is found or does it continue through all locations (and if so, how are conflicts resolved)?</p> <p><em>Also, please confirm or deny those locations and provide any other locations I have failed to mention.</em></p>
<p>Assembly loading is a rather elaborate process which depends on lots of different factors like configuration files, publisher policies, appdomain settings, CLR hosts, partial or full assembly names, etc.</p> <p>The simple version is that the GAC is first, then the private paths. %PATH% is never used.</p> <p>It is best to use <a href="https://learn.microsoft.com/en-us/dotnet/framework/tools/fuslogvw-exe-assembly-binding-log-viewer" rel="nofollow noreferrer">Assembly Binding Log Viewer (Fuslogvw.exe)</a> to debug any assembly loading problems.</p> <p><strong>EDIT</strong> <a href="https://learn.microsoft.com/en-us/dotnet/framework/deployment/how-the-runtime-locates-assemblies" rel="nofollow noreferrer">How the Runtime Locates Assemblies</a> explains the process in more detail.</p>
<blockquote> <p>No longer is the current directory searched first when loading DLLs! This change was also made in Windows XP SP1. The default behavior now is to look in all the system locations first, then the current directory, and finally any user-defined paths.</p> </blockquote> <p>(ref. <a href="http://weblogs.asp.net/pwilson/archive/2003/06/24/9214.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/pwilson/archive/2003/06/24/9214.aspx</a>)</p> <p>The default search order, which can be changed by the application, is also described on MSDN: <a href="https://learn.microsoft.com/en-gb/windows/win32/dlls/dynamic-link-library-search-order" rel="nofollow noreferrer">Dynamic-Link Library Search Order</a>.</p>
7,261
<p>We're running into performance issues with our implementation of Team Foundation Build Server and I'm running out of ideas on how to speed things up. We've already added a few PropertyGroup elements to increase the performance on several steps (SkipClean, SkipLabel, SkipInitializeWorkspace), but I think we need to undergo a major restructuring to fix things. Here's our setup:</p> <ul> <li>We've got about 40 web applications that are each very different, but run off a bunch of shared assemblies</li> <li>Each of these web applications has their own solution;</li> <li>There are around 10 to 25 shared assemblies referenced by each of these web applications;</li> <li>There exists a build definition containing all the solutions which is fired on each check-in to the trunk;</li> </ul> <p>And here's the basic problems we're encountering</p> <ul> <li>During the build, it will build each shared assembly as many times as it is referenced, rather than building once and using for each app</li> <li>File copy time is reeeeally slow for the drop directory. It has to be over network share and won't take a local path.</li> <li>Every so many builds, one or more of the output files gets "locked" and causes the build to break even if compilation is fine.</li> <li>And another thing - I've also tried separate build definitions, but doing so will also force another workspace to be gotten on Get Latest version. I'd much rather have it be that the build server contains one version of the trunk to build off of.</li> </ul> <p>Over the last several months we've given in to lethargy and ignored this problem, but now the build time is over an hour to an hour and a half.</p> <p>I'm toying around with the idea of learning and switching to Cruise Control for the greater control I'd have. Anyone disagree with that?</p> <p>Any help is most appreciated. Thanks!</p>
<p>First, it sounds as if all of your web apps are contained within the same Team Project. If that's true, split them out into logical groupings. Typically a single Team Project should comprise of a single Deployment model. </p> <p>Second, split the shared assemblies into a their own Team Project. Once moved you have a couple choices, you can branch either the source or the compiled DLLs to the Team Projects that need them. They can have their own unit tests and you can extend team build to automatically merge on a successful test if you are so inclined.</p> <p>To sum up, you need to simplify your build strategy. </p>
<p>Speaking from personal experience on the CruiseControl suggestion - remember it's a continuous integration "framework". It won't solve all your problems out of the box (componentized builds, firing on each component change, and serialized builds though will make things a lot better). It'll take quite some configuration (and maybe even customization) to get things how you want, so be prepared to invest some time. Of course, you'll reap a massive payoff in the long run if your build time gets right down - if you can't ignore the problem any more, it's worth investing some time on a better CI solution.</p> <p>Be aware though that any CI effort is only as good as the policies you have in place. We had huge policy voids when it came to version labeling, releasing, dependencies, beta releases of binaries, archiving builds... and many other issues that we didn't even consider at the time.</p> <p>Also, be prepared to dedicate at least some resources to maintaining the thing. It's not a full-time job (and I for one love doing it, since it produces continual process improvement). Our customizations have taken us from a 2 hour monolithic build of our first product to over 400 components in 20 products that build in parallel on multiple machines within about 20 minutes, so it's well worth it.</p>
38,001
<p>I have a set of data that models a hierarchy of categories. A root category contains a set of top-level categories. Each top-level category contains a set of sub-categories.</p> <p>Each sub category has a set of organizations. A given organization can appear in multiple sub categories. </p> <p>The leaf nodes of this hierarchy are organizations. An organization can potentially appear in multiple sub-categories.</p> <p>The data is stored in three SQL tables:</p> <pre><code>organizations organization_id organization_name 1 Org A 2 Org B 3 Org C 4 Org D 5 Org E 6 Org F categories category_id parent_id category_name 0 NULL Top Level Category 1 0 First Category 2 0 Second Category 3 1 Sub Category A 4 1 Sub Category B 5 1 Sub Category C 6 2 Sub Category D organizations_categories -- Maps organizations to sub_categories organization_id category_id 1 3 2 3 2 6 3 4 4 4 5 4 6 5 6 4 7 6 8 6 </code></pre> <p>I would like to be able to select a list of all unique organizations under a given category or sub-category. </p> <p>The way I'm doing it right now involves first figuring out which sub categories have been requested and then looping through each sub_category in code and performing a select to get all organizations mapped to that category. The results of each select are appended to an array. This array contains duplicates whenever an organization appears in multiple sub categories.</p> <p>I would love to replace this kludge with a query that can efficiently select a list of distinct organizations given an id of one of the categories in the hierarchy.</p> <p>I am devloping this solution using PHP and MySQL.</p> <p>Thanks for your time and suggestions.</p>
<p>Assuming that your hierarchy is always exactly 3 levels deep:</p> <pre><code>SELECT DISTINCT O.organization_id, O.organization_name FROM Categories CAT INNER JOIN Categories SUB ON SUB.parent_id = CAT.category_id INNER JOIN Category_Organizations CO ON CO.category_id = SUB.category_id INNER JOIN Organizations O ON O.organization_id = CO.organization_id WHERE CAT.category_id = @category_id </code></pre> <p>You can modify that by one level to allow you to pass a sub category id. If you don't know at the time whether or not you have a category id or a sub category id then you can do the following:</p> <pre><code>SELECT DISTINCT O.organization_id, O.organization_name FROM Categories CAT LEFT OUTER JOIN Categories SUB ON SUB.parent_id = CAT.category_id INNER JOIN Category_Organizations CO ON CO.category_id IN (CAT.category_id, SUB.category_id) INNER JOIN Organizations O ON O.organization_id = CO.organization_id WHERE CAT.category_id = @category_id </code></pre> <p>If your hierarchy may have an unknown number of levels (or you think it might in the future) then check out <a href="https://rads.stackoverflow.com/amzn/click/com/1558609202" rel="nofollow noreferrer" rel="nofollow noreferrer">Joe Celko's Trees and Hierarchies in SQL for Smarties</a> for alternative ways to model a hierarchy. It's probably a good idea to do that anyway.</p>
<p>Not sure if your data model will allow it, but you can use a single index column and a Binary Tree to easily store this information in a single 'OrganizationTree' table. Also has the benefit you use a single query with no modifications to search at the category, subcategory, or organization levels (E.g. give me all results of X subcategory)</p> <p>Hope this helps.</p> <p>Adam.</p>
49,592
<p>Ok guys any idea how i may go about creating an answers file for an unattended install for say WinAmp?</p> <p>So far all my research points to is doing an unattended install for windows or some other OS. What I want to do is create an unattended install for a 3rd party software. Are there tools to do this? Or is unattended install for 3rd party software just a pipe dream?</p>
<p>The term you should be googling is "silent install" rather than "unattended install".</p> <p>Most likely you're looking for MSI based installation which can be silently installed by</p> <pre><code>MSIEXEC /I file.msi /QUIET </code></pre> <p>For non-MSI installs, you can either repackage them or follow the documentation for the specific product.</p> <p>Virtually any software company will be able to provide you with the instructions for unattended installations of their product, best practice would suggest contact the vendor first before trying your own approach. Your "homegrown" solution might not be tested or supported and may provide problems down the track.</p> <p>Last for WinAmp I'm not sure about silent installs of this, I think they use a non-MSI format so my instructions won't help much :)</p>
<p>AFAIK, it's just a pipe dream for software that doesn't provide you with a mechanism in the installer to do one. </p> <p>If you have a macro utility, you could record the mouse and key presses you want for the install and automate it that way though. Try <a href="http://www.google.co.uk/search?q=macro+tools" rel="nofollow noreferrer">some of these</a></p>
38,158
<p>In a C# windows forms application. I have a splash screen with some multi-threaded processes happening in the background. What I would like to do is when I display the splash screen initially, I would like to have it appear to "fade in". And then, once all the processes finish, I would like it to appear as though the splash screen is "fading out". I'm using C# and .NET 2.0. Thanks.</p>
<p>You could use a timer to modify the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.form.opacity(VS.80).aspx" rel="noreferrer">Form.Opacity level</a>.</p>
<p>You can use the Opacity property for the form to alter the fade (between 0.0 and 1.0).</p>
10,976
<p>Are pipes considered dangerous to use in Windows, from a security standpoint?</p>
<p>Pipes aren't a particular security risk in Windows. If you're worried about security, make sure you set the security descriptor on the pipe to an appropriate DACL. If your usage requires that the pipe is open for anyone to connect to, then you have to treat the incoming data as suspicious, just like any file or network input.</p>
<p>If you are concerned about network sniffing, I suppose they could be since I don't think that pipes between systems are encrypted. I don't know exactly how they are implemented in Windows, but I would expect that pipes between processes/threads on the same machine would be implemented with shared memory and not let traffic leak outside the box. If you need secure communication between systems, I'd go with secure sockets.</p>
28,991
<p>I have a master page with a search box and button at the top. This search functionality is taking over the "enter" key for all my web forms that use this master page. That is, if I have a login page that uses this master page and the user enters in their username/password and hits "enter", instead of logging in the user the system performs a search.</p> <p>What's the best way to set up the default submit buttons. I could wrap everything in asp Panels and set the DefaultButton property, but that seems a bit tedious. Is there a better way?</p>
<p>use defaultbutton property of form or panel</p> <pre><code>&lt;form defaultbutton=“button1” runat=“server”&gt; &lt;asp:button id=“button1” text=“Same Page” runat=“server”/&gt; &lt;asp:panel defaultbutton=“button2” runat=“server”&gt; &lt;asp:textbox id=“foo” runat=“server”/&gt; &lt;asp:button id=“button2” runat=“server”/&gt; &lt;/asp:panel&gt; &lt;/form&gt; </code></pre>
<p>set focus on the text box ,</p> <p>Page.RegisterStartupScript("SetFocus", "&lt; script >document.getElementById('" + TextBox1.ClientID + "').focus();&lt; /script >");</p> <p>and then</p> <p>In the keydown event for the last textbox you can do something like this:</p> <p>If e.KeyCode = Keys.Enter Then Me.Button1.Select() End If</p>
43,173
<p>I would like to handle an OracleException thrown when my network/database connection is interrupted, where can I find out what error codes I might can receive?</p> <p>I guess since we are talking about a connection interruption these would be technically TNS errors such as ORA-12560 "TNS:protocol adapter error." But I have noticed a couple others depending on where exactly the connection is lost and would like to get a full list.</p>
<p>Take a look at <a href="http://download.oracle.com/docs/cd/B28359_01/server.111/b28278/toc.htm" rel="nofollow noreferrer">Oracle Database Error Messages 11g Release 1 (11.1)</a>. And here are the <a href="http://www.oracle.com/pls/db111/search?remark=quick_search&amp;word=TNS&amp;partno=b28278" rel="nofollow noreferrer">search results for TNS errors</a>.</p>
<p>There's a full list here: <a href="http://ora-code.com" rel="nofollow noreferrer">http://ora-code.com</a></p> <p>But note that some of them, like "TNS:protocol adapter error", can actually mean many different things.</p>
19,317
<p>What's the best way to protect system integrity while running possibly malicious third party executables?</p> <p>I would like to allow a program to be able to store some information for its own use during execution, but disallow access to the network and to devices, and of course to other users' data and the overall system.</p> <p>A few constraints: 1. This needs to be able to run on Windows. 2. I can't restrict the language (e.g. "just use Java"). 3. It needs to have native, or near-native performance. 4. Ideally it should be able to run in the background as a service.</p> <p>Can I simply use a restricted-privilege windows user? Would it be safe?</p> <p>Do I have to use a virtualization environment? Are there any free ones?</p> <p>Other ideas?</p>
<p><a href="http://www.sandboxie.com/" rel="noreferrer">Sandboxie</a> could be a first solution. Very easy.</p> <p>Setting up a restricted account can work too. But you still have to be aware of some problems depending on what you use.</p> <p>VM's are also quite rapid nowadays.</p>
<p>Although not a perfect solution for what you are getting to I have a few options that I have used in the past.</p> <p>1.) Use a virtual environment. I personally prefer VMWare after using it for a whiel ($189) as it works well and just easy to work with. THis at least isolates the application into a test bed that you can use to evaulate it, and see if it does anything bad.</p> <p>2.) Use a limited account in vista or others, this will at least prevent it from getting access to critical files, however, it isn't foolpoof!</p> <p><strong>edit</strong></p> <p>I'll also second the recommendation that if you are really scared, DO NOT put the VM on your network.</p>
44,451
<p>I'm using C# and i have written a locally installed application that dynamically generates files which need to be on an FTP server.</p> <p>Do i generate them to disk then upload them to the FTP server? or is there a way to open a stream to an FTP server and write the files directly?</p>
<p>Check the code sample I gave in this answer, doesn't rely on writing to files. It's not SQL specific and was just a suggestion on how to use SQL CLR integration assemblies to upload output from sql queries to an FTP server. The for loop in the method is just to demonstrate writing to the FTP stream. You should be able to rework to you needs:</p> <p><a href="https://stackoverflow.com/questions/20587/execute-stored-procedure-sql-2005-and-place-results-into-a-csv-file-on-a-ftp-lo#20689">How to write stored procedure output directly to a file on an FTP without using local or temp files?</a></p>
<p>Since you are using c# I'm thinking maybe you are in a Windows Env. Something I know little about :)</p> <p>If you are dealing with a unix env, you could just pipe your output thru SSH, which would also take care of encryption overhead.</p>
17,685
<p>How can I close a browser window without receiving the <em>Do you want to close this window</em> prompt?</p> <p>The prompt occurs when I use the <code>window.close();</code> function.</p>
<p>My friend... there is a way but "hack" does not begin to describe it. You have to basically exploit a bug in IE 6 &amp; 7. </p> <p>Works every time!</p> <p>Instead of calling <code>window.close()</code>, redirect to another page. </p> <p>Opening Page:</p> <pre><code>alert("No whammies!"); window.open("closer.htm", '_self'); </code></pre> <p>Redirect to another page. This fools IE into letting you close the browser on this page. </p> <p>Closing Page:</p> <pre><code>&lt;script type="text/javascript"&gt; window.close(); &lt;/script&gt; </code></pre> <p>Awesome huh?!</p>
<p>The best solution I have found is:</p> <pre><code>this.focus(); self.opener=this; self.close(); </code></pre>
8,227
<p>I'm using a Delphi 2009 VCL TProgressBar as a kind of "empty/full" gauge.</p> <p>On Vista, with Aero theme enabled, this has an animation associated with it, which is annoying and inappropriate for an gauge.</p> <p>Is there any way of disabling this (NOT by adjusting user's theme settings!) to prevent the animation on this control?</p> <p>To clarify, I want something basically identical to the 'disk space used' meters in Windows Explorer. No animation, but still with a nice border and shading effects.</p> <p>Update:</p> <p>I understand that I need a "meter", rather than a true progress bar. How can a themed meter be implemented using the standard windows progress bar control?</p>
<p>As per the <a href="http://msdn.microsoft.com/en-us/library/aa511486.aspx" rel="noreferrer">Vista UI guidelines for progress bars</a> you should not be using a TProgressBar for such purposes at all, it states:</p> <blockquote> <p>Use progress bars only for progress. Use meters to indicate percentages that aren't related to progress.</p> </blockquote> <p>There are a lot of Third-Party components (for example <a href="http://www.abaecker.biz/" rel="noreferrer">Abakus VCL</a>) that are aimed at Process Automation applications and the like, maybe you could use one of these controls instead?</p>
<p>Have a look at <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1127776&amp;SiteID=1" rel="nofollow noreferrer">this forum thread</a>. It is the only promising link I found, and the first posting mentions the different progress bar states, so changing the properties Smooth, State and Style will probably not help.</p> <p>If the the tip in the last posting is indeed the only way to draw the progress bar in meter style, then your best option is to create a descendent class of TProgressBar, override the WM_PAINT handler, check for Vista and enabled themes, and in that case use the functions in UxTheme to paint the different parts of the control.</p>
40,462
<p>Help with using the xapian php wrapper.</p> <p>I have a couple of custom exception handlers for different categories of errors (I'm thinking of seperating them out more).<br> Xapian handles errors by throwing standard Exception objects. I would like to use a custom exception handler for these though. How do I go about using a custom exception for a standard Exception that has already been thrown? Or any other ideas, perhaps how to get Xapian to throw some other exception type?</p>
<p>the kludgy way: wrap every xapian API call in try..catch blocks, and throw more specific custom exceptions in the catch clause.</p> <p>or the hackish way: modify the source of the xapian php extension (which i assume is written in C?) to throw custom exceptions (that you would also have to define in the extension source)</p>
<p>Catch the generic exceptions from Xapian, figure out what they are, then throw more specific expections.</p> <p>Or...if you'd like Xapian to behave differently than it currently does, well, it <em>is</em> an open source project. You know what to do. :)</p>
40,219
<p>In my application I need to temporarily gray out the minimize button of the main form. Any ideas how this can be achieved? I don't mind doing p/invokes to Win32 dlls.</p> <p>Edit: Graying out the minimize button would be the preferred solution, but is there any other way of preventing the form from becoming minimized?</p>
<p>I read your comment in regards to my response and was able to drum up a more complete solution for you. I ran this quickly and it seemed to have the behavior that you wanted. Instead of deriving your winforms from Form, derive from this class:</p> <pre><code> using System; using System.Windows.Forms; using System.ComponentModel; namespace NoMinimizeTest { public class MinimizeControlForm : Form { private const int WM_SYSCOMMAND = 0x0112; private const int SC_MINIMIZE = 0xf020; protected MinimizeControlForm() { AllowMinimize = true; } protected override void WndProc(ref Message m) { if (!AllowMinimize) { if (m.Msg == WM_SYSCOMMAND) { if (m.WParam.ToInt32() == SC_MINIMIZE) { m.Result = IntPtr.Zero; return; } } } base.WndProc(ref m); } [Browsable(true)] [Category("Behavior")] [Description("Specifies whether to allow the window to minimize when the minimize button and command are enabled.")] [DefaultValue(true)] public bool AllowMinimize { get; set; } } } </code></pre> <p>You could do a bit more if you wanted to be able to decide whether to allow minimizing at the time the click is sent, for instance:</p> <pre><code> using System; using System.Windows.Forms; using System.ComponentModel; namespace NoMinimizeTest { public class MinimizeControlForm : Form { private const int WM_SYSCOMMAND = 0x0112; private const int SC_MINIMIZE = 0xf020; protected MinimizeControlForm() { } protected override void WndProc(ref Message m) { if (m.Msg == WM_SYSCOMMAND) { if (m.WParam.ToInt32() == SC_MINIMIZE && !CheckMinimizingAllowed()) { m.Result = IntPtr.Zero; return; } } base.WndProc(ref m); } private bool CheckMinimizingAllowed() { CancelEventArgs args = new CancelEventArgs(false); OnMinimizing(args); return !args.Cancel; } [Browsable(true)] [Category("Behavior")] [Description("Allows a listener to prevent a window from being minimized.")] public event CancelEventHandler Minimizing; protected virtual void OnMinimizing(CancelEventArgs e) { if (Minimizing != null) Minimizing(this, e); } } } </code></pre> <p>For more information about this window notification, see the <a href="http://msdn.microsoft.com/en-us/library/ms646360(VS.85).aspx" rel="noreferrer" title="WM_SYSCOMMAND Notification">MSDN article about it</a>.</p>
<p>You can also implement handle to the Minimize event to cancel the command</p>
41,255
<p>do you know any good algorithms that match two strings and then return a percentage in how many percent those two strings match?</p> <p>And are there some, that work with databases too?</p>
<p>The <a href="http://en.wikipedia.org/wiki/Levenshtein_distance" rel="noreferrer">Levenstein distance</a> is such a measure. It basically tells you how many characters need to be edited, deleted or added, to get from the first to the second string. I'm not sure whether some database systems support that.</p> <p>But I know for sure that a much more simplified algorithm named <a href="http://en.wikipedia.org/wiki/Soundex" rel="noreferrer">Soundex</a> is supported in some database systems.</p>
<p>Would this be of help? I just ran into it. <a href="https://stackoverflow.com/questions/188476/comparing-two-strings-producing-a-numeric-delta">Comparing Two Strings producing a numeric delta</a></p>
45,845
<p>I'm generating a coupon based on dynamic input and a cropped image, and I'm displaying the coupon using ntml and css right now, the problem is, printing this has become an issue because of how backgrounds disappear when printing and other problems, so I think the best solution would be to be able to generate an image based on the html, or set up some kind of template that takes in strings and an image, and generates an image using the image fed in as a background and puts the coupon information on top.</p> <p>Is there anything that does this already?</p> <p>This is for an ASP.NET 3.5 C# website!</p> <p>Thanks in advance.</p> <p>edit: It'd be great if the output could be based on the HTML input, as the coupon is designed by manipulating the DOM using jQuery and dragging stuff around, it all works fine, it's just when it comes to the printing (to paper) it has z-indexing issues.</p>
<p>What you can do is create an aspx page that changes the response type to be in the format you want and then put the image into the stream. I created a barcode generator that does a similar thing. Excluding all the formalities of generating the image, you'll Page_Load will look something like this:</p> <pre><code>Bitmap FinalBitmap = new Bitmap(); MemoryStream msStream = new MemoryStream(); strInputParameter == Request.Params("MagicParm").ToString() // Magic code goes here to generate your bitmap image. FinalBitmap.Save(msStream, ImageFormat.Png); Response.Clear(); Response.ContentType = "image/png"; msStream.WriteTo(Response.OutputStream); if ((FinalBitmap != null)) FinalBitmap.Dispose(); </code></pre> <p>and that's it! Then all you have to do in your image is set the URL to be something like RenderImage.aspx?MagicParm=WooHoo or whatever you need. That way you can have it render whatever you want to specify.</p>
<p>There is a very powerful image creation library called <a href="http://www.boutell.com/gd/" rel="nofollow noreferrer">GD</a> which I often use with PHP.</p> <p>I am led to believe there is a wrapper for this library that ASP programmers can use. <a href="http://www.codeproject.com/KB/asp/GDLibraryWrapper.aspx" rel="nofollow noreferrer">Try this</a></p>
43,380
<p>I have this function in my Javascript Code that updates html fields with their new values whenever it is called. The problem cannot be with the function itself because it works brilliantly in every section except for one. Here is the JS function:</p> <pre><code> function updateFields() { document.getElementById('bf').innerHTML = bill.time[breakfast][bill.pointPartOfWeek]; document.getElementById('ln').innerHTML = bill.time[lunch][bill.pointPartOfWeek]; document.getElementById('dn').innerHTML = bill.time[dinner][bill.pointPartOfWeek]; document.getElementById('se').innerHTML = bill.time[special][bill.pointPartOfWeek]; document.getElementById('fdr').innerHTML = bill.time[full][bill.pointPartOfWeek]; document.getElementById('cost').innerHTML = bill.cost; } </code></pre> <p>And it executes fine in the following instance:</p> <pre><code> &lt;select onchange='if(this.selectedIndex == 0) {bill.unholiday();updateFields()} else { bill.holiday();updateFields()}' id='date' name='date'&gt; &lt;option value='else'&gt;Jan. 02 - Nov. 20&lt;/option&gt; &lt;option value='christmas'&gt;Nov. 20 - Jan. 01&lt;/option&gt; &lt;/select&gt; </code></pre> <p>but in this very similar code, the last line of the function doesn't seem to execute (it doesn't update the cost field, but updates everything else)</p> <pre><code> &lt;select onchange='if(this.selectedIndex == 0) {bill.pointPartOfWeek = 1;} else { bill.pointPartOfWeek = 2;}updateFields();alert(updateFields());' id='day' name='day'&gt; &lt;option value='0'&gt;Monday thru Thursday&lt;/option&gt; &lt;option value='1'&gt;Friday, Saturday, or Sunday&lt;/option&gt; &lt;/select&gt; &lt;br /&gt; </code></pre> <p>Strangely enough, the total cost variable itself is updated, but the field that represents the variable is not. If you use another section of the page that wouldn't change the value of the total cost but calls the updateFields function again, the cost field then updates correctly. It must be an issue with the function called. </p> <p>Note: we know that the function executes because it does 5 out of 6 of the things it is supposed to do. This is a strange issue. </p> <p>Edit: The pastebin for the entire page my be helpful. Here it is:</p> <p><a href="http://pastebin.com/f70d584d3" rel="nofollow noreferrer">http://pastebin.com/f70d584d3</a></p>
<p>I'm curious, is it possible that there are actually 2 elements with an id of "cost"? That could, by updating the first one it finds, cause this issue. Different browsers may have different ways of implementing document.getElementById() so you might get even more inconsistent results with different browsers if this is the case.</p> <p>UPDATE: It turns out that you need to call bill.holiday() or bill.unholiday() before calling updateFields() in your second select.</p>
<p>The problem is that the cost property on the billiard object has not been updated when you call updateFields(). You need to call bill.calculate() which updates the cost property.</p>
25,301
<p>I am trying to animate an object, let's say its a car. I want it go from point</p> <p><em>x1,y1,z1</em></p> <p>to point <em>x2,y2,z2</em> . It moves to those points, but it appears to be <em>drifting</em> rather than pointing in the direction of motion. So my question is: how can I solve this issue in my updateframe() event? Could you point me in the direction of some good resources?</p> <p>Thanks.</p>
<p>First off how do you represent the road?</p> <p>I recently done exactly this thing and I used <a href="http://en.wikipedia.org/wiki/Cubic_Hermite_spline" rel="nofollow noreferrer">Catmull-Rom</a> splines for the road. To orient an object and make it follow the spline path you need to interpolate the current <em>x,y,z</em> position from a <em>t</em> that walks along the spline, then orient it along the Frenet Coordinates System or <a href="http://en.wikipedia.org/wiki/Frenet_Frame#Frenet_frame" rel="nofollow noreferrer">Frenet Frame</a> for that particular position.</p> <p>Basically for each point you need 3 vectors: the Tangent, the Normal, and the Binormal. The Tangent will be the actual direction you will like your object (car) to point at.</p> <p>I choose Catmull-Rom because they are easy to deduct the tangents at any point - just make the (vector) difference between 2 other near points to the current one. (Say you are at <em>t</em>, pick <em>t-epsilon</em> and <em>t+epsilon</em> - with epsilon being a small enough constant).</p> <p>For the other 2 vectors, you can use <a href="http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html" rel="nofollow noreferrer">this iterative method</a> - that is you start with a known set of vectors on one end, and you work a new set based on the previous one each <em>updateframe()</em> ).</p>
<p>I think interpolating is giving the drift you are seeing. You need to model the way steering works .. your update function should 1) move the car always in the direction of where it is pointing and 2) turn the car toward the current target .. one should not affect the other so that the turning will happen and complete more rapidly than the arriving. </p>
37,355
<p>I can download a file from Tinkercad as any of these:</p> <pre><code>.STL .OBJ .X3D .VRML </code></pre> <p>Is there a way to convert any of those file types to .DWG?</p>
<p>For designing your part, especially considering the repetitive mathematics involved, I would consider to learn to use OpenSCAD. I've learned the program and it fits your modeling requirement quite well. I feel it's easy to learn and is somewhat easier for folks who have a programming background. I don't have one, but it's still a logical progression to learn this program.</p> <p>Regarding the SLS aspect, that also jumped out at me as a suitable answer. Solid shapes require to have "drain holes" to reduce the amount of powder consumed by the process.</p> <p>I am assembling a Sintratec SLS printer and your model is the sort of thing I would enjoy to create with the printer. I've not yet listed my Sintratec printer on 3dhubs to solicit business, simply because it's not yet a fully assembled printer!</p> <p>I did a quick Google search for "openscad tetrahedral honeycomb" and found this link:</p> <p><a href="http://forum.openscad.org/Beginner-Honeycomb-advice-needed-td4556.html" rel="nofollow noreferrer">http://forum.openscad.org/Beginner-Honeycomb-advice-needed-td4556.html</a></p> <p>The result is more a polygonal honeycomb, not a true 3d tetrahedron, but it's a start. The file that created it is fewer than a few dozen lines of code.</p> <p>The post is old enough that the internal links no longer work but the OP posted his module code and that does work:</p> <p><a href="https://i.stack.imgur.com/rO5Je.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rO5Je.png" alt="enter image description here"></a></p> <p>I'm not sure how personal contact works in stackexchange, but I'd be willing to work with you regarding creating your code and if the printer ever gets assembled, printing out your part.</p> <p><a href="https://i.stack.imgur.com/hohRb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hohRb.png" alt="enter image description here"></a></p> <p>Adding a picture again, to show the latest revision, based on the updated information:</p> <p><a href="https://i.stack.imgur.com/Gna6W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gna6W.png" alt="enter image description here"></a></p>
<p>In short, I don't think printing the full tetrahedral honeycomb design is a good approach considering the application of the part. Here are few things to note when attempting to 3D print the tetrahedral honeycomb:</p> <p>I wouldn't recommend trying to 3D print this with a an FDM/FFF printer as you will most likely need supports and there would not be enough strength laterally. You may be able to <em>print</em> the design using SLA, but handling would be very difficult before post-processing as the part is very brittle post-print until a heat treat or curing process is done to chemically solidify. The post-process of the SLA could determine how strong the part is (ie. stainless steel powder, infused with bronze in a heat treat process would be good for such a part).</p> <p>While SLS may be the best method for 3D printing this type of design, for that size part (30x30x10cm) you're looking at an expensive print regardless of whether or not you print it yourself.</p> <p>Instead, I would highly recommend finding (or designing your own) a joint connector that would allow you to join wood/plastic dowels in the tetrahedral honeycomb shape. Not only will this be cheaper for you in the long run (easier to replace a few broken segments than an entire 3D printed model), but it could provide more structural strength for something that could potentially get banged around, like a tricopter.</p> <p>For example, <a href="http://www.thingiverse.com/thing:176263" rel="nofollow noreferrer">this model</a> on Thingiverse (not my model) shows an example of how you can utilize 3D printing complex or custom joints that allow you to connect dowels in the shape you're looking for. It'd kind of be like building with <a href="https://www.google.com/search?q=k&#39;nex&amp;hl=en&amp;biw=1920&amp;bih=918&amp;site=webhp&amp;source=lnms&amp;tbm=isch&amp;sa=X&amp;ved=0ahUKEwjurNmd2fzLAhVL1mMKHZ9RA44Q_AUIBygC" rel="nofollow noreferrer">K'Nex</a>.</p> <p>As far as designing said joint, you could model a single "inner" joint that has 18 connectors (8 on XY plane, 6 on YZ plane, and 4 on XZ plane). Below is a crude example of what I mean drawn in Google SketchUp: <a href="https://i.stack.imgur.com/dlTMG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dlTMG.png" alt="enter image description here"></a></p>
247
<p>The tiny text entry cursor in the Visual Studio 2005's editor is driving me nuts. I'd ideally like to be able to highlight (say in yellow) the entire line that I'm currently on, but I'll settle for just making the cursor bigger and/or a different colour. Any help gratefully received! </p>
<p><a href="http://www.codekana.com/" rel="nofollow noreferrer">CodeKana</a> allows you to highlight the current line among other nice features. AFAIK Visual Studio has no built-in support for highlighting or otherwise making the current line obvious.</p>
<p>Under Control Panel, Personalization, Choose Mouse Pointers, try different color schemes/pointers for the Text Select cursor, "Windows Inverted (system scheme)" seems to work very well for me.</p> <p>I found this solution here: <a href="http://social.msdn.microsoft.com/forums/en-US/vssetup/thread/3b131a04-9a51-42c9-b69e-73e6e70c15a7" rel="nofollow">http://social.msdn.microsoft.com/forums/en-US/vssetup/thread/3b131a04-9a51-42c9-b69e-73e6e70c15a7</a></p>
20,929
<p>Is there a way to hide the text limit line in netbeans 6.5?</p>
<p>In NetBeans 6.9, setting Right Margin to 0 effectively hides the text limit line.<br> Set the value in Preferences > Editor > Formatting > All Languages > Right Margin.<br> <em>(Mac OS X 10.6.4, NetBeans 6.9)</em></p>
<p>Remember to go to tools, options, fonts &amp; colors, highlighting tab, text limit line selected before exporting ccp.zip....</p>
18,775
<p>How do I set the background colour of items in a list box dynamically? i.e. there is some property on my business object that I'm binding too, so based on some business rules I want the background colour to be different?</p> <pre><code> &lt;ListBox Background="Red"&gt; &lt;ListBox.ItemContainerStyle&gt; &lt;Style TargetType="ListBoxItem"&gt; &lt;Setter Property="Background" Value="Red"/&gt; &lt;/Style&gt; &lt;/ListBox.ItemContainerStyle&gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;StackPanel Orientation="Horizontal" Margin="5"&gt; &lt;TextBlock VerticalAlignment="Bottom" FontFamily="Comic Sans MS" FontSize="12" Width="70" Text="{Binding Name}" /&gt; &lt;TextBlock VerticalAlignment="Bottom" FontFamily="Comic Sans MS" FontSize="12" Width="70" Text="{Binding Age}" /&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; </code></pre> <p>EDIT: It says <a href="http://msdn.microsoft.com/en-us/library/cc189093(VS.95).aspx" rel="nofollow noreferrer">here</a></p> <blockquote> <p>In Silverlight, you must add x:Key attributes to your custom styles and reference them as static resources. Silverlight does not support implicit styles applied using the TargetType attribute value.</p> </blockquote> <p>Does this impact my approach?</p>
<p>Ok - if you need custom logic to determine the background then I would look into building a simple IValueConverter class. You just need to implement the IValueConverter interface and, in its Convert method, change the supplied value into a Brush. </p> <p>Here's a quick post from Sahil Malik that describes IValueConverters - it might help:</p> <p><a href="http://blah.winsmarts.com/2007-3-WPF__DataBinding_to_Calculated_Values--The_IValueConverter_interface.aspx" rel="nofollow noreferrer">http://blah.winsmarts.com/2007-3-WPF__DataBinding_to_Calculated_Values--The_IValueConverter_interface.aspx</a></p>
<p>@Matt Thanks for the reply. I'll look into triggers.</p> <p>My only problem is that, the logic for determining whether a row should be coloured is slightly more involved so I cant just checking a property, so I actually need to run some logic to determine the colour. Any ideas?</p> <p>I guess I could make a UI object with all the relevant fields I need, but I kinda didnt want to take the approach.</p>
18,384
<p>I am working working on the early release of Azure from Microsoft and am not able to write to a memory stream. Keep getting an exception. I fixed the issue by using a different technique to achieve my end goal, however I wanted to know if there is a way to do it. Given that Azure is a shared infrastructure I cannot change the security level.</p>
<p>There shouldn't be any medium trust issues with writing to a MemoryStream. How are you writing to it? What's the exception?</p>
<p>I will try to reproduce it. I was doing it on the dev fabric of window's azure. Simply wanted to serialize an object to memory.</p>
39,515
<p>What is the best way to actively monitor if a .NET Windows service is still running (e.g not hung)? The service needs to periodically respond to events raised by a timer.</p> <p>Thanks</p> <p>Jon</p>
<p>"Not hung" is always a hard condition to definitively detect, and will depend on the details of your service.</p> <p>In general any form of interprocess communication can be used. One simple approach is to create a <strong>named</strong> shared memory mapping and simply write information to it periodically from your service. Another process can monitor the shared memory and see if its state stops changing. </p> <p>The advantage of this approach is that you can extend the shared memory block to include other diagnostics which may help diagnose any issues.</p>
<p>The obvious solution seems to be, check if it's still responding. So add a low-frequency watchdog timer. I don't know where you want to monitor liveliness, but in most places you should be able to read from a named pipe. Then translate the watchdog timer event into a write to the named pipe. If you don't observe reads, you know your service is failing to respond to at least one timer.</p>
26,872
<p>In the latest MVC preview, I'm using this route for a legacy URL:</p> <pre><code>routes.MapRoute( "Legacy-Firefox", // Route name "Firefox-Extension/", // URL with parameters new { controller = "Home", action = "Firefox", id = "" } // Parameter defaults ); </code></pre> <p>The problem is that both of these URL's work: <a href="http://example.com/Firefox-Extension" rel="nofollow noreferrer">http://example.com/Firefox-Extension</a> <a href="http://example.com/Firefox-Extension/" rel="nofollow noreferrer">http://example.com/Firefox-Extension/</a></p> <p>I only want the second to work (for SEO). Also, when I create a link to that page, the routing engine gives me back a URL without a trailing slash.</p> <p>This is the code I'm using to generate the link:</p> <pre><code>&lt;%= Html.ActionLink("Firefox Extension", "Firefox", "Home")%&gt; </code></pre> <p>I believe can fix the first problem by using an HTTP handler to do a 301 redirect to the URL with the trailing slash. However, I want to link to the URL with the trailing slash, and I'm hoping to not have to hard-code the version with the slash.</p> <p>Anyone know how to force the route to use a trailing slash?</p>
<p>When you write your links, you should always include the final slash. I don't know if this applies to the mvc framework (or URL Routing in general), but I know that for static resources, if you don't put the slash in you add a slight overhead as the request gets done twice. </p> <p>The slash immediately identifies the url as pointing to a directory. No need to parse files.</p> <p>Again, I don't believe this applies when you use URL routing, but I haven't looked into it.</p> <p>Check <a href="http://dmiessler.com/study/hyperlink_trailing_slash/" rel="nofollow noreferrer">HERE for an article about the trailing slash</a></p> <p>edit: Upon thinking about this... I think it's probably better to leave off the slash, instead of trying to include it. When you're using url routing, you're using the URL to route directly to a resource. As opposed to pointing to a directory with an index.html or default.aspx, you're pointing to a specific file.</p> <p>I know the difference is subtle, but it may be better to stick to the non-slash for Routed Urls, rather than fight with the framework.</p> <p>Use a trailing slash strictly when you're actually pointing to a directory. Thought I guess you could just append a slash to the end every time if you really didn't like it.</p>
<p>Here a overload for RouteLinkEx(HtmlHelper, string,string, object)</p> <pre><code> public static string RouteLinkEx(this HtmlHelper helper, string text, string routeName, object routeValues) { UrlHelper uh = new UrlHelper(helper.ViewContext.RequestContext); // Add trailing slash to the url of the link string url = uh.RouteUrl(routeName, routeValues) + "/"; TagBuilder builder = new TagBuilder("a") { InnerHtml = !string.IsNullOrEmpty(text) ? HttpUtility.HtmlEncode(text) : string.Empty }; //builder.MergeAttributes(new RouteValueDictionary(htmlAttributes)); builder.MergeAttribute("href", url); return builder.ToString(TagRenderMode.Normal); //--- } </code></pre>
18,645
<p>Using <strong>sc</strong> command we can query, start , stop windows services.<br> For ex: </p> <pre><code>sc query "windows service name" </code></pre> <p>The <strong>sc config</strong> command changes the configuration of the service, but I don't know how to use it. </p> <p>Could someone tell me how we can set the username and password for any windows service?</p>
<p>This works:</p> <pre><code>sc.exe config "[servicename]" obj= "[.\username]" password= "[password]" </code></pre> <p>Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)</p> <p>Just keep in mind that:</p> <ul> <li>The spacing in the above example matters. <code>obj= "foo"</code> is correct; <code>obj="foo"</code> is not.</li> <li>'.' is an alias to the local machine, you can specify a domain there (or your local computer name) if you wish.</li> <li>Passwords aren't validated until the service is started</li> <li>Quote your parameters, as above. You can sometimes get by without quotes, but good luck.</li> </ul>
<p>In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:</p> <pre><code>sc.exe config Service obj= user password= pass </code></pre> <p>Specyfying the .exe extension, PowerShell bypasses the alias lookup.</p> <p>HTH</p>
39,708
<p>I would like to build a regexp in Java that would be passed in a FilenameFilter to filter the files in a dir.</p> <p>The problem is that I can't get the hang of the regexp "mind model" :)</p> <p>This is the regexp that I came up with to select the files that I would like to exclude </p> <p>((ABC|XYZ))+\w*Test.xml</p> <p>What I would like to do is to select all the files that end with Test.xml but do not start with ABC or XYZ.</p> <p>Could you please add any resources that could help me in my battle with regexps.</p> <p>Thanks</p> <p>The following resource explains a lot of things about regexp <a href="http://www.regular-expressions.info/refadv.html" rel="nofollow noreferrer">regular-expressions.info</a></p>
<p>This stuff is easier, faster and more readable without regexes.</p> <pre><code>if (str.endsWith("Test.xml") &amp;&amp; !str.startsWith("ABC")) </code></pre>
<p>This will select files that do not begin in A, B, C, X, Y, or Z, and that end in Test.xml:</p> <p>"[^ABCXYZ].*Test\\.xml\\z"</p> <ul> <li>[^ABCXYZ]: Any character not in the set A, B, C, X, Y, Z.</li> <li>.*: Any character, zero or more times</li> <li>Test: The exact text "Test"</li> <li>\\.: The dot character (need to escape using backslash, and if you're in a string, that backslash needs to be escaped... by a backslash!)</li> <li>xml: The exact text "xml"</li> <li>\\z: The end of the input</li> </ul>
48,016
<p>Currently we are using prototype and jQuery as our js frameworks. Right now, jQuery is set to $j() to prevent conflicts from prototype.</p> <p>In the past, we've used a lot of prototype's Element.down(), Element.next(), and Element.previous() to traverse the DOM. However, I need a simple way to retrieve the last child element. I know i can loop through an array by using Element.childElements() but I would like something inline that reads cleanly and can be pipelined.</p> <p>Just thought I would ask before I go reinventing the wheel. Here's a snippet of code that has lastChild in it that needs to be replaced:</p> <pre><code>_find : function(rows, address) { var obj = null; for (var i=0; i &lt; rows.length &amp;&amp; obj == null; i++) { if (rows[i].down().className == 'b') obj = this._find(rows[i].lastChild.down().down().childElements(), address); else if (rows[i].lastChild.getAttribute('tabAddress') == address) return rows[i].lastChild; } return obj; } </code></pre>
<p>Guys, note that the selector functions return arrays of elements (not single elements), so you must adddress the element in the result array by index: [0].</p> <p>Code in prototype</p> <pre><code>//if you only have the id of the parent var lastChild = $$("#parent :last-child")[0]; //or //if you have the actual DOM element var lastChild = $(element).select(":last-child")[0]; </code></pre> <p>Code in Jquery</p> <pre><code>//if you only have the id of the parent var lastChild = $("#parent :last-child")[0]; //or //if you have the actual DOM element var lastChild = $(":last-child", element)[0]; </code></pre> <p>Code in plain vanilla javascript</p> <pre><code>var element = document.getElementById("parent"); var lastChild = element.childNodes[element.childNodes.length - 1]; </code></pre> <p>Also note that these can return null if the parent element has no child nodes.</p> <ul> <li><a href="http://www.quirksmode.org/css/firstchild.html" rel="noreferrer">Some info on the CSS :last-child selector</a></li> </ul>
<p>In case anyone finds this while searching the web to answer their question, with Prototype you can do:</p> <pre><code>Element.childElements().last(); </code></pre>
28,127
<p>I am looking for a lightweight source control system for use on "hobby" projects with only one person (myself) working on the project. Does anyone have any suggestions? Ideally it should interface with Visual Studio either naively or through another plug-in, outside of that, anything that works would be nice to be replace Gmail as source control.</p>
<p>You can use <a href="http://www.assembla.com/home" rel="nofollow noreferrer">assembla.com</a> to host your project. They offer subversion, git and mercurial hosting. I personally use their subversion hosting for a free and private one-man project. As an added bonus, you also get a wiki and a ticketing system. Which can help you manage your stuff.</p> <p>And the best thing is that you don't have to setup your subversion server and it is hosted off-site.</p> <p>It's really good for a free service. </p> <p>Personnaly, i use <a href="http://tortoisesvn.tigris.org/" rel="nofollow noreferrer">TortoiseSVN</a> as my client but it isn't integrated in visual studio.</p> <p>For the integration, you can try <a href="http://www.visualsvn.com/visualsvn/" rel="nofollow noreferrer">VisualSVN</a> (not free) or <a href="http://ankhsvn.open.collab.net/" rel="nofollow noreferrer">AnkhSVN</a> (free)</p>
<p>i will never use SVN again for a personal project - ya its great compared to CVS, but isn't even in the same class as the modern breed of distributed version control systems. GIT has been mentioned already but a) it has shaky windows support b) complicated learning curve. I now use BZR which "just works".</p> <p><a href="http://bazaar-vcs.org/BzrVsGit" rel="nofollow noreferrer">bzr vs git</a><br> <a href="http://doc.bazaar-vcs.org/latest/en/mini-tutorial/index.html" rel="nofollow noreferrer">bzr in 5 minutes</a></p>
3,753
<p>I'm trying to use the page-break-inside CSS directive, the class of which is to be attached to a div tag or a table tag (I think this may only work on block elements, in which case it would have to be the table).</p> <p>I've tried all the tutorials that supposedly describe exactly how to do this, but nothing works. Is this an issue of browser support or has anyone actually gotten this working, the exact bit of CSS looks like this:</p> <pre><code>@media print { .noPageBreak { page-break-inside : avoid; } } </code></pre>
<p>Safari 1.3 and later (don't know about 4) do <strong>not</strong> support page-break-inside (try it, or see here: <a href="http://reference.sitepoint.com/css/page-break-inside" rel="nofollow noreferrer">http://reference.sitepoint.com/css/page-break-inside</a>). Neither do Firefox 3 or IE7 (don't know about 8).</p> <p>In a practical sense, support for this attribute is SO spotty, it doesn't make sense to use it at all at this point. You'd be lucky if even 10% of your visitors have browsers that can support this.</p> <p>The solution I used was to add</p> <p><code>page-break-after:always</code></p> <p>to certain divs, or add a "page-breaker" div in where you want breaks. This is quite ham-handed, I know, because it doesn't do quite what you want, and causes content to not reach the bottom of the printed page, but unfortunately there isn't a better solution (prove me wrong!).</p> <p>Another approach is to create a stylesheet that removes all extraneous elements (<code>display:none</code>) and causes the main content to flow in one main column. Basically, turn it into a single column, text-only document.</p> <p>Finally, avoid floats and columns when styling for printers, it can make IE (and FF) act wacky.</p>
<blockquote> <p>I'm trying to use the page-break-inside CSS directive, the class of which is to be attached to a div tag or a table tag (I think this may only work on block elements, in which case it would have to be the table).</p> </blockquote> <p>Firstly, there's no need to guess. Just look at <a href="http://www.w3.org/TR/CSS21/page.html#propdef-page-break-inside" rel="nofollow noreferrer">the specification</a>, and you'll see that it does indeed only apply to block-level elements.</p> <p>Secondly, <code>&lt;div&gt;</code> elements are usually block-level elements, so there's no problem applying <code>page-break-inside</code> to a <code>&lt;div&gt;</code> element.</p> <p>Finally, you don't need to wrap it in <code>@media</code>. You only need <code>@media</code> if you want to apply media-independent rules to only one medium, for instance, if you want to use <code>display: block</code> only for one medium. In this case, you don't need to hide those rules from other media, because they'll only apply to paged media anyway.</p>
14,337
<p>I am trying to do something like this:</p> <pre><code>while @nrOfAuthlevels &gt;= @myAuthLevel begin set @myAuthLevel = @myAuthLevel + 1 SELECT Role.name, Role.authorityLevel FROM [dbo].[Role] ORDER BY Role.authorityLevel end </code></pre> <p>The result of this stored procedure shall be a table with all Role.authorityLevel below my own. But this generates several tables.</p>
<p>If you want to keep that current structure, then you would need to insert into a temporary table for every step through the while loop, and outside of that return from the TEMP table.</p> <p>That said, why not just use a <strong>WHERE</strong> clause to get the expected return results:</p> <pre><code>SELECT Role.Name, Role.AuthorityLevel FROM dbo.Role WHERE Role.AuthorityLevel &lt; @MyAuthLevel ORDER BY Role.AuthorityLevel </code></pre>
<p>Create a temp table before the loop and don't select data, but insert data to this temp table:</p> <pre><code>create table #tmp ( Name type, authorityLevel type ) while @nrOfAuthlevels &gt;= @myAuthLevel begin set @myAuthLevel = @myAuthLevel + 1 insert into #tmp values( SELECT Role.name, Role.authorityLevel FROM [dbo].[Role] where ... ) end </code></pre>
32,781
<p>I have the following situation:</p> <p>A user will define a certain filter on a page, and on postback I will query the database using that filter and return a bunch of matching records to the user, each with a checkbox next to it, so he can choose whether to act on each of those records.</p> <p>In Classic ASP / PHP I can generate a lot of controls named "chk__*" and then on postback go through all the $<em>POST entries looking for the ones prefixed "chk</em>".</p> <p>What is the best way to do this in ASP.Net 2.0?</p> <p>I can do it easily by implementing a Repeater with a Template containing the checkbox, bind the Repeater to a Dataset, and then on the second Postback, I just do:</p> <pre><code>For Each it As RepeaterItem In repContacts.Items Dim chkTemp As CheckBox = DirectCast(it.FindControl("cbSelect"), CheckBox) If chkTemp.Checked Then End If Next </code></pre> <p>However this has the <em>slight</em> disadvantage of giving me a HUGE Viewstate, which is really bad because the client will need to re-upload the whole viewstate to the server, and these people will probably be using my site over a crappy connection.</p> <p>Any other ideas? (I can also create the controls dynamically and iterate through Request.Form as in the old days, however, I was looking for a cleaner </p>
<p>Do it the same way you did it in classic ASP. Use &lt;input type="checkbox"&gt; instead of &lt;asp:checkbox&gt;. You can access the raw post paramaters using Request.Form</p>
<p>Disable the ViewState. In case it cannot be done try using <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.sessionpagestatepersister.aspx" rel="nofollow noreferrer">Session to store the view state</a></p>
29,164
<p>We are doing some performance tests on our website and we are getting the following error a lot:</p> <pre><code>*** 'C:\inetpub\foo.plex' log message at: 2008/10/07 13:19:58 DBD::ODBC::st execute failed: [Microsoft][SQL Native Client]String data, right truncation (SQL-22001) at C:\inetpub\foo.plex line 25. </code></pre> <p>Line 25 is the following:</p> <pre><code>SELECT DISTINCT top 20 ZIP_CODE, CITY, STATE FROM Zipcodes WHERE (ZIP_CODE like ?) OR (CITY like ?) ORDER BY ZIP_CODE </code></pre> <p>And lastly, this is perl code.</p> <p>Any ideas?</p> <p><strong>EDIT</strong>: the issue here was that I was searching in the zip file with the string "74523%" which is too long. I ended up just not adding the % if they give five digits.</p>
<p>Either the parameter supplied for <code>ZIP_CODE</code> is larger (in length) than <code>ZIP_CODE</code>s column width or the parameter supplied for <code>CITY</code> is larger (in length) than <code>CITY</code>s column width. </p> <p>It would be interesting to know the values supplied for the two <code>?</code> placeholders.</p>
<p>If the connection is done via PHP, we solved with the connection parameter &quot;CharacterSet&quot;:</p> <pre><code>sqlsrv_connect(DB_PTH_HOST, array( &quot;Database&quot; =&gt; ***, &quot;UID&quot; =&gt; ***, &quot;PWD&quot; =&gt; ***, &quot;CharacterSet&quot; =&gt; &quot;UTF-8&quot;)); </code></pre>
22,187
<p>I am using jQuery. I call a JavaScript function with next html:</p> <pre><code>&lt;li&gt;&lt;span&gt;&lt;a href="javascript:uncheckEl('tagVO-$id')"&gt;$tagname&lt;/a&gt;&lt;/span&gt;&lt;/li&gt; </code></pre> <p>I would like to remove the <code>li</code> element and I thought this would be easy with the <code>$(this)</code> object. This is my JavaScript function:</p> <pre><code>function uncheckEl(id) { $("#"+id+"").attr("checked",""); $("#"+id+"").parent("li").css("color","black"); $(this).parent("li").remove(); // This is not working retrieveItems(); } </code></pre> <p>But <code>$(this)</code> is undefined. Any ideas?</p>
<p>Try something like this (e.g. to hide the <code>&lt;li&gt;</code>):</p> <pre><code>function unCheckEl(id, ref) { (...) $(ref).parent().parent().hide(); // this should be your &lt;li&gt; } </code></pre> <p>And your link:</p> <pre><code>&lt;a href="javascript:uncheckEl('tagVO-$id', \$(this))"&gt; </code></pre> <p><code>$(this)</code> is not present inside your function, because how is it supposed to know where the action is called from? You pass no reference in it, so <code>$(this)</code> could refer to everything but the <code>&lt;a&gt;</code>.</p>
<p>Why not something like:</p> <pre><code>&lt;li id="uncheck_tagVO-$id"&gt;$tagname&lt;/li&gt; </code></pre> <p>and</p> <pre><code>$('li').click( function() { var id = this.id.split("_")[1]; $('#'+id).attr("checked","").parent("li").css("color","black"); $(this).remove(); retrieveItems(); }); </code></pre>
8,530
<p>For some reason I am having troubles with a DBI handle. Basically what happened was that I made a special connect function in a perl module and switched from doing:</p> <pre><code>do 'foo.pl' </code></pre> <p>to</p> <pre><code>use Foo; </code></pre> <p>and then I do</p> <pre><code>$dbh = Foo-&gt;connect; </code></pre> <p>And now for some reason I keep getting the error:</p> <blockquote> <p>Can't locate object method "rollback" via package "Foo" at ../Foo.pm line 171.</p> </blockquote> <p>So the weird thing is that $dbh is definitely not a Foo, it's just defined in foo. Anyway, I haven't had any troubles with it up until now. Any ideas what's up?</p> <p><strong>Edit</strong>: @Axeman: <code>connect</code> did not exist in the original. Before we just had a string that we used like this:</p> <pre><code>do 'foo.pl'; $dbh = DBI-&gt;connect($DBConnectString); </code></pre> <p>and so <code>connect</code> is something like this</p> <pre><code>sub connect { my $dbh = DBI-&gt;connect('blah'); return $dbh; } </code></pre>
<p>From <a href="http://perldoc.perl.org/perlfunc.html#do-EXPR" rel="nofollow noreferrer">perlfunc</a>:</p> <blockquote><pre> do 'stat.pl'; is just like eval `cat stat.pl`; </pre></blockquote> <p>So when you <code>do 'foo.pl'</code>, you execute the code in the current context. Because I don't know what goes on in <code>foo.pl</code> or <code>Foo.pm</code>, I can't tell you what's changed. But, I can tell you that it's always executed in the current context, and now in executes in <code>Foo::</code> namespace. </p> <p>The way you're calling this, you are passing <code>'Foo'</code> as the first parameter to <code>Foo::connect</code> or the returned sub from <code>Foo-&gt;can('connect')</code>. It seems that somehow that's being passed to some code that thinks it's a database handle, and that's telling that object to <code>rollback</code>. </p>
<p>I agree with Axeman. You should probably be calling your function using</p> <pre><code>use Foo; ... $dbh = Foo::connect(); </code></pre> <p>instead of Foo->connect();</p>
24,313
<p>I'd like to use JavaScript to calculate the width of a string. Is this possible without having to use a monospace typeface?</p> <p>If it's not built-in, my only idea is to create a table of widths for each character, but this is pretty unreasonable especially supporting <a href="http://en.wikipedia.org/wiki/Unicode" rel="noreferrer">Unicode</a> and different type sizes (and all browsers for that matter).</p>
<p>Create a DIV styled with the following styles. In your JavaScript, set the font size and attributes that you are trying to measure, put your string in the DIV, then read the current width and height of the DIV. It will stretch to fit the contents and the size will be within a few pixels of the string rendered size.</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-js lang-js prettyprint-override"><code>var fontSize = 12; var test = document.getElementById("Test"); test.style.fontSize = fontSize; var height = (test.clientHeight + 1) + "px"; var width = (test.clientWidth + 1) + "px" console.log(height, width);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#Test { position: absolute; visibility: hidden; height: auto; width: auto; white-space: nowrap; /* Thanks to Herb Caudill comment */ }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="Test"&gt; abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ &lt;/div&gt;</code></pre> </div> </div> </p>
<pre><code>var textWidth = (function (el) { el.style.position = 'absolute'; el.style.top = '-1000px'; document.body.appendChild(el); return function (text) { el.innerHTML = text; return el.clientWidth; }; })(document.createElement('div')); </code></pre>
14,391
<p>From what I have read best practice is to have classes based on an interface and loosely couple the objects, in order to help code re-use and unit test.</p> <p>Is this correct and is it a rule that should always be followed? </p> <p>The reason I ask is I have recently worked on a system with 100’s of very different objects. A few shared common interfaces but most do not and wonder if it should have had an interface mirroring every property and function in those classes?</p> <p>I am using C# and dot net 2.0 however I believe this question would fit many languages. </p>
<p>It's useful for objects which really provide a service - authentication, storage etc. For simple types which don't have any further dependencies, and where there are never going to be any alternative implementations, I think it's okay to use the concrete types.</p> <p>If you go overboard with this kind of thing, you end up spending a <em>lot</em> of time mocking/stubbing everything in the world - which can often end up creating brittle tests.</p>
<p>I agree with kpollock. Interfaces are used to get a common ground for objects. The fact that they can be used in IOC containers and other purposes is an added feature. </p> <p>Let's say you have several types of customer classes that vary slightly but have common properties. In this case it is great to have a <code>ICustomer</code> interface to bound them together, logicaly. By doing that you could create a <code>CustomerHander</code> class/method that handels ICustomer objects the same way instead of creating a handerl method for each variation of customers. </p> <p>This is the strength of interfaces. If you only have a single class that implements an interface, then the interface isn't to much help, it just sits there and does nothing.</p>
45,922
<p>What I'm looking for is a simple timer queue possibly with an external timing source and a poll method (in this way it will be multi-platform). Each enqueued message could be an object implementing a simple interface with a <code>virtual onTimer()</code> member function.</p>
<p><code>Boost::ASIO</code> contains an asynchronous timer implementation. That might work for you. </p>
<p>It doesn't fit all of your criteria, but... I wrote a series of blog posts about a timer queue for windows that is implemented in terms of an external time provider and that is either polled or driven by a thread. The series comes with source code and tests and the point of it was to demonstrate the testing of reasonably complex code. Anyway, you might be able to make use of some of the code or ideas if nobody comes up with a better fit.</p> <p>Articles start here: <a href="http://www.lenholgate.com/archives/000306.html" rel="nofollow noreferrer"><a href="http://www.lenholgate.com/archives/000306.html" rel="nofollow noreferrer">http://www.lenholgate.com/archives/000306.html</a></a></p>
15,447
<p>Does your work environment use Harvest SCM? I've used this now at two different locations and find it appalling. In one situation I wrote a conversion script so I could use CVS locally and then daily import changes to the Harvest system while I was sleeping. The corp was fanatic about using Harvest, despite 80% of the programmers crying for something different. It was needlessly complicated, slow and heavy. It is now a job requirement for me that Harvest is not in use where I work.</p> <p>Has anyone else used Harvest before? What's your experience? As bad as mine? Did you employ other, different workarounds? Why is this product still purchased today?</p>
<p>Chances are, your company has some sort of contract with CA - are you using a lot of other CA software in-house?</p> <p><strong>Edit:</strong> Guess so!</p>
<p>I have been using HARVEST for the last 4 years and i love it. The kind of support it gives you to control the code movement is really fantastic. We use HARVEST to deploy applications on to Websphere. It also do an amazing work in deploying the plugins into the web server along with the application. When you want to have a process in place for moving the code in a big enterprise environment, i don't think any other tool can even come closer to HARVEST.</p>
4,579
<p>Is it possible to catch an recycle event in the global.asax?</p> <p>I know Application_End will be triggered but is there a way to know that it was triggered by a recycle of the application pool?</p> <p>thx, Lieven Cardoen aka Johlero</p>
<p>So, here is an idea how this could work.</p> <p>Based on my <a href="https://stackoverflow.com/questions/294113/iis-recycle-globalasax#294126">previous answer</a> (attach to AppDomain.CurrentDomain.ProcessExit) and <a href="https://stackoverflow.com/users/12702/stephbu">stephbu</a>'s comment:</p> <blockquote> <p>This will trap most structured process teardowns e.g. - but I'm not sure that it will trap all tear downs. e.g. <a href="http://blogs.msdn.com/jmstall/archive/2006/11/26/process-exit-event.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/jmstall/archive/2006/11/26/process-exit-event.aspx</a> Process recycle will kill the process if it seems to be hung - your handler wouldn't get called.</p> </blockquote> <p>I suggest following strategy:</p> <p>In the (regular) ProcessExit handler (which we suppose will not be called on a application pool recycling), write some file to disk like "<code>app_domain_end_ok.tmp</code>".</p> <p>Then in the Application_Start of your global.asax check for this file. If it doesn't exist it is a sign that the application was not terminated in a clean way (or that it is the first time ever it started). Don't forget to delete this file from disk after the check.</p> <p>I didn't try that myself, but it could be worth a try. </p>
<p>I was much more successful with attaching to DomainUnload event, it is triggered on AppPool recycle and stoppage of the AppPool itself.</p> <p><code>AppDomain.CurrentDomain.DomainUnload += this.CurrentDomainOnProcessExit;</code></p>
37,542
<p>The default Python install on OS X 10.5 is 2.5.1 with a FAT 32 bit (Intel and PPC) client. I want to setup apache and mysql to run django. In the past, I have run Apache and MySQL to match this install in 32 bit mode (even stripping out the 64 bit stuff from Apache to make it work).</p> <p>I want to upgrade Python to 64 bit. I am completely comfortable with compiling it from source with one caveat. How do I match the way that the default install is laid out? Especially, with regards to site-packages being in <code>/Library/Python/2.5/</code> and not the one in buried at the top of the framework once I compile it. </p>
<p>Personally, I wouldn't worry about it until you see a problem. Messing with the default python install on a *Nix system can cause more trouble than it's worth. I can say from personal experience that you never truly understand what python has done for the nix world until you have a problem with it.</p> <p>You can also add a second python installation, but that also causes more problems than it's worth IMO.</p> <p>So I suppose the best question to start out with would be why exactly do you want to use the 64 bit version of python?</p>
<p>Essentially, yes. I was not sure you could do it like that (current version does not do it like that). When using the python install script, however, there is no option (that I can find) to specify where to put directories and files (eg --prefix). I was hoping to match the current layout of python related files so as to avoid 'polluting' my machine with redundant files.</p>
4,969
<p>I have an asp.net url path which is being generated in a web form, and is coming out something like "/foo/bar/../bar/path.aspx", and is coming out in the generated html like this too. It should be shortened to "/foo/bar/path.aspx". </p> <p>Path.Combine didn't fix it. Is there a function to clean this path up? </p>
<p>You could create a helper class which wrapped the UriBuilder class in System.Net</p> <pre><code>public static class UriHelper { public static string NormalizeRelativePath(string path) { UriBuilder _builder = new UriBuilder("http://localhost"); builder.Path = path; return builder.Uri.AbsolutePath; } } </code></pre> <p>which could then be used like this:</p> <pre><code>string url = "foo/bar/../bar/path.aspx"; Console.WriteLine(UriHelper.NormalizeRelativePath(url)); </code></pre> <p>It is a bit hacky but it would work for the specific example you gave.</p> <p><strong>EDIT: Updated to reflect Andrew's comments.</strong></p>
<p>Sarcastic's reply is so much better than mine, but if you were working with filesystem paths, my <strong>ugly hack below</strong> could turn out to be useful too. (Translation: I typed it, so I'll be damned if I don't post it :)</p> <p>Path.Combine just slaps two strings together, paying attention to leading or trailing slashes. As far as I know, the only Path method that does normalization is Path.GetFullPath. The following will give you the "cleaned up" version.</p> <pre><code>myPath = System.IO.Path.GetFullPath(myPath); </code></pre> <p>Of course, there is the small issue that the resulting path will be rooted and the forward slashes will be converted to back slashes (like "C:\foo\bar\path.aspx"). But if you know the parent root of the original path, stripping out the root should not be a big problem.</p>
7,787
<p>Yacc does not permit objects to be passed around. Because the %union can only contain POD types, complex objects must be new'd and passed around by pointer. If a syntax error occurs, the yacc parser just stops running, and references to all of those created objects are lost.</p> <p>The only solution I've come up with is that all new'd object inherit a particular base class, be added to a container when allocated, and if there is an error everything in that container can be deleted.</p> <p>Does anyone know of any better yacc tricks to solve this problem?</p> <p>Please don't tell me to choose a different parser.</p>
<p>I love Yacc, but the discriminating union stack does present a challenge.</p> <p>I don't know whether you are using C or C++. I've modified Yacc to generate C++ for my own purposes, but this solution can be adapted to C.</p> <p>My preferred solution is to pass an interface to the owner down the parse tree, rather than constructed objects up the stack. Do this by creating your own stack outside of Yacc's. Before you invoke a non-terminal that allocates an object, push the owner of that object to this stack.</p> <p>For example:</p> <pre><code>class IExpressionOwner { public: virtual ExpressionAdd *newExpressionAdd() = 0; virtual ExpressionSubstract *newExpressionSubtract() = 0; virtual ExpressionMultiply *newExpressionMultiply() = 0; virtual ExpressionDivide *newExpressionDivide() = 0; }; class ExpressionAdd : public Expression, public IExpressionOwner { private: std::auto_ptr&lt;Expression&gt; left; std::auto_ptr&lt;Expression&gt; right; public: ExpressionAdd *newExpressionAdd() { ExpressionAdd *newExpression = new ExpressionAdd(); std::auto_ptr&lt;Expression&gt; autoPtr(newExpression); if (left.get() == NULL) left = autoPtr; else right = autoPtr; return newExpression; } ... }; class Parser { private: std::stack&lt;IExpressionOwner *&gt; expressionOwner; ... }; </code></pre> <p>Everything that wants an expression has to implement the IExpressionOwner interface and push itself to the stack before invoking the expression non-terminal. It's a lot of extra code, but it controls object lifetime.</p> <p><strong>Update</strong></p> <p>The expression example is a bad one, since you don't know the operation until after you've reduced the left operand. Still, this technique works in many cases, and requires just a little tweaking for expressions.</p>
<p>Use <a href="http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/smart_ptr.htm" rel="nofollow noreferrer">smart pointers</a>!</p> <p>Or, if you're uncomfortable depending on yet another library, you can always use <a href="http://www.gotw.ca/publications/using_auto_ptr_effectively.htm" rel="nofollow noreferrer">auto_ptr</a> from the C++ standard library.</p>
9,063
<p>I have a MySQL database behind a firewall which can only be accessed via an SSH connection. Does anyone know of an implementation of java.sql.Connection which would allow me to make an SSH connection to this database?</p>
<p>You can use SSH's port forwarding to do this. While not a pure java.sql.Connection, it will allow you to tunnel the connection through ssh.</p> <pre>ssh -L 3306:localhost:3306 remote.mysql.host.com</pre> <p>This will forward port 3306 on your local machine to port 3306 on remote.mysql.host.com. This will allow you to connect to port 3306 on your local machine, and it will be tunnelled to remote.mysql.host.com.</p> <p>If you're looking to do it all in Java, create the ssh connection with <a href="http://www.jcraft.com/jsch/" rel="noreferrer">JSch</a>.</p>
<p>Here is an <a href="https://github.com/newjam/mysql_ssh_tunnel_example/blob/master/src/main/java/com/github/newjam/test/tunnel/Tunnel.java#L54" rel="nofollow">example</a> using the library <a href="https://github.com/hierynomus/sshj" rel="nofollow">sshj</a>.</p>
31,432
<p>does the TableLayoutPanel exist in VS 2005?</p>
<p>Yes, it first appeared in .NET 2.0</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel(VS.80).aspx</a></p>
<p>Yes, TableLayoutPanel is a standard component of the .NET 2.0, thus it is usable from VS2k5.</p>
18,711
<p>This is my code:</p> <pre><code>import datetime today = datetime.date.today() print(today) </code></pre> <p>This prints: <code>2008-11-22</code> which is exactly what I want.</p> <p>But, I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p> <pre><code>import datetime mylist = [] today = datetime.date.today() mylist.append(today) print(mylist) </code></pre> <p>This prints the following: </p> <pre><code>[datetime.date(2008, 11, 22)] </code></pre> <p>How can I get just a simple date like <code>2008-11-22</code>?</p>
<h2>The WHY: dates are objects</h2> <p>In Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings or timestamps.</p> <p>Any object in Python has TWO string representations:</p> <ul> <li><p>The regular representation that is used by <code>print</code> can be get using the <code>str()</code> function. It is most of the time the most common human readable format and is used to ease display. So <code>str(datetime.datetime(2008, 11, 22, 19, 53, 42))</code> gives you <code>'2008-11-22 19:53:42'</code>.</p> </li> <li><p>The alternative representation that is used to represent the object nature (as a data). It can be get using the <code>repr()</code> function and is handy to know what kind of data your manipulating while you are developing or debugging. <code>repr(datetime.datetime(2008, 11, 22, 19, 53, 42))</code> gives you <code>'datetime.datetime(2008, 11, 22, 19, 53, 42)'</code>.</p> </li> </ul> <p>What happened is that when you have printed the date using <code>print</code>, it used <code>str()</code> so you could see a nice date string. But when you have printed <code>mylist</code>, you have printed a list of objects and Python tried to represent the set of data, using <code>repr()</code>.</p> <h2>The How: what do you want to do with that?</h2> <p>Well, when you manipulate dates, keep using the date objects all long the way. They got thousand of useful methods and most of the Python API expect dates to be objects.</p> <p>When you want to display them, just use <code>str()</code>. In Python, the good practice is to explicitly cast everything. So just when it's time to print, get a string representation of your date using <code>str(date)</code>.</p> <p>One last thing. When you tried to print the dates, you printed <code>mylist</code>. If you want to print a date, you must print the date objects, not their container (the list).</p> <p>E.G, you want to print all the date in a list :</p> <pre><code>for date in mylist : print str(date) </code></pre> <p>Note that <em><strong>in that specific case</strong></em>, you can even omit <code>str()</code> because print will use it for you. But it should not become a habit :-)</p> <h2>Practical case, using your code</h2> <pre><code>import datetime mylist = [] today = datetime.date.today() mylist.append(today) print mylist[0] # print the date object, not the container ;-) 2008-11-22 # It's better to always use str() because : print &quot;This is a new day : &quot;, mylist[0] # will work &gt;&gt;&gt; This is a new day : 2008-11-22 print &quot;This is a new day : &quot; + mylist[0] # will crash &gt;&gt;&gt; cannot concatenate 'str' and 'datetime.date' objects print &quot;This is a new day : &quot; + str(mylist[0]) &gt;&gt;&gt; This is a new day : 2008-11-22 </code></pre> <h2>Advanced date formatting</h2> <p>Dates have a default representation, but you may want to print them in a specific format. In that case, you can get a custom string representation using the <code>strftime()</code> method.</p> <p><code>strftime()</code> expects a string pattern explaining how you want to format your date.</p> <p>E.G :</p> <pre><code>print today.strftime('We are the %d, %b %Y') &gt;&gt;&gt; 'We are the 22, Nov 2008' </code></pre> <p>All the letter after a <code>&quot;%&quot;</code> represent a format for something:</p> <ul> <li><code>%d</code> is the day number (2 digits, prefixed with leading zero's if necessary)</li> <li><code>%m</code> is the month number (2 digits, prefixed with leading zero's if necessary)</li> <li><code>%b</code> is the month abbreviation (3 letters)</li> <li><code>%B</code> is the month name in full (letters)</li> <li><code>%y</code> is the year number abbreviated (last 2 digits)</li> <li><code>%Y</code> is the year number full (4 digits)</li> </ul> <p>etc.</p> <p><a href="http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior" rel="noreferrer">Have a look at the official documentation</a>, or <a href="http://strftime.org" rel="noreferrer">McCutchen's quick reference</a> you can't know them all.</p> <p>Since <a href="http://www.python.org/dev/peps/pep-3101/" rel="noreferrer">PEP3101</a>, every object can have its own format used automatically by the method format of any string. In the case of the datetime, the format is the same used in strftime. So you can do the same as above like this:</p> <pre><code>print &quot;We are the {:%d, %b %Y}&quot;.format(today) &gt;&gt;&gt; 'We are the 22, Nov 2008' </code></pre> <p>The advantage of this form is that you can also convert other objects at the same time.<br /> With the introduction of <a href="https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals" rel="noreferrer">Formatted string literals</a> (since Python 3.6, 2016-12-23) this can be written as</p> <pre><code>import datetime f&quot;{datetime.datetime.now():%Y-%m-%d}&quot; &gt;&gt;&gt; '2017-06-15' </code></pre> <h2>Localization</h2> <p>Dates can automatically adapt to the local language and culture if you use them the right way, but it's a bit complicated. Maybe for another question on SO(Stack Overflow) ;-)</p>
<pre><code>import datetime import time months = ["Unknown","January","Febuary","Marchh","April","May","June","July","August","September","October","November","December"] datetimeWrite = (time.strftime("%d-%m-%Y ")) date = time.strftime("%d") month= time.strftime("%m") choices = {'01': 'Jan', '02':'Feb','03':'Mar','04':'Apr','05':'May','06': 'Jun','07':'Jul','08':'Aug','09':'Sep','10':'Oct','11':'Nov','12':'Dec'} result = choices.get(month, 'default') year = time.strftime("%Y") Date = date+"-"+result+"-"+year print Date </code></pre> <p>In this way you can get Date formatted like this example: 22-Jun-2017</p>
40,158
<p>Are there any good libraries (preferably with commented source) for standard datastructures (Linked list, array list, queue, stack etc.) for x86 (or others) in Assembler ? I don't like to reinvent (and debug !) the wheel....</p>
<p>Why not just find a good C library and call it from your asm?</p> <p>Or if you need "inline" functionality:</p> <ul> <li>Compile the functions you want to use into a Hello World program.</li> <li>Disassemble the program.</li> <li>Rewrite the assembly as asm/pre-processor macros.</li> </ul>
<p>You'd be best asking in one of the Assembler-specific groups rather than here. Try:</p> <ul> <li>the recently-released <a href="http://www.masm32.com/" rel="nofollow noreferrer">MASM32 SDK v10</a> which gives a link to the <a href="http://www.masm32.com/board/index.php" rel="nofollow noreferrer">MASM Forum</a>. </li> <li>the <a href="http://www.winasm.net/" rel="nofollow noreferrer">WinAsm</a> site.</li> </ul> <p>Google said there were some data structures demo-ed on Microsoft's <a href="http://msdn.microsoft.com/en-us/library/t13a3526(VS.80).aspx" rel="nofollow noreferrer">MASM Samples</a> page, but I didn't go hunting.</p> <p>Another possibility is to check out <a href="http://webster.cs.ucr.edu/AsmTools/HLA/index.html" rel="nofollow noreferrer">HLA</a>, the High Level Assembly Language. The blurb there is, in part,</p> <blockquote> <p>Now you can enjoy all of the benefits of high-level and low-level languages, all rolled into a single language! HLA, the High-Level Assembler lets you write true low-level code while enjoying the benefits of high-level language programming. Don't let the name fool you; you can do anything with HLA that you can do with a traditional low-level assembler. All the same instructions are present, all the same low-level programming facilities are present. The difference between HLA and low-level assemblers is that you're not stuck using low-level programming paradigms when they're not needed. Watch your productivity soar when using HLA; and write far more efficient programs than you could using high-level languages.</p> </blockquote> <p>IIRC, their support for data structures is quite good. </p>
39,709
<p>How can I render after executing an action in a restful controller instead of redirecting.</p> <p>I have a controller with standard actions, and I added a special action that adds data to the resource in question, via a form on the #show page (Think comments on a post). I am validating the input from the form and want to re-render the show action on error and redirect to the show action on success.</p> <p>I want to render to save the user from inputting their info twice, but when I try to render the show action with an error in the flash[:notice] I get an error saying that I am not specifying an ID. When I do specify an ID, it tries to render a new template that doesn't exist yet.</p> <p>I am thinking that it should be a as simple as:</p> <pre><code>def add_comment if my_validation? save the object redirect_to :action =&gt; "show", :id =&gt; params[:id] else render :action =&gt; "show", :id =&gt; params[:id] end end </code></pre> <p>This is not my actual code, just something I put together just now as an example.</p>
<p>The best way is to re-render the :new</p> <pre><code>def create @obj = TheObject.new(params[:object]) render :action =&gt; :new unless @obj.save end </code></pre> <p>And in the new.html.erb</p> <pre><code>&lt;% form_for :obj, :url =&gt; object_url(@obj), :html =&gt; {:method =&gt; :post} do |f| %&gt; &lt;%= f.text_field :name %&gt; &lt;% end %&gt; </code></pre> <p>That way, the inputs in the form will be pre-filled with what the user entered.</p>
<p>Create a new data object and add the values from the form, before you rerender, think it would work then. If you still get problems, try setting a boolean for editing new vs. existing rows, or create two different views entirely.</p> <p>I've done it before but I don't quite remember how. Sometimes when I used the very typical use of the MVC pattern, it was allmost "automagical", othertimes (as I had to use an old quirky database) I had to code all the magic myself; sometimes usin the <code>.new?</code> function (or what it was called) on the ActiveRecord object, othertimes I used temporary "magic values" for ID (typically alphabetic strings for invalid id values.</p> <p>(I appologize if I made some mistakes, it's a while since I coded Rails code...) </p>
44,398
<p>By default the webjump hotlist has the following which I use quite often:</p> <pre><code>M-x webjump RET Google M-x webjump RET Wikipedia </code></pre> <p>How can I add 'Stackoverflow' to my list?</p>
<p>Here's some example code in <a href="http://www.opensource.apple.com/darwinsource/10.0/emacs-39/emacs/lisp/webjump.el" rel="nofollow noreferrer">a webjump.el file on a site run by Apple:</a></p> <pre><code>;; (require 'webjump) ;; (global-set-key "\C-cj" 'webjump) ;; (setq webjump-sites ;; (append '( ;; ("My Home Page" . "www.someisp.net/users/joebobjr/") ;; ("Pop's Site" . "www.joebob-and-son.com/") ;; ) ;; webjump-sample-sites)) </code></pre>
<p>Here's some example code in <a href="http://www.opensource.apple.com/darwinsource/10.0/emacs-39/emacs/lisp/webjump.el" rel="nofollow noreferrer">a webjump.el file on a site run by Apple:</a></p> <pre><code>;; (require 'webjump) ;; (global-set-key "\C-cj" 'webjump) ;; (setq webjump-sites ;; (append '( ;; ("My Home Page" . "www.someisp.net/users/joebobjr/") ;; ("Pop's Site" . "www.joebob-and-son.com/") ;; ) ;; webjump-sample-sites)) </code></pre>
8,408
<p>Is there a way in Python to handle XML files similar to the way PHP's SimpleXML extension does them?</p> <p>Ideally I just want to be able to access certain xml datas from a list object.</p>
<p>There is a long list of libraries associated with XML processing on the <a href="http://wiki.python.org/moin/PythonXml" rel="nofollow noreferrer">Python wiki</a>. Note that a number of them are included in the standard library. Most of them will do what you are looking for:</p> <blockquote> <p>to access certain xml datas from a list object</p> </blockquote> <p>which is a bit vague, and perhaps some more concrete use-case might narrow down that list for you.</p>
<p><a href="http://lxml.de/objectify.html" rel="nofollow">lxml.objectify</a> does exactly what you want</p> <pre><code>In [1]: from lxml import objectify In [2]: x = objectify.fromstring("""&lt;response&gt;&lt;version&gt;1.2&lt;/version&gt;&lt;amount&gt;1.01&lt;/amount&gt;&lt;currency&gt;USD&lt;/currency&gt;&lt;/response&gt;""") In [3]: x.version Out[3]: 1.2 In [4]: x.amount Out[4]: 1.01 In [5]: x.currency Out[5]: 'USD' </code></pre>
42,335
<p>Here is a command on free bsd</p> <pre><code>sudo pw usermod ksbuild -s /usr/local/bin/bash </code></pre> <p>how do I do the equivalent on RHEL?</p>
<p>chsh</p> <p>(Change Shell)</p>
<p>To change the default setting of all new users, edit the setting in the defaults file: /etc/default/useradd</p>
36,464
<p>This question is regarding the performance issue in Mac OS X</p> <p>Canvas3D object is embedded in a JPanel; then the panel is integrated with the rest of the Swing-built application. Within that Canvas I am rendering a simple cube by applying certain transformations. At the initial launch It works fine. But when i try to resize the window or perform some operations on vertical or horizontal split bar buttons.Swing components take certain time to appear on the screen. A flashy white coloured thing appears first then swing components will appear? ( Totally saying flickering kind of stuff will happen). Is there any to solve this issue? </p> <p>Kindly help me in this regard.</p> <p>J3DSwinger</p>
<p>I imagine there are better ways to do it, but the <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/gdb/gdb_6.html#SEC37" rel="noreferrer">finish</a> command executes until the current stack frame is popped off and prints the return value -- given the program</p> <pre><code>int fun() { return 42; } int main( int argc, char *v[] ) { fun(); return 0; } </code></pre> <p>You can debug it as such --</p> <pre><code>(gdb) r Starting program: /usr/home/hark/a.out Breakpoint 1, fun () at test.c:2 2 return 42; (gdb) finish Run till exit from #0 fun () at test.c:2 main () at test.c:7 7 return 0; Value returned is $1 = 42 (gdb) </code></pre> <p>The <code>finish</code> command can be abbreviated as <code>fin</code>. Do NOT use the <code>f</code>, which is abbreviation of <code>frame</code> command!</p>
<p>Here's how todo this with no symbols.</p> <pre><code>gdb ls This GDB was configured as "ppc64-yellowdog-linux-gnu"... (no debugging symbols found) Using host libthread_db library "/lib64/libthread_db.so.1". (gdb) break __libc_start_main Breakpoint 1 at 0x10013cb0 (gdb) r Starting program: /bin/ls (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) Breakpoint 1 at 0xfdfed3c (no debugging symbols found) [Thread debugging using libthread_db enabled] [New Thread 4160418656 (LWP 10650)] (no debugging symbols found) (no debugging symbols found) [Switching to Thread 4160418656 (LWP 10650)] Breakpoint 1, 0x0fdfed3c in __libc_start_main () from /lib/libc.so.6 (gdb) info frame Stack level 0, frame at 0xffd719a0: pc = 0xfdfed3c in __libc_start_main; saved pc 0x0 called by frame at 0x0 Arglist at 0xffd71970, args: Locals at 0xffd71970, Previous frame's sp is 0xffd719a0 Saved registers: r24 at 0xffd71980, r25 at 0xffd71984, r26 at 0xffd71988, r27 at 0xffd7198c, r28 at 0xffd71990, r29 at 0xffd71994, r30 at 0xffd71998, r31 at 0xffd7199c, pc at 0xffd719a4, lr at 0xffd719a4 (gdb) frame 0 #0 0x0fdfed3c in __libc_start_main () from /lib/libc.so.6 (gdb) info fr Stack level 0, frame at 0xffd719a0: pc = 0xfdfed3c in __libc_start_main; saved pc 0x0 called by frame at 0x0 Arglist at 0xffd71970, args: Locals at 0xffd71970, Previous frame's sp is 0xffd719a0 Saved registers: r24 at 0xffd71980, r25 at 0xffd71984, r26 at 0xffd71988, r27 at 0xffd7198c, r28 at 0xffd71990, r29 at 0xffd71994, r30 at 0xffd71998, r31 at 0xffd7199c, pc at 0xffd719a4, lr at 0xffd719a4 </code></pre> <p>Formatting kinda messed up there, note the use of "info frame" to inspect frames, and "frame #" to navigate your context to another context (up and down the stack)</p> <p>bt also show's an abbreviated stack to help out.</p>
33,573
<p>Sometimes my Oracle database on Windows gets hosed. How do I do a manual uninstall of Oracle?</p>
<p>The six-step process to remove all things Oracle from a Windows machine:</p> <p>A. <strong>Delete the Oracle services</strong>: In the registry, go to <code>\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services</code> and delete everything that starts with "Oracle"</p> <p>B. <strong>Remove other Oracle stuff from the registry</strong>: Go to <code>\HKEY_LOCAL_MACHINE\SOFTWARE\</code> and delete the key ORACLE</p> <p>C. <strong>Reboot</strong></p> <p>D. <strong>Delete all the Oracle software</strong> from the directories where you installed it</p> <p>E. <strong>Delete the Oracle software inventory</strong>: Delete the directory <code>C:\Program Files\Oracle</code>. You must do this no matter where you installed your Oracle software - the Oracle installer automatically writes information here. </p> <p>F. <strong>Delete all shortcuts</strong> from your Start menu.</p> <p>G. <strong>Remove</strong> the Oracle directories from PATH Environment Variable.</p> <p>To simplify cleanup in the future, I'd strongly recommend you install your Oracle products in one or more virtual machines. </p>
<p>Assuming a unix type OS and that you properly installed it using an account named oracle...</p> <p>find / -user oracle -exec rm -fr {} \;</p> <p>That having been said, this must be done as root and you had better not mind loss of any and all files that belong to oracle. There will be no... NO recovery from this method.</p>
10,950
<p>I have a border element with rounded corners containing a 3x3 grid. The corners of the grid are sticking out of the border. How can I fix that? I tried using ClipToBounds but didn't get anywhere. Thanks for your help</p>
<p>Here are the highlights of this <a href="https://stackoverflow.com/questions/324641/how-to-make-the-contents-of-a-round-cornered-border-be-also-round-cornered#325003">thread</a> mentioned by <a href="https://stackoverflow.com/users/8091/jobi-joy">Jobi</a></p> <ul> <li>None of the decorators (i.e. Border) or layout panels (i.e. Stackpanel) come with this behavior out-of-the-box.</li> <li>ClipToBounds is for layout. ClipToBounds does not prevent an element from drawing outside its bounds; it just prevents children's layouts from 'spilling'. Additionally ClipToBounds=True is not needed for most elements because their implementations dont allow their content's layout to spill anyway. The most notable exception is Canvas.</li> <li>Finally Border considers the rounded corners to be drawings inside the bounds of its layout.</li> </ul> <p>Here is an implementation of a class that inherits from Border and implements the proper functionality:</p> <pre><code> /// &lt;Remarks&gt; /// As a side effect ClippingBorder will surpress any databinding or animation of /// its childs UIElement.Clip property until the child is removed from ClippingBorder /// &lt;/Remarks&gt; public class ClippingBorder : Border { protected override void OnRender(DrawingContext dc) { OnApplyChildClip(); base.OnRender(dc); } public override UIElement Child { get { return base.Child; } set { if (this.Child != value) { if(this.Child != null) { // Restore original clipping this.Child.SetValue(UIElement.ClipProperty, _oldClip); } if(value != null) { _oldClip = value.ReadLocalValue(UIElement.ClipProperty); } else { // If we dont set it to null we could leak a Geometry object _oldClip = null; } base.Child = value; } } } protected virtual void OnApplyChildClip() { UIElement child = this.Child; if(child != null) { _clipRect.RadiusX = _clipRect.RadiusY = Math.Max(0.0, this.CornerRadius.TopLeft - (this.BorderThickness.Left * 0.5)); _clipRect.Rect = new Rect(Child.RenderSize); child.Clip = _clipRect; } } private RectangleGeometry _clipRect = new RectangleGeometry(); private object _oldClip; } </code></pre>
<p>Make the grid smaller or the border larger. So that the border element completely contains the grid.</p> <p>Alternatively see if you can make the grid's background transparent, so that the "sticking out" isn't noticeable.</p> <p><b>Update:</b> Oops, didn't notice this was a WPF question. I'm not familiar with that. This was general HTML/CSS advice. Maybe it helps...</p>
42,039
<p>In my automated NAnt build we have a step that generates a lot of code off of the database (using SubSonic) and the code is separated into folders that match the schema name in the database. For example:</p> <ul> <li>/generated-code <ul> <li>/dbo <ul> <li>SomeTable.cs</li> <li>OtherTable.cs</li> </ul></li> <li>/abc <ul> <li>Customer.cs</li> <li>Order.cs </li> </ul></li> </ul></li> </ul> <p>The schema names are there to isolate the generated classes that an app will need. For example, there is an ABC app, that will pull in the generated code from this central folder. I'm doing that on a pre-build event, like this:</p> <blockquote> <p>del /F /Q $(ProjectDir)Entities\generated*.cs</p> <p>copy $(ProjectDir)....\generated-code\abc*.cs $(ProjectDir)Entities\generated*.cs</p> </blockquote> <p>So on every build, the Nant script runs the generator which puts all the code into a central holding place, then it kicks off the solution build... which includes pre-build events for each of the projects that need their generated classes.</p> <p>So here's the friction I'm seeing:</p> <p>1) Each new app needs to setup this pre-build event. It kind of sucks to have to do this.</p> <p>2) In our build server we don't generate code, so I actually have an IF $(ConfigurationName) == "Debug" before each of those commands, so it doens't happen for release builds</p> <p>3) Sometimes the commands fail, which fails our local build. It will fail if: - there is no generated code yet (just setting up a new project, no database yet) - there is no existing code in the directory (first build)</p> <p>usually these are minor fixes and we've just hacked our way to getting a new project or a new machine up and running with the build, but it's preventing me from my 1-click-build Nirvana.</p> <p>So I'd like to hear suggestions on how to improve this where it's a bit more durable. Maybe move the copying of the code into the application folders into the NAnt script? This seems kind of backwards to me, but I'm willing to listen to arguments for it.</p> <p>OK, fire away :)</p>
<p>How often does your DB schema change? Wouldn't it be possible to generate the database-related files on demand (e.g. when the schema changes) and then check them into your code repository?</p> <p>If your database schema doesn't change, you can also package the compiled *.cs classes and distribute the archive to other projects.</p>
<p>We have two projects in our solution that are built completely out of generated code. Basically, we run the code generator .exe as a post-build step for another project and along with generating the code, it automates the active instance of visual studio to make sure that the generated project is in the solution, that it has all of the generated code files, and that they are checked out/added to TFS as necessary. </p> <p>It very rarely flakes out during the VS automation stage, and we have to run it "by hand" but that's usually only if you have several instances of VS open with >1 instance of the solution open and it can't figure out which one it's supposed to automate. </p> <p>Our solution and process are such that the generation should always be done and correct before our auto-build gets to it, so this approach might not work for you. </p>
6,821
<p>Our subversion repository has been moved to a new host, and we have old applications that connect to that host. We CANNOT add an alias for the new server with the old name, how can we re-connect our checked out clients to the new repository?</p>
<p>Example:</p> <pre><code>svn switch --relocate \ http://svn.example.com/path/to/repository/path/within/repository \ http://svnnew.example.com/new/repository/path/within/repository </code></pre> <p>One thing which is to remember, lets assume you checked out the project "path/within/repository" then you have to go to the <strong>root of your working copy</strong>, and execute the above command. it is <strong>NOT</strong> enough just to use the repository root (as in <em>svn switch --relocate <a href="http://svn.example.com/path/to/repository/" rel="noreferrer">http://svn.example.com/path/to/repository/</a> <a href="http://svnnew.example.com/new/repository/" rel="noreferrer">http://svnnew.example.com/new/repository/</a></em>), because that wouldn't work.</p>
<p>SVN command line - see <a href="http://svnbook.red-bean.com/en/1.5/svn.ref.svn.c.switch.html" rel="nofollow noreferrer">svn switch</a></p> <p>TortoiseSVN - see <a href="http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-relocate.html" rel="nofollow noreferrer">relocate dialog</a></p>
13,783
<p>How can I find out which row in a JTable the user just clicked?</p>
<p>Try this: </p> <p><code>aJTable.rowAtPoint(evt.getPoint());</code></p>
<p>If you only ever care about listening to selections on the JTable:</p> <pre><code>jTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { int sel = jTable.getSelectedRow(); } }); </code></pre>
30,172
<p>I am getting the following error while loading a page.</p> <p>[HttpException (0x80004005): Cannot use a leading .. to exit above the top directory.]</p> <p>No idea what to do ? Can anyone help me ?</p>
<p>I'm guessing you have done something like this:</p> <pre><code>Response.Redirect("../SomePage.aspx"); </code></pre> <p>When using relative paths, you can only navigate to pages that are in the same Virtual Directory as the one the page making the request is in. What you have done is called this from a page that is at the top of the Virtual Directory tree. So you have some options:</p> <ol> <li>Correct your url so that it does not point to a higher level. ie: remove the <code>../</code></li> <li>Use a full url. ie: <code>http://www.example.com/SomePage.aspx</code></li> <li>Use IIS to set the Virtual Directory at a higher level.</li> </ol> <p>For Option 3: </p> <ol> <li>Open up IIS manager. </li> <li>Go to the directory that the page is in and right click/properties. </li> <li>On the Virtual Directory tab select Remove.</li> <li>Close the dialogue and right click/properties on the directory you do want to be the root.</li> <li>On the Virtual Directory tab select Add</li> </ol>
<p>Depending on your circumstances this may or may not help but I had this error last week. The solution for me was to change the Web settings in My Project to use the local IIS server instead of the Visual Studio web server.</p>
34,601
<p>Any good suggestions? Input will be the name of a header file and output should be a list (preferably a tree) of all files including it directly or indirectly.</p>
<p>If you have access to GCC/G++, then the <a href="http://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html#Preprocessor-Options" rel="noreferrer"><code>-M</code> option</a> will output the dependency list. It doesn't do any of the extra stuff that the other tools do, but since it is coming from the compiler, there is no chance that it will pick up files from the "wrong" place.</p>
<p><a href="http://www.scitools.com/products/understand/" rel="nofollow noreferrer">Understand for C++</a> should be able to help you: it builds a database that you can access from Perl.</p>
6,375
<p>I want to run javascript/Python/Ruby inside my application. </p> <p>I have an application that creates process automatically based on user's definition. The process is generated in C#. I want to enable advanced users to inject script in predefined locations. Those scripts should be run from the C# process. For example, the created process will have some activities and in the middle the script should be run and then the process continues as before. Is there a mechanism to run those scripts from C#? </p>
<p>Basically, you have two problems: how to define point of injections in your generated code, and how to run python / ruby / whatev scripts from there.</p> <p>Depending on how you generate the process, one possible solution would be to add a function to each possible point of injection. The function would check, whether the user has associated any scripts with given points, and if so, runs the script by invoking <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython" rel="nofollow noreferrer">IronPython</a> / <a href="http://www.ironruby.net/" rel="nofollow noreferrer">IronRuby</a> (with optionally given parameters).</p> <p>Disadvantages include: limited accessibility from the scripts to the created process (basically, only variables passed as parameters could be accessed); as well as implementation limits (IronPython's current version omits several basic system functions).</p>
<p>You can compile C# code "on the fly" into an in-memory assembly. I think this is possible with IronPython and IronRuby as well. Look at the <a href="http://msdn.microsoft.com/en-us/library/system.codedom.compiler.codedomprovider.createprovider.aspx" rel="nofollow noreferrer">CodeDomProvider.CreateProvider</a> method.</p> <p>If you need to run scripts a lot, or if your process runs for a long time, you might want to load these assemblies into another AppDomain. And unload the AppDomain after you're done with the script. Otherwise you are unable to remove them from memory. This has some consequenses on the other classes in your project, because you have to marshall all calls.</p>
14,546
<p>I was trying to add the XML schema to an existing EJB project. JAXB is used to bind the XML-Schema to a Java class. As we are going to use the search engine to crawl through DTO when EJB is in session.</p> <p>I could not find any direct approach as to map entity class file to XML-Schema. </p> <p>The only way we could achieve so far is to create the Web Services, generate the WSDL which generates xml-schema (XSD) and then parsing the XSD file thru JAXB (xjc command) to create java class files. Now using mapping-binding.xml file we can map both XML and Java class file.</p> <p>But now again the issue is to how map this to entity class. </p> <p>This is what we want to achieve:</p> <ul> <li>XML Data Object with XML Schema, (This is already present in the JAXB specification). </li> <li>Entity Bean then Extends or has an interface to this JAXB object. </li> <li>All Persistence functions are managed by the Entity Bean... </li> <li>The Entity Bean would then contain the XML Marshalling and UnMarshalling features found in JAXB.. </li> <li>A Value Object could be retrieved in binary or XML form from the Entity Bean Object. </li> <li>A JSP could easily extract the XML Schema and XML Data from the Value Object and perform operations on it such as XSL transformations. </li> </ul> <p>My argument is that the Entity Beans have no standard way for interfacing to JAXB objects.</p> <p>Castor may be the solution, but then again we have to implement web services or using castor JDO’s.</p> <p>I found XStream to be pretty useful as it uses a converter class in which you can call the entity bean class objects and generate a xml file. But I was not preferring to use another class but incorporate the functions in existing bean class.</p> <p>Can you help me in this regard?</p> <hr> <p>I will tell you what I am actually trying to achieve. I'm creating a search engine which will be evoked during the EJB in session and will use crawler thru the DTO's and get the snapshot in XML format. Search will be on different criteria.</p> <p>Lucene is one of the search engine tools but then it uses its own properties and files (will act more like standalone)</p> <p>I already have DTO's which are used by webservices to communicate between PHP &amp; Java application (EJB-layer). I wanted to re-use those DTO's in jaxb as a crawler to get the output from tables in XML which I am not able to do as JAXB uses its own generated classes thru xml-schema. Like you said I have yet not found a way to instruct JAXB to bean classes.</p>
<p>Tightly coupling your data model (entity beans) to your XML interface might not be the best idea in the world; it prevents you from changing one without changing the other.</p> <p>I'm not 100% sure I understand what you are trying to do, but I think there is a way to instruct JAXB to extend classes rather than create new ones. You could create your Entity Beans as normal, and have your JAXB-generated beans extend those with the extra information.</p> <p>I can say that getting Entity beans instances from somewhere <em>other</em> than your persistence layer (such as deserializing them from XML) is going to be a <em>huge</em> problem for you.</p> <p>Also note that using XML to communicate between Java applications (such as between a JSP/Servlet and EJB layer) is a bad idea; the marshaling and added verbosity of the XML buys you very little; serializing objects via RMI (which is what EJB will do for you) would be much easier to implement, test and maintain.</p>
<p><a href="http://www.eclipse.org/eclipselink/moxy.php" rel="nofollow noreferrer">EclipseLink JAXB (MOXy)</a> can be used to map JPA entities to XML.</p> <p>For more information see:</p> <ul> <li><a href="http://wiki.eclipse.org/EclipseLink/Examples/MOXy/JPA" rel="nofollow noreferrer">http://wiki.eclipse.org/EclipseLink/Examples/MOXy/JPA</a></li> </ul>
12,749
<p>What are good methodologies for creating sprocs that reduce the pain of debugging? And what tools are out there for debugging stored procedures?</p> <p>Perhaps most importantly, what are indications to look out for that errors are happening in a sproc and not in the code? I hope I'm not all over the board too terribly bad here. Votes for answers to any of the above. Thanks.</p> <p>For what it's worth, I work in a .NET environment, SQL servers.</p>
<p>One technique I use in stored procedures to make them easier to debug (without IDE or debuggers) for SQL Server 2005 procedures:</p> <p>I add an input parameter named @Debug = 0 (defaulted to 0 = off) at the end of the parameter list for the procedure.</p> <p>I then add if (@Debug = 1) print '...';</p> <p>statements in the code at key junctures to display any useful internal values etc.</p> <p>Yes, it's "old school" and debuggers that let you "walk the code" are great - but this works for anyone from any SQL tool (including anyone debugging without your same IDE).</p> <p>Ron</p>
<p>A couple of patterns I have seen successfully used are 'diagnostic' or 'test' modes and logging.</p> <p>test or diagnostic modes are useful when you are doing dynamic SQL execution. Make sure you can see what you are going to execute. If you have areas where you need (or should) be checking for errors consider logging to a table with enough details so you can diagnose what is going on. </p>
13,201
<p>I haven't had to interact w/MSSQL much in my development career, though I've spent many an hour working with MySQL.</p> <p>An M.B.A. friend of mine is starting a job where she needs to gain functional knowledge of MSSQL Server, and I'd really like to help.</p> <p><strong>What are the differences between MSSQL and MySQL?</strong></p> <p><strong>How would you recommend a non-technical person go about learning the ups and downs of MSSQL Server?</strong></p> <hr> <p>[update] Previous database design skills are naught. I've given her to short and long on what a database does from a high-level.</p>
<p>I'd love to say, "you can't". But that would be untrue (or at least mean).</p> <p>If she has any background with database design at all, then this is merely a new RDBMS. </p> <p>If she's never done database design, the place to start is not so much with MS SQL, but with how databases work, in my opinion.</p> <p><em>Database Design for Mere Mortals</em> is a good place to start. From there I'd move to an MS SQL -specific book, such as <em>Microsoft SQL Server Unleashed</em>.</p>
<p>From the perspective of the database user, the backend is generally irrelevant if they understand some basic concepts.</p> <p>First and most important concept for the non-technical user is GIGO (Garbage in Garbage out). Bad data is useless data. Check everything you enter into a database for correctness. You really don't want the customer's product to be mailed to San Diego, VA instead of CA.</p> <p>Then next most important thing is to really understand your user interface and how it works. I've spent a lot of time fixing up junk because users didn't know what they were supposed to put in fields in databases (it would have helped if the developers had not allowed non-email type data to be entered into the email field, but you can't send an email to 757-111-6789). It is never a good idea to put the wrong kind of data into a field because you don't have another place to put it. As a user, you may have no idea what the database is going to use that data for and wrong data can completely stop a process or break something really important. If you don't know what to put in a field, then ask. Don't put junk into a field just because it is required. (Hint, it is required for a reason, that usually means this is data critical to the operation of the database, do not fake this information.)</p> <p>Now if this person is doing reporting, then the critical concepts become understanding boolean algebra and a very strong undertanding of joins. If you have these two concepts down pat, you have 80-90% of what you need to query a database. </p> <p>The specifics of the database supported also become important. You need to understand what is stored in what tables (or what views to use) and how they relate to each other. Coming into a new job, I would sit down with the developers if possible and get an overview of the design and whatI would need to know to get the data. I would review existing report queries to see how the data is currently being retrieved and use that to ask questions if I don't understand what the person did. Even a database expert will need to spend some time doing this when faced with a new database, so there is no reason to be shy in asking these questions when you are new.</p> <p>Final thing is to learn how to report a problem to the developers. Problems that are not reported don't get fixed! Problems that are not reproducable because the user didn't provide screen shots and a context for what she was doing when the error occurred, don't get fixed either. New data fields that are needed as business requirements change, don't get added to the database until the developers know about them (Please ask for a Notes field if you need it instead of entering junk data into a field like email that you personally are not using for instance). New business requirements often require a lot of work in the backend to change how things work, it isn't as simple as adding a field on a form. Please be aware of that too when you make requests.</p>
23,266
<p>I use TortoiseSVN 1.5.3 and VisualSVN 1.5.3 (Subversion 1.5.2)</p> <p>Suppose that I create a new branch (/branches/branch1) of the trunk(/trunk) then someone (also using TortoiseSVN 1.5.3) merges their branch back into the trunk. </p> <p>I try to merge from the trunk into the branch (to aquire all changes which might have beemn merged into the trunk by others)</p> <p>I do not specify any particular revision(s) because I want the merge-tracking to determine which revisions I need to merge. I expect these to be revisions after the one in which I created the branch.</p> <p>When I start the merge, the output dialog seems to merge every revision back to revision 1. this causes everything in the repository to be 'added'.</p> <p>What a I doing wrong?.... I expected a single revision to be targeted and for this to be a very quick operation.</p> <p>I have tried...</p> <pre><code>SVNAdmin Upgrade &lt;MyRepoPath&gt; </code></pre> <p>This resulted in a an instantaneous success message after which I repeated my experiment with no change in results</p> <p>Update: I have noticed that the TortoiseSVN dialog says "To merge all revisions, leave the box empty."... does this mean that TortoiseSVN is adding the 1-Head explicity and that there is no way to use Merge-Tracking? That would seem a bit strange.</p>
<p>SOLVED: The answer appears to be down to a workaround we implemented here for some previous bugs in Subversion.</p> <p>The workaround involved the use of SomeUserName@ being placed in the url. thus</p> <pre><code>http://SomeUsername@Myserver:8080/myrepo/trunk </code></pre> <p>...was being used instead of...</p> <pre><code>http://Myserver:8080/myrepo/trunk </code></pre> <p>It seems that the working copy of the branch was retrieved without this addition and the Merge was being done to a url with this addtion. this led Subversion to deduce that they were 2 different urls and naturally(ish) deduced they had no common history from which to locate the startpoint to merge from.</p> <p><strong>Thus the solution is to ensure the format of the 'from' url used for the merge matches the format of the url used by the working copy.</strong></p>
<p>I think you need to use the Branch as your from URL. The reason is that your Trunk revision is now higher than your Branch, and so you need to start with the lowest revision.</p>
21,135
<p>I have been looking in to doing some test driven development for one of the applications that I'm currently writing(OLE wrapper for an OLE object). The only problem is that I am using the express versions of Visual Studio(for now), at the moment I am using VB express but sometimes I use C# express. </p> <p>Is it possible to do TDD in the express versions? If so what are the bast was to go about it?</p> <p>Cheers.</p> <p>EDIT. By the looks of things I will have to buy the full visual studio so that I can do integrated TDD, hopefully there is money in the budget to buy a copy :). For now I think I will use Nunit like everyone is saying.</p>
<p><a href="http://www.nunit.org/index.php" rel="noreferrer">Nunit</a> seems to work independently, why not try it with the express versions of Visual Studio?</p> <p>It looks like you have to use the test dlls outside of VS , from the Nunit GUI.</p>
<p>For unit testing you can use <a href="http://www.nunit.org/index.php" rel="nofollow noreferrer">NUnit</a>.</p> <p>For code completion you can use <a href="http://www.ncover.com/" rel="nofollow noreferrer">NCover</a> and <a href="http://webscripts.softpedia.com/script/Development-Scripts-js/NCoverExplorer-29187.html" rel="nofollow noreferrer">NCoverExplorer</a>.</p> <p>All the above don't plug into Visual Studio Express but they do have their own UI. I normally run my tests using a batch script.</p>
32,206
<p>This Linq to SQL query ...</p> <pre><code> Return (From t In Db.Concessions Where t.Country = "ga" Select t.ConcessionID, t.Title, t.Country) </code></pre> <p>... is generating this SQL:</p> <pre><code>SELECT [t0].[ConcessionID], [t0].[Title], [t0].[Country] FROM [dbo].[Concessions] AS [t0] WHERE [t0].[Country] = ga </code></pre> <p>... when what I want is</p> <pre><code>WHERE [t0].[Country] = 'ga' </code></pre> <p>Any ideas why?</p>
<p>Wild guess.... could it be?</p> <p><code>t.Country = "ga"</code></p> <p>vs.</p> <p><code>t.Country == "ga"</code></p>
<p>the select should be</p> <pre><code>Select New With {t.ConcessionID, t.Title, t.Country} </code></pre> <p>rather than </p> <pre><code>Select t.ConcessionID, t.Title, t.Country </code></pre> <p>you need to create a new instance of an anonymous type to contain the fields.</p>
21,717
<p>I'm developing a graphical application to present data (not a game but a real workhorse app). It needs to be cross platform, so I have chosen:</p> <ul> <li>python</li> <li>openGL (I need 3D, blending, textures etc)</li> <li>pyopengl</li> <li>wx/pywx - windowing, dialogs etc.</li> </ul> <p>The last component - WX - raises the question. I can put together a very nice looking app (the prototypes look slick) - but when I need to interact with the user to ask questions, get input, I have to use WX. It makes the app look inconsistent to have traditional UI with traditional dialogs and combos and text entry on top of a full screen 3D app with blending, smooth motion, textures etc.</p> <p>Has anyone developed a GUI using OpenGL and python? Can you share with me the toolkits and/or tricks you used? I need combos, text entry, buttons, radios, option buttons, tree view.</p> <p>There are some toolkits out there, but they are either incomplete or old and unmaintained. A great example is pyUI (<a href="http://pyui.sourceforge.net/" rel="nofollow noreferrer">http://pyui.sourceforge.net/</a>) - looks slick but untouched for years.</p>
<p>This is not an answer, more of a plea: Please don't do that.</p> <p>Your reimplemented widgets will lack all sorts of functionality that users will miss. Will your text-entry boxes support drag'n'drop? Copy/paste? Right-to-left scripts? Drag-select? Double-click-select? Will all these mechanisms follow the native conventions of each platform you support?</p> <p>With Wx your widgets might look inconsistant with the app, but at least they'll look consistant with the OS which is just as important. And more importantly, they'll do what users expect.</p> <p>(edit) Three posts, and -3 points? Screw this den of karma-whores. Original poster: I have implemented a basic set of widgets in OpenGL (for a game UI) and it was an endless nightmare of a job.</p>
<p>my friend.<br> I believe I have found your answer ;)<br> <a href="http://glinter.sourceforge.net/" rel="nofollow">http://glinter.sourceforge.net/</a></p> <p>I havn't yet tried it, but it seems quite promising. (I'll edit this if it doesn't work)</p> <p>EDIT:<br> eh...<br> it uses Tk, PMW, and WX...<br> (not quite what I want)</p> <p>you can give the CVS download a try...<br> (there's no released packages, but the CVS runs)</p>
10,370
<p>This is to all the C# gurus. I have been banging my head on this for some time already, tried all kinds of advice on the net with no avail. The action is happening in Windows Mobile 5.0.</p> <p>I have a DLL named MyDll.dll. In the MyDll.h I have:</p> <pre><code>extern "C" __declspec(dllexport) int MyDllFunction(int one, int two); </code></pre> <p>The definition of MyDllFunction in MyDll.cpp is:</p> <pre><code>int MyDllFunction(int one, int two) { return one + two; } </code></pre> <p>The C# class contains the following declaration:</p> <pre><code>[DllImport("MyDll.dll")] extern public static int MyDllFunction(int one, int two); </code></pre> <p>In the same class I am calling MyDllFunction the following way:</p> <pre><code>int res = MyDllFunction(10, 10); </code></pre> <p>And this is where the bloody thing keeps giving me "Can't find PInvoke DLL 'MyDll.dll'". I have verified that I can actually do the PInvoke on system calls, such as "GetAsyncKeyState(1)", declared as:</p> <pre><code> [DllImport("coredll.dll")] protected static extern short GetAsyncKeyState(int vKey); </code></pre> <p>The MyDll.dll is in the same folder as the executable, and I have also tried putting it into the /Windows folder with no changes nor success. Any advice or solutions are greatly appreciated.</p>
<p>Maybe this seems like an obvious thing to check, but are you compiling the native DLL for the correct CPU architecture? IIRC, Windows Mobile runs on multiple CPU architectures.</p>
<p>The exception you listed and the pinvoke signature you put in the question have different names: MyDll.dll and ThreadBenchLib.dll respectively. Was that a typo or the problem?</p> <p>If it's not the problem try opening the DLL in <a href="http://www.dependencywalker.com/" rel="nofollow noreferrer">depends</a>. It's possible the DLL load is failing because of an unmet dependency. </p>
41,380
<p>As a passionate JavaScript developer, I'd like to know if there's any quality Podcasts out there, devoted to JavaScript. (Both video and audio).</p> <p>I am currently subscribing to:</p> <ul> <li><a href="http://developer.yahoo.com/yui/theater/" rel="noreferrer">YUI Theater</a></li> <li><a href="http://ajaxian.com/by/category/podcasts" rel="noreferrer">Audible Ajax</a></li> </ul>
<p><a href="http://www.javascriptshow.com" rel="noreferrer">The JavaScript Show</a> just launched and, I may be biased, but think it's pretty awesome.</p>
<p>You can check out the OpenWeb Podcast:</p> <p><a href="http://openwebpodcast.com/" rel="nofollow noreferrer">http://openwebpodcast.com/</a></p>
17,573
<p>What is the default location for the MySQL configuration file on a redhat linux box?</p>
<p>Just found it, it is /etc/my.cnf</p>
<p>From the header of '/etc/mysql/my.cnf':</p> <pre><code>MariaDB programs look for option files in a set of locations which depend on the deployment platform. [...] For information about these locations, do: 'my_print_defaults --help' and see what is printed under "Default options are read from the following files in the given order:" More information at: http://dev.mysql.com/doc/mysql/en/option-files.html </code></pre>
44,404
<p>Back in the old days, Help was not trivial but possible: generate some funky .rtf file with special tags, run it through a compiler, and you got a WinHelp file (.hlp) that actually works really well.</p> <p>Then, Microsoft decided that WinHelp was not hip and cool anymore and switched to CHM, up to the point they actually axed WinHelp from Vista.</p> <p>Now, CHM maybe nice, but everyone that tried to open a .chm file on the Network will know the nice "Navigation to the webpage was canceled" screen that is caused by security restrictions.</p> <p>While there are ways to make CHM work off the network, this is hardly a good choice, because when a user presses the Help Button he wants help and not have to make some funky settings.</p> <p>Bottom Line: I find CHM absolutely unusable. But with WinHelp not being an option anymore either, I wonder what the alternatives are, especially when it comes to integrate with my Application (i.e. for WinHelp and CHM there are functions that allow you to directly jump to a topic)?</p> <p>PDF has the disadvantage of requiring the Adobe Reader (or one of the more lightweight ones that not many people use). I could live with that seeing as this is kind of standard nowadays, but can you tell it reliably to jump to a given page/anchor?</p> <p>HTML files seem to be the best choice, you then just have to deal with different browsers (CSS and stuff).</p> <p><em>Edit:</em> I am looking to create my own Help Files. As I am a fan of the "No Setup, Just Extract and Run" Philosophy, i had that problem many times in the past because many of my users will run it off the network, which causes exactly this problem.</p> <p>So i am looking for a more robust and future-proof way to provide help to my users without having to code a different help system for each application i make.</p> <p>CHM is a really nice format, but that Security Stuff makes it unusable, as a Help system is supposed to provide help to the user, not to generate even more problems.</p>
<p>HTML would be the next best choice, ONLY IF you would serve them from a public web server. If you tried to bundle it with your app, all the files (and images (and stylesheets (and ...) ) ) would make CHM look like a gift from gods.</p> <p>That said, when actually bundled in the installation package, (instead of being served over the network), I found the CHM files to work nicely.</p> <p>OTOH, another pitfall about CHM files: Even if you try to open a CHM file on a <strong>local</strong> disk, you may bump into the security block if you initially downloaded it from somewhere, because the file could be marked as "came from external source" when it was obtained.</p>
<p>I use a commercial package called AuthorIT that can generate a number of different formats, such as chm, html, pdf, word, windows help, xml, xhtml, and some others I have never heard of (does dita ring a bell?). It is a content management system oriented towards the needs of technical documentation writers. The advantage is that you can use and re-use the same content to build a set of guides, and then generate them in different formats.</p> <p>So the bottom line relative to the question of choosing chm or html or whatever is that if you are using this you are not locked into a given format, but you can provide several among which the user can choose, and you can even add more formats as you go along, at no extra cost.</p> <p>If you just have one guide to create it won't be worth your while, but if you have a documentation set to manage then it is the best to my knowledge. Their support is very helpful also.</p>
2,355
<p>Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like <code>obj.attr</code> ? Or perhaps write get accessors ? What are the accepted naming styles for such things ?</p> <p><strong>Edit:</strong> Can you elaborate on the best-practices of naming attributes with a single or double leading underscore ? I see in most modules that a single underscore is used.</p> <hr> <p>If this question has already been asked (and I have a hunch it has, though searching didn't bring results), please point to it - and I will close this one.</p>
<p>The generally accepted way of doing things is just using simple attributes, like so</p> <pre><code>>>> class MyClass: ... myAttribute = 0 ... >>> c = MyClass() >>> c.myAttribute 0 >>> c.myAttribute = 1 >>> c.myAttribute 1 </code></pre> <p>If you do find yourself needing to be able to write getters and setters, then what you want to look for is "python class properties" and <a href="http://tomayko.com/writings/getters-setters-fuxors" rel="noreferrer">Ryan Tomayko's article on Getters/Setters/Fuxors</a> is a great place to start (albeit a little long)</p>
<p>Some people use getters and setters. Depending on which coding style you use you can name them getSpam and seteggs. But you can also make you attributes readonly or assign only. That's a bit awkward to do. One way is overriding the </p> <pre><code>&gt; __getattr__ </code></pre> <p>and </p> <pre><code>&gt; __setattr__ </code></pre> <p>methods.</p> <h2>Edit:</h2> <p>While my answer is still true, it's not right, as I came to realize. There are better ways to make accessors in python and are not very awkward.</p>
20,035
<p>I'm trying to perform a simple LINQ query on the Columns property of a DataTable:</p> <pre><code>from c in myDataTable.Columns.AsQueryable() select c.ColumnName </code></pre> <p>However, what I get is this:</p> <blockquote> <p>Could not find an implementation of the query pattern for source type 'System.Linq.IQueryable'. 'Select' not found. Consider explicitly specifying the type of the range variable 'c'.</p> </blockquote> <p>How can I get the DataColumnCollection to play nice with LINQ?</p>
<p>How about:</p> <pre><code>var x = from c in dt.Columns.Cast&lt;DataColumn&gt;() select c.ColumnName; </code></pre>
<p>You could also use:</p> <pre><code>var x = from DataColumn c in myDataTable.Columns select c.ColumnName </code></pre> <p>It will effectively do the same as Dave's code: "in a query expression, an explicitly typed iteration variable translates to an invocation of Cast(IEnumerable)", according to the <a href="http://msdn.microsoft.com/en-us/library/bb341406.aspx" rel="noreferrer"><code>Enumerable.Cast&lt;TResult&gt; Method</code></a> MSDN article.</p>
29,354
<p>Should operations that could take some time be performed in a constructor or should the object be constructed and then initialised later.</p> <p>For example when constructing an object that represents a directory structure should the population of the object and its children be done in the constructor. Clearly, a directory can contain directories and which in turn can contain directories and so on.</p> <p>What is the elegant solution to this?</p>
<p>To summarize:</p> <ul> <li><p>At a minimum, your constructor needs to get the object configured to the point that its invariants are true.</p></li> <li><p>Your choice of invariants may affect your clients.(Does the object promise to be ready for access at all times? Or only only in certain states?) A constructor that takes care of all of the set-up up-front may make life simpler for the class's clients.</p></li> <li><p>Long-running constructors are not inherently bad, but may be bad in some contexts.</p></li> <li><p>For systems involving a user-interaction, long-running methods of any type may lead to poor responsiveness, and should be avoided.</p></li> <li><p>Delaying computation until after the constructor may be an effective optimization; it may turn out to be unnecessary to perform all the work. This depends on the application, and shouldn't be determined prematurely.</p></li> <li><p>Overall, it depends.</p></li> </ul>
<p>Try to have what you think is necessary there and dont think about if it will be slow or fast. Preoptimization is a time waster so code it, profile it and optimize it if needed. </p>
37,528
<p>Is there a difference between using a makefile and a Makefile?</p>
<p>gmake uses the first "make" file found using the following order:</p> <p>GNUmakefile, makefile, Makefile</p> <p>Otherwise, they are semantically equivalent. GNU recommends only using GNUmakefile if you are using GNU extensions.</p> <p><a href="http://www.gnu.org/software/make/manual/html_node/Makefile-Names.html#Makefile-Names" rel="nofollow noreferrer">Source</a></p>
<p>Oops. Should've Googled it.</p> <p>If a directory has a makefile and a Makefile, gmake will take the makefile in preference.</p>
31,407
<p>Does anyone know if its possible to create a new property on an existing Entity Type which is based on 2 other properties concatenated together?</p> <p>E.g. My Person Entity Type has these fields "ID", "Forename", "Surname", "DOB"</p> <p>I want to create a new field called "Fullname" which is </p> <pre><code>Forenames + " " + Surname </code></pre> <p>So i end up with "ID", "Forename", "Surname", "DOB", "Fullname".</p> <p>I know i can do this using Linq programmatically i.e.</p> <pre><code>var results = from p in db.People select new { ID = p.ID, Forename = p.Forename, Surname = p.Surname, DOB = p.DOB, Fullname = p.Forename+ " " + p.Surname }; </code></pre> <p>Then calling something like</p> <pre><code>var resultsAfterConcat = from q in results where q.Fullname.Contains(value) select q; </code></pre> <p>However i'd really like to use Linq to Entities to do this work for me at the Conceptual Model level.</p>
<p>Not yet, but maybe soon. First, note that your suggested query will not work at all in LINQ to Entities, with or without the property, because, at present, it doesn't support Contains. The new version of the Entity Framework in .NET 4.0, however, is supposed to support custom methods in LINQ to Entities queries. You can see <a href="http://mschnlnine.vo.llnwd.net/d1/pdc08/WMV-HQ/TL20.wmv" rel="nofollow noreferrer">a video about this from PDC</a>. Essentially, you have to write the custom method twice; once in code, and once on your database (e.g., in a calculated field). See the video for more information.</p>
<p>Craig,</p> <p>Sarted watching the video, then realised it's over an hour long, so will have to watch it when i have more time. Just to let you know though.. <strong><em>Contains</em></strong> seems to be working ok for me, here's the SQL that's generated by Linq to Entities:</p> <pre><code>SELECT 1 AS [C1], [Extent1].[PeopleID] AS [PeopleID], [Extent1].[Forenames] AS [Forenames], [Extent1].[Surname] AS [Surname] FROM [dbo].[People] AS [Extent1] WHERE (CHARINDEX(N'Dave', [Extent1].[Forenames] + N' ' + [Extent1].[Surname])) &gt; 0 </code></pre> <p>It seems to work a treat. Using <strong><em>CHARINDEX</em></strong> to workout if the Concatinated field contains the entered text which is the above case was "<strong><em>Dave</em></strong>".</p> <p>Thanks Dave</p>
38,337
<p>I am currently using NUnit and testing a class library. Up until now, I have used a list of constants at the top of the test class to hold some static test variables. Is this the best way to do this, or is there a more fluent way to handle it?</p>
<p>By "static test variables" do you actually mean constants (whether genuine constant, immutable instances or just ones you don't change)? I use those frequently, and just put them at the top of the test class.</p> <p>If there are several related test classes, it can be handy to separate out common values into a different class though. (It <em>could</em> act as your base class, but I'm not terribly fond of using inheritance just to get access to things more easily. Java static imports are handy there...)</p>
<p>Whenever I can, I store data externally in an xml file that we check into source control. </p>
23,207
<p>Sorry in advance for the long question. What I'm really interested in is a way to programmatically check if the executing windows identity has adequate windows privileges to write to a directory (or file) in an ASP.NET web services application. But I'll settle for retrieving effective delete (modify) privileges for a user for a given directory or file. The problem is that I would like to be able to do this without either writing temporary files OR necessarily performing the IO action and handling the exception. </p> <p>Yes, there is a question on this already ( see <a href="https://stackoverflow.com/questions/137031/how-can-i-programmatically-determine-if-i-have-write-privileges-using-c-in-net">How can I programmatically determine if I have write privileges using C# in .Net?</a>) Normally I would agree with the accepted answer that the best method is to just try the IO action and handle any exceptions -- System.IO methods do throw System.UnauthorizedAccessException to indicate failure as a result of privilege denial. But in the case of of UPLOADING files, I'd really like to check the privileges BEFORE wasting the time and resources of uploading the data since it is only AFTER upload that we can attempt to write the file or folder in question. I pity any users uploading a 2GB file over http only to be told after the upload completes that they don't have permissions to upload the file to the destination.</p> <p>The usual approach to testing write access if you don't want to perform the actual write is to write a temporary file. The other question has an answer pointing this out. This is what our code currently does. BUT windows security allows write access without delete privileges. Users with ONLY write access but no delete end up leaving all sorts of undeleted .tmp files. And no, we don't want to use a Domain admin account to reset the ACL on the tmp files and then delete them. The approach I've been taking is to check if the user has write privileges using System.IO.Directory.GetAccessControl(..) or System.IO.File.GetAccessControl(..) and dealing with the various access rules and ACE returns... but with this I still have issues dealing with EFFECTIVE privileges -- i.e. in most cases I also have to look up the user's membership in any of the groups listed in the ACE that do have permissions on the object. There has to be an easier way.... doesn't there?</p>
<p>Well kudos for going the extra mile on user experience AND trying to maintain clean program structure. Maybe if you're uploading only you could try to create an empty 'placeholder' file with the same name as the final 2GB file will have, then just overwrite it. Not perfect since you could still end up with an empty file, but pretty easy and at least a little bit more elegant that some of the alternatives.</p>
<p>You could also have permanent file, say 'access_test.txt', which you try to overwrite with a datestamp or something to first to test the current access.</p>
48,227
<p>Since I kicked off the process of inserting 7M rows from one table into two others, I'm wondering now if there's a faster way to do this. The process is expected to finish in an hour, that's 24h of processing.</p> <p>Here's how it goes:</p> <p>The data from this table</p> <pre><code>RAW (word VARCHAR2(4000), doc VARCHAR2(4000), count NUMBER); </code></pre> <p>should find a new home in two other cluster tables T1 and T2</p> <pre><code>CREATE CLUSTER C1 (word VARCHAR2(4000)) SIZE 200 HASHKEYS 10000000; CREATE CLUSTER C2 (doc VARCHAR2(4000)) SIZE 200 HASHKEYS 10000000; T1 (word VARCHAR2(4000), doc VARCHAR2(4000), count NUMBER) CLUSTER C1(word); T2 (doc VARCHAR2(4000), word VARCHAR2(4000), count NUMBER) CLUSTER C2(doc); </code></pre> <p>through Java inserts with manual commit like this</p> <pre><code>stmtT1 = conn.prepareStatement("insert into T1 values(?,?,?)"); stmtT2 = conn.prepareStatement("insert into T2 values(?,?,?)"); rs = stmt.executeQuery("select word, doc, count from RAW"); conn.setAutoCommit(false); while (rs.next()) { word = rs.getString(1); doc = rs.getString(2); count = rs.getInt(3); if (commitCount++==10000) { conn.commit(); commitCount=0; } stmtT1.setString(1, word); stmtT1.setString(2, doc); stmtT1.setInt(3, count); stmtT2.setString(1, doc); stmtT2.setString(2, word); stmtT2.setInt(3,count); stmtT1.execute(); stmtT2.execute(); } conn.commit(); </code></pre> <p>Any ideas?</p>
<p>The first thing I'd recommend is to do a simple insert-select statement, and let the database handle all the data movement. Not so useful if you're moving data between two machines, or if you don't have rollback segments large enough to handle the entire query.</p> <p>The second thing I is to learn about the <a href="http://file:///usr/local/java/jdk-1.5/docs/api/java/sql/PreparedStatement.html#addBatch()" rel="nofollow noreferrer">addBatch()</a> method. As you've written your code, it makes a round-trip to the database for every row that you're inserting, which adds network overhead.</p> <p>Third, unless you already have lots of rows in the destination tables is to drop any indexes before your inserts, and recreate afterward. If you leave the indexes in place, they have to be updated for every row, adding to the dirty block overhead.</p> <p>And finally: do you need clustered tables? My experience has been that they don't buy you a lot (caveat: that experience was on a single tablespace).</p>
<p>Unless you have some special reason to handle data in app, I would go for direct INSERT AS SELECT. Using Parallel DML can give you tremendous difference. </p> <p>Check also INSERT ALL syntax (1 read for 2 writes) if that fits your needs.</p> <p>Unless you have IO problems, 1h should be more than enough...</p> <p>Regards</p>
47,673
<p>I'm conducting experiments regarding e-mail spam. One of these experiments require sending mail thru Tor. Since I'm using Python and smtplib for my experiments, I'm looking for a way to use the Tor proxy (or other method) to perform that mail sending. Ideas how this can be done?</p>
<p>If you're using a version of Java prior to 8... you can use <a href="http://joda-time.sourceforge.net/" rel="noreferrer">Joda Time</a> and <a href="http://joda-time.sourceforge.net/api-release/org/joda/time/format/PeriodFormatter.html" rel="noreferrer"><code>PeriodFormatter</code></a>. If you've really got a duration (i.e. an elapsed amount of time, with no reference to a calendar system) then you should probably be using <code>Duration</code> for the most part - you can then call <code>toPeriod</code> (specifying whatever <code>PeriodType</code> you want to reflect whether 25 hours becomes 1 day and 1 hour or not, etc) to get a <code>Period</code> which you can format.</p> <p>If you're using Java 8 or later: I'd normally suggest using <code>java.time.Duration</code> to represent the duration. You can then call <code>getSeconds()</code> or the like to obtain an integer for standard string formatting as per bobince's answer if you need to - although you should be careful of the situation where the duration is negative, as you probably want a <em>single</em> negative sign in the output string. So something like:</p> <pre><code>public static String formatDuration(Duration duration) { long seconds = duration.getSeconds(); long absSeconds = Math.abs(seconds); String positive = String.format( "%d:%02d:%02d", absSeconds / 3600, (absSeconds % 3600) / 60, absSeconds % 60); return seconds &lt; 0 ? "-" + positive : positive; } </code></pre> <p>Formatting this way is <em>reasonably</em> simple, if annoyingly manual. For <em>parsing</em> it becomes a harder matter in general... You could still use Joda Time even with Java 8 if you want to, of course.</p>
<p>in scala, no library needed:</p> <pre><code>def prettyDuration(str:List[String],seconds:Long):List[String]={ seconds match { case t if t &lt; 60 =&gt; str:::List(s"${t} seconds") case t if (t &gt;= 60 &amp;&amp; t&lt; 3600 ) =&gt; List(s"${t / 60} minutes"):::prettyDuration(str, t%60) case t if (t &gt;= 3600 &amp;&amp; t&lt; 3600*24 ) =&gt; List(s"${t / 3600} hours"):::prettyDuration(str, t%3600) case t if (t&gt;= 3600*24 ) =&gt; List(s"${t / (3600*24)} days"):::prettyDuration(str, t%(3600*24)) } } val dur = prettyDuration(List.empty[String], 12345).mkString("") </code></pre>
33,456
<p>I am trying to use <code>WebClient</code> to download a file from web using a WinForms application. However, I really only want to download HTML file. Any other type I will want to ignore.</p> <p>I checked the <code>WebResponse.ContentType</code>, but its value is always <code>null</code>. </p> <p>Anyone have any idea what could be the cause?</p>
<p>Given your update, you can do this by changing the .Method in GetWebRequest:</p> <pre><code>using System; using System.Net; static class Program { static void Main() { using (MyClient client = new MyClient()) { client.HeadOnly = true; string uri = "http://www.google.com"; byte[] body = client.DownloadData(uri); // note should be 0-length string type = client.ResponseHeaders["content-type"]; client.HeadOnly = false; // check 'tis not binary... we'll use text/, but could // check for text/html if (type.StartsWith(@"text/")) { string text = client.DownloadString(uri); Console.WriteLine(text); } } } } class MyClient : WebClient { public bool HeadOnly { get; set; } protected override WebRequest GetWebRequest(Uri address) { WebRequest req = base.GetWebRequest(address); if (HeadOnly &amp;&amp; req.Method == "GET") { req.Method = "HEAD"; } return req; } } </code></pre> <p>Alternatively, you can check the header when overriding GetWebRespons(), perhaps throwing an exception if it isn't what you wanted:</p> <pre><code>protected override WebResponse GetWebResponse(WebRequest request) { WebResponse resp = base.GetWebResponse(request); string type = resp.Headers["content-type"]; // do something with type return resp; } </code></pre>
<p>You could issue the first request with the HEAD verb, and check the content-type response header? [edit] It looks like you'll have to use HttpWebRequest for this, though.</p>
18,524
<p>I'm building a simple ASP.NET web application in VS 2008 with a SQL 2005 database. I'm working on Vista and I'd prefer not to install IIS (I'd rather just us Cassini for local testing). Here's what I've tried:</p> <ul> <li><p>FrontPage Server Extensions. I installed these on my server, but they broke my default web site and I still couldn't publish from VS 2008 via FPSE.</p></li> <li><p>FTP. I setup an FTP site rooted at my IIS web root and that worked for a single, default web site. When I setup a second site and move the two into sub-folders, the FTP publishing method from VS couldn't handle publishing to a sub-directory. Security is also a problem with this method since it sends the credentials as clear text.</p></li> </ul> <p>I've considered a couple of alternatives:</p> <ul> <li><p>Install CruiseControl.NET on the server and configure it so that I can start a build on the server and, if it succeeds, XCopy deploy the site to IIS. I'm not that keen, however, on running my build process on my public-facing web server.</p></li> <li><p>Live Mesh. I considered XCopy deploying to a local directory and using Live Mesh to replicate it to a virtual directory on my server.</p></li> </ul> <p>Does anyone have a tried and true method of solving this problem?</p> <p>Thanks, Jim</p>
<p>Just publish it with Visual Studio to a local directory and then copy the contents of the local directory via FTP/SFTP/SCP to the server.</p> <p>If you need an SFTP server for Windows, check out <a href="http://filezilla-project.org/" rel="nofollow noreferrer">FileZilla</a>. It can do FTP and SFTP as well, and also it has a server and a client component.</p>
<p>I use <a href="http://www.microsoft.com/downloads/details.aspx?familyId=0AA30AE8-C73B-4BDD-BB1B-FE697256C459&amp;displaylang=en" rel="nofollow noreferrer">Web Deployment Projects</a> to publish to a local folder - which gives me a little more control than a straight publish, then copy to the server like DrJokepu</p>
36,002
<p>I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word".</p> <p>My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?</p>
<p>You could try:</p> <pre><code>&gt;&gt;&gt; re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWord") 'Word Word Word' </code></pre>
<p>I think regexes are the way to go here, but just to give a pure python version without (hopefully) any of the problems ΤΖΩΤΖΙΟΥ has pointed out:</p> <pre><code>def splitCaps(s): result = [] for ch, next in window(s+" ", 2): result.append(ch) if next.isupper() and not ch.isspace(): result.append(' ') return ''.join(result) </code></pre> <p>window() is a utility function I use to operate on a sliding window of items, defined as:</p> <pre><code>import collections, itertools def window(it, winsize, step=1): it=iter(it) # Ensure we have an iterator l=collections.deque(itertools.islice(it, winsize)) while 1: # Continue till StopIteration gets raised. yield tuple(l) for i in range(step): l.append(it.next()) l.popleft() </code></pre>
24,262
<p>As I stated in <a href="https://stackoverflow.com/questions/341192/segmentation-fault-using-sdl-with-c-trying-to-blit-images">this question</a>, I am using SDL for a small game I'm developing. Now I am having problems with SDL_DisplayFormatAlpha. I am trying to create a surface with an alpha channel from a PNG image. It was working before, but now that I've done some slight refactoring something got broken. I've narrowed it down to this constructor:</p> <pre><code> Surface::Surface( tfilename file ) { // initialize the surface data member to the image indicated by filename SDL_Surface *tempSurface; tempSurface = IMG_Load( file.c_str() ); if ( !tempSurface ) { surface = NULL; exit(1); } else { surface = SDL_DisplayFormatAlpha( tempSurface ); //surface = tempSurface; } SDL_FreeSurface( tempSurface ); } </code></pre> <p>This compiles just fine, but when I run it I get a Segmentation fault. The error reported by gdb:</p> <pre> Program received signal SIGSEGV, Segmentation fault. [Switching to Thread 0xb79c16c0 (LWP 8089)] 0xb7e8b9a3 in SDL_DisplayFormatAlpha () from /usr/lib/libSDL-1.2.so.0 </pre> <p>The stack trace is as follows:</p> <pre> #0 0xb7e8b9a3 in SDL_DisplayFormatAlpha () from /usr/lib/libSDL-1.2.so.0 #1 0x0804987e in Surface (this=0x804d060, file=@0xbfb20760) at Surface.cpp:16 #2 0x0804a159 in Image (this=0x804d038, x=0, y=0, file=@0xbfb207a0) at Image.cpp:16 #3 0x0804a3de in Object (this=0x804d028, imageFile=@0xbfb207dc) at Object.cpp:4 #4 0x080491cb in Application (this=0xbfb20810) at Application.cpp:8 #5 0x08048e0d in main () at main.cpp:5 </pre> <p>If I comment out <code>surface = SDL_DisplayFormatAlpha( tempSurface );</code> and <code>SDL_FreeSurface( tempSurface );</code> and uncomment <code>surface = tempSurface;</code> like so:</p> <pre><code> Surface::Surface( tfilename file ) { // initialize the surface data member to the image indicated by filename SDL_Surface *tempSurface; tempSurface = IMG_Load( file.c_str() ); if ( !tempSurface ) { surface = NULL; exit(1); } else { //surface = SDL_DisplayFormatAlpha( tempSurface ); surface = tempSurface; } //SDL_FreeSurface( tempSurface ); }</code></pre> <p>Then it seems to work just fine. Can anyone tell me what's going on? Actually, the transparency seems to work, too when I comment out SDL_DisplayFormatAlpha. Is that function only meant to be used with images that do not already have an alpha channel?</p>
<p>IMG_Load should handle transparent PNG's automatically, as the end of your post notes. What is the actual exception/error being thrown? Your stack trace doesn't show that.</p>
<p>If you read the link here (related function):</p> <p><a href="http://sdl.beuc.net/sdl.wiki/SDL_DisplayFormat" rel="nofollow noreferrer">SDL_DisplayFormat</a></p> <p>"You have to call SDL_Init before using the SDL_DisplayFormat function. If you don't, your program will crash with an access violation."</p> <p>Could that be your problem?</p>
44,572
<p>Fairly long winded, but hopefully makes sense;</p> <p>I understand that G-code is executed line-by-line, and in the main printing phase each instruction is effectively go to location XY (assuming staying within the layer) at a set speed with a set extrusion amount (not rate, as far as I can tell). </p> <p>Imagine you were printing a single road width, say 10&nbsp;mm long. If the single instruction says to move that 10&nbsp;mm at a set speed and extrude 10mm of material (which is, I guess, not 10mm of filament), with infinite acceleration and deceleration of the nozzle and extruder gears, then a linear amount of material would be extruded per unit length along the 10&nbsp;mm. However, given that there is some acceleration and deceleration, that extrusion must be non-linear. </p> <p>My questions are as follows; - Is it possible to counteract this within a single line of Gcode by having a variable extrusion rate? - Can the machine do so regardless of the instructions given to it? - Is this effect embraced somehow? - Does the need to accelerate both the nozzle position and filament effectively cancel out? -Would/could you aim instead to split a single straight line of filament into multiple lines of G-code, some extruding (say in the middle), and some not (say at each end)?</p>
<p>My understanding is that the printer firmware will define the maximum acceleration and speeds for each axis (X, Y, Z, and E). When executing a line of g-code that involves more than one axis, the acceleration for each will be limited such that they all begin and end, including acceleration together.</p> <p>During the start and end of a line, when the print nozzle is moving more slowly, the extruder will also move slowly. In the middle of the line, the extruder will move faster. The amount of material extruded per distance will be constant over the length of the line.</p> <p>Another way to look at it - suppose you could accelerate quickly on X with a high top speed, but slowly on Y. A move only in the X direction could happen quickly. A move only in the Y direction would be slower. If you want to move at a 45-degree angle, you will need to slow down X so that it doesn't get ahead of Y.</p> <p>If you did want to intentionally vary the amount of extrusion per distance during a line, you would need to break it into multiple segments with individual lines of g-code.</p>
<h1>No</h1> <p>G-code is written line separated, starting with one command what to do, then who does it with what factors. For example <code>G1 X10 F100 E10</code> says this:</p> <ul> <li><code>G1</code> Move...</li> <li><code>X10</code> The X axis by 10</li> <li><code>F100</code> Use the factor to 100 units</li> <li><code>E10</code> Also: the Extruder by 10</li> </ul> <p>To my knowledge any repeated or invalid expression is simply ignored (or overwritten). So <code>G1 X10 F100 E10 F200</code> gets parsed as either <code>G1 X10 F100 E10</code> or <code>G1 X10 E10 F200</code>, depending on how your firmware interpreter is set up.</p>
1,218
<p>I have develop an XNA game on computer 1. When I send it to computer two (and I have everything to be able to run XNA Code). When the program execute game.run, I get an InvalidOperationException. </p> <p>I didn't tried to run code from computer two on computer one. But I know that both machine can run the code I've wrote on them.</p> <p>Do you have any idea ?</p> <p>EDIT : Oh, I added the asnwer, but I can't select my post as the answer...</p> <hr> <p>CallStack : </p> <blockquote> <p>App.exe!App.Program.Main(string[] args = {Dimensions:[0]}) Line 14 C#</p> </blockquote> <p>And here is the code</p> <pre><code>static class Program { /// &lt;summary&gt; /// The main entry point for the application. /// &lt;/summary&gt; static void Main(string[] args) { using (Game1 game = new Game1()) { game.Run(); } } } </code></pre> <p>And the same code run on another machine</p>
<p>I finally found the problem. For a reason, the hardware acceleration setting was set to None. So the project wouldn't start. </p> <p>Thanks for all your reply.</p>
<p>The docs say Game.Run will throw that exception if Game.Run is called more than once. What does the rest of the exception say? i.e. Message, StackTrace, etc?</p>
20,833
<p>Is there a way to say something like:</p> <p>sizeof(type)? Or type.Size? </p> <p>Right now I am looking at using code like:</p> <pre><code>if (type.Equals(typeof(int))) return sizeof(int); else if (type.Equals(typeof(long))) return sizeof(long); </code></pre> <p>etc, etc, for every single data type. </p> <p>There must be an cleaner solution, no?</p>
<p>Try Marshal.SizeOf()</p> <p><a href="http://msdn.microsoft.com/en-us/library/5s4920fa.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/5s4920fa.aspx</a></p>
<p>Maybe you can go <code>Convert.ToString(type.MaxValue, 2).Length / 8</code> ?</p>
47,482
<p>Just looking for the first step basic solution here that keeps the honest people out.</p> <p>Thanks, Mike</p>
<p>Sure thing, the simplest way is this:</p> <pre><code>select foo from bar where baz in (1,2,3) </code></pre>
<p>while <code>in</code> is a shortcut for <code>or</code> and I wasn't sure how I could combine <code>in</code> with <code>and</code>, I did it this way</p> <pre><code> SELECT * FROM table WHERE column1='x' AND (column2='y' OR column2='z'); </code></pre>
3,846
<p>I want to get started on HMM's, but don't know how to go about it. Can people here, give me some basic pointers, where to look?</p> <p>More than just the theory, I like to do a lot of hands-on. So, would prefer resources, where I can write small code snippets to check my learning, rather than just dry text.</p>
<p>Have you tried: Russel and Norvig's Artificial Intelligence: A Modern Approach. </p> <p>I realise that this is heavy on theory, but it also contains useful code samples that can be used to help your learning.</p> <p>You can also check out: <a href="http://www.kanungo.com/software/software.html" rel="nofollow noreferrer">http://www.kanungo.com/software/software.html</a> for a c-implementation of a HMM</p>
<p>Great videos as of Stanford Online AI course are available: See unit 11.</p> <p><a href="https://www.ai-class.com/course/video/videolecture/138" rel="nofollow">https://www.ai-class.com/course/video/videolecture/138</a></p>
9,537
<p>I am writing an unit test for a mvc web application that checks if a returned list of anonymous variables(in a jsonresult) is correct. therefore i need to iterate through that list but i cannot seem to find a way to do so.</p> <p>so i have 2 methods</p> <p>1) returns a json result . In that json result there is a property called data. that property is of type object but internally it's a list of anonymous variables</p> <p>2) the method calls method 1 and checks if the returned jsonresult is ok.</p> <p>if i run the test and i break the debugger i can hover over the result and see the items in it. i just don't find a way to do so in code.(just using a foreach isn't possible because at the point i need it i'm not in the method that created the anonymous method)</p>
<p>I think you mean "anonymous type" everywhere you've said "anonymous variable" - but you can still iterate over the list with <code>foreach</code>, just declaring the iteration variable as type <code>object</code>:</p> <pre><code>foreach (object o in myList) { // Not sure what you're actually trying to do in here... } </code></pre> <p>If you need to check the contents, you can use the fact that anonymous types override <code>ToString</code> in a useful way. Your test can check the result of projecting each element to a string. Indeed, you could convert your result object to a sequence of strings quite easily:</p> <pre><code>var strings = ((IEnumerable) result).Cast&lt;object&gt;.Select(x =&gt; x.ToString()); </code></pre> <p>Then test <code>strings</code> possibly using <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.sequenceequal.aspx" rel="nofollow noreferrer"><code>SequenceEqual</code></a>.</p>
<p>Create an identical set of objects to the one you expect, then serialize both it and the result.Data of the action under unit test. Finally, compare the streams to see if they are identical.</p>
39,275
<p>New to visual studio and programing in general.</p> <p>I am starting to work on a asp.net project. At home I have a computer running Windows 2008 Server with SQL 2008 and Visual 2008 running.</p> <p>I want to install the same thing on my laptop win2008/sql2008/vs2008 so I can take it with me on the go.</p> <p>What I want to know is how would I synchronized the two, where projects would syncrhonized to my laptop and I can take it on the go, then when i return and connect it to my network, it synchronizes back to my main workstation so the two are always the same?</p>
<p>It sounds like you want to use <a href="http://en.wikipedia.org/wiki/Revision_control" rel="nofollow noreferrer">revision control software</a>.</p> <p>If that's not the case (you don't want to check-in changes every time you change from one machine to another), you can probably script something with <a href="http://en.wikipedia.org/wiki/Rsync" rel="nofollow noreferrer">rsync</a>.</p>
<p>What about saving your project files directly to a thumb drive?</p> <p>Either that, or you set up a batch file to copy them files to/from the thumb drive before and after each session. This is more cumbersome, but quite safer <em>otoh</em>.</p>
21,262
<p>We all have our favourite database. If you look objectively at your chosen database, what drawbacks does it have and what could be improved?</p> <p>The rules:</p> <ul> <li>One reply per drawback with;</li> <li>a short description of the limitation, followed by;</li> <li><p>a more detailed description, an explanation of how it could be done better or an example of another technology that does not have the same limitation.</p></li> <li><p>Do not diss any database that you haven't used extensively. It is easy to take potshots at other technologies but we want to learn form your experience, not your prejudice.</p></li> </ul>
<p>Oracle databases are quite expensive</p> <p>Oracle does what it does well but the licensing costs are horrendous. That has been improved by the release of Oracle XE but the limitations of that mean that it is a growth constraint on you solution.</p>
<p>PostgreSQL doesn't have a good failover solution, but I understand they're working on it.</p>
14,555
<p>For loading time considerations I am using a runtime css file in my Flex Application.</p> <p>I am having a problem with a multi line text control :</p> <pre><code>&lt;mx:Text id="txtDescription" selectable="false" styleName="imageRolloverButtonTextDark" width="100%" textAlign="center" text="{_rolloverText}"/&gt; </code></pre> <p>When my CSS stylesheet has loaded the text style correctly changes, but the height is not recalculated. It appears to be just a single line field.</p> <p>FYI: The control is not actually visible, and triggered by a rollover. So I dont really care if the stylesheet hasnt loaded and they get standard system text. I jsut want it to be the correct height when it has been loaded.</p>
<p>Per the Adobe documentation for Text</p> <blockquote> <p>Sizing a Text control</p> <p>Flex sizes the Text control as follows:</p> <p>If you specify a pixel value for both the height and width properties, any text that exceeds the size of the control is clipped at the border.</p> <p>If you specify an explicit pixel width, but no height, Flex wraps the text to fit the width and calculates the height to fit the required number of lines.</p> <p>If you specify a percentage-based width and no height, Flex does not wrap the text, and the height equals the number of lines as determined by the number of Return characters.</p> <p>If you specify only a height and no width, the height value does not affect the width calculation, and Flex sizes the control to fit the width of the maximum line.</p> <p>As a general rule, if you have long text, you should specify a pixel-based width property. If the text might change and you want to ensure that the Text control always takes up the same space in your application, set explicit height and width properties that fit the largest expected text.</p> </blockquote> <p>So the trick I've used to deal with this is to have the Text get its width via a binding expression from whatever container limits it's width, typically the immediate parent.</p> <p>e.g.</p> <pre><code>&lt;mx:Canvas id="box" width="100%" backgroundColor="Red"&gt; &lt;mx:Text width="{box.width}" text="{someReallyLongString}" /&gt; &lt;/mx:Canvas&gt; </code></pre>
<p>Could you use a fixed pixel width instead of 100%? I've had issues with 100% being wrongly calculated on dynamic text controls before.</p>
40,042
<p>I want to implement an ISAPI filter like feature using HttpModule in IIS7 running under IIS Integrated Request Processing Pipeline mode.</p> <p>The goal is to look at the incoming request at the Web Server level, and inject some custom HttpHeaders into the request. <code>(for ex: HTTP\_EAUTH\_ID)</code></p> <p>And later in the page lifecycle of an ASPX page, i should be able to use that variable as</p> <pre><code>string eauthId = Request.ServerVariables["HTTP\_EAUTH\_ID"].ToString(); </code></pre> <p>So implementing this module at the Web Server level, is it possible to alter the ServerVariables collection ?? </p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.web.httprequest.servervariables.aspx" rel="nofollow noreferrer">HttpRequest.ServerVariables</a> Property is a read-only collection. So, you cannot directly modify that. I would suggest storing your custom data in <a href="http://www.odetocode.com/Articles/111.aspx" rel="nofollow noreferrer">httpcontext</a> (or global application object or your database) from your httpmodule and then reading that shared value in the aspx page.</p> <p>If you still want to modify server variables, there is a hack technique mentioned in this <a href="http://forums.asp.net/t/1125149.aspx" rel="nofollow noreferrer">thread</a> using Reflection.</p>
<p>I believe the server variables list only contains the headers sent from the browser to the server.</p>
8,564