instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>When I use the <code>MouseUp</code> event, I can get it to fire with a mouse right-click. But <code>MouseLeftButtonUp</code> won't fire with either click!</p> <pre class="lang-xml prettyprint-override"><code>&lt;Button MouseLeftButtonUp="btnNewConfig_MouseUp" Name="btnNewConfig"&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;Image Source="Icons\new.ico" Height="24" Width="24" Margin="5"/&gt; &lt;TextBlock VerticalAlignment="Center"&gt;New&lt;/TextBlock&gt; &lt;/StackPanel&gt; &lt;/Button&gt; </code></pre> <p>I know this is most likely something simple. Thanks for the help!</p>
<p>Looks like <code>Button</code> control is eating up that event Since <code>Button.Click</code> is actually a combination of <code>LeftButtonDown</code> event and <code>LeftButtonUp</code> event.</p> <p>But you can subscribe to the tunneled event <strong><code>PreviewMouseLeftButtonUp</code></strong> on the <code>Button</code> instead of <code>LeftButtonUp</code>.</p>
<p><code>Button</code> is using the Mouse[Left/Right]Button[Up/Down] events (and marking them as <code>Handled</code>) for its <code>Button.Click</code> events.</p> <p>As <a href="https://stackoverflow.com/a/318304/10927863">Jobi said</a>, you can use the <code>PreviewMouseLeftButtonUp</code> event, but I want to suggest that you create your own button template and modify its behavior. (i.e. not mark the <code>MouseLeftButtonUp</code> as <code>Handled = true</code>) or simply use something else than a <code>Button</code> as your parent container (depends on what you really need it for).</p>
41,134
<p>What tools allows me keep track of tags when doing web development? For example, I would like to be able to quickly find whether I missed closing a div tag.</p> <p>At the moment I am using notepad++ to write html. It highlights starting and ending tags, but it can take me time to review almost all tags to find where I went wrong.</p>
<p><a href="http://tidy.sourceforge.net/" rel="nofollow noreferrer">HTMLTidy</a> is pretty much the de-facto standard for this kind of thing nowadays</p> <p><a href="http://dev.int64.org/tidy.html" rel="nofollow noreferrer">Tidy Windows Installer</a></p> <p><a href="http://tidy.sourceforge.net/docs/faq.html" rel="nofollow noreferrer">Tidy FAQ</a></p>
<p>Indenting is helpful. I also find the <a href="http://users.skynet.be/mgueury/mozilla/" rel="nofollow noreferrer" title="Html Validator">Html Validator</a> extension for Firefox to be handy for checking for HTML issues once you're viewing the page in the browser (which is especially handy for checking server-generated HTML).</p>
14,498
<p>With squid, we can cache webpages. I am not sure if it provides the same number of caching methods as ASP.NET caching (I primarily use ASP.NET), but it's a tool to cache webpages.</p> <p>Then we have memcached, which can cache database tables. I believe this is correct, and it is like SqlCacheDependency (correct me if I am wrong).</p> <p>However, is there any situation in a large web application where one would find room to use memcached, squid, AND ASP.NET (or PHP, JSP - application framework-level) caching.</p> <p>Thanks!</p>
<p>Try the method <code>rstrip()</code> (see doc <a href="http://docs.python.org/2/library/stdtypes.html#str.rstrip" rel="noreferrer">Python 2</a> and <a href="https://docs.python.org/3/library/stdtypes.html#str.rstrip" rel="noreferrer">Python 3</a>)</p> <pre><code>&gt;&gt;&gt; 'test string\n'.rstrip() 'test string' </code></pre> <p>Python's <code>rstrip()</code> method strips <em>all</em> kinds of trailing whitespace by default, not just one newline as Perl does with <a href="http://perldoc.perl.org/functions/chomp.html" rel="noreferrer"><code>chomp</code></a>.</p> <pre><code>&gt;&gt;&gt; 'test string \n \r\n\n\r \n\n'.rstrip() 'test string' </code></pre> <p>To strip only newlines:</p> <pre><code>&gt;&gt;&gt; 'test string \n \r\n\n\r \n\n'.rstrip('\n') 'test string \n \r\n\n\r ' </code></pre> <p>In addition to <code>rstrip()</code>, there are also the methods <code>strip()</code> and <code>lstrip()</code>. Here is an example with the three of them:</p> <pre><code>&gt;&gt;&gt; s = &quot; \n\r\n \n abc def \n\r\n \n &quot; &gt;&gt;&gt; s.strip() 'abc def' &gt;&gt;&gt; s.lstrip() 'abc def \n\r\n \n ' &gt;&gt;&gt; s.rstrip() ' \n\r\n \n abc def' </code></pre>
<p>A catch all:</p> <pre><code>line = line.rstrip('\r|\n') </code></pre>
34,656
<p>I am aware that in <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> there are three timer types (see <em><a href="http://msdn.microsoft.com/en-us/magazine/cc164015.aspx" rel="noreferrer">Comparing the Timer Classes in the .NET Framework Class Library</a></em>). I have chosen a threaded timer as the other types can drift if the main thread is busy, and I need this to be reliable.</p> <p>The way this timer works in the control of the timer is put on another thread so it can always tick along with the work begin completed on the parent thread when it is not busy.</p> <p>The issue with this timer in a console application is that while the timer is ticking along on another thread the main thread is not doing anything to the application closes.</p> <p>I tried adding a <code>while true</code> loop, but then the main thread is too busy when the timer does go off.</p>
<p>You can use something like <code>Console.ReadLine()</code> to block the main thread, so other background threads (like timer threads) will still work. You may also use an <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.autoresetevent" rel="noreferrer">AutoResetEvent</a> to block the execution, then (when you need to) you can call Set() method on that AutoResetEvent object to release the main thread. Also ensure that your reference to Timer object doesn't go out of scope and garbage collected.</p>
<p>According to <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.timer?view=net-5.0" rel="nofollow noreferrer">MSDN</a> and the other answers, a minimal working example of a Console application using a System.Threading.Timer without exiting immediately :</p> <pre><code>private static void Main() { using AutoResetEvent autoResetEvent = new AutoResetEvent(false); using Timer timer = new Timer(state =&gt; Console.WriteLine(&quot;One second has passed&quot;), autoResetEvent, TimeSpan.Zero, new TimeSpan(0, 0, 1)); autoResetEvent.WaitOne(); } </code></pre>
2,243
<p>I have made a SVG image, or more like mini application, for viewing graphs of data. I want to include this in a HTML page, and call methods on the SVG image.</p> <p>Example:</p> <pre><code>&lt;object id="img" data="image.svg" width="500" height="300"/&gt; &lt;script&gt;document.getElementById("img").addData([1,23,4]);&lt;/script&gt; </code></pre> <p>Is it at all possible to call methods on the SVG document? If so, how do I declare the methods to expose in the SVG file, and how do I call them from the HTML document?</p>
<p>Solution:</p> <p>in svg:</p> <pre><code>&lt;script&gt;document.method = function() {}&lt;/script&gt; </code></pre> <p>in html (using prototype to add event listeners):</p> <pre><code>&lt;script&gt;$("img").observe("load", function() {$("img").contentDocument.method()}); </code></pre> <p>You need to listen to the load event on the image. Once the image is loaded, you can use the <code>element.contentDocument</code> to access the document variable on the svg document. Any methods added to that, will be available.</p>
<p>For support in IE6, have a look at <a href="http://code.google.com/p/svgweb/" rel="nofollow">SVGWeb</a>.</p> <p>There are examples on how to manipulate SVG with JavaScript in the sample code supplied with the library.</p> <p>There is also a fair amount of information in the archives of the mailing list.</p>
16,740
<p>I need to do a comparaison between an object and NULL. When the object is not NULL I fill it with some data.</p> <p>Here is the code :</p> <pre><code> if (region != null) { .... } </code></pre> <p>This is working but when looping and looping sometime the region object is NOT null (I can see data inside it in debug mode). In step-by-step when debugging, it doesn't go inside the IF statement... When I do a Quick Watch with these following expression : I see the (region == null) return false, AND (region != null) return false too... <strong>why and how?</strong></p> <p><strong>Update</strong></p> <p>Someone point out that the object was == and != overloaded:</p> <pre><code> public static bool operator ==(Region r1, Region r2) { if (object.ReferenceEquals(r1, null)) { return false; } if (object.ReferenceEquals(r2, null)) { return false; } return (r1.Cmr.CompareTo(r2.Cmr) == 0 &amp;&amp; r1.Id == r2.Id); } public static bool operator !=(Region r1, Region r2) { if (object.ReferenceEquals(r1, null)) { return false; } if (object.ReferenceEquals(r2, null)) { return false; } return (r1.Cmr.CompareTo(r2.Cmr) != 0 || r1.Id != r2.Id); } </code></pre>
<p>Is the == and/or != operator overloaded for the region object's class?</p> <p>Now that you've posted the code for the overloads:</p> <p>The overloads should probably look like the following (code taken from postings made by <a href="https://stackoverflow.com/questions/155458/c-object-is-not-null-but-myobject-null-still-return-false#155488">Jon Skeet</a> and <a href="https://stackoverflow.com/questions/155458/c-object-is-not-null-but-myobject-null-still-return-false#155508">Philip Rieck</a>):</p> <pre><code>public static bool operator ==(Region r1, Region r2) { if (object.ReferenceEquals( r1, r2)) { // handles if both are null as well as object identity return true; } if ((object)r1 == null || (object)r2 == null) { return false; } return (r1.Cmr.CompareTo(r2.Cmr) == 0 &amp;&amp; r1.Id == r2.Id); } public static bool operator !=(Region r1, Region r2) { return !(r1 == r2); } </code></pre>
<p>So is it that these checks here are not right:</p> <pre><code>public static bool operator !=(Region r1, Region r2) { if (object.ReferenceEquals(r1, null)) { return false; } if (object.ReferenceEquals(r2, null)) { return false; } ... </code></pre>
18,803
<p>This is on iPhone 0S 2.0. Answers for 2.1 are fine too, though I am unaware of any differences regarding tables.</p> <p>It feels like it should be possible to get text to wrap without creating a custom cell, since a <code>UITableViewCell</code> contains a <code>UILabel</code> by default. I know I can make it work if I create a custom cell, but that's not what I'm trying to achieve - I want to understand why my current approach doesn't work.</p> <p>I've figured out that the label is created on demand (since the cell supports text and image access, so it doesn't create the data view until necessary), so if I do something like this:</p> <pre><code>cell.text = @""; // create the label UILabel* label = (UILabel*)[[cell.contentView subviews] objectAtIndex:0]; </code></pre> <p>then I get a valid label, but setting <code>numberOfLines</code> on that (and lineBreakMode) doesn't work - I still get single line text. There is plenty of height in the <code>UILabel</code> for the text to display - I'm just returning a large value for the height in <code>heightForRowAtIndexPath</code>.</p>
<p>Here is a simpler way, and it works for me:</p> <p>Inside your <code>cellForRowAtIndexPath:</code> function. The first time you create your cell:</p> <pre><code>UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; cell.textLabel.lineBreakMode = UILineBreakModeWordWrap; cell.textLabel.numberOfLines = 0; cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0]; } </code></pre> <p>You'll notice that I set the number of lines for the label to 0. This lets it use as many lines as it needs.</p> <p>The next part is to specify how large your <code>UITableViewCell</code> will be, so do that in your <code>heightForRowAtIndexPath</code> function:</p> <pre><code>- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *cellText = @"Go get some text for your cell."; UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0]; CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT); CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; return labelSize.height + 20; } </code></pre> <p>I added 20 to my returned cell height because I like a little buffer around my text.</p>
<p>I don't think you can manipulate a base <code>UITableViewCell's</code> private <code>UILabel</code> to do this. You could add a new <code>UILabel</code> to the cell yourself and use <code>numberOfLines</code> with <code>sizeToFit</code> to size it appropriately. Something like:</p> <pre><code>UILabel* label = [[UILabel alloc] initWithFrame:cell.frame]; label.numberOfLines = &lt;...an appriate number of lines...&gt; label.text = &lt;...your text...&gt; [label sizeToFit]; [cell addSubview:label]; [label release]; </code></pre>
15,745
<p>I've asked a question before on the extruder gear clicking on my CR-10, but I'm certain its because of the nozzle getting clogged for some reason. I'm using a standard 0.4&nbsp;mm nozzle with white PLA and randomly during the print the extruder gear starts clicking on the fast parts and then under extrudes the rest of the print, eventually the hobbed gear digs away at the filament and doesn't grip anymore. Why would the nozzle keep getting clogged? Could it be because the filament isn't high enough quality and is leaving particles in the nozzle? </p> <p><a href="https://i.stack.imgur.com/j83BN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j83BN.jpg" alt="enter image description here"></a></p> <p>Additionally, when I performed a cold pull after breaking up the blockage on the inside, the filament came out like a thin film even though it was purging fine before I cooled it down. Why?</p> <p><a href="https://i.stack.imgur.com/PwXZl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PwXZl.jpg" alt="enter image description here"></a></p> <ul> <li>190&nbsp;&deg;C nozzle temperature (tried printing at 210&nbsp;&deg;C and the filament burned)</li> <li>50&nbsp;&deg;C bed temperature</li> <li>60&nbsp;mm/s speed, outline 50&nbsp;% - first layer being 30&nbsp;mm/s</li> <li>0.2&nbsp;mm layer height</li> </ul> <p>This starting happening after I returned to printing after a 6 month break, with the filament being stored in a cool and dry cupboard for around a year (the filament was on the cheaper side, but still highly recommended by SUNLU)</p>
<p>Turns out the filament was the problem, I tried printing a model with a high quality sample PLA filament I had and it printed perfectly; one of the cleanest prints I've had. Never skimp on filament.</p> <p><img src="https://i.stack.imgur.com/AT3cW.jpg" alt="enter image description here"></p>
<p>White PLA is usually some of the worst stuff to print with, generally avoid it. I would say. I myself are having a lot of problems with it as well.</p>
1,457
<p>(Java question)</p> <p>If I reference a field in an inner class, does this cause a circular dependency between the enclosing class and the inner class?</p> <p>How can I avoid this? </p> <p>Here is an example:</p> <pre><code>public class Outer { private Other o; private Inner i; public Outer() { o = new Other(); i = new Inner() { public void doSomething() { o.foo(); } }; } } </code></pre>
<p><strong>Static vs instance class:</strong> If you declare the inner class as static then the instances of the inner class doesn't have any reference to the outer class. If it's not satic then your inner object efectivelly points to the outer object that created it (it has an implicit reference, in fact, if you use reflection over its constructors you'll see an extra parameter for receiving the outer instance).</p> <p><strong>Inner instance points outer instance:</strong> Circular reference is in case each instance points the other one. A lot of times you use inner classes for elegantly implementing some interface and accessing private fields while not implementing the interface with the outer class. It does mean inner instance points outer instance but doesn't mean the opposite. Not necesary a circular reference.</p> <p><strong>Closing the circle:</strong> Anyway there's nothing wrong with circular referencing in Java. Objects work nicely and when they're not more referenced they're garbage collected. It doesn't matter if they point each other.</p>
<p>The syntax you're using in the example is a little off there is no declaration of the class or interface Inner. But there isn't anything wrong with the concept of the example. In Java it will work fine.</p> <p>I'm not sure what you're doing here, but you may want to consider a more simple design for maintainability etc.</p> <p>It's a common pattern for anonymous event handlers to reference elements of their parent class, so no reason to avoid it if that's the case, that's how Java was designed instead of having function pointers.</p>
14,397
<p>I am currently porting a lot of code from an MFC-based application to a DLL for client branding purposes.</p> <p>I've come across an unusual problem. This bit of code is the same in both systems:</p> <pre><code>// ... CCommsProperties props; pController-&gt;GetProperties( props ); if (props.handshake != HANDSHAKE_RTS_CTS) { props.handshake = HANDSHAKE_RTS_CTS; pController-&gt;RefreshCommProperties( props ); } // ... in another file: void CControllerSI::RefreshCommProperties ( const CCommsProperties&amp; props ) { // ... code ... } </code></pre> <p>CommProperties is a wrapper for the comm settings, serialization of etc. and pController is of type ControllerSI which itself is a layer between the actual Comms and the Application.</p> <p>On the original MFC version the setting of handshake to RTS-CTS sticks but when running as the DLL version it resets itself to 0 as soon as the function is entered. The code is contained entirely in the DLL section of the code, so there are no boundaries.</p> <p>The main differences between the original and the new modules is the variables that call the various dialogs have been removed and the removed #includes</p> <p>I've lost an afternoon to this and I don't really want to lose any more...</p>
<p>It is difficult to see what is wrong from the given code alone. Some general pointers:</p> <ol> <li><p>The object is initialized and processed in different binary modules with incompatible linking (such as C-run times)</p></li> <li><p>If the class/structure is shared it is not exported/imported correctly.</p></li> <li><p>The class(s) are defined in more than one place, and you are not including the correct definitions.</p></li> </ol> <p>The above three are the most likely causes, especially, if all fields are reset to their default initialized values.</p> <p>if this is only happening with only one or two fields, the structure may be poorly aligned and you may need to rearrange the fields to correct these (check that in release too).</p> <p>In general, I am tempted to hypothesize that the object you have intialized is not the one <code>RefreshCommProperties()</code> sees, for some reason, may be one of the three above.</p>
<p>To really figure out what is going on, you probably need to post your source code -- or at least as much to replicate the problem. Unfortunately, StackOverflow doesn't seem like it encourages this. You could post your code on an FTP site or go to a site that allows posting of source code (like CodeGuru).</p>
19,518
<p>I'm just starting to pick up ASP.Net MVC and find myself writing a lot of &lt;%= %> in the views. Intellisense does supply the closing %>, but I find that typing the introductory &lt;%= to be burdensome (they are tough for me to type :-)).</p> <p>I've dabbled around a bit with Rails and the NetBeans IDE where I was able to type:</p> <pre><code>r&lt;tab&gt; - which would expand to &lt;% %&gt; </code></pre> <p>and</p> <pre><code>re&lt;tab&gt; - which would expand to &lt;%= %&gt; </code></pre> <p>Can something similar be done in the Visual Studio 2008 IDE?</p>
<p>This macro function should do it:</p> <p>The main code will do one of two things, if nothing is selected it will just insert the &lt;%= %> code construct, if you have something currently selected in the editor, it will wrap that code with the construct E.G. &lt;%= selected code here %></p> <pre><code>Public Sub WrapMVC() Try DTE.UndoContext.Open("Wrap MVC") Dim OutText As String = "" Dim OutFormat As String = "&lt;%={0} %&gt;" DTE.ActiveDocument.Selection.Text = String.Format(OutFormat, ActiveWindowSelection) Finally DTE.UndoContext.Close() End Try End Sub </code></pre> <p><strong>Helper Routines:</strong></p> <pre><code>Friend Function ActiveWindowSelection() As String If DTE.ActiveWindow.ObjectKind = EnvDTE.Constants.vsWindowKindOutput Then Return OutputWindowSelection() End If If DTE.ActiveWindow.ObjectKind = "{57312C73-6202-49E9-B1E1-40EA1A6DC1F6}" Then Return HTMLEditorSelection() End If Return SelectionText(DTE.ActiveWindow.Selection) End Function Private Function HTMLEditorSelection() As String Dim hw As EnvDTE.HTMLWindow = ActiveDocument.ActiveWindow.Object Dim tw As TextWindow = hw.CurrentTabObject Return SelectionText(tw.Selection) End Function Private Function OutputWindowSelection() As String Dim w As Window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput) Dim ow As OutputWindow = w.Object Dim owp As OutputWindowPane = ow.OutputWindowPanes.Item(ow.ActivePane.Name) Return SelectionText(owp.TextDocument.Selection) End Function Private Function SelectionText(ByVal sel As EnvDTE.TextSelection) As String If sel Is Nothing Then Return "" End If If sel.Text.Length &lt;= 2 Then SelectWord(sel) End If If sel.Text.Length &lt;= 2 Then Return "" End If Return sel.Text End Function Private Sub SelectWord(ByVal sel As EnvDTE.TextSelection) Dim leftPos As Integer Dim line As Integer Dim pt As EnvDTE.EditPoint = sel.ActivePoint.CreateEditPoint() sel.WordLeft(True, 1) line = sel.TextRanges.Item(1).StartPoint.Line leftPos = sel.TextRanges.Item(1).StartPoint.LineCharOffset pt.MoveToLineAndOffset(line, leftPos) sel.MoveToPoint(pt) sel.WordRight(True, 1) End Sub </code></pre>
<p>I believe <a href="http://www.dotnetjunkies.ddj.com/Article/C95AC204-DE44-4D4A-A2B7-1EB1BE14A8A1.dcik" rel="nofollow noreferrer">Code Snippets</a> would fit the bill.</p>
32,772
<p>What's the most efficient way to calculate the last day of the prior quarter?</p> <p>Example: given the date 11/19/2008, I want to return 9/30/2008.</p> <p>Platform is SQL Server </p>
<p>If @Date has the date in question</p> <pre><code>Select DateAdd(day, -1, dateadd(qq, DateDiff(qq, 0, @Date), 0)) </code></pre> <p>EDIT: Thanks to @strEagle below, simpler still is:</p> <pre><code>Select dateadd(qq, DateDiff(qq, 0, @Date), -1) </code></pre>
<p><strong>In amazon redshift:</strong></p> <p>Last day of the previous quarter:</p> <pre><code>select dateadd(day,-1,DATE_TRUNC('qtr', current_date)) from whatever </code></pre> <p>Last day of current quarter:</p> <pre><code>select dateadd(qtr,1,dateadd(day,-1,DATE_TRUNC('qtr', current_date))) from whatever </code></pre>
38,837
<p>I am starting a new web application in PHP and this time around I want to create something that people can extend by using a plugin interface. </p> <p>How does one go about writing 'hooks' into their code so that plugins can attach to specific events?</p>
<p>You could use an Observer pattern. A simple functional way to accomplish this:</p> <pre><code>&lt;?php /** Plugin system **/ $listeners = array(); /* Create an entry point for plugins */ function hook() { global $listeners; $num_args = func_num_args(); $args = func_get_args(); if($num_args &lt; 2) trigger_error("Insufficient arguments", E_USER_ERROR); // Hook name should always be first argument $hook_name = array_shift($args); if(!isset($listeners[$hook_name])) return; // No plugins have registered this hook foreach($listeners[$hook_name] as $func) { $args = $func($args); } return $args; } /* Attach a function to a hook */ function add_listener($hook, $function_name) { global $listeners; $listeners[$hook][] = $function_name; } ///////////////////////// /** Sample Plugin **/ add_listener('a_b', 'my_plugin_func1'); add_listener('str', 'my_plugin_func2'); function my_plugin_func1($args) { return array(4, 5); } function my_plugin_func2($args) { return str_replace('sample', 'CRAZY', $args[0]); } ///////////////////////// /** Sample Application **/ $a = 1; $b = 2; list($a, $b) = hook('a_b', $a, $b); $str = "This is my sample application\n"; $str .= "$a + $b = ".($a+$b)."\n"; $str .= "$a * $b = ".($a*$b)."\n"; $str = hook('str', $str); echo $str; ?&gt; </code></pre> <p><strong>Output:</strong></p> <pre><code>This is my CRAZY application 4 + 5 = 9 4 * 5 = 20 </code></pre> <p><strong>Notes:</strong></p> <p>For this example source code, you must declare all your plugins before the actual source code that you want to be extendable. I've included an example of how to handle single or multiple values being passed to the plugin. The hardest part of this is writing the actual documentation which lists what arguments get passed to each hook.</p> <p>This is just one method of accomplishing a plugin system in PHP. There are better alternatives, I suggest you check out the WordPress Documentation for more information.</p>
<p>I am surprised that most of the answers here seem to be geared about plugins that are local to the web application, ie, plugins that run on the local web server.</p> <p>What about if you wanted the plugins to run on a different - remote - server? The best way to do this would be to provide a form that allows you to define different URLs that would be called when particular events occur in your application.</p> <p>Different events would send different information based on the event that just occurred.</p> <p>This way, you would just perform a cURL call to the URL that has been provided to your application (eg over https) where remote servers can perform tasks based on information that has been sent by your application.</p> <p>This provides two benefits:</p> <ol> <li>You don't have to host any code on your local server (security)</li> <li>The code can be on remote servers (extensibility) in different languages other then PHP (portability)</li> </ol>
2,244
<p>I find that whenever I begin writing an app in Java/C#, things start off good, but over time, as the app becomes more complex, it just gets more and more complicated. I've become aware of the fact that I'm not very good at design and high level architecture. All my classes become fairly strongly coupled and the design isn't "elegant" at all. I'm fairly competent at "low level" programming. That is, I can get just about anything done within a function or a class, but my high level design is weak and I'd really like to improve it. Does anyone have pointers to techniques, books, etc. that would be helpful in making me a better software engineer?</p>
<p><strong>Books:</strong></p> <ul> <li>Code Complete, by Steve McConnel</li> <li>Design Patterns, by Gamma, et. al.</li> </ul>
<p>Try making program outlines and diagrams before you start, and have someone else review and critique it. Then as the program grows, continually update the outlines and diagrams to include the new functionality. Get it reviewed and critiqued by someone else. Eventually, assuming you are learning from the critiques, you will become better at designing programs.</p> <p>Books and tutorials can only get you so far. While you do need to learn the tools and methods available, knowledge on its own won't help you here. Practice is what will make you better at design, along with having a mentor coach you from time to time to show you how you can better apply some of the knowledge you've gained from the books.</p>
30,777
<p>On the Python side, I can create new numpy record arrays as follows:</p> <pre><code>numpy.zeros((3,), dtype=[('a', 'i4'), ('b', 'U5')]) </code></pre> <p>How do I do the same from a C program? I suppose I have to call <code>PyArray_SimpleNewFromDescr(nd, dims, descr)</code>, but how do I construct a <code>PyArray_Descr</code> that is appropriate for passing as the third argument to <code>PyArray_SimpleNewFromDescr</code>?</p>
<p>Use <code>PyArray_DescrConverter</code>. Here's an example:</p> <pre><code>#include &lt;Python.h&gt; #include &lt;stdio.h&gt; #include &lt;numpy/arrayobject.h&gt; int main(int argc, char *argv[]) { int dims[] = { 2, 3 }; PyObject *op, *array; PyArray_Descr *descr; Py_Initialize(); import_array(); op = Py_BuildValue("[(s, s), (s, s)]", "a", "i4", "b", "U5"); PyArray_DescrConverter(op, &amp;descr); Py_DECREF(op); array = PyArray_SimpleNewFromDescr(2, dims, descr); PyObject_Print(array, stdout, 0); printf("\n"); Py_DECREF(array); return 0; } </code></pre> <p>Thanks to <a href="https://stackoverflow.com/users/9530/adam-rosenfield">Adam Rosenfield</a> for pointing to Section 13.3.10 of the <a href="http://numpy.scipy.org/numpybook.pdf" rel="nofollow noreferrer">Guide to NumPy</a>.</p>
<p>See the <a href="http://csc.ucdavis.edu/~chaos/courses/nlp/Software/NumPyBook.pdf" rel="nofollow noreferrer">Guide to NumPy</a>, section 13.3.10. There's lots of different ways to make a descriptor, although it's not nearly as easy as writing <code>[('a', 'i4'), ('b', 'U5')]</code>.</p>
26,370
<p>I have a text string value that I'd like to persist from one web page to another without using query strings or the session/view states. I've been trying to get the ASP http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hiddenfield.aspx">HiddenField control to pass information from one web form to a <i>different</i> form.<br><br> All the hiddenfield control examples that I've seen is to preserve round trips from the client to the server for the same form.<br><br> Is there way for a form to access the ASP controls (and their values) from the previously-rendered form? Or is the initial form simply disposed of in memory by the time the second form executes it's <i>OnLoad</i> method?</p>
<p>If both pages live in the same application you can use Server.Transfer:</p> <p>firstpage.aspx:</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { Server.Transfer("~/secondpage.aspx"); } </code></pre> <p>secondpage.aspx:</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { Page previousPage = (Page) HttpContext.Current.PreviousHandler; Label previousPageControl = (Label) previousPage.FindControl("theLabel"); label.Text =previousPageControl.Text; } </code></pre> <p>A somewhat better solution would be implementing an interface on your first page where you expose properties for the values needed by the second page.</p>
<p>I would presume that the Response.Redirect() sends a Location: HTTP header to do a redirect.</p> <p>As HTTP is stateless, I'd also presume that these variables are inaccessible.</p> <p>There are however, solutions.</p> <ol> <li>Print a form with hidden fields, and use javascript to submit it</li> <li>Redirect in the code internally (load up the thing it needs to get to manually)</li> <li>Store the data in some temporary database table somewhere, and pass along a unique ID</li> </ol> <p>However, from my experience, I can't understand why you might need to do this (other than re-submitting a form after a user authentication - which hopefully you should be able to use method 2 for</p>
21,909
<p>I'm a bit newbieish when it comes to the deeper parts of OSX configuration and am having to put up with a fairly irritating niggle which while I can put up with it, I know under Windows I could have sorted in minutes.</p> <p>Basically, I have an external disk with two volumes: </p> <p>One is an HFS+ volume which I use for TimeMachine backups. The other, an NTFS volume that I use for general file copying etc on Mac and Windows boxes.</p> <p>So what happens is that whenever I plug in the disk into my Mac USB, OSX goes off and mounts both volumes and shows an icon on the desktop for each. The thing is that to remove the disk you have to eject the volume and in this case do it for both volumes, which causes an annoying warning dialog to be shown every time. </p> <p>What I'd prefer is some way to prevent the NTFS volume from auto-mounting altogether. I've done some hefty googling and here's a list of things I've tried so far:</p> <ul> <li>I've tried going through options in Disk Utility</li> <li>I've tried setting AutoMount to No in /etc/hostconfig but that is a bit too global for my liking.</li> <li>I've also tried the suggested approach to putting settings in fstab but it appears the OSX (10.5) is ignoring these settings.</li> </ul> <p>Any other suggestions would be welcomed. Just a little dissapointed that I can't just tick a box somewhere (or untick).</p> <p>EDIT: Thanks heaps to hop for the answer it worked a treat. For the record it turns out that it wasn't OSX not picking up the settings I actually had "msdos" instead of "ntfs" in the fs type column.</p>
<p>The following entry in <code>/etc/fstab</code> will do what you want, even on 10.5 (Leopard):</p> <pre><code>LABEL=VolumeName none ntfs noauto </code></pre> <p>If the file is not already there, just create it. Do not use <code>/etc/fstab.hd</code>! No reloading of <code>diskarbitrationd</code> needed.</p> <p>If this still doesn't work for you, maybe you can find a hint in the syslog.</p>
<p>This is not directly an answer, but</p> <blockquote> <p>The thing is that to remove the disk you have to eject the volume and in this case do it for both volumes</p> </blockquote> <p>I have a similar situation.</p> <p>OSX remembers where you put your icons on the desktop - I've moved the icons for both of my removable drives to <em>just</em> above where the trash can lives.</p> <p>Eject procedure becomes</p> <ul> <li>Hit top-left of screen with mouse to show desktop</li> <li>Drag small box around both removable drives</li> <li>Drag 2cm onto trash so they both get ejected</li> <li>Remove firewire cable</li> </ul>
4,121
<p>I assume that <code>char* = "string"</code> is the same to <code>char* = new char[6]</code>. I believe these strings are created on the heap instead of the stack. So do I need to destroy them or free their memory when I'm done using them or do they get destroyed by themselves?</p>
<p>No. You only need to manually free strings when you manually allocate the memory yourself using the <code>malloc</code> function (in C) or the <code>new</code> operator (in C++). If you do not use <code>malloc</code> or <code>new</code>, then the <code>char*</code> or string will be created on the stack or as a compile-time constant.</p>
<p>new is always an allocation whereas defining a string inline actually embeds the data in the program itself and cannot be changed (some compilers allow this by a smart trick, don't bother).</p> <p>Some compilers type inline strings so that you cannot modify the buffer.</p> <pre><code>char* const sz1 = "string"; // embedded string, immutable buffer char* sz2 = new char[10]; // allocated string, should be deleted </code></pre>
7,475
<p>I have this piece of code in my PHP code:</p> <pre><code>while ($row = mysqli_fetch_assoc($result)) { extract($row); echo "&lt;tr&gt;"; echo "&lt;td bgcolor='#FFFFFF'&gt;&lt;input id='bookArray[]' name='bookArray[]' type='checkbox' value='$book_id' /&gt;$book_id&lt;/td&gt;"; echo "&lt;td bgcolor='#FFFFFF'&gt;$threat_name&lt;/td&gt;"; echo "&lt;/tr&gt;"; } </code></pre> <p>In HTML page, I want to use jQuery serialize() method to sent array of selected books in bookArray[]. In my JavaScript,</p> <pre><code>var selectedbooks = $("book_form").serialize(); alert (selectedbooks); </code></pre> <p>In the alert message box, i did not get any value (empty string).</p> <p>Previously when i am using Prototype, it worked nicely.</p>
<p>easy: <code>serialize().replace(/%5B%5D/g, '[]')</code></p>
<p>You may need to change your PHP as @Tomalak suggests, but you will also need to change your javascript. To reference a named element use the #name selector:</p> <pre><code>var selectedbooks = $('form#book_form').serialize();; </code></pre>
39,135
<p>I have a form with a textarea. Users enter a block of text which is stored in a database.</p> <p>Occasionally a user will paste text from Word containing smart quotes or emdashes. Those characters appear in the database as: –, ’, “ ,â€</p> <p>What function should I call on the input string to <em>convert smart quotes to regular quotes and emdashes to regular dashes</em>? </p> <p>I am working in PHP.</p> <p>Update: Thanks for all of the great responses so far. The page on Joel's site about encodings is very informative: <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow noreferrer">http://www.joelonsoftware.com/articles/Unicode.html</a></p> <p>Some notes on my environment:</p> <p>The MySQL database is using UTF-8 encoding. Likewise, the HTML pages that display the content are using UTF-8 (Update:) by explicitly setting the meta content-type.</p> <p>On those pages the smart quotes and emdashes appear as a diamond with question mark.</p> <p>Solution:</p> <p>Thanks again for the responses. The solution was twofold:</p> <ol> <li>Make sure the database and HTML files were explicitly set to use UTF-8 encoding.</li> <li>Use <code>htmlspecialchars()</code> instead of <code>htmlentities()</code>.</li> </ol>
<p>This sounds like a Unicode issue. Joel Spolsky has a good jumping off point on the topic: <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="noreferrer">http://www.joelonsoftware.com/articles/Unicode.html</a></p>
<p>We would often use standard string replace functions for that. Even though the nature of ASCII/Unicode in that context is pretty murky, it works. Just make sure your php file is saved in the right encoding format, etc. </p>
21,179
<p>I'm developing an invisible Java Applet, that will be controlled entirely from JavaScript.</p> <p>I can call the applet's Java methods easily, and I can call JavaScript methods from within the applet by using <code>netscape.javascript.JSObject.getWindow(this).call()</code>.</p> <p>But in order to register a JavaScript callback in the applet, I guess I would need an JavaScript function object of some sort.</p> <p>I would like to do:</p> <pre><code>public void registerCallback( SomeJavascriptFunction func ) { ... } </code></pre> <p>Which I could call from Javascript:</p> <pre><code>myapplet.registerCallback(function(){ alert("called back"); }); </code></pre> <p>So I could call this function in later code:</p> <pre><code>func.call( ... ); </code></pre> <p>Does something like this exist? How can I do this?</p> <p>Rigth now I'm thinking of creating some Javascript to handle this callback mechanism instead of doing so from the applet.</p>
<p>I am brand new to Java &lt;-> JavaScript communication, as I planned to explore it this week. A good opportunity here... :-)</p> <p>After some tests, it seems you cannot pass a JS function to a Java applet. Unless I am doing it the wrong way...</p> <p>I tried:</p> <pre><code>function CallJava() { document.Applet.Call("Does it work?"); document.Applet.Call(function () { alert("It works!"); }); document.Applet.Call(DoSomething); // A simple parameterless JS function document.Applet.Call(window.location); } function DumbTest(message, value) { alert("This is a dumb test with a message:\n" + message + "\n" + value); } </code></pre> <p>where Call is (are) defined as:</p> <pre><code>public void Call(String message) { JSObject win = (JSObject) JSObject.getWindow(this); String[] arguments = { "Call with String", message }; win.call("DumbTest", arguments); } public void Call(JSObject jso) { JSObject win = (JSObject) JSObject.getWindow(this); String[] arguments = { "Call with JSObject", jso.toString() }; win.call("DumbTest", arguments); } </code></pre> <p>When I pass a JS function (all tests in FF3), I get a null on the Java side.</p> <p>Note that the following Java routine allows to display the JS code of DumberTest function!</p> <pre><code>public int Do() { JSObject win = (JSObject) JSObject.getWindow(this); JSObject doc = (JSObject) win.getMember("document"); JSObject fun = (JSObject) win.getMember("DumberTest"); JSObject loc = (JSObject) doc.getMember("location"); String href = (String) loc.getMember("href"); String[] arguments = { href, fun.toString() }; win.call("DumbTest", arguments); return fun.toString().length(); } </code></pre> <p>To the point: I made a JS function:</p> <pre><code>function RegisterCallback(cbFunction) { var callback = cbFunction.toString(); // We get JS code var callbackName = /^function (\w+)\(/.exec(callback); document.Applet.RegisterCallback(callbackName[1]); } </code></pre> <p>I extract the name of the JS function from the toString result and pass it to Java applet. I don't think we can handle anonymous functions because Java call JS functions by name.</p> <p>Java side:</p> <pre><code>String callbackFunction; public void RegisterCallback(String functionName) { callbackFunction = functionName; } void UseCallbackFunction() { if (callbackFunction == null) return; JSObject win = (JSObject) JSObject.getWindow(this); win.call(callbackFunction, null); } </code></pre>
<p>win.eval() will call a predefined javascript.</p> <pre><code>String callbackFunction; public void RegisterCallback(String functionName) { callbackFunction = functionName; } void UseCallbackFunction() { if (callbackFunction == null) return; JSObject win = (JSObject) JSObject.getWindow(this); win.eval(callbackFunction); } </code></pre>
37,791
<p>I am using Enterprise Library 4.0 and I can't find any documentation on creating a custom logging filter. Has anyone done this or seen any good online documentation on this?</p>
<p><a href="https://web.archive.org/web/20160512123637/http://geekswithblogs.net:80/.NETonMyMind/archive/2006/05/15/78201.aspx" rel="nofollow noreferrer">Using Custom Filters in the Enterprise Library Logging Block</a></p> <p>Great Article.</p>
<p>Perusing through EntLib's source code would probably help you if the documentation is scant; it's well-written and well-commented.</p>
18,163
<p>I'm trying to select more than 80,000 record in SQL Server in a table that has millions of records. The issue is that I've the correct Index, but it takes more than 15 minutes to return the recordset.</p> <p>I'm using MS SQL Server 2000, I found a pagination method using stored procedures but it uses a temporal table that I have to insert the entire Result Set and then select the quantity of record I'm going to show per page. This method takes too long.</p> <p>Any help for a faster way that I can implement ?</p>
<p>You'll have to edit this to implement your input parameters for user's filtering and sort options, but the general principle will apply.. I used this technique with SQL 2000 in 2000/2001 timeframe with 90M record table to deliver fast paging for 150-200k row resultsets. Since only the key is in the temp table, it is a very narrow, very small temp tabl;e, and performance is fast, (and it only has to read the main table index, not the table itself, for this step) Then, when actually generating data from main table for actual (smaller) return resultset (only @PageSize rows) the query only has to read a very few records... </p> <pre><code>Create Procedure GetPagedData @Page Integer = 1, @PageSize Integer = 100, @UsersFilteringCOnditions, @UsersSortOptions As Set NoCount On Declare @Start Integer, Declare @End Integer Declare @NumRecs Integer -- Declare a temp table variable to hold all the pk values... Declare @Keys Table (rowNum integer Identity Primary Key NotNull, keyVal Integer Not Null) -- Insert all the Primary Keys into the temp table variable... Insert @keys(keyVal) Select PrimaryKey From MyMillionRowTable Where UsersFilterConditionsAreTrue Order By UsersSortOptions -- Then, select from your big table only the data -- from the rows for the page the user wants Select @NumRecs = Count(*) From Keys Set @End = @Page * @PageSize Set @Start = @End + 1 - @PageSize Select {Insert ColumnListHere} From MyMillionRowTable T Join @Keys K On K.KeyVal = T.PrimaryKey Where K.rowNum Between @Start And @End </code></pre>
<p>There are a few of options. The usual DB tuning tricks (on which I'm not an expert). Is it possible to extract the subset data you care about into a smaller table behind the scenes?</p>
49,954
<p>I have found <a href="http://www.jamesholmes.com/struts/console/help.html" rel="nofollow noreferrer">Struts Console Tool</a> but its development stopped in 2004, so it works with Netbeans 3.2.</p> <p>Is there a way to install it under Netbeans 6.5?</p> <p>Are there any options to edit struts-config.xml above the XML level?</p>
<p>Netbeans supports automatic <code>struts-config.xml</code> modifications. For instance if you right click on your project and choose <code>New/Struts Action</code> Netbeans will not only create a new class, but it can also modify your <code>struts-config.xml</code> and add a new <code>&lt;action&gt;</code> tag. Of course it's not a complex GUI, but you don't have to manually edit <code>struts-config.xml</code> all the time.</p>
<p>You need a tool to write a very simple XML file? Especially when the IDE should offer you tag completion, member list assistance, etc, in the XML editor?</p>
47,296
<p>I am trying to set my DOS environment variable in Ruby, and have it persist after the script exits. For example, if I want a ruby script <code>set_abc_env.rb</code> to set environment variable 'ABC' to 'blah', I expect to run the following:</p> <pre><code>C:&gt; echo %ABC% C:&gt; set_abc_env.rb C:&gt; echo %ABC% blah </code></pre> <p>How do I do this?</p>
<p>You can access environment variables via Ruby ENV object:</p> <pre><code>i = ENV['ABC']; # nil ENV['ABC'] = '123'; i = ENV['ABC']; # '123' </code></pre> <p>Bad news is, as MSDN <a href="http://msdn.microsoft.com/en-us/library/ms682009(VS.85).aspx" rel="noreferrer">says</a>, a process can never directly change the environment variables of another process that is not a child of that process. So when script exits, you lose all changes it did.</p> <p>Good news is what Microsoft Windows stores environment variables in the registry and it's possible to <a href="http://support.microsoft.com/kb/104011" rel="noreferrer">propagate</a> environment variables to the system. This is a way to modify user environment variables:</p> <pre><code>require 'win32/registry.rb' Win32::Registry::HKEY_CURRENT_USER.open('Environment', Win32::Registry::KEY_WRITE) do |reg| reg['ABC'] = '123' end </code></pre> <p>The documentation also says you should log off and log back on or broadcast a WM_SETTINGCHANGE message to make changes seen to applications. This is how broadcasting can be done in Ruby:</p> <pre><code>require 'Win32API' SendMessageTimeout = Win32API.new('user32', 'SendMessageTimeout', 'LLLPLLP', 'L') HWND_BROADCAST = 0xffff WM_SETTINGCHANGE = 0x001A SMTO_ABORTIFHUNG = 2 result = 0 SendMessageTimeout.call(HWND_BROADCAST, WM_SETTINGCHANGE, 0, 'Environment', SMTO_ABORTIFHUNG, 5000, result) </code></pre>
<p>For anyone else looking for a solution for this and looking for a more of a hack that doesn't require logging in or out I came up with this solution for a similar problem :</p> <p><strong>WORKAROUND:</strong></p> <p>My work around is dependent on combination of ruby and a command line utility called <a href="http://barnyard.syr.edu/~vefatica/#SETENV" rel="nofollow">SETENV.EXE</a> develped by Vincent Fatica. It's more than a decade old at this point but works fine in windows XP ( didn't test under Windows 7 yet). It works better than setx utility available from MS IMHO. At lest for deleting stuff. Make sure setenv is available from command line. Put it in some c:\tools and put c:\tools in your PATH.</p> <p>Here is a short example of a method using it:</p> <pre><code>def switch_ruby_env if RUBY_VERSION.match("1.8.7").nil? `setenv -m CUSTOM_PATH " "` else `setenv -m CUSTOM_PATH -delete` end end </code></pre>
23,073
<p>I would like to create a database backed interactive AJAX webapp which has a custom (specific kind of events, editing) calendaring system. This would involve quite a lot of JavaScript and AJAX, and I thought about Google Web Toolkit for the interface and Ruby on Rails for server side.</p> <p>Is Google Web Toolkit reliable and good? What hidden risks might be if I choose Google Web Toolkit? Can one easily combine it with Ruby on Rails on server side? Or should I try to use directly a JavaScript library like jQuery?</p> <p>I have no experience in web development except some HTML, but I am an experienced programmer (c++, java, c#), and I would like to use only free tools for this project.</p>
<p>RoR is actually one of the things the GWT is made to work well with, as long as you're using REST properly. It's in the Google Web Toolkit Applications book, and you can see a demo from the book using this kind of idea <a href="http://www.gwtapps.com/?page_id=33" rel="noreferrer">here</a>. That's not to say that you won't have any problems, but I think the support is definitely out there for it.</p> <p>There's a neat project for making RoR/GWT easy that you can find <a href="http://code.google.com/p/gwt-on-rails/" rel="noreferrer">here</a> (MIT license). I haven't had a chance to try it out yet, but it looks like a good amount of thought has been put into it. One catch is that it looks like it hasn't been fully tested with 2.1 Rails yet, just 2.0, so you may run into a few (probably minor and fixable) errors.</p>
<p>You could also consider <a href="http://grails.org/" rel="nofollow noreferrer">Grails</a> ("Groovy on Rails") which gives you the benefits of a Rails framework and the use of the Java VM.</p>
5,067
<p>I googled a lot, and could not find a single open source implementation of SFTP in .NET. All i got is 3rd party component for SFTP. can anyone help me with SFTP implenetation in .NET ?</p>
<p>See <a href="https://stackoverflow.com/questions/86458/how-do-i-upload-a-file-to-an-sftp-server-in-c-net#86510">this question</a> and <a href="http://sourceforge.net/projects/sharpssh" rel="nofollow noreferrer">shrpssh</a>, which was the accepted answer.</p>
<p>You may want to check out Granados</p> <p><a href="http://www.csharpopensource.net/granados.aspx" rel="nofollow noreferrer">http://www.csharpopensource.net/granados.aspx</a></p>
21,659
<p>web2py to is a Python framework but shares the "convention over configuration" design that Ruby on Rails has. On the plus side it packages a lot more functionality with its s standard distribution and we claim it is faster and easier to use.</p> <p>Has any Rails user tried it? What is your impression?</p> <p>No rants please. Just technical comments.</p>
<p>c'mon guys... your only argument is "Technical differences are rather irrelevant." and "it don't matter what web framework you use"? I disagree. The size of the users base has more to do with marketing and how long a framework has been around. By that argument ASP and PHP are better than Rails.</p> <p>Has anybody here used both Rails and web2py?</p> <p>web2py runs on webfaction and any hosting provider that supports mod_proxy or mod_wsgi or mod_fcgi, and runs on Google App Engine (rails does not). There is also a dedicated web2py hosting provider (star-nix.com).</p>
<p>I would say the biggest "con" of using webpy over Rails is that there are not a lot of Rails-specific hosting services around, and the huge community based around it (there are Rails plugins and tools for.. everything). The same cannot be said for web2py.</p> <p>It depends what you want to do with it - if it's something to write your personal site with, and you already have a server to host it on, use whatever you prefer. If it's something to distribute for others to run, Rails has more options for hosting, and a bigger community, so it may be a better choice.</p> <p>Technical differences are rather irrelevant. Every framework can basically do the same (generate web-pages). What is important is community, ease of use, useful feature-sets, ability to host it and so on - and those are all really subjective.</p> <p>I still use PHP quite often, not because "it's better", but because I can host it on a huge majority of web-hosts. I also use Rails because as it has a good, and very active community. The actually technicalities of the framework wasn't ever a consideration, really..</p> <p>I could probably put together a list of why web2py is "better"/"worse" than Rails - Rails may be 0.04sec/request slower at generating templates containing loops, or web2py may have a good DB model generator, or some other technical reason - but those may not be relevant to you at all</p>
42,382
<p>I have inherited some code for a custom CMS that is a little out of my league and keep stumbling over the same errors, Notice: Undefined variable: media in /Applications/MAMP/htdocs/Chapman/Chapman_cms/admin/team-2.php on line 48. This is supposed to create new users and edit old users. However, it does not work when I try and add a new user.</p> <p>Below is the pertinant code:</p> <pre><code>$db = new database("mysql",$dbHost,$dbName,$dbUser,$dbPass); $target = 'add'; if ($_GET['task'] == 'edit') { $media = $db-&gt;get_row(edit_media_item($db, $_GET['team_id'])); $target = 'update'; &lt;p&gt;&lt;label for="copy"&gt;Full Name:&lt;/label&gt; &lt;input type="text" name="title" value="&lt;?=$media['title']?&gt;" /&gt; &lt;textarea name="media" id="media" cols="30" rows="5" style="width: 100%"&gt;&lt;?=$media['copy']?&gt;&lt;/textarea&gt;&lt;/p&gt; &lt;input type="hidden" name="process" value="&lt;?=$target.",copy,4,team-1,".$media['id'].""?&gt;"&gt; &lt;p&gt;&lt;input type="submit" name="save" value="Submit" /&gt; &lt;input type="reset" name="reset" value="Reset" /&gt;&lt;/p&gt; &lt;/form&gt; </code></pre> <p>Any help would be much appreciated.</p>
<p>To remove the notice in the right way is to do this with the code</p> <pre><code>&lt;?php if(isset($media['copy'])){ echo $media['copy']; } ?&gt; </code></pre>
<p>The code you posted does not do any creating, so that problem does not stemfrom this bit of code.</p> <p>The undefined notice is from the <code>&lt;?=$media['copy']?&gt;</code> bit. $media was never defined. If this is not an issue, ignore it and tell PHP to not output notices. This isn't exactly good practice, but if you're not getting paid to fix every little thing, I'd say it's a feasible alternative.</p> <p>To suppress notices add this code anywhere before the notices occur or better yet into a global include:</p> <pre><code>error_reporting(E_ERROR | E_WARNING | E_PARSE); </code></pre> <p>For more info: <a href="http://www.php.net/error_reporting" rel="nofollow noreferrer">http://www.php.net/error_reporting</a></p>
18,981
<p>I need to test some HTTP interaction with a client I'd rather not modify. What I need to test is the behavior of the server when the client's requests include a certain, static header.</p> <p>I'm thinking the easiest way to run this test is to set up an HTTP proxy that inserts the header on every request. What would be the simplest way to set this up?</p>
<p>I do something like this in my development environment by configuring Apache on port 80 as a proxy for my application server on port 8080, with the following Apache config:</p> <pre><code>NameVirtualHost * &lt;VirtualHost *&gt; &lt;Proxy http://127.0.0.1:8080/*&gt; Allow from all &lt;/Proxy&gt; &lt;LocationMatch "/myapp"&gt; ProxyPass http://127.0.0.1:8080/myapp ProxyPassReverse http://127.0.0.1:8080/myapp Header add myheader "myvalue" RequestHeader set myheader "myvalue" &lt;/LocationMatch&gt; &lt;/VirtualHost&gt; </code></pre> <p>See <a href="http://httpd.apache.org/docs/current/mod/core.html#locationmatch" rel="noreferrer">LocationMatch</a> and <a href="http://httpd.apache.org/docs/current/mod/mod_headers.html#requestheader" rel="noreferrer">RequestHeader</a> documentation.</p> <p>This adds the header <em>myheader: myvalue</em> to requests going to the application server.</p>
<p>If you have ruby on your system, how about a small Ruby Proxy using Sinatra (make sure to install the Sinatra Gem). This should be easier than setting up apache. The code can be found <a href="http://thecoderslife.blogspot.com/2015/07/a-http-proxy-using-sinatra.html" rel="nofollow">here.</a></p>
18,665
<p>Has anybody implemented a feature where if the user has not touched the screen for a certain time period, you take a certain action? I'm trying to figure out the best way to do that.</p> <p>There's this somewhat-related method in UIApplication:</p> <pre><code>[UIApplication sharedApplication].idleTimerDisabled; </code></pre> <p>It'd be nice if you instead had something like this:</p> <pre><code>NSTimeInterval timeElapsed = [UIApplication sharedApplication].idleTimeElapsed; </code></pre> <p>Then I could set up a timer and periodically check this value, and take some action when it exceeds a threshold.</p> <p>Hopefully that explains what I'm looking for. Has anyone tackled this issue already, or have any thoughts on how you would do it? Thanks.</p>
<p>Here's the answer I had been looking for:</p> <p>Have your application delegate subclass UIApplication. In the implementation file, override the sendEvent: method like so:</p> <pre><code>- (void)sendEvent:(UIEvent *)event { [super sendEvent:event]; // Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets. NSSet *allTouches = [event allTouches]; if ([allTouches count] &gt; 0) { // allTouches count only ever seems to be 1, so anyObject works here. UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase; if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded) [self resetIdleTimer]; } } - (void)resetIdleTimer { if (idleTimer) { [idleTimer invalidate]; [idleTimer release]; } idleTimer = [[NSTimer scheduledTimerWithTimeInterval:maxIdleTime target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO] retain]; } - (void)idleTimerExceeded { NSLog(@"idle time exceeded"); } </code></pre> <p>where maxIdleTime and idleTimer are instance variables.</p> <p>In order for this to work, you also need to modify your main.m to tell UIApplicationMain to use your delegate class (in this example, AppDelegate) as the principal class:</p> <pre><code>int retVal = UIApplicationMain(argc, argv, @"AppDelegate", @"AppDelegate"); </code></pre>
<p>Outside is 2021 and I would like share my approach to handle this without extending the UIApplication. I will not describe how to create a timer and reset it. But rather how to catch all events. So your AppDelegate starts with this:</p> <pre><code>@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? </code></pre> <p>So all you need to do is to subclass UIWindow and override <code>sendEvent</code>, like below</p> <pre><code>import UIKit class MyWindow: UIWindow { override func sendEvent(_ event: UIEvent){ super.sendEvent(event) NSLog(&quot;Application received an event. Do whatever you want&quot;) } } </code></pre> <p>And later create window with our class:</p> <pre><code>self.window = MyWindow(frame: UIScreen.main.bounds) </code></pre>
34,447
<p>Is there any way to direct C# to ignore <code>NullReferenceException</code> (or any specific exception for that matter) for a set of statements. This is useful when trying to read properties from a deserialized object that may contain many null objects in it. Having a helper method to check for null could be one way but I'm looking for something close to 'On Error Resume Next' (from VB) at a block of statement level.</p> <p>EDIT:Try-Catch will skip the succeeding statements on exception</p> <pre><code>try { stmt 1;// NullReferenceException here, will jump to catch - skipping stmt2 and stmt 3 stmt 2; stmt 3; } catch (NullReferenceException) { } </code></pre> <p>For Example: I'm deserializing an XML message to an object and then try to access a property like</p> <pre><code>Message.instance[0].prop1.prop2.ID </code></pre> <p>now prop2 could be a null object (because it doesn't exists in XML Message - an optional element in XSD). right now I need to check for null for each element in the hierarchy before accessing the leaf element. i.e I've to check if instance[0], prop1, prop2 are not null, before accessing 'ID'.</p> <p>Is there a better way that avoids null-checking for each element in the hierarchy?</p>
<p>In short: no. Null-check the reference before trying to use it. One useful trick here might be C# 3.0 extension methods... they allow you to <em>appear to</em> invoke something on a null reference without error:</p> <pre><code>string foo = null; foo.Spooky(); ... public static void Spooky(this string bar) { Console.WriteLine("boo!"); } </code></pre> <p>Other than that - perhaps some use of the conditional operator?</p> <pre><code>string name = obj == null ? "" : obj.Name; </code></pre>
<pre><code>try { // exceptions thrown here... } catch (NullReferenceException) { } </code></pre>
38,137
<p>Per this <a href="http://www.15seconds.com/issue/040830.htm" rel="nofollow noreferrer">helpful article</a> I have confirmed I have a connection pool leak in some application on my IIS 6 server running W2k3. </p> <p>The tough part is that I'm serving 300 websites written by 700 developers from this server in 6 application pools, 50% of which are .NET 1.1 which doesn't even show connections in the CLR Data performance counter. I could watch connections grow on my end if everything were .NET 2.0+, but I'm even out of luck on that slim monitoring tool. </p> <p>My 300 websites connect to probably 100+ databases spread out between Oracle, SQLServer and outliers, so I cannot watch the connections from the database end either. </p> <p>Right now my best and only plan is to do a loose binary search for my worst offenders. I will kill application pools and slowly remove applications from them until I find which individual applications result in the most connections dropping when I kill their pool. But since this is a production box and I like continued employment, this could take weeks as a tracing method. </p> <p>Does anyone know of a way to interrogate the IIS connection pools to learn their origin or owner? Is there an MSMQ trigger I might be able to which I might be able to attach when they are created? Anything silly I'm overlooking? </p> <p>Kevin</p> <p>(I'll include the error code to facilitate others finding your answers through search: Exception: System.InvalidOperationException Message: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.)</p>
<p>Try starting with this <a href="http://msdn.microsoft.com/en-us/library/aa175863(SQL.80).aspx" rel="nofollow noreferrer">first article from Bill Vaughn</a>.</p>
<p>Todd Denlinger wrote a fantastic class <a href="http://www.codeproject.com/KB/database/connectionmonitor.aspx" rel="nofollow">http://www.codeproject.com/KB/database/connectionmonitor.aspx</a> which watches Sql Server connections and reports on ones that have not been properly disposed within a period of time. Wire it into your site, and it will let you know when there is a leak. </p>
19,727
<p>Another easy one hopefully.</p> <p>Let's say I have a collection like this:</p> <pre><code>List&lt;DateTime&gt; allDates; </code></pre> <p>I want to turn that into </p> <pre><code>List&lt;List&lt;DateTime&gt;&gt; dividedDates; </code></pre> <p>where each List in 'dividedDates' contains all of the dates in 'allDates' that belong to a distinct year.</p> <p>Is there a bit of LINQ trickery that my tired mind can't pick out right now?</p> <p><strong>Solution</strong></p> <p>The Accepted Answer is correct.</p> <p>Thanks, I don't think I was aware of the 'into' bit of GroupBy and I was trying to use the .GroupBy() sort of methods rather than the SQL like syntax. And thanks for confirming the ToList() amendment and including it in the Accepted Answer :-)</p>
<pre><code>var q = from date in allDates group date by date.Year into datesByYear select datesByYear.ToList(); q.ToList(); //returns List&lt;List&lt;DateTime&gt;&gt; </code></pre>
<p>Here's the methods form.</p> <pre> allDates .GroupBy(d => d.Year) .Select(g => g.ToList()) .ToList(); </pre>
9,514
<p>Has anyone implements Subversion with Siteminder as authentication provider ? If yes, would it be possible to provide an overview of how the whole setup is done ?</p> <p>Since I am using only HTTP authentication, I think it would be easier to integrate with SM, but I am not able to find much help on this on the net.</p> <p>Is there any pitfall with this setup ? is this even possible ?</p>
<p>SVN with Siteminder has been implemented and is working now. Since there is not much of information out there on this, I would like to post the overview of steps followed:</p> <ol> <li>Cookie based authentcation was disabled on Siteminder end</li> <li>HTTP AUTH was enabled (in Siteminder) and all webdav methods were added to policy server to be handled by SiteMinder</li> <li>Authentication was disabled on apache end (HTTP Auth) for SVN</li> </ol>
<p>Look for information about <strong>Apache</strong> and Siteminder as Apache is responsible for the HTTP transport stuff in Subversion</p>
9,936
<p>I want to have a web based admin to upload, delete files and folders in Amazon S3 on ASP.NET website. <br/> I am pretty sure something like this already exist, has anyone seen it? </p>
<p>Have you tried this one? <a href="http://www.codeplex.com/ThreeSharp" rel="nofollow noreferrer">http://www.codeplex.com/ThreeSharp</a></p>
<p><a href="http://www.cloudberrylab.com" rel="nofollow">Cloudberry has some cool products, I love the backup besides the explorer.</a></p>
29,247
<p>I'd love to use PHP variables in my CSS files but I don't want to load up the whole Symfony stack for each file load. Any one have any best practices and/or plugins to manage their CSS files in Symfony?</p>
<p>but you dont need full symfony stack for that ( except if you need some internal symfony state / variable ).</p> <p>You just use</p> <pre><code>&lt;link rel="stylesheet" type="text/css" media="screen" href="/css/mycss.php" /&gt; </code></pre> <p>and then you can use php inside your css. you could add appropriate headers (text/css) with header in php.</p>
<p>Here's one good Plugin that tries to manage and/or combine your assets:</p> <p><a href="http://www.symfony-project.org/plugins/sfCombinePlugin" rel="nofollow noreferrer">http://www.symfony-project.org/plugins/sfCombinePlugin</a></p> <p>Here's their description:</p> <blockquote> <p>Combines multiple JavaScript and CSS files into one JavaScript and one CSS file at runtime, in order to minimize the number of HTTP requests required to render a given page. This plugin works in distributed environments, supports asset version keys, and is highly customizable.</p> </blockquote> <p>Also, since it's compiled, you <em>may</em> be able to use simple PHP as long as the variables stick within the same file.</p>
48,342
<p>I have a c# site which makes use of a lot of images with embedded english text. </p> <p>How can I use a standard resource file to swap out images depending on the language?</p> <p>I have a resx file in my App_GlobalResources directory, but I can't seem to get it plugged into an asp:image control for the imageurl correctly.</p> <p>Ideas?</p> <p><strong>UPDATE:</strong> </p> <p>For some further information, here is the image tag code:</p> <pre><code>&lt;asp:image runat="server" ID="img2" ImageUrl="&lt;%$Resources: Resource, cs_logo %&gt;" /&gt; </code></pre> <p>The result on the client side is:</p> <pre><code>&lt;img id="img2" src="System.Drawing.Bitmap" style="border-width:0px;" /&gt; </code></pre> <p>Note that the source is obviously not what I expected...</p>
<p>you can store the url of the image in your resource file and use the following inline code in the control </p> <pre><code>&lt;asp:Image ImageUrl="&lt;%$resources:Image1 %&gt;" /&gt; </code></pre> <h3>Update</h3> <p>this <a href="http://aspalliance.com/726" rel="noreferrer">link</a> could be helpful on what you are trying to accomplish</p> <p>or </p> <p>you can also try to stored the resource as string and set the value to the url location instead of storing the image in the resouce file.</p>
<p>if you are using global resources file you need to add it like this </p> <pre><code>&lt;img id="WelocmeICon" runat="server" alt="welcome icon" src="&lt;%$resources:NmcResource,WelcomeIcon %&gt;" /&gt; </code></pre> <p>and because i use img control i added runatserver and id for it </p>
30,360
<p>Does anyone have any code examples on how to create controllers that have parameters other than using a Dependency Injection Container? </p> <p>I see plenty of samples with using containers like StructureMap, but nothing if you wanted to pass in the dependency class yourself.</p>
<p>You can use poor-man's dependency injection:</p> <pre><code>public ProductController() : this( new Foo() ) { //the framework calls this } public ProductController(IFoo foo) { _foo = foo; } </code></pre>
<p>You can create an IModelBinder that spins up an instance from a factory - or, yes, the container. =)</p>
14,870
<p>My professor did an informal benchmark on a little program and the Java times were: 1.7 seconds for the first run, and 0.8 seconds for the runs thereafter. </p> <ul> <li><p>Is this due entirely to the loading of the runtime environment into the operating environment ?</p> <p>OR </p></li> <li><p>Is it influenced by Java's optimizing the code and storing the results of those optimizations (sorry, I don't know the technical term for that)?</p></li> </ul>
<p>Okay, I found where I read that. This is all from &quot;Learning Java&quot; (O'Reilly 2005):</p> <blockquote> <p>The problem with a traditional JIT compilation is that optimizing code takes time. So a JIT compiler can produce decent results but may suffer a significant latency when the application starts up. This is generally not a problem for long-running server-side applications but is a serious problem for client-side software and applications run on smaller devices with limited capabilities. To address this, Sun's compiler technology, called HotSpot, uses a trick called adaptive compilation. If you look at what programs actually spend their time doing, it turns out that they spend almost all their time executing a relatively small part of the code again and again. The chunk of code that is executed repeatedly may be only a small fraction of the total program, but its behavior determines the program's overall performance. Adaptive compilation also allows the Java runtime to take advantage of new kinds of optimizations that simply can't be done in a statically compiled language, hence the claim that Java code can run faster than C/C++ in some cases.</p> <p>To take advantage of this fact, HotSpot starts out as a normal Java bytecode interpreter, but with a difference: it measures (profiles) the code as it is executing to see what parts are being executed repeatedly. Once it knows which parts of the code are crucial to performance, HotSpot compiles those sections into optimal native machine code. Since it compiles only a small portion of the program into machine code, it can afford to take the time necessary to optimize those portions. The rest of the program may not need to be compiled at all—just interpreted—saving memory and time. In fact, Sun's default Java VM can run in one of two modes: client and server, which tell it whether to emphasize quick startup time and memory conservation or flat out performance.</p> <p>A natural question to ask at this point is, Why throw away all this good profiling information each time an application shuts down? Well, Sun has partially broached this topic with the release of Java 5.0 through the use of shared, read-only classes that are stored persistently in an optimized form. This significantly reduces both the startup time and overhead of running many Java applications on a given machine. The technology for doing this is complex, but the idea is simple: optimize the parts of the program that need to go fast, and don't worry about the rest.</p> </blockquote> <p>I'm kind of wondering how far Sun has gotten with it since Java 5.0.</p>
<p>Java JVM (actually might change from different implementations of the JVM) when first started out will interpret the byte code. Once it detects that the code will be running enough number of times JITs it to native machine language so it runs faster. </p>
9,361
<p>Is it possible to just send a JPanel or any other component to the printer? Or do I have to implement all the drawing to the graphics object by hand?</p> <p>I have tried to use the Print* functions of the JPanel to print to the graphics object but the page that gets printed is blank.</p>
<p>Check out the Java printing API <a href="http://java.sun.com/docs/books/tutorial/2d/printing/gui.html" rel="nofollow noreferrer">and tutorial</a> along with JComponent.print(Graphics).</p> <p>Here is a rudimentary class which will print any component which fits on 1 page (I can't take credit for this, I got the code from <a href="http://courseweb.xu.edu.ph/courses/ics10/swing/Printing.htm" rel="nofollow noreferrer">Marty Hall's tutorial</a>):</p> <pre><code>import java.awt.*; import java.awt.print.*; import javax.swing.*; /** * Generic component printer. This object allows any AWT or Swing component (or DCT system) * to be printed by performing it pre and post print responsibilities. * &lt;p&gt; * When printing components, the role of the print method is nothing more than to scale the Graphics, turn off double * buffering, and call paint. There is no particular reason to put that print method in the component being printed. A * better approach is to build a generic printComponent method to which you simply pass the component you want printed. * &lt;p&gt; * With Swing, almost all components have double buffering turned on by default. In general, this is a great benefit, * making for convenient and efficient painting. However, in the specific case of printing, it can is a huge problem. * First, since printing components relies on scaling the coordinate system and then simply calling the component's * paint method, if double buffering is enabled printing amounts to little more than scaling up the buffer (off-screen * image) which results in ugly low-resolution printing like you already had available. Secondly, sending these huge * buffers to the printer results in huge print spooler files which take a very long time to print. Consequently this * object globally turns off double buffering before printing and turns it back on afterwards. * &lt;p&gt; * Threading Design : [x] Single Threaded [ ] Threadsafe [ ] Immutable [ ] Isolated */ public class ComponentPrinter extends Object implements Printable { // ***************************************************************************** // INSTANCE PROPERTIES // ***************************************************************************** private Component component; // the component to print // ***************************************************************************** // INSTANCE CREATE/DELETE // ***************************************************************************** public ComponentPrinter(Component com) { component=com; } // ***************************************************************************** // INSTANCE METHODS // ***************************************************************************** public void print() throws PrinterException { PrinterJob printJob=PrinterJob.getPrinterJob(); printJob.setPrintable(this); if(printJob.printDialog()) { printJob.print(); } } public int print(Graphics gc, PageFormat pageFormat, int pageIndex) { if(pageIndex&gt;0) { return NO_SUCH_PAGE; } RepaintManager mgr=RepaintManager.currentManager(component); Graphics2D g2d=(Graphics2D)gc; g2d.translate(pageFormat.getImageableX(),pageFormat.getImageableY()); mgr.setDoubleBufferingEnabled(false); // only for swing components component.paint(g2d); mgr.setDoubleBufferingEnabled(true); // only for swing components return PAGE_EXISTS; } // ***************************************************************************** // STATIC METHODS // ***************************************************************************** static public void printComponent(Component com) throws PrinterException { new ComponentPrinter(com).print(); } } // END PUBLIC CLASS </code></pre>
<p>please consider <a href="https://stackoverflow.com/a/49378186/1273555">this answer</a> for printing a <code>Component</code> to multiple pages:</p> <pre><code>import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.print.*; import javax.swing.RepaintManager; public class PrintMultiPageUtil implements Printable, Pageable { private Component componentToBePrinted; private PageFormat format; private int numPages; public PrintMultiPageUtil(Component componentToBePrinted) { this.componentToBePrinted = componentToBePrinted; // get total space from component Dimension totalSpace = this.componentToBePrinted.getPreferredSize(); // calculate for DIN A4 format = PrinterJob.getPrinterJob().defaultPage(); numPages = (int) Math.ceil(totalSpace .height/format.getImageableHeight()); } public void print() { PrinterJob printJob = PrinterJob.getPrinterJob(); // show page-dialog with default DIN A4 format = printJob.pageDialog(printJob.defaultPage()); printJob.setPrintable(this); printJob.setPageable(this); if (printJob.printDialog()) try { printJob.print(); } catch(PrinterException pe) { System.out.println("Error printing: " + pe); } } public int print(Graphics g, PageFormat pageFormat, int pageIndex) { if ((pageIndex &lt; 0) | (pageIndex &gt;= numPages)) { return(NO_SUCH_PAGE); } else { Graphics2D g2d = (Graphics2D)g; g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY() - pageIndex * pageFormat.getImageableHeight()); disableDoubleBuffering(componentToBePrinted); componentToBePrinted.paint(g2d); enableDoubleBuffering(componentToBePrinted); return(PAGE_EXISTS); } } public static void disableDoubleBuffering(Component c) { RepaintManager currentManager = RepaintManager.currentManager(c); currentManager.setDoubleBufferingEnabled(false); } public static void enableDoubleBuffering(Component c) { RepaintManager currentManager = RepaintManager.currentManager(c); currentManager.setDoubleBufferingEnabled(true); } @Override public int getNumberOfPages() { // TODO Auto-generated method stub return numPages; } @Override public PageFormat getPageFormat(int arg0) throws IndexOutOfBoundsException { return format; } @Override public Printable getPrintable(int arg0) throws IndexOutOfBoundsException { // TODO Auto-generated method stub return this; } } </code></pre>
44,299
<p>I want to know what exactly is the sequence of calls that occurs when a getter/setter created through Class::MethodMaker is called?</p> <p>How much costlier are getter/setters defined by MethodMaker than the native ones (overwritten in the module)?</p>
<p>I don't have a simple answer for your question regarding Class::MethodMaker performance. As a previous answer mentioned, you can use the debugger to find out what's going on under the hood. However, I know that Class::MethodMaker generates <em>huge</em> amounts of code at install time. This would indicate three separate things to me:</p> <ol> <li>Regarding run-time, it's <em>probably</em> on the faster side of the whole slew of method generators. Why generate loads of code at install time otherwise?</li> <li>It installs O(Megabytes) of code on your disk!</li> <li>It may potentially be slow at compile time, depending on what parts of the generated code are loaded for simple use cases.</li> </ol> <p>You really need to spend a few minutes to think about what you really need. If you want simple accessor methods auto-generated but write anything more complicated by hand, maybe look at Class::Accessor::Fast. Or, if you want the fastest possible accessor-methods, investigate Class::XSAccessor, whose extra-simple methods run as C/XS code and are approximately twice as fast as the fastest Perl accessor. (Note: I wrote the latter module, so take this with a grain of salt.)</p> <p>One further comment: if you're ever going to use the PAR/PAR::Packer toolkit for packaging your application, note that the large amount of code of Class::MethodMaker results in a significantly larger executable and a slower initial start-up time. Additionally, there's a known incompatibility between C::MethodMaker and PAR. But that may be considered a PAR bug.</p>
<p>The real question is: does it matter?</p> <p>It's yet another accessors generating module. These modules all have a speed/functionality trade-off. Just pick one that offers everything you need. It's not like accessors are likely to become a bottleneck in your application.</p>
8,745
<p>I have a database with 2 tables.</p> <p>One of the tables holds a row containing numbers, from 0 to 10.</p> <p>In PHP, I do this: </p> <pre><code>$query = "SELECT ".$param." FROM issues WHERE ".$param." &gt;=0"; $result = @mysql_query($query) or showError("query failed"); if (!($record = mysql_fetch_array($result))) return null; return $record; </code></pre> <p>The $param holds the name of the row.</p> <p>I kinda expected to get an array holding the number 0 to 10, but instead I get an array with 2 elements:</p> <pre><code>array( [0] = 0 [row_name] = 0 . . . // AND SO ON ) </code></pre> <p>And that's it.</p> <p>I've never worked with these functions before and <a href="http://www.php.net" rel="nofollow noreferrer">www.php.net</a> doesn't have any examples that really help...</p>
<p>I'm not exactly sure what you are trying to achieve here, but I think what you want is:</p> <pre><code>// query... $records = array(); while($r = mysql_fetch_array($result)) { $records[] = $r; } return $records; </code></pre>
<p>By default <a href="http://it.php.net/mysql_fetch_array" rel="nofollow noreferrer">mysql_fetch_array</a> returns both normal and associative arrays, so you can access the values by position ($result[0]) or by name ($result['user_name'])':</p> <pre><code>array mysql_fetch_array ( resource $result [, int $result_type ] ) </code></pre> <blockquote> <p>result_type: The type of array that is to be fetched. It's a constant and can take the following values: MYSQL_ASSOC, MYSQL_NUM, and the default value of MYSQL_BOTH.</p> </blockquote>
45,635
<p>I need to open a password protected shared folder on a network to gain access to an Access 97 database. How do I open the folder and pass in the password?</p>
<p>found here <a href="http://www.mredkj.com/vbnet/vbnetmapdrive.html" rel="noreferrer">http://www.mredkj.com/vbnet/vbnetmapdrive.html</a></p> <pre><code>Public Declare Function WNetAddConnection2 Lib "mpr.dll" Alias "WNetAddConnection2A" _ ( ByRef lpNetResource As NETRESOURCE, ByVal lpPassword As String, _ ByVal lpUserName As String, ByVal dwFlags As Integer) As Integer Public Declare Function WNetCancelConnection2 Lib "mpr" Alias "WNetCancelConnection2A" _ (ByVal lpName As String, ByVal dwFlags As Integer, ByVal fForce As Integer) As Integer &lt;StructLayout(LayoutKind.Sequential)&gt; _ Public Structure NETRESOURCE Public dwScope As Integer Public dwType As Integer Public dwDisplayType As Integer Public dwUsage As Integer Public lpLocalName As String Public lpRemoteName As String Public lpComment As String Public lpProvider As String End Structure Public Const ForceDisconnect As Integer = 1 Public Const RESOURCETYPE_DISK As Long = &amp;H1 Public Function MapDrive(ByVal DriveLetter As String, ByVal UNCPath As String) As Boolean Dim nr As NETRESOURCE Dim strUsername As String Dim strPassword As String nr = New NETRESOURCE nr.lpRemoteName = UNCPath nr.lpLocalName = DriveLetter &amp; ":" strUsername = Nothing '(add parameters to pass this if necessary) strPassword = Nothing '(add parameters to pass this if necessary) nr.dwType = RESOURCETYPE_DISK Dim result As Integer result = WNetAddConnection2(nr, strPassword, strUsername, 0) If result = 0 Then Return True Else Return False End If End Function Public Function UnMapDrive(ByVal DriveLetter As String) As Boolean Dim rc As Integer rc = WNetCancelConnection2(DriveLetter &amp; ":", 0, ForceDisconnect) If rc = 0 Then Return True Else Return False End If End Function </code></pre>
<p>one solution would be to map the network folder to an available drive letter. You could accomplish that using Windows OS commands:</p> <pre><code>System.Diagnostics.Process.Start("net.exe", "use K: \\Server\URI\path\here /USER:&lt;username&gt; &lt;password&gt;" ) </code></pre> <p>Simply replace the username and password with the credentials you need and make sure the drive letter is available.</p> <p>To disconnect you can call</p> <pre><code>System.Diagnostics.Process.Start("net.exe", "use /delete K:" ) </code></pre>
41,552
<p>I'm trying to figure out how to parse out the text of an email from any quoted reply text that it might include. I've noticed that usually email clients will put an "On such and such date so and so wrote" or prefix the lines with an angle bracket. Unfortunately, not everyone does this. Does anyone have any idea on how to programmatically detect reply text? I am using C# to write this parser.</p>
<p>I did a lot more searching on this and here's what I've found. There are basically two situations under which you are doing this: when you have the entire thread and when you don't. I'll break it up into those two categories:</p> <p><strong>When you have the thread:</strong></p> <p>If you have the entire series of emails, you can achieve a very high level of assurance that what you are removing is actually quoted text. There are two ways to do this. One, you could use the message's Message-ID, In-Reply-To ID, and Thread-Index to determine the individual message, it's parent, and the thread it belongs to. For more information on this, see <a href="http://www.faqs.org/rfcs/rfc822.html" rel="noreferrer">RFC822</a>, <a href="http://www.faqs.org/rfcs/rfc2822.html" rel="noreferrer">RFC2822</a>, <a href="http://www.jwz.org/doc/threading.html" rel="noreferrer">this interesting article on threading</a>, or <a href="http://people.dsv.su.se/~jpalme/ietf/message-threading.html" rel="noreferrer">this article on threading</a>. Once you have re-assembled the thread, you can then remove the external text (such as To, From, CC, etc... lines) and you're done. </p> <p>If the messages you are working with do not have the headers, you can also use similarity matching to determine what parts of an email are the reply text. In this case you're stuck with doing similarity matching to determine the text that is repeated. In this case you might want to look into a <a href="http://en.wikipedia.org/wiki/Levenshtein_distance" rel="noreferrer">Levenshtein Distance algorithm</a> such as <a href="http://www.codeproject.com/KB/recipes/Levenshtein.aspx" rel="noreferrer">this one on Code Project</a> or <a href="http://www.codeproject.com/KB/recipes/improvestringsimilarity.aspx" rel="noreferrer">this one</a>. </p> <p>No matter what, if you're interested in the threading process, check out <a href="http://academiccommons.columbia.edu/download/fedora_content/download/ac:162861/CONTENT/yeh_harnly_06.pdf" rel="noreferrer">this great PDF on reassembling email threads</a>.</p> <p><strong>When you don't have the thread:</strong></p> <p>If you are stuck with only one message from the thread, you're doing to have to try to guess what the quote is. In that case, here are the different quotation methods I have seen:</p> <ol> <li>a line (as seen in outlook).</li> <li>Angle Brackets</li> <li>"---Original Message---"</li> <li>"On such-and-such day, so-and-so wrote:"</li> </ol> <p>Remove the text from there down and you're done. The downside to any of these is that they all assume that the sender put their reply on top of the quoted text and did not interleave it (as was the old style on the internet). If that happens, good luck. I hope this helps some of you out there!</p>
<p>It is old post, however, not sure if you are aware github has <a href="https://github.com/github/email_reply_parser" rel="nofollow">a Ruby lib</a> extracting the reply. If you use .NET, I have a .NET one at <a href="https://github.com/EricJWHuang/EmailReplyParser" rel="nofollow">https://github.com/EricJWHuang/EmailReplyParser</a></p>
35,208
<p>I am trying to use a DynamicResource in Storyboard contained within a ControlTemplate.</p> <p>But, when I try to do this, I get a 'Cannot freeze this Storyboard timeline tree for use across threads' error.</p> <p>What is going on here?</p>
<p>No, you can't use a DynamicResource in a Storyboard that is contained within a Style or ControlTemplate. In fact, you can't use a data binding expression either.</p> <p>The story here is that everything within a Style or ControlTemplate must be safe for use across threads and the timing system actually tries to freeze the Style or ControlTemplate to make them thread-safe. However, if a DynamicResource or data binding expression is present, it is unable to freeze them.</p> <p>For more info see: <a href="http://msdn.microsoft.com/en-us/library/ms742868.aspx" rel="noreferrer">MSDN Link</a>. Check out the 'Animate in a Style' and the 'Animate in a ControlTemplate' sections (this documentation page is rather long).</p> <p>And for a workaround (at least for my scenario) see: <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/9336022f-badb-4b40-a86c-a50ab1a64ba5/" rel="noreferrer">WPF Forum Post</a>.</p> <p>Hope this helps someone. I've lost more than enough hair on it.</p> <p>Cory</p>
<p>While you can have <code>DynamicResource</code> in a <code>ControlTemplate</code>, you just can't have one in a <code>StoryBoard</code>.</p> <p>I worked around this with a <code>Opacity</code> (or <code>Visibility</code>) hack. You can add two elements to your <code>ControlTemplate</code>. Each of them uses one of the <code>DynamicResources</code> but only one of them is visible. You can set the <code>Visibility</code> or <code>Opacity</code> of each element via the <code>Storyboard</code></p>
18,631
<p>I have a file that lists filenames, each on it's own line, and I want to test if each exists in a particular directory. For example, some sample lines of the file might be</p> <pre><code>mshta.dll foobar.dll somethingelse.dll </code></pre> <p>The directory I'm interested in is <code>X:\Windows\System32\</code>, so I want to see if the following files exist:</p> <pre><code>X:\Windows\System32\mshta.dll X:\Windows\System32\foobar.dll X:\Windows\System32\somethingelse.dll </code></pre> <p>How can I do this using the Windows command prompt? Also (out of curiosity) how would I do this using bash or another Unix shell?</p>
<p>In cmd.exe, the <strong>FOR /F %</strong><em>variable</em> <strong>IN (</strong> <em>filename</em> <b>) DO</b> <em>command</em> should give you what you want. This reads the contents of <em>filename</em> (and they could be more than one filenames) one line at a time, placing the line in %variable (more or less; do a HELP FOR in a command prompt). If no one else supplies a command script, I will attempt.</p> <p>EDIT: my attempt for a cmd.exe script that does the requested:</p> <pre><code>@echo off rem first arg is the file containing filenames rem second arg is the target directory FOR /F %%f IN (%1) DO IF EXIST %2\%%f ECHO %%f exists in %2 </code></pre> <p>Note, the script above <em>must</em> be a script; a FOR loop in a .cmd or .bat file, for some strange reason, must have double percent-signs before its variable.</p> <p>Now, for a script that works with bash|ash|dash|sh|ksh :</p> <pre><code>filename="${1:-please specify filename containing filenames}" directory="${2:-please specify directory to check} for fn in `cat "$filename"` do [ -f "$directory"/"$fn" ] &amp;&amp; echo "$fn" exists in "$directory" done </code></pre>
<p>In Windows:</p> <pre><code> type file.txt >NUL 2>NUL if ERRORLEVEL 1 then echo "file doesn't exist" </code></pre> <p>(This may not be the best way to do it; it is a way I know of; see also <a href="http://blogs.msdn.com/oldnewthing/archive/2008/09/26/8965755.aspx" rel="nofollow noreferrer"><a href="http://blogs.msdn.com/oldnewthing/archive/2008/09/26/8965755.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/oldnewthing/archive/2008/09/26/8965755.aspx</a></a>)</p> <p>In Bash:</p> <pre><code> if ( test -e file.txt ); then echo "file exists"; fi </code></pre>
18,179
<p>When using </p> <pre><code>$('.foo').click(function(){ alert("I haz class alertz!"); return false; }); </code></pre> <p>in application.js, and</p> <pre><code>&lt;a href = "" class = "foo" id = "foobar_1" &gt;Teh Foobar &lt;/a&gt; </code></pre> <p>in any div that initializes with the page, when clicking "Teh Foobar" it alerts and doesn't follow the link. However, when using the same code in application.js, and</p> <pre><code>&lt;a href = "" class = "foo" id = "foobar_1" &gt;Teh Foobar &lt;/a&gt; </code></pre> <p>is being returned into a div by a</p> <pre><code>form_remote_tag </code></pre> <p>when clicked, "Teh Foobar" fails to alert, and functions as a link.</p> <p>What is happening, and how do I get around it?</p>
<p>We've used <a href="http://www.openssl.org/" rel="noreferrer">OpenSSL</a> with good success. Portable, standards compliant and easy to use.</p>
<p><a href="http://www.gnupg.org/related_software/gpgme/index.en.html" rel="nofollow noreferrer">GPGme</a>. Simple to use and compatible with the <a href="http://www.ietf.org/rfc/rfc4880.txt" rel="nofollow noreferrer">OpenPGP format</a></p>
21,823
<p>Does anyone know of a library or set of classes for splines - specifically b-splines and NURBS (optional). </p> <p>A fast, efficient b-spline library would be so useful for me at the moment.</p>
<p>1.) For B Splines - You should check Numerical Recipes in C (there is book for that and it is also available online for reference)</p> <p>2.) Also check: <a href="http://sourceforge.net/projects/einspline/" rel="noreferrer">sourceforge.net/projects/einspline/</a> &amp; <a href="http://www.gnu.org/software/gsl/manual/html_node/Basis-Splines.html" rel="noreferrer">this</a></p> <p>-AD</p>
<p><a href="https://github.com/SINTEF-Geometry/SISL" rel="nofollow">SISL</a> seems to be a good NURBS library (under the AGPL licence). It is part of <a href="http://www.sintef.no/Geometry-Toolkits" rel="nofollow">GoTools</a> which can be cloned <a href="https://github.com/SINTEF-Geometry/GoTools" rel="nofollow">here</a>.</p>
42,399
<p>I have a SOAP client in Ruby that I'm trying to get working with a Ruby SOAP server, to no avail. The client works fine over SSL with a Python SOAP server, but not with the Ruby version. Here's what the server looks like:</p> <pre><code>require 'soap/rpc/standaloneServer' require 'soap/rpc/driver' require 'rubygems' require 'httpclient' def cert(filename) OpenSSL::X509::Certificate.new(File.open("path to cert.cert") { |f| f.read }) end def key(filename) OpenSSL::PKey::RSA.new(File.open("path to rsaprivate.key") { |f| f.read }) end class Server &lt; SOAP::RPC::HTTPServer ~code snipped for readability~ end server = Server.new(:BindAddress =&gt; HelperFunctions.local_ip, :Port =&gt; 1234, :SSLCertificate =&gt; cert("path to cert"), :SSLPrivateKey =&gt; key("path to rsa private key")) new_thread = Thread.new { server.start } </code></pre> <p>I've trimmed some of the code out for readability's sake (e.g., I have some methods in there I expose) and it works fine with SSL off. But when the client tries to connect, it sees this:</p> <pre><code>warning: peer certificate won't be verified in this SSL session /usr/lib/ruby/1.8/net/http.rb:567: warning: using default DH parameters. /usr/lib/ruby/1.8/net/http.rb:586:in `connect': unknown protocol (OpenSSL::SSL::SSLError) </code></pre> <p>I tried taking some advice from <a href="https://stackoverflow.com/questions/128660/how-can-i-make-rubys-soaprpcdriver-work-with-self-signed-certificates">this post</a> and now I see this message:</p> <pre><code>/usr/lib/ruby/1.8/soap/httpconfigloader.rb:64:in `set_ssl_config': SSL not supported (NotImplementedError) </code></pre> <p>Any ideas on how to fix this would be greatly appreciated.</p>
<p>Arg. I was trying to follow along <a href="http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/108292" rel="nofollow noreferrer">this link</a> and it turns out I was missing a simple include statement:</p> <pre><code>require 'webrick/https' </code></pre> <p>That, combined with the help from the link in the original question solves the problem. Hopefully this saves someone else down the line an hour of grief :)</p>
<p>Me too.. and don't forget to put the :SSLEnable => true spend couple of hours figuring that out...</p> <pre><code>server = Server.new(:BindAddress =&gt; HelperFunctions.local_ip, :Port =&gt; 1234, :SSLEnable =&gt; true, :SSLCertificate =&gt; cert("path to cert"), :SSLPrivateKey =&gt; key("path to rsa private key")) </code></pre>
24,346
<p>How can you get a recent release, i.e. 4.2+, of g++/gcc for windows? Mingw's standard g++ is 3.4.5 which is 3 years old, released Nov 2005. Mingw have a 4.2 version but this is only in the Alpha stage. I cannot find a stable recent release of g++ for windows, surely I must be missing something.</p>
<p><a href="http://www.tdragon.net/" rel="nofollow noreferrer">Twilight Dragon Media</a> track and regularly release GCC releases usable for MinGW environments.</p> <p>The current release is based on GCC 4.3.2.</p> <p>The packages can be downloaded <a href="http://www.tdragon.net/recentgcc/" rel="nofollow noreferrer">here</a>. I've started using the 4.3.2-TDM1 release in production after testing it extensively for over two months. The only iffy thing I hit is cross-DLL exceptions in C++, but C++ exceptions have been broken in MinGW for ages and most of our code doesn't use them anyway, or ar least doesn't use them across library boundaries.</p> <p>There's a more recent release available (4.3.2-TDM2, been out for a couple of days). The release notes say it "differs from the first only in two bugs that have been fixed -- one related to temporary files and one related to header paths. A new TDM/MinGW installer has been released concurrently." Haven't tested it yet, though.</p> <p>Edit: 4.3.3-TDM1 appears to be stable so far - haven't come across any errors in pre-production use. After having tested it exensively, I can recommend 4.3.2-TDM2 for production use.</p>
<p>You can get a MinGW distro that uses gcc 4.3.3 <a href="http://nuwen.net/mingw.html" rel="nofollow noreferrer">here</a> - I've played with it but not used it in anger. It comes complete with boost and several other useful libraries</p>
47,509
<p>Is there any way other than using reflection to access the members of a anonymous inner class?</p>
<p>Anonymous inner classes have a type but no name.</p> <p>You can access fields not defined by the named supertype. However once assigned to a named type variable, the interface is lost.</p> <p>Obviously, you can access the fields from within the inner class itself. One way of adding code is through an instance initialiser:</p> <pre><code>final AtomicInteger y = new AtomicInteger(); new Runnable() { int x; { x = 5; doRun(this); y.set(x); } public void run() { ... blah ... } }; </code></pre> <p>The value returned by the anonymous inner class expression has the anonymous type, so you have one chance to use it outside of the class itself:</p> <pre><code>final int y = new Runnable() { int x; { x = 5; doRun(this); } public void run() { ... blah ... } }.x; </code></pre> <p>You can also pass it through a method declared similar to:</p> <pre><code>&lt;T extends Runnable&gt; T doRun(T runnable); </code></pre>
<p>If it implements an interface or extends an existing class, you can access the members defined in the interface or base class.</p>
41,353
<p>I am trying to set a <code>javascript</code> <code>date</code> so that it can be submitted via <code>JSON</code> to a <code>.NET</code> type, but when attempting to do this, <code>jQuery</code> sets the <code>date</code> to a full <code>string</code>, what format does it have to be in to be converted to a <code>.NET</code> type?</p> <pre><code>var regDate = student.RegistrationDate.getMonth() + "/" + student.RegistrationDate.getDate() + "/" + student.RegistrationDate.getFullYear(); j("#student_registrationdate").val(regDate); // value to serialize </code></pre> <p>I am using <code>MonoRail</code> on the server to perform the binding to a <code>.NET</code> type, that aside I need to know what to set the form hidden field value to, to get properly sent to <code>.NET</code> code.</p>
<p><a href="http://support.microsoft.com/kb/320687" rel="nofollow noreferrer" title="KB Article 320687">Microsoft KB Article 320687</a> has a detailed answer to this question.</p> <p>Basically, you override the WndProc method to return HTCAPTION to the WM_NCHITTEST message when the point being tested is in the client area of the form -- which is, in effect, telling Windows to treat the click exactly the same as if it had occured on the caption of the form.</p> <pre><code>private const int WM_NCHITTEST = 0x84; private const int HTCLIENT = 0x1; private const int HTCAPTION = 0x2; protected override void WndProc(ref Message m) { switch(m.Msg) { case WM_NCHITTEST: base.WndProc(ref m); if ((int)m.Result == HTCLIENT) m.Result = (IntPtr)HTCAPTION; return; } base.WndProc(ref m); } </code></pre>
<p>VC++ 2010 Version (of FlySwat's):</p> <pre><code>#include &lt;Windows.h&gt; namespace DragWithoutTitleBar { using namespace System; using namespace System::Windows::Forms; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Data; using namespace System::Drawing; public ref class Form1 : public System::Windows::Forms::Form { public: Form1(void) { InitializeComponent(); } protected: ~Form1() { if (components) { delete components; } } private: System::ComponentModel::Container ^components; HWND hWnd; #pragma region Windows Form Designer generated code void InitializeComponent(void) { this-&gt;SuspendLayout(); this-&gt;AutoScaleDimensions = System::Drawing::SizeF(6, 13); this-&gt;AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this-&gt;ClientSize = System::Drawing::Size(640, 480); this-&gt;FormBorderStyle = System::Windows::Forms::FormBorderStyle::None; this-&gt;Name = L"Form1"; this-&gt;Text = L"Form1"; this-&gt;Load += gcnew EventHandler(this, &amp;Form1::Form1_Load); this-&gt;MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &amp;Form1::Form1_MouseDown); this-&gt;ResumeLayout(false); } #pragma endregion private: System::Void Form1_Load(Object^ sender, EventArgs^ e) { hWnd = static_cast&lt;HWND&gt;(Handle.ToPointer()); } private: System::Void Form1_MouseDown(Object^ sender, System::Windows::Forms::MouseEventArgs^ e) { if (e-&gt;Button == System::Windows::Forms::MouseButtons::Left) { ::ReleaseCapture(); ::SendMessage(hWnd, /*WM_NCLBUTTONDOWN*/ 0xA1, /*HT_CAPTION*/ 0x2, 0); } } }; } </code></pre>
5,008
<p>It's one of those things that seems to have an odd curve where the more I think about it, the more it makes sense. To a certain extent, of course. And then it doesn't make sense to me at all.</p> <p>Care to enlighten me?</p>
<p>Because in most cases you've got to sort your results first. For example, when you search on Google, <a href="http://www.google.com.au/search?hl=en&amp;safe=off&amp;q=google&amp;start=1000&amp;sa=N" rel="noreferrer">you can view only up to 100 pages of results</a>. They don't bother sorting by page-rank beyond 1000 websites for given keyword (or combination of keywords).</p> <p><strong>Pagination is fast. Sorting is slow.</strong></p>
<p>Of course sorting on a random query takes some time, but if you're having problems with the same paginated query being used regulary, there's either something wrong with the database setup (improperly indexing/none at all, too little memory etc. I'm not a db-manager) or you're doing pagination seriously wrong: </p> <p>Terribly wrong: e.g. doing <code>select * from hugetable where somecondition;</code> into an array getting the page count with the array.length pick the relevant indexes and dicard the array - then repeating this for each page... That's what I call seriously wrong. </p> <p>The better solution two queries: one getting just the count then another getting results using <code>limit</code> and <code>offset</code>. (Some proprietary, nonstandard-sql server might have a one query option, I dunno)</p> <p>The bad solution might actually work quite okay in on small tables (in fact it's not unthinkable that it's faster on very small tables, because the overhead of making two queries is bigger than getting all rows in one query. I'm not saying it <em>is</em> so...) but as soon as the database begins to grow the problems become obvious.</p>
4,925
<p>I am trying to write a Windows Form and ASP.NET C# front-end and MSAccess backend for a pretty small database concept I have. </p> <p>I have written this application once before in just MSAccess but I now need the app and database to be in different places. I have now figured out (thanks to a StackOverflow user) that ADO will be a bad choice because it has to have a connection open all of the time. </p> <p>I bought Microsoft ADO.Net 2.0 Step-by-Step and I have read through some of it and understand (I think) the basic concepts at play in ADO.NET. (Datasets and the like)</p> <p>Where I get confused is the actual implementation. What I want to know is do any of you know of a C# project that has a database backend which is open source that I can go look at the code and see how they did it. I find I learn better that way. The book has a CD with code examples that I may turn to, but I would rather see real code in a real app. </p>
<p>If you're targeting modern versions of Windows (Windows 2000) and above, you can use the <a href="https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-updatelayeredwindow" rel="nofollow noreferrer">UpdateLayeredWindow</a> function to display any bitmap (including one with an alpha channel, if so desired).</p> <p>I <a href="https://faithlife.codes/blog/2008/09/displaying_a_splash_screen_with_c_introduction/" rel="nofollow noreferrer">blogged a four-part series</a> on how to write a C++ Win32 app that does this. If you need to wait for exactly ten seconds to close the splash screen (instead of until the main window is ready), you would need to use Dan Cristoloveanu's suggested technique of a timer that calls DestroyWindow.</p>
<p>It's a Win32 api FAQ</p> <p>See professional Win32api forum news://194.177.96.26/comp.os.ms-windows.programmer.win32 where it has been answered hundreds of times for 20 years..</p>
20,262
<p>What i mean exactly is that build.xml that actually included those plugins like findbugs etc. Or nicely done build.xml </p>
<p>A great resource for sample Ant build files is Google code search. <a href="http://code.google.com/search/#q=build.xml" rel="nofollow noreferrer">Search Google Code for build.xml</a>. Once you search, narrow it down to "Project Hosting" to get the real meat. You will find dozens of examples of real, working, usable build.xml files.</p> <p>For example, here's the <a href="http://code.google.com/p/fbug/source/browse/branches/firebug1.3/build.xml" rel="nofollow noreferrer">build file for Firebug</a>, the <a href="http://code.google.com/p/clojure-contrib/source/browse/branches/lazy/build.xml" rel="nofollow noreferrer">build file for the Clojure language</a>, the <a href="http://code.google.com/p/google-web-toolkit/source/browse/trunk/build.xml?spec=svn5418&amp;r=5418" rel="nofollow noreferrer">build file for GWT</a> and the <a href="http://code.google.com/p/google-guice/source/browse/build.xml" rel="nofollow noreferrer">build file for Google Guice</a>.</p> <p>Of course, there are other fine repositories of source code, here is a <a href="https://github.com/search?type=Code&amp;language=XML&amp;q=build.xml&amp;repo=&amp;langOverride=&amp;x=12&amp;y=13&amp;start_value=1" rel="nofollow noreferrer">build.xml file search on GitHub</a>, a <a href="http://www.google.com/search?q=site%3Asourceforge.net+build.xml" rel="nofollow noreferrer">Google search of SourceForge.net for build.xml files</a> and a <a href="http://www.google.com/search?q=site%3Asvn.riaforge.org+build.xml" rel="nofollow noreferrer">Google search of RIAForge.org for build.xml files</a></p> <p>Another good way to find quality build files is a <a href="http://www.google.com/search?q=allinurl%3Abuild.xml" rel="nofollow noreferrer">Google search for build.xml in the URL</a>, which will result with a good variety. Add to that query an aspect or programming language of choice, and you will have what you need in no time.</p>
<p>You could use maven 2, because it has built-in plugin support.And all the stuff like: PMD, Findbugs, Checkstyle etc , could be integrated automatically . If you have some existing code it could be called from maven you could use maven-antrun-plugin. </p>
18,969
<p>I have problems opening a berkeley db in python using bdtables. As bdtables is used by the library I am using to access the database, I need it to work.</p> <p>The problem seems to be that the db environment I am trying to open (I got a copy of the database to open), is version 4.4 while libdb is version 4.6. I get the following error using bsddb.dbtables.bsdTableDB([dbname],[folder]):</p> <pre><code>(-30972, "DB_VERSION_MISMATCH: Database environment version mismatch -- Program version 4.6 doesn't match environment version 4.4") </code></pre> <p>However, bsddb.btopen([dbname]) works.</p> <p>I have also tried installing db4.4-util, db4.5-util and db4.6-util. Trying to use db4.6_verify results in:</p> <pre><code>db4.6_verify: Program version 4.6 doesn't match environment version 4.4 db4.6_verify: DB_ENV-&gt;open: DB_VERSION_MISMATCH: Database environment version mismatchs </code></pre> <p>db4.4_verify results in the computer just hanging, and nothing happening.</p> <p>Finally, if I run db4.4_recover on the database, that works. However, afterwards I get the following error 'No such file or directory' in python.</p>
<p>I think answers should go in the "answer" section rather than as an addendum to the question since that marks the question as having an answer on the various question-list pages. I'll do that for you but, if you also get around to doing it, leave a comment on my answer so I can delete it.</p> <p>Quoting "answer in question":</p> <p>Verifying everything in this question, I eventually solved the problem. The 'No such file or directory' are caused by some __db.XXX files missing. Using</p> <pre><code>bsddb.dbtables.bsdTableDB([dbname],[folder], create=1) </code></pre> <p>after db4.4_recover, these files got created and everything is now working.</p> <p>Still, it was a bit of an obscure problem, and initially hard to figure out. But thanks to the question <a href="https://stackoverflow.com/questions/37644/examining-berkeley-db-files-from-the-cli">Examining Berkeley DB files from the CLI</a>, I got the tools I needed. I'll just post it here if someone ends up with the same problem in the future and end up at stackoverflow.com</p>
<p>Damn, verifying everything in this question I eventually solved the problem. The 'No such file or directory' are caused by some __db.XXX files missing. Using bsddb.dbtables.bsdTableDB([dbname],[folder], create=1) after db4.4_recover, these files got created and everything is now working.</p> <p>Still, it was a bit of an obscure problem, and initially hard to figure out. But thanks to the question Examining Berkeley DB files from the CLI I got the tools I needed. I'll just post it here if someone ends up with the same problem in the future and end up at stackoverflow.com</p>
21,932
<p>I'm a bit surprised I haven't found a good open source library for performing common network tasks. There are a few very good commercial libraries, but they're too expensive to use on an open source project. </p> <p>Anyone know of any?</p>
<p>SSH.NET Library - <a href="https://github.com/sshnet/SSH.NET" rel="nofollow noreferrer">https://github.com/sshnet/SSH.NET</a></p> <p>Inspired by Sharp.SSH, this library is complete rewrite using .NET 4.0, without any third party dependencies and utilizes parallelism as much as possible to allow best performance.</p> <p>It's been a solid C# implementation of client side SSH.</p>
<p>IIRC, FTP is built in to .NET, (System.Net.FtpWebRequest) and last time I looked (a couple of years ago, admittedly) I couldn't find any free SSH / SFTP assemblies. That might have changed, though.</p>
18,487
<p>Is it possible to find the <code>foreach</code> index?</p> <p>in a <code>for</code> loop as follows:</p> <pre><code>for ($i = 0; $i &lt; 10; ++$i) { echo $i . ' '; } </code></pre> <p><code>$i</code> will give you the index.</p> <p>Do I have to use the <code>for</code> loop or is there some way to get the index in the <code>foreach</code> loop?</p>
<pre><code>foreach($array as $key=&gt;$value) { // do stuff } </code></pre> <p><code>$key</code> is the index of each <code>$array</code> element</p>
<pre><code>foreach(array_keys($array) as $key) { // do stuff } </code></pre>
17,042
<p>I'm wondering what is the quickest and most reliable way to forward mail from an IMAP account.</p> <p>My university does not allow our student-mailbox to forward to a private e-mail account (everybody uses either Gmail or Hotmail here). It's a political thing, not technical. We do have IMAP access to the mailbox. I would like to have a service which downloads the mail through IMAP, and forwards. And it would be nice to scale it, so thousands of students can use it. Eventually, I want to build a public signup page, and have it processed automatically from there. </p> <p>So far, I've made a decent PHP script which connects, downloads headers and body parts, and ties it all together. I have two problems with that. </p> <p>1) I'm downloading all kind of parts, and sticking them back together. I hope that every exotic attached file, weird encoded piece of text and every type of header survives this. I'm not even sure I have the complete header.</p> <p>2) The to: e-mail address becomes the private e-mail address, not the original student e-mail address. I think this is lame, and inconvenient in searching and archiving.</p> <p>Is the PHP script the way to go? Is there a trick using a particular linux mail service/daemon? Does IMAP have a 'forward' command, I'm missing? </p>
<p>You might want to look at <A HREF="http://www.fetchmail.info//" rel="nofollow noreferrer">Fetchmail</A>, as this sounds like the problem it was designed to solve. Fetchmail retrieves mail from POP/IMAP/etc servers and forwards it to SMTP/LMTP/etc servers. Fetchmail has the advantage of a few years and lots of users ironing out problems with various IMAP servers.</p>
<p>If using Gmail you can configure GMAIL to pick up mail from other accounts.</p>
8,184
<p>I work on quite a few DotNetNuke sites, and occasionally (I haven't figured out the common factor yet), when I use the Database Publishing Wizard from Microsoft to create scripts for the site I've created on my Dev server, after running the scripts at the host (usually GoDaddy.com), and uploading the site files, I get an error... I'm 99.9% sure that it's not file related, so not sure where to begin in the DB. Unfortunately with DotNetNuke you don't get the YSOD, but a generic error, with no real way to find the actual exception that has occured.</p> <p>I'm just curious if anyone has had similar deployment issues using the Database Publishing Wizard, and if so, how they overcame them? I own the RedGate toolset, but some hosts like GoDaddy don't allow you to direct connect to their servers...</p>
<p>The Database Publishing Wizard's generated scripts usually need to be tweaked since it sometimes gets the order wrong of table/procedure creation when dealing with constraints. What I do is first backup the database, then run the script, and if I get an error, I move that query to the end of the script. Continue restoring the database and running the script until it works.</p>
<p>You should be able to expose the underlying error message by setting the following in the web.config:</p> <pre><code>customErrors mode="Off" </code></pre> <p>Could you elaborate on "and uploading the site files"? New instance of DNN? updating an existing site? upgrading DNN version? If upgrade or update -- what files are you adding/overwriting?</p> <p>Also, when using GoDaddy, can you check to verify that the web site's identity (network service or asp.net machine account depending on your IIS version) has sufficient permissions to the website's file system? It should have modify permissions and these may need to be reapplied if you are overwriting files.</p> <ul> <li>IIS6 (XP, Server 2000, 2003) = ASP.Net Machine Account</li> <li>IIS7 (Vista, Server 2008) = Network Service</li> </ul>
3,560
<p>That is a problem I'm facing right now. I need to specify the hardware that will run my piece of software. The thing is: the project isn't finished yet, and I need it running in "real" conditions before I can go on, conditions which I cannot reproduce at home; what I can test at home barely scratches them. We don't have much money to spend (it's a research at college). Feels like a catch-22.</p> <p>How can one get a good approximation of what setup is needed without having the means to simulate accurate work conditions?</p>
<p>If you need to test your setup on a machine with less specifications then your own machine then you could use a virtual pc setup to test it and just keep reducing the virtual pc settings until your software stops performing adequately.</p> <p>If its the other way around, then I think, as Paul said, its a case of begging or borrowing until you get what you need.</p>
<p>Can't you beg, borrow or steal the biggest hardware you can get, and then once it's in those "real" conditions, start reducing the capacity either by hardware changes (removing memory, underclocking) or by software (running other programs that consume memory or CPU cycles) until you find a point where it doesn't work as well as desired, and then specify a minimum hardware level that will meet or exceed those conditions?</p>
20,616
<p>I am following a VB tutorial to do some <a href="http://blogs.msdn.com/bethmassi/archive/2008/04/25/querying-html-with-linq-to-xml.aspx" rel="nofollow noreferrer">HTML manipulation using LINQ</a> </p> <p>It has the following construct</p> <pre><code>Imports &lt;xmlns="http://www.w3.org/1999/xhtml"&gt; </code></pre> <p>How do I do the same in C#?</p> <p>There appears to be something called an XMLNamespaceManager that may hold the solution, but I am too foolish to understand how to work it, and I am not sure it is the correct tree to bark up.</p> <p>Got any advice?</p>
<p>VB.Net has a feature called <code>XML Literals</code> that is not present in C#. This import statement adds a namespace for use with those literals.</p> <p>In researching this information, I found this link helpful:<br> <a href="http://blogs.msdn.com/bethmassi/archive/2007/10/30/quickly-import-and-export-excel-data-with-linq-to-xml.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/bethmassi/archive/2007/10/30/quickly-import-and-export-excel-data-with-linq-to-xml.aspx</a><br> It's also very informative for working with Excel xml docs, but that's a side issue ;)</p>
<p>I think the example you're looking at may be using XML literals, which are not supported in C#.</p>
39,388
<p>I need to do a date comparison in Mysql without taking into account the time component i.e. i need to convert '2008-11-05 14:30:00' to '2008-11-05'</p> <p>Currently i am doing this:</p> <pre><code>SELECT from_days(to_days(my_date)) </code></pre> <p>Is there a proper way of doing this?</p>
<p>Yes, use the <a href="http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_date" rel="noreferrer">date</a> function:</p> <pre><code>SELECT date(my_date) </code></pre>
<p>You could use <code>ToShortDateString();</code></p>
33,581
<p>I'm writing a helper method for ASP.NET MVC and I need to call <code>Url.Content</code> to get an appropriate URL for the context. However, in order to create a new <code>UrlHelper()</code> I need to get the current <code>RequestContext</code> (<code>System.Web.Routing.RequestContext</code> to be precise) and I'm not sure how to grab it. Anyone know?</p>
<p>If the current IHttpHandler is MvcHandler, you can use</p> <pre><code>((MvcHandler)HttpContext.Current.Handler).RequestContext </code></pre>
<p>Don't create a new one. Just extend the existing UrlHelper, just like you'd extend HtmlHelper:</p> <pre><code>public static string IdLink(this UrlHelper helper, Guid id) { //... </code></pre> <p>If you must use both HtmlHelper and UrlHelper, pass one of them as a regular (non-"this") argument.</p>
45,709
<p>The following code produces an error hr=0x80020005 (wrong type).</p> <pre><code>#import &lt;msi.dll&gt; using namespace WindowsInstaller; main() { ::CoInitialize(NULL); InstallerPtr pInstaller("WindowsInstaller.Installer"); DatabasePtr pDB = pInstaller-&gt;OpenDatabase( "c:\\foo\\bar.msi", msiOpenDatabaseModeTransact); } </code></pre> <p>I think the reason is that behind the scene, there is MsiOpenDatabase(), which take a LPCTSTR as second argument. This second argument can be MSIDBOPEN_TRANSACT whose definition is</p> <pre><code>#define MSIDBOPEN_TRANSACT (LPCTSTR)1 </code></pre> <p>I do not know if it is possible to give a variant with the good inner type as second argument. The <code>_variant_t</code> constructor does many checks, so I can't disguise an int into a char* so easily.</p> <p>Has anyone tried to use this method in C++?</p> <p><strong>Edit:</strong></p> <p>My version of msi.dll is 3.1.4000.2805, my system is XP SP 2, and the code is supposed to run on any machine with XP or Vista.</p> <p>urls to MSDN articles are welcome.</p> <p>On the same machine, the call to the low-level equivalent:</p> <pre><code>MsiOpenDatabase("c:\\foo\\bar.msi", MSIDBOPEN_TRANSACT); </code></pre> <p>works perfectly.</p>
<p>I finally got the answer on <a href="http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/225c2a86-aa2e-4eab-b2be-0897c695eb7f/?ppud=4&amp;ffpr=0" rel="nofollow noreferrer">msdn forums</a></p> <pre><code>DatabasePtr pDB = pInstaller-&gt;OpenDatabase( "c:\\foo\\bar.msi", (long)msiOpenDatabaseModeTransact); </code></pre>
<p>MSDN says <a href="http://msdn.microsoft.com/en-us/library/aa370338(VS.85).aspx" rel="nofollow noreferrer">OpenDatabase</a> is available from MSI version 4.0 onwards, <a href="http://msdn.microsoft.com/en-us/library/bb736312(VS.85).aspx" rel="nofollow noreferrer">transactions</a> in general from MSI 4.5 onwards. Just a hunch, but could it be that your MSI is outdated? I once had some mysterious trouble with an outdated MSI version.</p>
42,190
<p>I'm looking for a c# snippet which I can insert in a Windows service. The code must empty the recycle bin for all users on the computer.</p> <p>I have previously tried using <code>SHEmptyRecycleBin</code> (ref <a href="http://www.codeproject.com/KB/cs/Empty_Recycle_Bin.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cs/Empty_Recycle_Bin.aspx</a>) however the code doesn't work when ran from a windows service as the service is running with local system privileges.</p>
<p>I think doing something like this is against Microsoft recommended practices. What are you trying to do that requires emptying the Recycle Bin from a Windows service?</p>
<p>First, have you tried running the service on an interactive user account? Maybe SHEmptyRecycleBin requires an interactive user even though it doesn't necessarily display a Window.</p> <p>Second, I'm not sure it's a good idea to delete other users' stuff but I guess you have a very good reason?</p>
3,009
<p>I currently have a cluster of 4 Apache web servers which are used to serve up static files of up to 30Mb in size. Generally, I can expect up to 5000 concurrent connections to these servers. What performance improvement would I expect to get by moving this to lighttpd?</p>
<p>I would expect it to handle the concurrency with much more ease and less memory overhead. I've stopped deploying Apache pretty much everywhere I can.</p> <p>You may also consider nginx for a comparison.</p>
<p>From the top of my head:</p> <ol> <li>Smaller memory footprint</li> <li>Quicker file reads</li> </ol> <p>Definitely check out the benchmark at their site, they provide a lot of information on this topic: <a href="http://www.lighttpd.net/benchmark" rel="nofollow">http://www.lighttpd.net/benchmark</a></p>
42,509
<p>I'm struggling to get around the 404 errors from asp.net mvc beta when deploying on IIS 6. I had this working in one of the previews by mapping .mvc in IIS but this no longer works. I've read <a href="http://msmvps.com/blogs/omar/archive/2008/06/30/deploy-asp-net-mvc-on-iis-6-solve-404-compression-and-performance-problems.aspx" rel="nofollow noreferrer">Omar's post</a> and several others on the web and tried their solutions but no luck so far.</p> <p>The home page opens without a problem on IIS 6 but others 404 and the site runs well on IIS 7.</p> <p>Has anybody deployed asp.net mvc beta to IIS 6 with success? If so, what adjustments did you need to make to the code and/or IIS settings to get it to work?</p>
<p>I found a solution to my problem from <a href="http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/" rel="nofollow noreferrer">Steve Sanderson's blog</a> (Thanks Steve):</p> <p>Use a wildcard mapping for <code>aspnet_isapi.dll</code>. This tells IIS 6 to process all requests using ASP.NET, so routing is always invoked, and there’s no problem. It’s dead easy to set up: </p> <ul> <li>open IIS manager (run -> inetmgr -> OK)</li> <li>right-click your app, go to Properties</li> <li>then Home Directory tab, then click Configuration.</li> <li>Under Wildcard application maps, click Insert (not Add, which is confusingly just above)</li> <li>then enter C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll for “Executable”, and uncheck Verify that file exists.</li> </ul>
<p>Url rewriting can help you to solve the problem. I've implemented solution allowing to deploy MVC application at any IIS version even when virtual hosting is used. <a href="http://www.codeproject.com/KB/aspnet/iis-aspnet-url-rewriting.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/aspnet/iis-aspnet-url-rewriting.aspx</a></p>
29,703
<p>If I have two objects, one being the list of items, and the other having a property storing the selected item of the other list, is it possible to update the selected item through binding in WPF?</p> <p>Lets say I have these two data structures:</p> <pre><code>public class MyDataList { public ObservableCollection&lt;Guid&gt; Data { get; set; } } public class MyDataStructure { public Guid ChosenItem { get; set; } } </code></pre> <p>Is it possible to bind a Listbox to an instance of both objects so that the ChosenItem property gets set by the selected item of the ListBox?</p> <p>EDIT: To make things a bit clearer, there might be many instances of MyDataStructure, each with a chosen item from MyDataList. The data list is common to all the instances, and I need a way to select an item and store that selection in the MyDataStructure.</p>
<p>I believe you should be able to do this (make sure to declare the local namespace):</p> <pre><code>&lt;Window.Resources&gt; &lt;local:MyDataStructure x:Key="mds1" /&gt; &lt;/Window.Resources&gt; &lt;ListBox ItemsSource="{Binding Data}" SelectedValue="{Binding Source={StaticResource mds1} Path=ChosenItem}"/&gt; </code></pre>
<p>Make this two properties inside a single class(Just to simplify the solution) and make the code ready for property changed events</p> <pre><code> public class MyDataList : INotifyPropertyChanged { private Guid _choosen; public ObservableCollection&lt;Guid&gt; Data { get; set; } public Guid ChosenItem { get { return _choosen; } set { _choosen = value; PropertyChanged(this, new PropertyChangedEventArgs("ChosenItem")); } } public event PropertyChangedEventHandler PropertyChanged; } </code></pre> <p>create an instance of this class and Bind to the DataContext of the ListBox Now write the ListBox XAML code as bellow. SelectedValue binding is doing the trick here.</p> <pre><code>&lt;ListBox ItemsSource="{Binding Data}" SelectedValue="{Binding Path=ChosenItem}" x:Name="listBox"/&gt; </code></pre>
46,253
<p>I am hoping to find a resource for lining up input elements in a HTML page. I find it difficult to get a select element and a text box to be the same width even when using the width style attribute, and it is even more difficult across browsers. Finally, file inputs seem impossible to get to the same width cross browser. Are there any good guides or tips for accomplishing this? Perhaps there are some default CSS attributes I should be setting.</p>
<p>I tested this out in Internet Explorer 7, Firefox 3 and Safari/Google Chrome. I definitely see the problem with <code>&lt;select&gt;</code> and <code>&lt;input type="file"&gt;</code>. My findings showed that if you styled all the inputs at the same width, the <code>&lt;select&gt;</code> would be about 5 pixels shorter in all browsers.</p> <p>Using the <a href="http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/" rel="nofollow noreferrer">Eric Meyer CSS reset script</a> does not help this issue, however if you simply make your <code>&lt;select&gt;</code> inputs 5 pixels wider you'll get very good (albeit not perfect) alignment in the major browsers. The only one that differs is Safari/Google Chrome, and it appears to be 1 or 2 pixels wider than all the other browsers.</p> <p>As far as the <code>&lt;input type="file"&gt;</code> is concerned, you don't have much flexibility with styling there. If JavaScript is an option for you, you can implement the method <a href="http://www.quirksmode.org/dom/inputfile.html" rel="nofollow noreferrer">shown on quirksmode</a> to achieve greater control over the styling of the file upload control.</p> <p>See my full working example below in XHTML 1.0 Strict for a typical form with consistent input widths. Note that this does not use the 100% width trick pointed out by others here because it has the same problem with inconsistent widths. Additionally there are no tables used to render the form as tables should only be used for tabular data and not layout.</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-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;title&gt;Example Form&lt;/title&gt; &lt;style type="text/css"&gt; label, input, select, textarea { display: block; width: 200px; float: left; margin-bottom: 1em; } select { width: 205px; } label { text-align: right; width: 100px; padding-right: 2em; } .clear { clear: both; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="#"&gt; &lt;fieldset&gt; &lt;legend&gt;User Profile&lt;/legend&gt; &lt;label for="fname"&gt;First Name&lt;/label&gt; &lt;input id="fname" name="fname" type="text" /&gt; &lt;br class="clear" /&gt; &lt;label for="lname"&gt;Last Name&lt;/label&gt; &lt;input id="lname" name="lname" type="text" /&gt; &lt;br class="clear" /&gt; &lt;label for="fav_lang"&gt;Favorite Language&lt;/label&gt; &lt;select id="fav_lang" name="fav_lang"&gt; &lt;option value="c#"&gt;C#&lt;/option&gt; &lt;option value="java"&gt;Java&lt;/option&gt; &lt;option value="ruby"&gt;Ruby&lt;/option&gt; &lt;option value="python"&gt;Python&lt;/option&gt; &lt;option value="perl"&gt;Perl&lt;/option&gt; &lt;/select&gt; &lt;br class="clear" /&gt; &lt;label for="bio"&gt;Biography&lt;/label&gt; &lt;textarea id="bio" name="bio" cols="14" rows="4"&gt;&lt;/textarea&gt; &lt;br class="clear" /&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
<p>Do you start your CSS files with some base settings? It may be useful to turn padding and margin off on all elements. I haven't tested to see if this could be affecting select / input elements.</p> <p>Here's an example CSS Reset from Eric Meyer:</p> <p><a href="http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/" rel="nofollow noreferrer">http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/</a></p>
21,794
<p>There are two popular naming conventions:</p> <ol> <li>vc90/win64/debug/foo.dll</li> <li>foo-vc90-win64-debug.dll</li> </ol> <p>Please discuss the problems/benefits associated with either approach.</p> <p>I am also wondering if it is possible to expose meta-data (i.e. compiler, platform, build-type) in approach #1 in an easy to use, cross-platform manner.</p>
<p>#2 is good for distribution, where several variation will be packaged in the same folder/zip file together. However, you probably don't want all that information in the file name itself, as it make it difficult to vary those via parameters to your makefile/csproj/nant script etc. It would be easier to have several files called "foo" in different folders (where you can decide the folder structure)</p>
<p>For .NET assemblies, you can store this information in the assembly itself:</p> <p><a href="http://www.codinghorror.com/blog/archives/000142.html" rel="nofollow noreferrer">http://www.codinghorror.com/blog/archives/000142.html</a></p> <p>I'm not familiar enough with other assembly types to know what they provide.</p>
12,231
<p>I'm currently in the process of setting up a continuous integration environment at work. We are using VisualSVN Server and CrusieControl.NET. Occasionally a build will fail and a symptom is that there are conflicts in the CruiseControl.NET working copy. I believe this is due to the way I've setup the Visual Studio solutions. Hopefully the more projects we run in this environment the better our understanding of how to set them up will be so I'm not questioning why the conflicts happen at this stage. To fix the builds I delete the working copy and force a new build - this works every time (currently). So my questions are: is deleting the working copy a valid part of a continuous integration build process, and how do I go about it?</p> <p>I've tried solutions including MSTask and calling delete from the command line but I'm not having any luck.</p> <p>Sorry for being so wordy - good job this is a beta :)</p>
<p>Doing a full delete before or after your build is good practice. This means that there is no chance of your build environment picking up an out of date file. Your building exactly against what is in the repository.</p> <p>Deleting the working copy is possible as I have done it with Nant. </p> <p>In Nant I would have a clean script in its own folder outwith the one I want to delete and would then invoke it from CC.net. </p> <p>I assume this should also be possible with a batch file. Take a look at the rmdir command <a href="http://www.computerhope.com/rmdirhlp.htm" rel="noreferrer">http://www.computerhope.com/rmdirhlp.htm</a></p> <p>@pauldoo</p> <p>I prefer my CI server to do a full delete as I don't want any surprise when I go to do a release build, which should always be done from a clean state. But it should be able to handle both, no reason why not</p>
<p>It is very common and generally a good practice for any build process to do a 'clean' before doing any significant build. This prevents any 'artifacts' from previous builds to taint the output.</p> <p>A clean is essentially what you are doing by deleting the working copy.</p>
2,959
<p>At work we recently upgraded from Microsoft SQL Server 7 to SQL 2005. The database engine is a lot more advanced, but the management studio is pretty awful in a number of ways. Most of our developers decided they preferred to stick with the old Query Analyzer tool, even though it had a lot of limitations.</p> <p>In my spare time, I decided to write a replacement for Query Analyzer / Management Studio that did the things our developers most needed to do. I finally got permission to release it for free: Versabanq Squel (versabanq.com/squel).</p> <p>Like I said, it's free, so this isn't a sales pitch. But it got me thinking. What I'm wondering is: are most of you satisfied with SQL Studio the way it is? Do people just use it because it's what Microsoft pushes on them? Are there many people out there looking for something better? Maybe I can get some support for long-term development of this, if it looks like there might be some wider interest.</p> <p>By the way, check out <a href="https://stackoverflow.com/questions/5170/sql-server-management-studio-alternatives">SQL Server Management Studio Alternatives</a>, someone else's earlier question on this topic. What I see there is that there are surprisingly few options. Why do you think that is?</p>
<p>While I would love something better, it would have to be significantly better and free. SMS is definetly a hog but I've gotten used to it. What I miss the most is Query Analyzer. I don't mind using SSMS to manage the server but having a fast lightweight, editor for SQL queries would be awsome...</p> <p>Did I mention free? Not something I'm willing to pay for right now. </p> <h1>EDIT</h1> <p>FYI I downloaded your tool looks neat but you need to add support for Windows Authentications unless I am just missing how its done. </p>
<p>I, for one, would definitely like something other than Management Studio. Is it just me, or do other people feel that it is <em>wayyyyy</em> slower than SQL Server 2000's Enterprise Manager? More features or not, I need something that can get the job done quickly.</p>
47,584
<p>I'd like to make status icons for a C# WinForms TreeList control. The statuses are combinations of other statuses (eg. a user node might be inactive or banned or inactive and banned), and the status icon is comprised of non-overlapping, smaller glyphs. </p> <p>I'd really like to avoid having to hand-generate all the possibly permutations of status icons if I can avoid it. </p> <p>Is it possible to create an image list (or just a bunch of bitmap resources or something) that I can use to generate the ImageList programmatically?</p> <p>I'm poking around the System.Drawing classes and nothing's jumping out at me. Also, I'm stuck with .Net 2.0.</p>
<pre><code>Bitmap image1 = ... Bitmap image2 = ... Bitmap combined = new Bitmap(image1.Width, image1.Height); using (Graphics g = Graphics.FromImage(combined)) { g.DrawImage(image1, new Point(0, 0)); g.DrawImage(image2, new Point(0, 0); } imageList.Add(combined); </code></pre>
<p>Just use Images.Add from the ImageList to add in the individual images. So, something like:</p> <pre><code> Image img = Image.FromStream( /*get stream from resources*/ ); ImageList1.Images.Add( img ); </code></pre>
12,239
<p>We are building a multi-tenant website in ASP.NET, and we must let each customer configure their own security model. They must be able to define their own roles, and put users in those roles. What is the best way to do this?</p> <p>There are tons of simple examples of page_load events that have code like:</p> <pre><code> if (!user.InGroup("Admin") Response.Redirect("/NoAccess.aspx"); </code></pre> <p>But that hard codes the groups and permissions in the code. How can I make it user configurable?</p>
<p>Perhaps put the configurable roles in a DB table, where you store the roles and tenant, and then the PagePermissions in another table, for example:</p> <pre><code>Table "Role" RoleId, TenantId, Role Table "PagePermissions" PageId, RoleId Table "UserRoles" UserId, RoleId </code></pre> <p>Then in the page load check whether the User is in a RoleId that has permissions for that page, for example:</p> <pre><code>Select PageId FROM UserRoles UR INNER JOIN PagePermissions PP ON UR.RoleId = PP.RoleID WHERE UR.Userid = @UserId AND PP.PageID = @PageId </code></pre> <p>If there are no rows returned then deny the user.</p>
<p>I would create a configuration system for the website that is easily managed in config-files. Where you could get typed members and use like this.</p> <pre><code>foreach(var group in ThisPageConfiguration.AcceptedRoleNames) if (user.IsInRole(group)) ... </code></pre> <p>Each customer could then configure their site in their configuration files... And every other type of things you'd want to configure.</p>
21,472
<p>I'm using the build-helper-maven-plugin to add it to my build, but I'd like to see the XREF source for this extra source directory as well.</p> <p>FYI:</p> <p><a href="http://maven.apache.org/plugins/maven-jxr-plugin/index.html" rel="nofollow noreferrer">maven-jxr-plugin</a> - The JXR plugin produces a cross-reference of the project's sources. The generated reports make it easier for the user to reference or find specific lines of code. It is also handy when used with the PMD plugin for referencing errors found in the code.</p> <p><a href="http://mojo.codehaus.org/build-helper-maven-plugin/index.html" rel="nofollow noreferrer">build-helper-maven-plugin</a> - This plugin contains various small independent goals to assist with Maven build lifecycle.</p>
<p>Rather than exposing your DAO beans directly, you should create some Spring MVC controller beans, and call those from the client-side (using AJAX). Ideally, the controllers should not call the DAOs directly, but should instead call service beans (and the service beans should call the DAOs). One advantage of this approach is that you can define your service methods to be transactional, i.e. whenever a service method begins a transaction is started, and whenever a service method returns (without an exception) the transaction is committed. If the boundaries of your transactions are your DAO methods then it is not possible to wrap several database calls in a single transaction.</p> <p>Of course there's no reason why you need to use Spring MVC - any web framework would suffice.</p>
<p>You have to expose your DAO's or beans by means of http. Typically you create a layer above the DAO layer to expose your services through HTTP, which are available to any AJAX framework such as jQuery. What jQuery and other frameworks ends up doing is using a special asynchronous request called XMLHttpRequest and then parse the server response (can be anything, pure HTML, JSON, XML, etc) and process it.</p> <p>Here's a link I found that shows Spring &amp; DWR with AJAX: <a href="http://bram.jteam.nl/index.php/2007/01/31/spring-dwr-ajax-made-easy/" rel="nofollow noreferrer">Bram Smeets Blog</a>.</p>
22,842
<p>I know about code-behind files, but what is the best real-world way of Designers that are using DreamWeaver or other Design Tools to work with Visual Studio programmers? </p> <p>For example, say you have a basic website with user interface forms hitting the database... the database work is definitely done by the developer but how to tie the designed forms with the database coding or client-side logic that may involve events on controls, or other GUI related tie-ins. Are the graphic designers also controlling application flow? There seems to be a large disconnect that needs addressed - especially when it comes time to tweak the design after it's been implemented.</p>
<p>Use another approach like <a href="http://en.wikipedia.org/wiki/Model-view-controller" rel="nofollow noreferrer">MVC</a>, separate your design from your logic. Like this every member (designer / developer) of the team can focus on what they do best.</p> <p>MVC implementations: <a href="http://www.asp.net/mvc/" rel="nofollow noreferrer">link</a> / <a href="http://www.castleproject.org/monorail/index.html" rel="nofollow noreferrer">link</a></p>
<p>Unfortunately this is an all too common problem. Dreamweaver typically doesn't write html that is friendly to a .net developer. If at all possible, get someone who can actually read, and write HTML,not just use the Dreamweaver WYSIWYG editor. </p> <p>I often found that if I'm working with a designer that doesn't know html, that I actually save a lot of time be just having them mock up everything in photoshop, then give me sliced up images. I find that my writing the actual HTML in a .net friendly format saves a ton of time, instead of having to go back and forth with the designer in this situation.</p>
36,854
<p>Are the any task tracking systems with command-line interface? </p> <p>Here is a list of features I'm interested in:</p> <ul> <li>Simple task template<br> Something like plain-text file with property:type pairs, for example:</li> </ul> <blockquote> <pre><code>description:string some-property:integer required </code></pre> </blockquote> <ul> <li>command line interface<br> for example: </li> </ul> <blockquote> <pre><code>// Creates task &lt;task tracker&gt;.exe -create {description: "Foo", some-property: 1} // Search for tasks with description field starting from F &lt;task tracker&gt;.exe -find { description: "F*" } </code></pre> </blockquote> <ul> <li><p>XCopy deployment<br> It should not require to install heavy DBMS</p></li> <li><p>Multiple users support<br> So it's not just a to-do list for a single person</p></li> </ul>
<blockquote> <p>Ditz is a simple, light-weight distributed issue tracker designed to work with distributed version control systems like darcs and git.</p> </blockquote> <p>Ditz: <a href="http://web.archive.org/web/20121212202849/http://gitorious.org/ditz" rel="nofollow noreferrer">http://web.archive.org/web/20121212202849/http://gitorious.org/ditz</a> </p> <p>Also cloned here: <a href="https://github.com/jashmenn/ditz" rel="nofollow noreferrer">https://github.com/jashmenn/ditz</a></p>
<p>Fogbugz has a <a href="http://support.fogcreek.com/default.asp?W840" rel="nofollow noreferrer">Command Line Client</a>.</p>
10,744
<p>I want to catch the NavigationService.Navigating event from my Page, to prevent the user from navigating forward. I have an event handler defined thusly:</p> <pre><code>void PreventForwardNavigation(object sender, NavigatingCancelEventArgs e) { if (e.NavigationMode == NavigationMode.Forward) { e.Cancel = true; } } </code></pre> <p>... and that works fine. However, I am unsure exactly where to place this code:</p> <pre><code>NavigationService.Navigating += PreventForwardNavigation; </code></pre> <p>If I place it in the constructor of the page, or the Initialized event handler, then NavigationService is still null and I get a NullReferenceException. However, if I place it in the Loaded event handler for the Page, then it is called every time the page is navigated to. If I understand right, that means I'm handling the same event multiple times. </p> <p>Am I ok to add the same handler to the event multiple times (as would happen were I to use the page's Loaded event to hook it up)? If not, is there some place in between Initialized and Loaded where I can do this wiring?</p>
<p>Create your own function to execute an OS command through the <a href="http://www.computerhope.com/shutdown.htm" rel="nofollow noreferrer">command line</a>?</p> <p>For the sake of an example. But know where and why you'd want to use this as others note.</p> <pre><code>public static void main(String arg[]) throws IOException{ Runtime runtime = Runtime.getRuntime(); Process proc = runtime.exec(&quot;shutdown -s -t 0&quot;); System.exit(0); } </code></pre>
<p>On Windows Embedded by default there is no shutdown command in cmd. In such case you need add this command manually or use function ExitWindowsEx from win32 (user32.lib) by using JNA (if you want more Java) or JNI (if easier for you will be to set priviliges in C code).</p>
4,523
<p>Can I determine from an ASP.NET application the transfer rate, i.e. how many KB per second are transferd?</p>
<p>You can set some performance counters on ASP.NET.</p> <p>See <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/852720c8-7589-49c3-a9d1-73fdfc9126f0.mspx?mfr=true" rel="nofollow noreferrer">here</a> for some examples.</p> <p>Some specific ones that may help you figure out what you want are:</p> <p><strong>Request Bytes Out Total</strong></p> <p>The total size, in bytes, of responses sent to a client. This does not include standard HTTP response headers.</p> <p><strong>Requests/Sec</strong></p> <p>The number of requests executed per second. This represents the current throughput of the application. Under constant load, this number should remain within a certain range, barring other server work (such as garbage collection, cache cleanup thread, external server tools, and so on).</p> <p><strong>Requests Total</strong></p> <p>The total number of requests since the service was started.</p>
<p>There are a number of debugging tools you can use to check this at the browser. It will of course vary by page, cache settings, server load, network connection speed, etc.</p> <p>Check out <a href="http://www.fiddlertool.com/fiddler/" rel="nofollow noreferrer">http://www.fiddlertool.com/fiddler/</a></p> <p>Or if you are using Firefox, the FireBug add-in <a href="http://addons.mozilla.org/en-US/firefox/addon/1843" rel="nofollow noreferrer">http://addons.mozilla.org/en-US/firefox/addon/1843</a></p>
12,774
<p>I have lots of mp3s on my site that I want my friends to be able to play only- but I don't want them all downloading as soon as the page opens and would prefer them to only start downloading into the buffer if someone wants to play it- is this possible with the embed tag? I can't seem to find anything on Google so I am wondering if it's something I'll have to do in JavaScript or think of an HTML work around.</p> <p>cheers</p>
<p>You can use javascript to construct the embeds and insert them into the DOM when a user clicks a button or something similar.</p>
<p>You will want to use the Object tag vs. the Embed tag for one, but that said, don't set the auto-play option and they won't load until requested.</p>
29,049
<p>I'm in the middle of building a pretty big site using asp.net (forms if it's of any interest), and I'm wondering if i need a logging framework such as log4net. I've used such frameworks before, but i don't see how i could put it to any use in this type of project. usually i think logging is needed for customer delivered application, where the log could be sent back and then analyzed for errors. what do you think?</p>
<p>Heck no - logging is <em>incredibly</em> important for web applications. If you log appropriately, it makes troubleshooting <em>so</em> much easier.</p> <p>Log4Net is probably a good bet as a framework. You might also want a way of gathering logs together from multiple servers - and even if you don't use more than one server at the moment, it's probably worth suggesting that you will do so at some point.</p> <p>One option for the centralisation is to copy the logs into a database - see <a href="https://stackoverflow.com/questions/290304">this question</a> for more opinions on that front.</p>
<p>I would certainly vouch for enterprise information sink (I think this is the right name, it's a Microsoft api for logging), or Enterprise Library.</p> <p>I use the latter for all sorts of things such as caching, logging, etc, and it is a very powerful and time saving tool. I also use health monitoring. This is for a large web application that I am building.</p> <p>You are spoilt for choice when it comes to logging in .NET, and the above two suggestions are great.</p>
42,433
<p>I want to copy text files and only text files from <code>src/</code> to <code>dst/</code></p> <pre> groovy:000> "cp src/*.txt dst/".execute().text ===> groovy:000> </pre> <p>You can see the command executes w/out error but the file <code>src/test.txt</code> does not get copied to <code>dst/</code></p> <p>This also fails: </p> <pre> groovy:000> "cp src/* dst/".execute().text ===> groovy:000> </pre> <p>However...</p> <pre> "cp src/this.txt dst/".execute().text </pre> <p>works</p> <p>Also,</p> <pre> "cp -R src/ dst".execute().text </pre> <p>works</p> <p>Why dose the wild card seem to cause my command to silently fail?</p>
<p>Wildcard expansion is performed by the shell, not by cp (or groovy). Your first example is trying to copy a file named *. You could make your command "sh -c 'cp ...'"</p>
<p>Wildcard expansion is performed by the shell, not by cp (or groovy). Your first example is trying to copy a file named *. You could make your command "sh -c 'cp ...'"</p>
22,162
<p>The following simple "calculator expression" grammar (BNF) can be easily parsed with the a trivial recursive-descent parser, which is predictive LL(1):</p> <pre><code>&lt;expr&gt; := &lt;term&gt; + &lt;term&gt; | &lt;term&gt; - &lt;term&gt; | &lt;term&gt; &lt;term&gt; := &lt;factor&gt; * &lt;factor&gt; &lt;factor&gt; / &lt;factor&gt; &lt;factor&gt; &lt;factor&gt; := &lt;number&gt; | &lt;id&gt; | ( &lt;expr&gt; ) &lt;number&gt; := \d+ &lt;id&gt; := [a-zA-Z_]\w+ </code></pre> <p>Because it is always enough to see the next token in order to know the rule to pick. However, suppose that I add the following rule:</p> <pre><code>&lt;command&gt; := &lt;expr&gt; | &lt;id&gt; = &lt;expr&gt; </code></pre> <p>For the purpose of interacting with the calculator on the command line, with variables, like this:</p> <pre><code>calc&gt; 5+5 =&gt; 10 calc&gt; x = 8 calc&gt; 6 * x + 1 =&gt; 49 </code></pre> <p>Is it true that I can not use a simple LL(1) predictive parser to parse <code>&lt;command&gt;</code> rules ? I tried to write the parser for it, but it seems that I need to know more tokens forward. Is the solution to use backtracking, or can I just implement LL(2) and always look two tokens forward ?</p> <p>How to RD parser generators handle this problem (ANTLR, for instance)?</p>
<p>THe problem with </p> <pre><code>&lt;command&gt; := &lt;expr&gt; | &lt;id&gt; = &lt;expr&gt; </code></pre> <p>is that when you "see" <code>&lt;id&gt;</code> you can't tell if it's the beginning of an assignement (second rule) or it's a "<code>&lt;factor&gt;</code>". You will only know when you'll read the next token.</p> <p>AFAIK ANTLR is LL(*) (and is also able to generate rat-pack parsers if I'm not mistaken) so it will probably handle this grammare considering two tokens at once.</p> <p>If you can play with the grammar I would suggest to either add a keyword for the assignment (e.g. <code>let x = 8</code>) :</p> <pre><code>&lt;command&gt; := &lt;expr&gt; | "let" &lt;id&gt; "=" &lt;expr&gt; </code></pre> <p>or use the <code>=</code> to signify evaluation:</p> <pre><code>&lt;command&gt; := "=" &lt;expr&gt; | &lt;id&gt; "=" &lt;expr&gt; </code></pre>
<p><a href="http://www.artima.com/lejava/articles/antlr_3.html" rel="nofollow noreferrer">ANTLR 3</a> uses a "LL(*)" parser as opposed to a LL(k) parser, so it will look ahead until it reaches the end of the input if it has to, without backtracking, using a specially optimized determinstic finite automata (DFA).</p>
15,648
<p>I've been working with code synthesis xsd to generate an xml tree to ensure constinency of the xml output to the original xsd.</p> <p>After initial testing, everything looked ok but when I tried entering invalid values (correct type, but outside the defined range), the values were allowed.</p> <p>Although the xml is well formed and conforms to the types set in the xsd, it is not a valid xml wrt the schema.</p> <p>Has anybody else used this tool and/or come up across this problem?</p>
<p>Try <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer">SimpleDateFormat</a>. You simply set a format such as the one in your example and then call parse on your dateStr.</p>
<h1><em>java.time</em></h1> <p>The <code>java.util</code> Date-Time API and their formatting API, <code>SimpleDateFormat</code> are outdated and error-prone. Since <code>java.sql.Timestamp</code> extends <code>java.util.Date</code>, it has got the same problems. It is recommended to stop using them completely and switch to the <a href="https://www.oracle.com/technical-resources/articles/java/jf14-Date-Time.html" rel="nofollow noreferrer">modern Date-Time API</a><sup>*</sup>.</p> <p><strong>Solution using <code>java.time</code>, the modern Date-Time API:</strong> You can define a <code>DateTimeFormatter</code> with <code>ResolverStyle</code> as <code>ResolverStyle.STRICT</code>, which is <code>ResolverStyle.SMART</code> by default.</p> <p><strong>Demo:</strong></p> <pre><code>import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; import java.time.format.ResolverStyle; import java.time.format.SignStyle; import java.time.temporal.ChronoField; import java.util.Locale; import java.util.stream.Stream; public class Main { public static void main(String[] args) { DateTimeFormatter dtf = new DateTimeFormatterBuilder() .appendValue(ChronoField.YEAR, 1, 4, SignStyle.NORMAL) .appendLiteral('-') .appendValue(ChronoField.MONTH_OF_YEAR, 1, 2, SignStyle.NORMAL) .appendLiteral('-') .appendValue(ChronoField.DAY_OF_MONTH, 1, 2, SignStyle.NORMAL) .appendLiteral(' ') .appendValue(ChronoField.HOUR_OF_DAY, 1, 2, SignStyle.NORMAL) .appendLiteral(':') .appendValue(ChronoField.MINUTE_OF_HOUR, 1, 2, SignStyle.NORMAL) .appendLiteral(':') .appendValue(ChronoField.SECOND_OF_MINUTE, 1, 2, SignStyle.NORMAL) .optionalStart() .appendLiteral('.') .appendFraction(ChronoField.NANO_OF_SECOND, 0, 3, false) .optionalEnd() .toFormatter(Locale.ENGLISH) .withResolverStyle(ResolverStyle.STRICT); // Test Stream.of( &quot;2008-06-31 23:59:59.000&quot;, &quot;2008-06-30 23:59:59.000&quot;, &quot;2008-6-30 23:59:59.000&quot;, &quot;2008-6-8 23:59:59.000&quot;, &quot;2008-6-8 2:59:59.000&quot;, &quot;2008-6-8 23:5:59.000&quot;, &quot;2008-6-8 23:59:9.000&quot;, &quot;2008-06-30 23:59:59&quot; ).forEach (s -&gt; { try { LocalDateTime ldt = LocalDateTime.parse(s, dtf); System.out.println(ldt); }catch(DateTimeParseException e) { System.out.printf(&quot;%s is an invalid date-time string.%n&quot;, s); // ... } }); } } </code></pre> <p><strong>Output:</strong></p> <pre><code>2008-06-31 23:59:59.000 is an invalid date-time string. 2008-06-30T23:59:59 2008-06-30T23:59:59 2008-06-08T23:59:59 2008-06-08T02:59:59 2008-06-08T23:05:59 2008-06-08T23:59:09 2008-06-30T23:59:59 </code></pre> <p><a href="https://ideone.com/GvnQtt" rel="nofollow noreferrer"><kbd>ONLINE DEMO</kbd></a></p> <p>Learn more about the modern Date-Time API from <strong><a href="https://docs.oracle.com/javase/tutorial/datetime/index.html" rel="nofollow noreferrer">Trail: Date Time</a></strong>. Check <a href="https://stackoverflow.com/a/67752047/10819573">this answer</a> and <a href="https://stackoverflow.com/a/67505173/10819573">this answer</a> to learn how to use <code>java.time</code> API with JDBC.</p> <h3>If at all, you need an instance of <code>java.sql.Timestamp</code>:</h3> <p>You can convert a <code>LocalDateTime</code> into <code>java.sql.Timestamp</code> using <a href="https://docs.oracle.com/javase/8/docs/api/java/sql/Timestamp.html#valueOf-java.lang.String-" rel="nofollow noreferrer"><code>Timestamp#valueOf</code></a> e.g.</p> <pre><code>LocalDateTime now = LocalDateTime.now(); Timestamp ts = Timestamp.valueOf(now); </code></pre> <hr /> <p><sup>* If you are working for an Android project and your Android API level is still not compliant with Java-8, check <a href="https://developer.android.com/studio/write/java8-support-table" rel="nofollow noreferrer">Java 8+ APIs available through desugaring</a>. Note that Android 8.0 Oreo already provides <a href="https://developer.android.com/reference/java/time/package-summary" rel="nofollow noreferrer">support for <code>java.time</code></a>. </sup></p>
28,069
<p>I've got a potentially rather large list of objects I'd like to bind to a ListBox in WPF. However, I'd like to have the List load itself incrementally. How can I bind a ListBox to an IEnumerable that loads itself on-demand in such a way that the listbox only tries to enumerate as much as it needs for the display?</p>
<p>WPF ListBox's use a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.virtualizingstackpanel.aspx" rel="nofollow noreferrer">VirtualizingStackPanel</a> as the layout control for its items. You can set the VirtualizingStackPanel to only load items as needed with the following XAML:</p> <pre><code>&lt;ListBox VirtualizingStackPanel.IsVirtualizing="True" ItemSource="..." /&gt; </code></pre>
<p>With winform, "virtual mode" - but AFAIK, this isn't the same in WPF. You could see <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/6d8e6f19-538a-4808-a5b0-4f6969041129/" rel="nofollow noreferrer">this MSDN forum</a> post.</p> <p>I largely agree with Drew Marsh - let the user filter the data, rather than scroll through it.</p>
45,476
<p>Say I have a sql query </p> <pre><code>SELECT fname, lname, dob, ssn, address1, address2, zip, phone,state from users </code></pre> <p>Now say the records are now either in dictionary base or a strongly typed collection.</p> <p>I have a grid view control and i want to bind it to my collection but I only want to display fname, lname, dob and ssn and not the other columns.</p> <p>Is there an easy way to extract the columns and then bind to the extracted item? Not sure if LINQ would be helpful here.</p> <p>This is a test project as I am getting familiar with the web world wqith VS-2008</p>
<p>Perhaps LINQ and an anonymous class could do the trick for you.</p> <pre><code>from user in UserCollection select new { FirstName=user.fname, LastName=user.lname, Dob=user.dob, SSN=user.ssn } </code></pre>
<p>You can use linq to return an anonymous type (AKA tuple). That tuple would contain only the properties you are looking for. Then you can bind your grid to that collection. Google anonymous types or tuples in C# to see what I mean.</p>
36,746
<p>How can you get the version information from a <code>.dll</code> or <code>.exe</code> file in PowerShell?</p> <p>I am specifically interested in <code>File Version</code>, though other version information (that is, <code>Company</code>, <code>Language</code>, <code>Product Name</code>, etc.) would be helpful as well.</p>
<p>Since PowerShell can call <a href="https://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> classes, you could do the following:</p> <pre><code>[System.Diagnostics.FileVersionInfo]::GetVersionInfo("somefilepath").FileVersion </code></pre> <p>Or as <a href="https://web.archive.org/web/20081004113553/https://kamhungsoh.com/blog/2008/01/powershell-file-version-information.html" rel="noreferrer">noted here</a> on a list of files:</p> <pre><code>get-childitem * -include *.dll,*.exe | foreach-object { "{0}`t{1}" -f $_.Name, [System.Diagnostics.FileVersionInfo]::GetVersionInfo($_).FileVersion } </code></pre> <p>Or even nicer as a script: <a href="https://jtruher3.wordpress.com/2006/05/14/powershell-and-file-version-information/" rel="noreferrer">https://jtruher3.wordpress.com/2006/05/14/powershell-and-file-version-information/</a></p>
<p>Here an alternative method. It uses Get-WmiObject CIM_DATAFILE to select the version.</p> <pre><code>(Get-WmiObject -Class CIM_DataFile -Filter "Name='C:\\Windows\\explorer.exe'" | Select-Object Version).Version </code></pre>
5,055
<p>When using <a href="http://log4perl.sourceforge.net/" rel="nofollow noreferrer">log4perl</a>, the debug log layout that I'm using is :</p> <pre><code>log4perl.appender.D10.layout=PatternLayout log4perl.appender.D10.layout.ConversionPattern=%d [pid=%P] %p %F{1} (%L) %M %m%n log4perl.appender.D10.Filter = DebugAndUp </code></pre> <p>This produces very verbose debug logs, for example:</p> <pre><code>2008/11/26 11:57:28 [pid=25485] DEBUG SomeModule.pm (331) functions::SomeModule::Test Test XXX was successfull 2008/11/26 11:57:29 [pid=25485] ERROR SomeOtherUnrelatedModule.pm (99999) functions::SomeModule::AnotherTest AnotherTest YYY has faled </code></pre> <p>This works great, and provides excellent debugging data.</p> <p>However, each line of the debug log contains different function names, pid length, etc. This makes each line layout differently, and makes reading debug logs much harder than it needs to be.</p> <p>Is there a way in log4perl to format the line so that the debugging metadata (everything up until the actual log message) be padded at the end with spaces/tabs, and have the actual message start at the same column of text?</p>
<p>You can pad the single fields that make up your entries. For example [pid=%5P] will always give you at least 5 characters for the PID. </p> <p>The <a href="http://search.cpan.org/~mschilli/Log-Log4perl-1.19/lib/Log/Log4perl/Layout/PatternLayout.pm#Quantify_placeholders" rel="noreferrer">"Quantify Placeholders" section</a> in the docs for Log::Log4perl::Layout gives more details. </p>
<p>There are a couple of ways to go with this, although you have to figure out which one works better for your situation:</p> <ol> <li><p>Use a different appender if you are working live. Have that appender use a pattern that shows only the information you want. If you're working in a single process, for instance, your alternate appender might leave off the PID and the timestamp. You might only need the file name and line number.</p></li> <li><p>Use <code>%n</code> to put newlines in the right place. That makes it multi-line output that is slightly harder to parse later, but you can choose another sequence for the input record separator (say, a literal "[EOL]") to make it easy to read entry-by-entry.</p></li> <li><p>Log to a database instead of a file. For your reports, select just the columns you want to inspect.</p></li> <li><p>Log everything, but write a filter to go through the log file ad-hoc to display just the parts that you want to see, such as only the debugging messages, the entries between certain times, only the entries involving a file, and so on.</p></li> </ol>
41,435
<p>If you are sending work/progress reports to the project lead on a daily or weekly basis, I wondered if you would consider using <a href="http://twitter.com" rel="nofollow noreferrer">Twitter</a> or similar services for these updates.</p> <p>Say if you're working remotely or with a distributed team and the project lead has a hard time getting an overview about the topics people are working on, and where the issues/time consumers are, would you set up some private accounts (or even a private company-internal service) to broadcast progress updates to your colleagues?</p> <p><strong>edit</strong> Thanks for the link to those products, but do you already use one of it in your company too? For real-life professional use?</p>
<p>Try <a href="http://laconi.ca/" rel="nofollow noreferrer">Laconica</a>: An open source Twitter-like system you could run on your own servers.</p>
<p>The <a href="http://en.blog.wordpress.com/2008/01/28/introducing-prologue/" rel="nofollow noreferrer">Prologue theme</a> for WordPress was designed with this in mind.</p>
7,472
<p>In this particular situation, there are 9 automated steps in a process that take varying lengths of time. We currently have a number showing percentage in the center of a progress bar, but it suffers from the common stop-and-go problem of racing up to 33%, waiting a long time, racing up to 55%, waiting an even longer time, then finishing.</p> <p>What's the best way to present this to the user? Should we remove the number, remove the whole progress bar in favor of an ajax-type circle animation, add descriptive text for the nine steps and checking them off or leave it the way it is? What are your thoughts?</p>
<p>If it really takes a long time, AJAX type of animation is probably not a good idea. I'd go with checklist of items.</p>
<p>I had almost the exact same problem. We also had 9 steps, so the bar would go 11%, 22% 33% etc. and also with some steps taking longer than others.</p> <p>I decided to make two of the longer steps count as two, so we how had 11 steps, so it wasn't as obvious, and the jumps weren't always even: 9%, 18%, 36%, 45%, 54%, 72%, 81%, 90%, done. The step values were always the same, but since the size of the step wasn't obvious, it worked..</p>
22,180
<p>I am building Java web applications, and I hate the traditional "code-compile-deploy-test" cycle. I want to type in one tiny change, then see the result INSTANTLY, without having to compile and deploy.</p> <p>Fortunately, <a href="http://www.mortbay.org/jetty/" rel="noreferrer">Jetty</a> is great for this. It is a pure-java web server. It comes with a really nice <a href="http://docs.codehaus.org/display/JETTY/Maven+Jetty+Plugin" rel="noreferrer">maven plugin</a> which lets you launch Jetty reading directly from your build tree -- no need to package a war file or deploy. It even has a scanInterval setting: put this to a non-zero value and it will watch your java files and various config files for changes and automatically re-deploy a few seconds after you make a change.</p> <p>There's just one thing keeping me from nirvana. I have javascript and css files in my src/main/webapp directory which just get served up by Jetty. I would like to be able to edit <em>these</em> and have the changes show up when I refresh the page in the browser. Unfortunately, Jetty holds these files open so I can't (on Windows) modify them while it is running.</p> <p>Does anyone know how to make Jetty let go of these files so I can edit them, then serve up the edited files for subsequent requests?</p>
<p>Jetty uses memory-mapped files to buffer static content, which causes the file-locking in Windows. Try setting <code>useFileMappedBuffer</code> for <code>DefaultServlet</code> to <code>false</code>.</p> <p><a href="http://www.eclipse.org/jetty/documentation/current/troubleshooting-locked-files-on-windows.html" rel="nofollow noreferrer">Troubleshooting Locked files on Windows (from the Jetty wiki)</a> has instructions.</p>
<p>It is probably the browser that is holding on to it.</p> <p>inside I.E : Tools | Internet Options | Temporary Internet Files > Settings, click the Radio button "Every visit to the page". press OK.</p> <p>Before you do that, Delete all the temporary internet files.</p>
22,288
<p>Howdy, I have a DataRow pulled out of a DataTable from a DataSet. I am accessing a column that is defined in SQL as a float datatype. I am trying to assign that value to a local variable (c# float datatype) but am getting an InvalidCastExecption </p> <pre><code>DataRow exercise = _exerciseDataSet.Exercise.FindByExerciseID(65); _AccelLimit = (float)exercise["DefaultAccelLimit"]; </code></pre> <p>Now, playing around with this I did make it work but it did not make any sense and it didn't feel right. </p> <pre><code>_AccelLimit = (float)(double)exercise["DefaultAccelLimit"]; </code></pre> <p>Can anyone explain what I am missing here?</p>
<p>A SQL float is a double according to <a href="http://msdn.microsoft.com/en-us/library/system.data.sqldbtype.aspx#Mtps_DropDownFilterText" rel="noreferrer"> the documentation for SQLDbType</a>.</p>
<p>I think the main question has been answered here but I feel compelled to add something for the section of the question that states that this works.</p> <blockquote> <p>_AccelLimit = (float)(double)exercise["DefaultAccelLimit"];</p> </blockquote> <p>The reason this "works" and the reason it "doesn't feel right" is that you are downgrading the double to a float by the second cast (the one on the left) so you are losing precision and effectively telling the compiler that it is ok to truncate the value returned.</p> <p>In words this line states... Get an object (that happens to hold a double in this case) Cast the object in to a double (losing all the object wrapping) Cast the double in to a float (losing all the fine precision of a double)</p> <p>e.g. If the value is say 0.0124022806089461 and you do the above then the value of AccelLimit will be 0.01240228</p> <p>as that is the extent of what a float in c# can get from the double value. Its a dangerous thing to do and I am pretty sure its a truncation too rather than a rounding but someone may want to confirm this as I am not sure.</p>
14,902
<p>If I change the url in the web.config file will the change be reflected in the .disco, .discomap, and .wsdl files that are in the WebReferences folder?</p> <p>[Edit]</p> <p>I'm using asp.net 2005</p>
<p>The change will not, as far as I'm aware, be reflected in all the other files. However, if you change the URL in web.config, your application will call the web service from the new URL at run-time. Check out this <a href="https://web.archive.org/web/20200808124012/http://geekswithblogs.net/ranganh/archive/2006/10/10/93654.aspx" rel="nofollow noreferrer">blog entry</a>. (No, it's not one of mine!)</p>
<p>As I can remember <strong>WSDL</strong> file contains the <strong>binding</strong>(s) (URL mappings) of your WS. So if you change the URL on your machine (in WSDL, Disco, etc.) that's enough.</p> <p>On the other hand don't forget to <strong>regenerate client proxies</strong>. They have to reflect WSDL changes.</p>
32,786
<p>How would I go about setting different authentication tags for different parts of my web app? Say I have:</p> <pre><code>/ /folder1/ /folder2/ </code></pre> <p>Would it be possible to specify different <code>&lt;authentication/&gt;</code> tags for each folder?</p> <p>I want folder1 to use Windows authentication but folder2 use Forms authentication. </p> <p>I tried doing in a <code>&lt;location/&gt;</code> tag but it doesn't look like you can have <code>&lt;authentication/&gt;</code> tags in a <code>&lt;location/&gt;</code> tags, at least not via VS 2008 with it's built in webserver.</p> <p>This errors out saying - Error 3 It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS. </p> <pre><code>&lt;location path="/folder1"&gt; &lt;system.web&gt; &lt;authentication mode="Forms" /&gt; &lt;authorization&gt; &lt;deny users="?"/&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;/location&gt; </code></pre>
<p>You can only have <code>&lt;authentication /&gt;</code> on the top level <code>web.config</code>. You may have to create multiple applications. ie you can create an application within an application and use different authentication modes in each one.</p>
<p>I think you can set the forms authentication authorization on folder1 to </p> <pre><code>&lt;allow users="*" /&gt; </code></pre> <p>then control the windows access via setting windows permissions on the folder.</p> <p>I haven't tried it, but I can't think of why that wouldn't work.</p>
41,214
<p>How would you design a content voting mechanism that could be applied polymorphically to multiple models / classes. (in a ruby on rails context preferably, but others are fine)</p> <p>Given that instances of these classes can be voted on: - Article - Question - Product</p> <p>Voters should not be required to register.</p> <p>Best effort should be made to limit voters to one vote per object. (1 vote for a particular article and one vote for a particular question, etc.). I.e. use ip detection, cookies, etc.</p>
<p>I'd suggest starting with Single Table Inheritance for a 'votable' interface and derive any votable classes from there. Starting details for STI: <a href="http://wiki.rubyonrails.org/rails/pages/singletableinheritance" rel="nofollow noreferrer">http://wiki.rubyonrails.org/rails/pages/singletableinheritance</a></p>
<p>Thanks for the answers guys. Yup, creating a polymorphic votable model is the way to go, however I was attempting to extract a more complete answer.</p> <p>For example here's what I'm thinking so far. A voteable class which can be tied to multiple classes (Article, Question, Product) in this scenario.</p> <p>Votes table: id:integer, vote:boolean, voteable_type:string (name of the class being voted on), voteable_id:integer (id of the class being voted on), voter_id (identifer for the user voting).</p> <p>Now we still need to try and limit votes to one per user without requiring some sort of registration. So the voter_id could be a composite containing the user's IP address and user_agent. This is where I'm open to ideas. The IP address captured is not necessarily unique if they're coming from a corp proxy etc. so combining the user agent shoud help somewhat. However you still have cases where two user's can have the same IP and user agent string. Also, you may not always be able to obtain this information if their browser doesn't send it in the request header, meaning that some user's simply won't get to vote... Also, IPs can be spoofed.</p> <p>Another possiblity would be using cookies, but I think this invites abuse from user's who want to spike the votes for a particular piece of content by clearing their cookies or scripting hits. Checking the user-agent here should help too, but you can fake a user-agent via script easily enough.</p> <p>There probably is no perfect solution, but I'm curious how other's have approached this. I.e. hacker news and even stackoverflow.</p>
32,808
<p>I bought some heating block cotton to insulate the exposed surface of my hot end. I thought the yellow as double-sticky but it appears to be Kapton.</p> <p>What can I use to attach it to the extruder?</p> <p><a href="https://i.stack.imgur.com/9FFOY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9FFOY.jpg" alt="enter image description here"></a></p> <p>My extruder is already covered on four sides. I want to cover the other two.<a href="https://i.stack.imgur.com/VLyKX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VLyKX.png" alt="enter image description here"></a></p>
<p>Kapton tape would be the logical material. It's unfortunate that your vendor did not supply that as a separate item, rather than sticking it to the "cotton" (I'm guessing not actually cotton, as things might get a bit scorching for cotton, so I'm assuming some type of ceramic fiber or the like.)</p>
<p>Not quite the answer to the question but closely related, so I venture. I use ordinary wool thread to insulate the hot end. I just wrap it carefully so it is covered everywhere. Very low cost, very effective. Wool can handle even the hottest extrusion temperatures easily.</p>
641
<p>I'm brand new to jQuery and have some experience using Prototype. In Prototype, there is a method to "flash" an element &mdash; ie. briefly highlight it in another color and have it fade back to normal so that the user's eye is drawn to it. Is there such a method in jQuery? I see fadeIn, fadeOut, and animate, but I don't see anything like "flash". Perhaps one of these three can be used with appropriate inputs?</p>
<p>My way is .fadein, .fadeout .fadein, .fadeout ......</p> <pre><code>$("#someElement").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100); </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function go1() { $("#demo1").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100)} function go2() { $('#demo2').delay(100).fadeOut().fadeIn('slow') }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#demo1, #demo2 { text-align: center; font-family: Helvetica; background: IndianRed; height: 50px; line-height: 50px; width: 150px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;button onclick="go1()"&gt;Click Me&lt;/button&gt; &lt;div id='demo1'&gt;My Element&lt;/div&gt; &lt;br&gt; &lt;button onclick="go2()"&gt;Click Me&lt;/button&gt; (from comment) &lt;div id='demo2'&gt;My Element&lt;/div&gt;</code></pre> </div> </div> </p>
<p>You can use this cool library to make any kind of animated effect on your element: <a href="http://daneden.github.io/animate.css/" rel="nofollow">http://daneden.github.io/animate.css/</a></p>
34,782
<p>in Erlang I have a supervisor-tree of processes, containing one that accepts tcp/ip connections. For each incoming connection I spawn a new process. Should this process be added to the supervisor tree or not?</p> <p>Regards, Steve</p>
<p>Yes, you should add these processes to the supervision heirarchy as you want them to be correctly/gracefully shutdown when your application is stopped. (Otherwise you end up leaking connections that will fail as the application infrastructure they depend on been shutdown).</p> <p>You could create a <code>simple_one_for_one</code> strategy supervisor say <code>yourapp_client_sup</code> that has a child spec of <code>{Id, {yourapp_client_connection, start_link_with_socket, []}, Restart, Shutdown, worker, temporary}</code>. The <code>temporary</code> type here is important because there's normally no useful restart strategy for a connection handler - you can't connect out to the client to restart the connection. <code>temporary</code> here will cause the supervisor to report the connection handler exit but otherwise ignore it.</p> <p>The process that does <code>gen_tcp:accept</code> will then create the connection handler process by doing <code>supervisor:start_child(yourapp_client_sup, [Socket,Options,...])</code> rather than <code>yourapp_client_sup:start_link(Socket, Options, ...)</code>. Ensure that the <code>youreapp_client_connection:start_link_with_socket</code> function starts the child via <code>gen_server</code> or <code>proc_lib</code> functions (a requirement of the <code>supervisor</code> module) and that the function transfers control of the socket to the child with <code>gen_tcp:controlling_process</code> otherwise the child won't be able to use the socket.</p> <p>An alternate approach is to create a dummy <code>yourapp_client_sup</code> process that <code>yourclient_connection_handler</code> processes can link to at startup. The <code>yourapp_client_sup</code> process will just exist to propagate <code>EXIT</code> messages from its parent to the connection handler processes. It will need to trap exists and ignore all <code>EXIT</code> messages other than those from its parent. On the whole, I prefer to use the <code>simple_one_for_one</code> supervisor approach.</p>
<p>If you expect these processes to be many, it could be a good idea to add a supervisor under your main supervisor as to separate responsibility (and maybe use the <code>simple_one_for_one</code> setting to make things simpler, maybe even simpler than your current case).</p> <p>The thing is, if you need to control these processes, it's always nice to have a supervisor. If it doesn't matter if they succeed or not, then you might not need one. But then again, I always argue that that is sloppy coding. ;-)</p> <p>The only thing I <em>wouldn't</em> do, is to add them to your existing tree, unless it is very obvious where they come from and they're fairly few.</p>
18,429