source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
93,357
I want to read the contents of a URL but don't want to "hang" if the URL is unresponsive. I've created a BufferedReader using the URL... URL theURL = new URL(url);URLConnection urlConn = theURL.openConnection();urlConn.setDoOutput(true);BufferedReader urlReader = new BufferedReader(newInputStreamReader(urlConn.getInputStream())); ...and then begun the loop to read the contents... do { buf = urlReader.readLine(); if (buf != null) { resultBuffer.append(buf); resultBuffer.append("\n"); } }while (buf != null); ...but if the read hangs then the application hangs. Is there a way, without grinding the code down to the socket level, to "time out" the read if necessary?
I think URLConnection.setReadTimeout is what you are looking for.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ] }
93,408
I saw some code like the following in a JSP <c:if test="<%=request.isUserInRole(RoleEnum.USER.getCode())%>"> <li>user</li></c:if> My confusion is over the "=" that appears in the value of the test attribute. My understanding was that anything included within <%= %> is printed to the output, but surely the value assigned to test must be a Boolean, so why does this work? For bonus points, is there any way to change the attribute value above such that it does not use scriptlet code? Presumably, that means using EL instead. Cheers,Don
All that the test attribute looks for to determine if something is true is the string "true" (case in-sensitive). For example, the following code will print "Hello world!" <c:if test="true">Hello world!</c:if> The code within the <%= %> returns a boolean, so it will either print the string "true" or "false", which is exactly what the <c:if> tag looks for.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ] }
93,417
Suppose you have a collection of a few hundred in-memory objects and you need to query this List to return objects matching some SQL or Criteria like query. For example, you might have a List of Car objects and you want to return all cars made during the 1960s, with a license plate that starts with AZ, ordered by the name of the car model. I know about JoSQL , has anyone used this, or have any experience with other/homegrown solutions?
I have used Apache Commons JXPath in a production application. It allows you to apply XPath expressions to graphs of objects in Java.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17542/" ] }
93,451
I would like to add AES encryption to a software product, but am concerned by increasing the size of the data. I am guessing that the data does increase in size, and then I'll have to add a compression algorithm to compensate.
AES does not expand data. Moreover, the output will not generally be compressible; if you intend to compress your data, do so before encrypting it. However, note that AES encryption is usually combined with padding , which will increase the size of the data (though only by a few bytes).
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/93451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
93,460
I work in a very small shop (2 people), and since I started a few months back we have been relying on Windows Scheduled tasks. Finally, I've decided I've had enough grief with some of its inabilities such as No logs that I can find except on a domain level (inaccessible to machine admins who aren't domain admins) No alerting mechanism (e-mail, for one) when the job fails. Once again, we are a small shop. I'm looking to do the analogous scheduling system upgrade than I'm doing with source control (VSS --> Subversion). I'm looking for suggestions of systems that Are able to do the two things outlined above Have been community-tested. I'd love to be a guinae pig for exciting software, but job scheduling is not my day job. Ability to remotely manage jobs a plus Free a plus. Cheap is okay, but I have very little interest in going through a full blown sales pitch with 7 power point presentations. Built-in ability to run common tasks besides .EXE's a (minor) plus (run an assembly by name, run an Excel macro by name a plus, run a database stored procedure, etc.).
I think you can look at : http://www.visualcron.com/
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7311/" ] }
93,472
Is it possible to use DateTimePicker (Winforms) to pick both date and time (in the dropdown)? How do you change the custom display of the picked value? Also, is it possible to enable the user to type the date/time manually?
Set the Format to Custom and then specify the format: dateTimePicker1.Format = DateTimePickerFormat.Custom;dateTimePicker1.CustomFormat = "MM/dd/yyyy hh:mm:ss"; or however you want to lay it out. You could then type in directly the date/time. If you use MMM, you'll need to use the numeric value for the month for entry, unless you write some code yourself for that (e.g., 5 results in May) Don't know about the picker for date and time together. Sounds like a custom control to me.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/93472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5363/" ] }
93,511
How to get a counter inside xsl:for-each loop that would reflect the number of current element processed. For example my source XML is <books> <book> <title>The Unbearable Lightness of Being </title> </book> <book> <title>Narcissus and Goldmund</title> </book> <book> <title>Choke</title> </book></books> What I want to get is: <newBooks> <newBook> <countNo>1</countNo> <title>The Unbearable Lightness of Being </title> </newBook> <newBook> <countNo>2</countNo> <title>Narcissus and Goldmund</title> </newBook> <newBook> <countNo>3</countNo> <title>Choke</title> </newBook></newBooks> The XSLT to modify: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:template match="/"> <newBooks> <xsl:for-each select="books/book"> <newBook> <countNo>???</countNo> <title> <xsl:value-of select="title"/> </title> </newBook> </xsl:for-each> </newBooks> </xsl:template></xsl:stylesheet> So the question is what to put in place of ???. Is there any standard keyword or do I simply must declare a variable and increment it inside the loop? As the question is pretty long I should probably expect one line or one word answer :)
position() . E.G.: <countNo><xsl:value-of select="position()" /></countNo>
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/93511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3241/" ] }
93,526
A Y-combinator is a computer science concept from the “functional” side of things. Most programmers don't know much at all about combinators, if they've even heard about them. What is a Y-combinator? How do combinators work? What are they good for? Are they useful in procedural languages?
If you're ready for a long read, Mike Vanier has a great explanation . Long story short, it allows you to implement recursion in a language that doesn't necessarily support it natively.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/93526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2729/" ] }
93,539
What is the difference between Views and Materialized Views in Oracle?
Materialized views are disk based and are updated periodically based upon the query definition. Views are virtual only and run the query definition each time they are accessed.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/93539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ] }
93,541
I have a custom user control with a textbox on it and I'd like to expose the baseline (of the text in the textbox) snapline outside of the custom control. I know that you create a designer (inherited from ControlDesigner) and override SnapLines to get access to the snaplines, but I'm wondering how to get the text baseline of a control that I have exposed by my custom user control.
I just had a similar need, and I solved it like this: public override IList SnapLines{ get { IList snapLines = base.SnapLines; MyControl control = Control as MyControl; if (control == null) { return snapLines; } IDesigner designer = TypeDescriptor.CreateDesigner( control.textBoxValue, typeof(IDesigner)); if (designer == null) { return snapLines; } designer.Initialize(control.textBoxValue); using (designer) { ControlDesigner boxDesigner = designer as ControlDesigner; if (boxDesigner == null) { return snapLines; } foreach (SnapLine line in boxDesigner.SnapLines) { if (line.SnapLineType == SnapLineType.Baseline) { snapLines.Add(new SnapLine(SnapLineType.Baseline, line.Offset + control.textBoxValue.Top, line.Filter, line.Priority)); break; } } } return snapLines; }} This way it's actually creating a temporary sub-designer for the subcontrol in order to find out where the "real" baseline snapline is. This seemed reasonably performant in testing, but if perf becomes a concern (and if the internal textbox doesn't move) then most of this code can be extracted to the Initialize method. This also assumes that the textbox is a direct child of the UserControl. If there are other layout-affecting controls in the way then the offset calculation becomes a bit more complicated.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/93541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2848/" ] }
93,551
Web applications that want to force a resource to be downloaded rather than directly rendered in a Web browser issue a Content-Disposition header in the HTTP response of the form: Content-Disposition: attachment; filename= FILENAME The filename parameter can be used to suggest a name for the file into which the resource is downloaded by the browser. RFC 2183 (Content-Disposition), however, states in section 2.3 (The Filename Parameter) that the file name can only use US-ASCII characters: Current [RFC 2045] grammar restrictsparameter values (and henceContent-Disposition filenames) toUS-ASCII. We recognize the greatdesirability of allowing arbitrarycharacter sets in filenames, but it isbeyond the scope of this document todefine the necessary mechanisms. There is empirical evidence, nevertheless, that most popular Web browsers today seem to permit non-US-ASCII characters yet (for the lack of a standard) disagree on the encoding scheme and character set specification of the file name. Question is then, what are the various schemes and encodings employed by the popular browsers if the file name “naïvefile” (without quotes and where the third letter is U+00EF) needed to be encoded into the Content-Disposition header? For the purpose of this question, popular browsers being: Google Chrome Safari Internet Explorer or Edge Firefox Opera
I know this is an old post but it is still very relevant. I have found that modern browsers support rfc5987, which allows utf-8 encoding, percentage encoded (url-encoded). Then Naïve file.txt becomes: Content-Disposition: attachment; filename*=UTF-8''Na%C3%AFve%20file.txt Safari (5) does not support this. Instead you should use the Safari standard of writing the file name directly in your utf-8 encoded header: Content-Disposition: attachment; filename=Naïve file.txt IE8 and older don't support it either and you need to use the IE standard of utf-8 encoding, percentage encoded: Content-Disposition: attachment; filename=Na%C3%AFve%20file.txt In ASP.Net I use the following code: string contentDisposition;if (Request.Browser.Browser == "IE" && (Request.Browser.Version == "7.0" || Request.Browser.Version == "8.0")) contentDisposition = "attachment; filename=" + Uri.EscapeDataString(fileName);else if (Request.Browser.Browser == "Safari") contentDisposition = "attachment; filename=" + fileName;else contentDisposition = "attachment; filename*=UTF-8''" + Uri.EscapeDataString(fileName);Response.AddHeader("Content-Disposition", contentDisposition); I tested the above using IE7, IE8, IE9, Chrome 13, Opera 11, FF5, Safari 5. Update November 2013: Here is the code I currently use. I still have to support IE8, so I cannot get rid of the first part. It turns out that browsers on Android use the built in Android download manager and it cannot reliably parse file names in the standard way. string contentDisposition;if (Request.Browser.Browser == "IE" && (Request.Browser.Version == "7.0" || Request.Browser.Version == "8.0")) contentDisposition = "attachment; filename=" + Uri.EscapeDataString(fileName);else if (Request.UserAgent != null && Request.UserAgent.ToLowerInvariant().Contains("android")) // android built-in download manager (all browsers on android) contentDisposition = "attachment; filename=\"" + MakeAndroidSafeFileName(fileName) + "\"";else contentDisposition = "attachment; filename=\"" + fileName + "\"; filename*=UTF-8''" + Uri.EscapeDataString(fileName);Response.AddHeader("Content-Disposition", contentDisposition); The above now tested in IE7-11, Chrome 32, Opera 12, FF25, Safari 6, using this filename for download: 你好abcABCæøåÆØÅäöüïëêîâéíáóúýñ½§!#¤%&()=`@£$€{[]}+´¨^~'-_,;.txt On IE7 it works for some characters but not all. But who cares about IE7 nowadays? This is the function I use to generate safe file names for Android. Note that I don't know which characters are supported on Android but that I have tested that these work for sure: private static readonly Dictionary<char, char> AndroidAllowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._-+,@£$€!½§~'=()[]{}0123456789".ToDictionary(c => c);private string MakeAndroidSafeFileName(string fileName){ char[] newFileName = fileName.ToCharArray(); for (int i = 0; i < newFileName.Length; i++) { if (!AndroidAllowedChars.ContainsKey(newFileName[i])) newFileName[i] = '_'; } return new string(newFileName);} @TomZ: I tested in IE7 and IE8 and it turned out that I did not need to escape apostrophe ('). Do you have an example where it fails? @Dave Van den Eynde: Combining the two file names on one line as according to RFC6266 works except for Android and IE7+8 and I have updated the code to reflect this. Thank you for the suggestion. @Thilo: No idea about GoodReader or any other non-browser. You might have some luck using the Android approach. @Alex Zhukovskiy: I don't know why but as discussed on Connect it doesn't seem to work terribly well.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/93551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6682/" ] }
93,591
A feature in Eclipse that I really miss is how you can auto-complete method parameters with currently in-scope variables. This feature will, with a single key combo ( ctrl + space ) fill in all method parameters. As long as my variables were named similarly to the method parameters, I never had a problem with this auto-complete. Is there a plugin or a native way to accomplish this in Intellij?
IntelliJ IDEA 9 now supports what they call "super completion" which matches the behavior you are looking for and is available through their early access program. (source: jetbrains.com ) IntelliJ IDEA 8 does not allow you to autocomplete more than one parameter at a time. You are forced to use Control - Shift - Space once for each parameter.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/93591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17854/" ] }
93,642
We require all requests for downloads to have a valid login (non-http) and we generate transaction tickets for each download. If you were to go to one of the download links and attempt to "replay" the transaction, we use HTTP codes to forward you to get a new transaction ticket. This works fine for a majority of users. There's a small subset, however, that are using Download Accelerators that simply try to replay the transaction ticket several times. So, in order to determine whether we want to or even can support download accelerators or not, we are trying to understand how they work. How does having a second, third or even fourth concurrent connection to the web server delivering a static file speed the download process? What does the accelerator program do?
You'll get a more comprehensive overview of Download Accelerators at wikipedia . Acceleration is multi-faceted First A substantial benefit of managed/accelerated downloads is the tool in question remembers Start/Stop offsets transferred and uses "partial" and 'range' headers to request parts of the file instead of all of it. This means if something dies mid transaction ( ie: TCP Time-out ) it just reconnects where it left off and you don't have to start from scratch. Thus, if you have an intermittent connection, the aggregate transfer time is greatly lessened. Second Download accelerators like to break a single transfer into several smaller segments of equal size, using the same start-range-stop mechanics, and perform them in parallel, which greatly improves transfer time over slow networks. There's this annoying thing called bandwidth-delay-product where the size of the TCP buffers at either end do some math thing in conjunction with ping time to get the actual experienced speed, and this in practice means large ping times will limit your speed regardless how many megabits/sec all the interim connections have. However, this limitation appears to be "per connection", so multiple TCP connections to a single server can help mitigate the performance hit of the high latency ping time. Hence, people who live near by are not so likely to need to do a segmented transfer, but people who live in far away locations are more likely to benefit from going crazy with their segmentation. Thirdly In some cases it is possible to find multiple servers that provide the same resource, sometimes a single DNS address round-robins to several IP addresses, or a server is part of a mirror network of some kind. And download managers/accelerators can detect this and apply the segmented transfer technique across multiple servers, allowing the downloader to get more collective bandwidth delivered to them. Support Supporting the first kind of acceleration is what I personally suggest as a "minimum" for support. Mostly, because it makes a users life easy, and it reduces the amount of aggregate data transfer you have to provide due to users not having to fetch the same content repeatedly. And to facilitate this, its recommended you, compute how much they have transferred and don't expire the ticket till they look "finished" ( while binding traffic to the first IP that used the ticket ), or a given 'reasonable' time to download it has passed. ie: give them a window of grace before requiring they get a new ticket. Supporting the second and third give you bonus points, and users generally desire it at least the second, mostly because international customers don't like being treated as second class customers simply because of the greater ping time, and it doesn't objectively consume more bandwidth in any sense that matters. The worst that happens is they might cause your total throughput to be undesirable for how your service operates. It's reasonably straight forward to deliver the first kind of benefit without allowing the second simply by restricting the number of concurrent transfers from a single ticket.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5581/" ] }
93,650
How do you apply stroke (outline around text) to a textblock in xaml in WPF?
Below is my more idiomatically WPF, full-featured take on this. It supports pretty much everything you'd expect, including: all font related properties including stretch and style text alignment (left, right, center, justify) text wrapping text trimming text decorations (underline, strike through etcetera) Here's a simple example of what can be achieved with it: <local:OutlinedTextBlock FontFamily="Verdana" FontSize="20pt" FontWeight="ExtraBold" TextWrapping="Wrap" StrokeThickness="1" Stroke="{StaticResource TextStroke}" Fill="{StaticResource TextFill}"> Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</local:OutlinedTextBlock> Which results in: Here's the code for the control: using System;using System.ComponentModel;using System.Globalization;using System.Windows;using System.Windows.Documents;using System.Windows.Markup;using System.Windows.Media;[ContentProperty("Text")]public class OutlinedTextBlock : FrameworkElement{ public static readonly DependencyProperty FillProperty = DependencyProperty.Register( "Fill", typeof(Brush), typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender)); public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register( "Stroke", typeof(Brush), typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender)); public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register( "StrokeThickness", typeof(double), typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(1d, FrameworkPropertyMetadataOptions.AffectsRender)); public static readonly DependencyProperty FontFamilyProperty = TextElement.FontFamilyProperty.AddOwner( typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(OnFormattedTextUpdated)); public static readonly DependencyProperty FontSizeProperty = TextElement.FontSizeProperty.AddOwner( typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(OnFormattedTextUpdated)); public static readonly DependencyProperty FontStretchProperty = TextElement.FontStretchProperty.AddOwner( typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(OnFormattedTextUpdated)); public static readonly DependencyProperty FontStyleProperty = TextElement.FontStyleProperty.AddOwner( typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(OnFormattedTextUpdated)); public static readonly DependencyProperty FontWeightProperty = TextElement.FontWeightProperty.AddOwner( typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(OnFormattedTextUpdated)); public static readonly DependencyProperty TextProperty = DependencyProperty.Register( "Text", typeof(string), typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(OnFormattedTextInvalidated)); public static readonly DependencyProperty TextAlignmentProperty = DependencyProperty.Register( "TextAlignment", typeof(TextAlignment), typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(OnFormattedTextUpdated)); public static readonly DependencyProperty TextDecorationsProperty = DependencyProperty.Register( "TextDecorations", typeof(TextDecorationCollection), typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(OnFormattedTextUpdated)); public static readonly DependencyProperty TextTrimmingProperty = DependencyProperty.Register( "TextTrimming", typeof(TextTrimming), typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(OnFormattedTextUpdated)); public static readonly DependencyProperty TextWrappingProperty = DependencyProperty.Register( "TextWrapping", typeof(TextWrapping), typeof(OutlinedTextBlock), new FrameworkPropertyMetadata(TextWrapping.NoWrap, OnFormattedTextUpdated)); private FormattedText formattedText; private Geometry textGeometry; public OutlinedTextBlock() { this.TextDecorations = new TextDecorationCollection(); } public Brush Fill { get { return (Brush)GetValue(FillProperty); } set { SetValue(FillProperty, value); } } public FontFamily FontFamily { get { return (FontFamily)GetValue(FontFamilyProperty); } set { SetValue(FontFamilyProperty, value); } } [TypeConverter(typeof(FontSizeConverter))] public double FontSize { get { return (double)GetValue(FontSizeProperty); } set { SetValue(FontSizeProperty, value); } } public FontStretch FontStretch { get { return (FontStretch)GetValue(FontStretchProperty); } set { SetValue(FontStretchProperty, value); } } public FontStyle FontStyle { get { return (FontStyle)GetValue(FontStyleProperty); } set { SetValue(FontStyleProperty, value); } } public FontWeight FontWeight { get { return (FontWeight)GetValue(FontWeightProperty); } set { SetValue(FontWeightProperty, value); } } public Brush Stroke { get { return (Brush)GetValue(StrokeProperty); } set { SetValue(StrokeProperty, value); } } public double StrokeThickness { get { return (double)GetValue(StrokeThicknessProperty); } set { SetValue(StrokeThicknessProperty, value); } } public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } public TextAlignment TextAlignment { get { return (TextAlignment)GetValue(TextAlignmentProperty); } set { SetValue(TextAlignmentProperty, value); } } public TextDecorationCollection TextDecorations { get { return (TextDecorationCollection)this.GetValue(TextDecorationsProperty); } set { this.SetValue(TextDecorationsProperty, value); } } public TextTrimming TextTrimming { get { return (TextTrimming)GetValue(TextTrimmingProperty); } set { SetValue(TextTrimmingProperty, value); } } public TextWrapping TextWrapping { get { return (TextWrapping)GetValue(TextWrappingProperty); } set { SetValue(TextWrappingProperty, value); } } protected override void OnRender(DrawingContext drawingContext) { this.EnsureGeometry(); drawingContext.DrawGeometry(this.Fill, new Pen(this.Stroke, this.StrokeThickness), this.textGeometry); } protected override Size MeasureOverride(Size availableSize) { this.EnsureFormattedText(); // constrain the formatted text according to the available size // the Math.Min call is important - without this constraint (which seems arbitrary, but is the maximum allowable text width), things blow up when availableSize is infinite in both directions // the Math.Max call is to ensure we don't hit zero, which will cause MaxTextHeight to throw this.formattedText.MaxTextWidth = Math.Min(3579139, availableSize.Width); this.formattedText.MaxTextHeight = Math.Max(0.0001d, availableSize.Height); // return the desired size return new Size(this.formattedText.Width, this.formattedText.Height); } protected override Size ArrangeOverride(Size finalSize) { this.EnsureFormattedText(); // update the formatted text with the final size this.formattedText.MaxTextWidth = finalSize.Width; this.formattedText.MaxTextHeight = finalSize.Height; // need to re-generate the geometry now that the dimensions have changed this.textGeometry = null; return finalSize; } private static void OnFormattedTextInvalidated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { var outlinedTextBlock = (OutlinedTextBlock)dependencyObject; outlinedTextBlock.formattedText = null; outlinedTextBlock.textGeometry = null; outlinedTextBlock.InvalidateMeasure(); outlinedTextBlock.InvalidateVisual(); } private static void OnFormattedTextUpdated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { var outlinedTextBlock = (OutlinedTextBlock)dependencyObject; outlinedTextBlock.UpdateFormattedText(); outlinedTextBlock.textGeometry = null; outlinedTextBlock.InvalidateMeasure(); outlinedTextBlock.InvalidateVisual(); } private void EnsureFormattedText() { if (this.formattedText != null || this.Text == null) { return; } this.formattedText = new FormattedText( this.Text, CultureInfo.CurrentUICulture, this.FlowDirection, new Typeface(this.FontFamily, this.FontStyle, this.FontWeight, FontStretches.Normal), this.FontSize, Brushes.Black); this.UpdateFormattedText(); } private void UpdateFormattedText() { if (this.formattedText == null) { return; } this.formattedText.MaxLineCount = this.TextWrapping == TextWrapping.NoWrap ? 1 : int.MaxValue; this.formattedText.TextAlignment = this.TextAlignment; this.formattedText.Trimming = this.TextTrimming; this.formattedText.SetFontSize(this.FontSize); this.formattedText.SetFontStyle(this.FontStyle); this.formattedText.SetFontWeight(this.FontWeight); this.formattedText.SetFontFamily(this.FontFamily); this.formattedText.SetFontStretch(this.FontStretch); this.formattedText.SetTextDecorations(this.TextDecorations); } private void EnsureGeometry() { if (this.textGeometry != null) { return; } this.EnsureFormattedText(); this.textGeometry = this.formattedText.BuildGeometry(new Point(0, 0)); }}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/93650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3798/" ] }
93,654
I'd sort of like to use SQLite from within C#.Net, but I can't seem to find an appropriate library. Is there one? An official one? Are there other ways to use SQLite than with a wrapper?
From https://system.data.sqlite.org : System.Data.SQLite is an ADO.NET adapter for SQLite. System.Data.SQLite was started by Robert Simpson. Robert still has commit privileges on this repository but is no longer an active contributor. Development and maintenance work is now mostly performed by the SQLite Development Team. The SQLite team is committed to supporting System.Data.SQLite long-term. "System.Data.SQLite is the original SQLite database engine and a complete ADO.NET 2.0 provider all rolled into a single mixed mode assembly. It is a complete drop-in replacement for the original sqlite3.dll (you can even rename it to sqlite3.dll). Unlike normal mixed assemblies, it has no linker dependency on the .NET runtime so it can be distributed independently of .NET." It even supports Mono.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/93654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93438/" ] }
93,655
I have an XML file that's the output from a database. I'm using the Java SAX parser to parse the XML and output it in a different format. The XML contains some invalid characters and the parser is throwing errors like 'Invalid Unicode character (0x5)' Is there a good way to strip all these characters out besides pre-processing the file line-by-line and replacing them? So far I've run into 3 different invalid characters (0x5, 0x6 and 0x7). It's a ~4gb database dump and we're going to be processing it a bunch of times, so having to wait an extra 30 minutes each time we get a new dump to run a pre-processor on it is going to be a pain, and this isn't the first time I've run into this issue.
I used Xalan org.apache.xml.utils.XMLChar class: public static String stripInvalidXmlCharacters(String input) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (XMLChar.isValid(c)) { sb.append(c); } } return sb.toString();}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8973/" ] }
93,692
I want to embed Javascript in a hobby game engine of mine. Now that we have the 5th generation of Javascript engines out (all blazing fast) I'm curious what engine would you choose to embed in a C++ framework (that includes actual ease of embeding it)? Note: Just to make it clear, I'm not interested in DOM scripting or writing Javascript in a browser. Here's a compilation of links so far and some tips from the thread SpiderMonkey tracemonkey (note:backwards compatible with spidermonkey): V8 Squirrelfish Just for the record, I love Lua and have already embedded it in game engines about 5 times at work. However now this is a hobby project, and I think that Javascript being known by most web developers and because its ECMA, Flash and Flex developers, a game engine that uses Javascript and XML for scripting would be more user-friendly and cater to a larger user base (and one that so far has not had a chance to use their skills for games) than one with Lua (and there are plenty of those around!). Also for the record I'll go with V8 on this one, mostly because I like it's C++ style.
Mozilla's SpiderMonkey is fairly easy and well-documented. It's a C API, but it's straightforward to wrap it in C++. It can be compiled to be thread-safe, which is useful for games since you'd likely want to have your main logic in one thread and user interface logic in a second thread. Google's V8 might be a good choice, since you're using C++, but I have no experience with it yet. According to the documentation (thanks to Daniel James ), V8 is not thread-safe, although this may change in the future. There's also WebKit's SquirrelFish , but I couldn't find a standalone version of that when I was looking earlier.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ] }
93,695
My users would like to be able to hit Ctrl + S to save a form. Is there a good cross-browser way of capturing the Ctrl + S key combination and submit my form? App is built on Drupal, so jQuery is available.
$(window).keypress(function(event) { if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true; alert("Ctrl-S pressed"); event.preventDefault(); return false;}); Key codes can differ between browsers, so you may need to check for more than just 115.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/93695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1902010/" ] }
93,716
How can I hide the title bar from a Windows Form but still have a Resizing Frame?
Setting FormBorderStyle = None will remove the title bar (at both design andrun time) - and also remove your ability to resize the form. If you need a border you can set: ControlBox = falseText = ""
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6151/" ] }
93,720
How do I represent an aggregation relation between two classes in UML, such that each class has a link to the other class's interface, not the implementing class? E.g. I have a class Foo that implements iFoo, and Bar that implements iBar. Foo should have a member variable of type iBar, and Bar should have a member variable of type iFoo. If I create an aggregation between the two implementing classes, then the member will be of the type of the implementing class, not the superclass. And aggregations between interfaces are invalid in UML (and don't make much sense).
Setting FormBorderStyle = None will remove the title bar (at both design andrun time) - and also remove your ability to resize the form. If you need a border you can set: ControlBox = falseText = ""
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16399/" ] }
93,744
For the life of me, I can't remember how to set, delete, toggle or test a bit in a bitfield. Either I'm unsure or I mix them up because I rarely need these. So a "bit-cheat-sheet" would be nice to have. For example: flags = flags | FlagsEnum.Bit4; // Set bit 4. or if ((flags & FlagsEnum.Bit4)) == FlagsEnum.Bit4) // Is there a less verbose way? Can you give examples of all the other common operations, preferably in C# syntax using a [Flags] enum?
I did some more work on these extensions - You can find the code here I wrote some extension methods that extend System.Enum that I use often... I'm not claiming that they are bulletproof, but they have helped... Comments removed... namespace Enum.Extensions { public static class EnumerationExtensions { public static bool Has<T>(this System.Enum type, T value) { try { return (((int)(object)type & (int)(object)value) == (int)(object)value); } catch { return false; } } public static bool Is<T>(this System.Enum type, T value) { try { return (int)(object)type == (int)(object)value; } catch { return false; } } public static T Add<T>(this System.Enum type, T value) { try { return (T)(object)(((int)(object)type | (int)(object)value)); } catch(Exception ex) { throw new ArgumentException( string.Format( "Could not append value from enumerated type '{0}'.", typeof(T).Name ), ex); } } public static T Remove<T>(this System.Enum type, T value) { try { return (T)(object)(((int)(object)type & ~(int)(object)value)); } catch (Exception ex) { throw new ArgumentException( string.Format( "Could not remove value from enumerated type '{0}'.", typeof(T).Name ), ex); } } }} Then they are used like the following SomeType value = SomeType.Grapes;bool isGrapes = value.Is(SomeType.Grapes); //truebool hasGrapes = value.Has(SomeType.Grapes); //truevalue = value.Add(SomeType.Oranges);value = value.Add(SomeType.Apples);value = value.Remove(SomeType.Grapes);bool hasOranges = value.Has(SomeType.Oranges); //truebool isApples = value.Is(SomeType.Apples); //falsebool hasGrapes = value.Has(SomeType.Grapes); //false
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/93744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15328/" ] }
93,770
For deployment reasons, I am trying to use IJW to wrap a C# assembly in C++ instead of using a COM Callable Wrapper. I've done it on other projects, but on this one, I am getting an EEFileLoadException. Any help would be appreciated! Managed C++ wrapper code (this is in a DLL): extern "C" __declspec(dllexport) IMyObject* CreateMyObject(void){ //this class references c# in the constructor return new CMyWrapper( );}extern "C" __declspec(dllexport) void DeleteMyObject(IMyObject* pConfigFile){ delete pConfigFile;}extern "C" __declspec(dllexport) void TestFunction(void){ ::MessageBox(NULL, _T("My Message Box"), _T("Test"), MB_OK);} Test Code (this is an EXE): typedef void* (*CreateObjectPtr)();typedef void (*TestFunctionPtr)();int _tmain testwrapper(int argc, TCHAR* argv[], TCHAR* envp[]){ HMODULE hModule = ::LoadLibrary(_T("MyWrapper")); _ASSERT(hModule != NULL); PVOID pFunc1 = ::GetProcAddress(hModule, "TestFunction"); _ASSERT(pFunc1 != NULL); TestFunctionPtr pTest = (TestFunctionPtr)pFunc1; PVOID pFunc2 = ::GetProcAddress(hModule, "CreateMyObject"); _ASSERT(pFunc2 != NULL); CreateObjectPtr pCreateObjectFunc = (CreateObjectPtr)pFunc2; (*pTest)(); //this successfully pops up a message box (*pCreateObjectFunc)(); //this tosses an EEFileLoadException return 0;} For what it's worth, the Event Log reports the following:.NET Runtime version 2.0.50727.143 - Fatal Execution Engine Error (79F97075) (80131506) Unfortunately, Microsoft has no information on that error.
The problem was where the DLLs were located. c:\dlls\managed.dll c:\dlls\wrapper.dll c:\exe\my.exe I confirmed this by copying managed.dll into c:\exe and it worked without issue. Apparently, the CLR won't look for managed DLLs in the path of the unmanaged DLL and will only look for it where the executable is. (or in the GAC). For reasons not worth going into, this is the structure I need, which meant that I needed to give the CLR a hand in located the managed dll. See code below: AssemblyResolver.h: /// <summary>/// Summary for AssemblyResolver/// </summary>public ref class AssemblyResolver{public:static Assembly^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args ){ Console::WriteLine( "Resolving..." ); Assembly^ thisAssembly = Assembly::GetExecutingAssembly(); String^ thisPath = thisAssembly->Location; String^ directory = Path::GetDirectoryName(thisPath); String^ pathToManagedAssembly = Path::Combine(directory, "managed.dll"); Assembly^ newAssembly = Assembly::LoadFile(pathToManagedAssembly); return newAssembly;}}; Wrapper.cpp: #include "AssemblyResolver.h"extern "C" __declspec(dllexport) IMyObject* CreateMyObject(void){ try { AppDomain^ currentDomain = AppDomain::CurrentDomain; currentDomain->AssemblyResolve += gcnew ResolveEventHandler( AssemblyResolver::MyResolveEventHandler ); return new CMyWrapper( ); } catch(System::Exception^ e) { System::Console::WriteLine(e->Message); return NULL; }}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/93770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066/" ] }
93,773
I was looking at DataMapper , which appeared at first glance to use the ActiveRecord ORM pattern. Other people said that it uses the DataMapper and/or the Domain Object pattern. What is the difference between those patterns?
The main difference between the two patterns is this: In the ActiveRecord you have one domain object that both knows all the business logic and how to save/update itself in the database, user.getLinkToProfile() and User::find(1), User::save(user) In the DataMapper pattern you have one domain object that holds all the business logic, for exmaple user.getLinkToProfile() (or something similar) but knows nothing about the database in question, in addition to this you have a mapper-object that is responsible for saving, updating, selecting, etc. user objects from the database which would have UserMapper::find(1), UserMapper.save(user) DataMapper is potentially more complex then ActiveRecord but it's a lot easier to develop your domain model and database asynchronous then with ActiveRecord.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/93773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17076/" ] }
93,834
I was recently working on an application that sent and received messages over Ethernet and Serial. I was then tasked to add the monitoring of DIO discretes. I throught, "No reason to interrupt the main thread which is involved in message processing, I'll just create another thread that monitors DIO." This decision, however, proved to be poor . Sometimes the main thread would be interrupted between a Send and a Receive serial message. This interruption would disrupt the timing and alas, messages would be lost (forever). I found another way to monitor the DIO without using another thread and Ethernet and Serial communication were restored to their correct functionality. The whole fiasco, however, got me thinking. Are their any general guidelines about when not to use multiple-threads and/or does anyone have anymore examples of situations when using multiple-threads is not a good idea? **EDIT:Based on your comments and after scowering the internet for information, I have composed a blog post entitled When is multi-threading not a good idea?
On a single processor machine and a desktop application, you use multi threads so you don't freeze the app but for nothing else really. On a single processor server and a web based app, no need for multi threading because the web server handles most of it. On a multi-processor machine and desktop app, you are suggested to use multi threads and parallel programming. Make as many threads as there are processors. On a multi-processor server and a web based app, no need again for multi threads because the web server handles it. In total, if you use multiple threads for other than un-freezing desktop apps and any other generic answer, you will make the app slower if you have a single core machine due to the threads interrupting each other. Why? Because of the hardware switches. It takes time for the hardware to switch between threads in total. On a multi-core box, go ahead and use 1 thread for each core and you will greatly see a ramp up.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25/" ] }
93,853
I have seen this problem arise in many different circumstances and would like to get the best practices for fixing / debugging it on StackOverflow. To use a real world example this occurred to me this morning: expected announcement.rb to define Announcement The class worked fine in development, testing and from a production console, but failed from in a production Mongrel. Here's the class: class Announcement < ActiveRecord::Base has_attachment :content_type => 'audio/mp3', :storage => :s3end The issue I would like addressed in the answers is not so much solving this specific problem, but how to properly debug to get Rails to give you a meaningful error as expected x.rb to define X.rb' is often a red herring... Edit (3 great responses so far, each w/ a partial solution ) Debugging: From Joe Van Dyk: Try accessing the model via a console on the environment / instance that is causing the error (in the case above: script/console production then type in 'Announcement'. From Otto: Try setting a minimal plugin set via an initializer, eg: config.plugins = [ :exception_notification, :ssl_requirement, :all ] then re-enable one at a time. Specific causes: From Ian Terrell: if you're using attachment_fu make sure you have the correct image processor installed. attachment_fu will require it even if you aren't attaching an image. From Otto: make sure you didn't name a model that conflicts with a built-in Rails class, eg: Request. From Josh Lewis: make sure you don't have duplicated class or module names somewhere in your application (or Gem list).
That is a tricky one. What generally works for me is to run "script/console production" on the production server, and type in: Announcement That will usually give you a better error message. But you said you already tried that?
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4748/" ] }
93,879
The located assembly's manifest definition does not match the assembly reference getting this when running nunit through ncover. Any idea?
This is a mismatch between assemblies: a DLL referenced from an assembly doesn't have a method signature that's expected. Clean the solution, rebuild everything, and try again. Also, be careful if this is a reference to something that's in the GAC; it could be that something somewhere is pointing to an incorrect version. Make sure (through the Properties of each reference) that the correct version is chosen or that Specific Version is set false.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/93879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
93,900
I have this workspace downloaded off the web and I try running it on a tomcat server from a fresh installation of Eclipse Ganymede. This particular project came with its own workspace. When I select Tomcat v6.0 I get a message Cannot create a server using the selected type Older tomcat versions are available, though. I guess I have to recreate some configuration setting. The question is which one? This seems to be some odd error as creating a new dynamic web project lets me configure tomcat for both of them
I had a similar problem, but my solution is a little simpler. The problem was causesd by renaming the original folder that was referenced by the server definition. Go to Window/Preferences/Server/Runtime Environments, remove the broken reference. Then, click 'Add' to create a new reference, select the appropriate tomcat version, click next and you'll see the incorrect path reference. Fix it. Move on.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/93900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10523/" ] }
93,930
Simple question: What Python GUI API's are out there and what are the advantages of any given API? I'm not looking for a religious war here, I'm just wanting to get a good handle on all that is out there in terms of Python GUI APIs.
Here's a good list.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145/" ] }
93,932
We are getting an error in a VB6 application that sends data back and forth over TCP sockets. We get a runtime error "out of string space". Has anyone seen this or have any thoughts on why this would happen? It seems like we are hitting some VB6 threshhold so any other thoughts would be helpful as well.
As others have pointed out, every string concatenation in VB will allocate a new string and then copy the data over and then de-allocate the original once it can. In a loop this can cause issues. To work around this you can create a simple StringBuilder class like this one: Option ExplicitPrivate data As StringPrivate allocLen As LongPrivate currentPos As LongPublic Function Text() As String Text = Left(data, currentPos)End FunctionPublic Function Length() As Long Length = currentPosEnd FunctionPublic Sub Add(s As String) Dim newLen As Long newLen = Len(s) If ((currentPos + newLen) > allocLen) Then data = data & Space((currentPos + newLen)) allocLen = Len(data) End If Mid(data, currentPos + 1, newLen) = s currentPos = currentPos + newLenEnd SubPrivate Sub Class_Initialize() data = Space(10240) allocLen = Len(data) currentPos = 1End Sub This class will minimize the number of string allocations by forcing the string to be built with spaces in it and then overwriting the spaces as needed. It re-allocates to roughly double its size when it finds that it does not have enough space pre-initialized. The Text method will return the portion of the string that is actually used.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/93932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ] }
93,976
How do you check if a one-character String is a letter - including any letters with accents? I had to work this out recently, so I'll answer it myself, after the recent VB6 question reminded me.
Just checking if a letter is in A-Z because that doesn't include letters with accents or letters in other alphabets. I found out that you can use the regular expression class for 'Unicode letter', or one of its case-sensitive variations: string.matches("\\p{L}"); // Unicode letterstring.matches("\\p{Lu}"); // Unicode upper-case letter You can also do this with Character class: Character.isLetter(character); but that is less convenient if you need to check more than one letter.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/93976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2670/" ] }
93,989
In .NET, what's the best way to prevent multiple instances of an app from running at the same time? And if there's no "best" technique, what are some of the caveats to consider with each solution?
Use Mutex. One of the examples above using GetProcessByName has many caveats. Here is a good article on the subject: http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx [STAThread]static void Main() { using(Mutex mutex = new Mutex(false, "Global\\" + appGuid)) { if(!mutex.WaitOne(0, false)) { MessageBox.Show("Instance already running"); return; } Application.Run(new Form1()); }}private static string appGuid = "c0a76b5a-12ab-45c5-b9d9-d693faa6e7b9";
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/93989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5682/" ] }
94,011
Here is my problem: I've got a dialog with some parameters that the user can change (via a spinner for example). Each time one of these parameters is changed, I launch a thread to update a 3D view according to the new parameter value. If the user changes another value (or the same value again by clicking many times on the spinner arrow) while the first thread is working, I would like to abort the first thread (and the update of the 3D view) and launch a new one with the latest parameter value. How can I do something like that? PS: There is no loop in the run() method of my thread, so checking for a flag is not an option: the thread updating the 3D view basically only calls a single method that is very long to execute. I can't add any flag in this method asking to abort either as I do not have access to its code.
Try interrupt() as some have said to see if it makes any difference to your thread. If not, try destroying or closing a resource that will make the thread stop. That has a chance of being a little better than trying to throw Thread.stop() at it. If performance is tolerable, you might view each 3D update as a discrete non-interruptible event and just let it run through to conclusion, checking afterward if there's a new latest update to perform. This might make the GUI a little choppy to users, as they would be able to make five changes, then see the graphical results from how things were five changes ago, then see the result of their latest change. But depending on how long this process is, it might be tolerable, and it would avoid having to kill the thread. Design might look like this: boolean stopFlag = false;Object[] latestArgs = null;public void run() { while (!stopFlag) { if (latestArgs != null) { Object[] args = latestArgs; latestArgs = null; perform3dUpdate(args); } else { Thread.sleep(500); } }}public void endThread() { stopFlag = true;}public void updateSettings(Object[] args) { latestArgs = args;}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2612/" ] }
94,037
How can I convert a character to its ASCII code using JavaScript? For example: get 10 from "\n".
"\n".charCodeAt(0);
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/94037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4465/" ] }
94,101
I've typed around 75wpm for the last few years but I've always wondered how people type +100wpm. I've searched but I primarily find typing tutors that teach you to type.. not teach you to type faster. So far the only tip I've come across is to learn dvorak. Are there exercises or tips to help break through the 75wpm wall?
Setting yourself up in an ergonomic typing position is a good start. Take a look at the diagram here - notice the arms in a straight line, feet on the floor, etc. In my experience most people tend to slow down when they get to unusual keys - numbers, symbols, punctuation, etc, so maybe some focused practice on those key combinations? practice typing out long strings of numbers and symbols, maybe try to use some Perl code as your copy-page :)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17177/" ] }
94,141
I have the following script, where the first and third document.writeline are static and the second is generated : <script language="javascript" type="text/javascript">document.write("<script language='javascript' type='text/javascript' src='before.js'><\/sc" + "ript>");document.write("<script language='javascript' type='text/javascript'>alert('during');<\/sc" + "ript>");document.write("<script language='javascript' type='text/javascript' src='after.js'><\/sc" + "ript>");</script> Firefox and Chrome will display before , during and after , while Internet Explorer first shows during and only then does it show before and after . I've come across an article that states that I'm not the first to encounter this, but that hardly makes me feel any better. Does anyone know how I can set the order to be deterministic in all browsers, or hack IE to work like all the other, sane browsers do? Caveats : The code snippet is a very simple repro. It is generated on the server and the second script is the only thing that changes. It's a long script and the reason there are two scripts before and after it are so that the browser will cache them and the dynamic part of the code will be as small as possible. It may also appears many times in the same page with different generated code.
No, this is the behavior of Internet Explorer. If you attach scripts dynamically, IE, Firefox, and Chrome will all download the scripts in an asynchronous manner. Firefox and Chrome will wait till all of the async requests return and then will execute the scripts in the order that they are attached in the DOM but IE executes the scripts in the order that they are returned over the wire. Since the alert takes less time to "retrieve" than an external javascript file, that likely explains the behavior that you are seeing. From Kristoffer Henriksson's post on the subject of asynchronous script loading : In this scenario IE and Firefox will download both scripts but Internet Explorer will also execute them in the order they finish downloading in whereas Firefox downloads them asynchronously but still executes them in the order they are attached in the DOM. In Internet Explorer this means your scripts cannot have dependancies on one another as the execution order will vary depending on network traffic, caches, etc. Consider using a Javascript loader. It will let you specify script dependencies and order of execution while also loading your scripts asynchronously for speed as well as smoothing out some of the browser differences. This is a pretty good overview of a few of them: Essential JavaScript: the top five script loaders . I've used both RequireJS and LabJS. In my opinion, LabJS is a little less opinionated.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4979/" ] }
94,153
I am attempting to use the 'tempfile' module for manipulating and creating text files. Once the file is ready I want to save it to disk. I thought it would be as simple as using 'shutil.copy'. However, I get a 'permission denied' IOError: >>> import tempfile, shutil>>> f = tempfile.TemporaryFile(mode ='w+t')>>> f.write('foo')>>> shutil.copy(f.name, 'bar.txt')Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> shutil.copy(f.name, 'bar.txt') File "C:\Python25\lib\shutil.py", line 80, in copy copyfile(src, dst) File "C:\Python25\lib\shutil.py", line 46, in copyfile fsrc = open(src, 'rb')IOError: [Errno 13] Permission denied: 'c:\\docume~1\\me\\locals~1\\temp\\tmpvqq3go'>>> Is this not intended when using the 'tempfile' library? Is there a better way to do this? (Maybe I am overlooking something very trivial)
The file you create with TemporaryFile or NamedTemporaryFile is automatically removed when it's closed, which is why you get an error. If you don't want this, you can use mkstemp instead (see the docs for tempfile ). >>> import tempfile, shutil, os>>> fd, path = tempfile.mkstemp()>>> os.write(fd, 'foo')>>> os.close(fd)>>> shutil.copy(path, 'bar.txt')>>> os.remove(path)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/94153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ] }
94,171
In C#.Net WPF During UserControl.Load -> What is the best way of showing a whirling circle / 'Loading' Indicator on the UserControl until it has finished gathering data and rendering it's contents?
I generally would create a layout like this: <Grid> <Grid x:Name="MainContent" IsEnabled="False"> ... </Grid> <Grid x:Name="LoadingIndicatorPanel"> ... </Grid></Grid> Then I load the data on a worker thread, and when it's finished I update the UI under the "MainContent" grid and enable the grid, then set the LoadingIndicatorPanel's Visibility to Collapsed. I'm not sure if this is what you were asking or if you wanted to know how to show an animation in the loading label. If it's the animation you're after, please update your question to be more specific.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/352728/" ] }
94,177
I have the following XAML: <TextBlock Text="{Binding ElementName=EditListBox, Path=SelectedItems.Count}" Margin="0,0,5,0"/><TextBlock Text="items selected"> <TextBlock.Style> <Style TargetType="{x:Type TextBlock}"> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=EditListBox, Path=SelectedItems.Count}" Value="1"> <Setter Property="TextBlock.Text" Value="item selected"></Setter> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style></TextBlock> The first text block happily changes with SelectedItems.Count, showing 0,1,2, etc. The datatrigger on the second block never seems to fire to change the text. Any thoughts?
The DataTrigger is firing but the Text field for your second TextBlock is hard-coded as "items selected" so it won't be able to change. To see it firing, you can remove Text="items selected". Your problem is a good candidate for using a ValueConverter instead of DataTrigger . Here's how to create and use the ValueConverter to get it to set the Text to what you want. Create this ValueConverter: public class CountToSelectedTextConverter : IValueConverter{ #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if ((int)value == 1) return "item selected"; else return "items selected"; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion} Add the namespace reference to your the assembly the converter is located: xmlns:local="clr-namespace:ValueConverterExample" Add the converter to your resources: <Window.Resources> <local:CountToSelectedTextConverter x:Key="CountToSelectedTextConverter"/></Window.Resources> Change your second textblock to: <TextBlock Text="{Binding ElementName=EditListBox, Path=SelectedItems.Count, Converter={StaticResource CountToSelectedTextConverter}}"/>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2284/" ] }
94,226
I have 4 versions of file A.txt in my subversion repository, say: A.txt.r1, A.txt.r2, A.txt.r3 and A.txt.r4. My working copy of the file is r4 and I want to switch back to r2. I don't want to use " svn update -r 2 A.txt " because this will delete all the revisions after r2, namely r3 and r4. So is there any way that I update my working copy to r2 and still having the option to switch to r3 and r4 later? Put it another way, I want to still be able to see all 4 revisions by using " svn log A.txt " after doing the update.
To make a new revision of A.txt that is equal to revision 2: svn up -r HEADsvn merge -r HEAD:2 A.txtsvn commit Also see the description in Undoing changes .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8203/" ] }
94,227
C++ is all about memory ownership - aka ownership semantics . It is the responsibility of the owner of a chunk of dynamically allocated memory to release that memory. So the question really becomes who owns the memory. In C++ ownership is documented by the type a raw pointer is wrapped inside thus in a good (IMO) C++ program it is very rare ( rare , not never ) to see raw pointers passed around (as raw pointers have no inferred ownership thus we can not tell who owns the memory and thus without careful reading of the documentation you can't tell who is responsible for ownership). Conversely, it is rare to see raw pointers stored in a class each raw pointer is stored within its own smart pointer wrapper. ( N.B.: If you don't own an object you should not be storing it because you can not know when it will go out of scope and be destroyed.) So the question: What type of ownership semantic have people come across? What standard classes are used to implement those semantics? In what situations do you find them useful? Lets keep 1 type of semantic ownership per answer so they can be voted up and down individually. Summary: Conceptually, smart pointers are simple and a naive implementation is easy. I have seen many attempted implementations, but invariably they are broken in some way that is not obvious to casual use and examples. Thus I recommend always using well tested smart pointers from a library rather than rolling your own. std::auto_ptr or one of the Boost smart pointers seem to cover all my needs. std::auto_ptr<T> : Single person owns the object. Transfer of ownership is allowed. Usage: This allows you to define interfaces that show the explicit transfer of ownership. boost::scoped_ptr<T> Single person owns the object. Transfer of ownership is NOT allowed. Usage: Used to show explicit ownership. Object will be destroyed by destructor or when explicitly reset. boost::shared_ptr<T> ( std::tr1::shared_ptr<T> ) Multiple ownership. This is a simple reference counted pointer. When the reference count reaches zero, the object is destroyed. Usage: When an object can have multiple owers with a lifetime that can not be determined at compile time. boost::weak_ptr<T> : Used with shared_ptr<T> in situations where a cycle of pointers may happen. Usage: Used to stop cycles from retaining objects when only the cycle is maintaining a shared refcount.
For me, these 3 kinds cover most of my needs: shared_ptr - reference-counted, deallocation when the counter reaches zero weak_ptr - same as above, but it's a 'slave' for a shared_ptr , can't deallocate auto_ptr - when the creation and deallocation happen inside the same function, or when the object has to be considered one-owner-only ever. When you assign one pointer to another, the second 'steals' the object from the first. I have my own implementation for these, but they are also available in Boost . I still pass objects by reference ( const whenever possible), in this case the called method must assume the object is alive only during the time of call. There's another kind of pointer that I use that I call hub_ptr . It's when you have an object that must be accessible from objects nested in it (usually as a virtual base class). This could be solved by passing a weak_ptr to them, but it doesn't have a shared_ptr to itself. As it knows these objects wouldn't live longer than him, it passes a hub_ptr to them (it's just a template wrapper to a regular pointer).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14065/" ] }
94,274
This has been a problem that I haven't been able to figure out for sometime. Preventing the second instance is trivial and has many methods, however, bringing back the already running process isn't. I would like to: Minimized: Undo the minimize and bring the running instance to the front. Behind other windows: Bring the application to the front. The language I am using this in is VB.NET and C#.
I found this code to be useful. It does the detection and optional activation of an existing application: http://www.codeproject.com/KB/cs/cssingprocess.aspx
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8505/" ] }
94,305
Lets say I have the option of identifying a code path to take on the basis of a string comparison or else iffing the type: Which is quicker and why? switch(childNode.Name){ case "Bob": break; case "Jill": break; case "Marko": break;}if(childNode is Bob){}elseif(childNode is Jill){}else if(childNode is Marko){} Update: The main reason I ask this is because the switch statement is perculiar about what counts as a case. For example it wont allow you to use variables, only constants which get moved to the main assembly. I assumed it had this restriction due to some funky stuff it was doing. If it is only translating to elseifs (as one poster commented) then why are we not allowed variables in case statements? Caveat: I am post-optimising. This method is called many times in a slow part of the app.
Greg's profile results are great for the exact scenario he covered, but interestingly, the relative costs of the different methods change dramatically when considering a number of different factors including the number of types being compared, and the relative frequency and any patterns in the underlying data. The simple answer is that nobody can tell you what the performance difference is going to be in your specific scenario, you will need to measure the performance in different ways yourself in your own system to get an accurate answer. The If/Else chain is an effective approach for a small number of type comparisons, or if you can reliably predict which few types are going to make up the majority of the ones that you see. The potential problem with the approach is that as the number of types increases, the number of comparisons that must be executed increases as well. if I execute the following: int value = 25124;if(value == 0) ...else if (value == 1) ...else if (value == 2) ......else if (value == 25124) ... each of the previous if conditions must be evaluated before the correct block is entered. On the other hand switch(value) { case 0:...break; case 1:...break; case 2:...break; ... case 25124:...break;} will perform one simple jump to the correct bit of code. Where it gets more complicated in your example is that your other method uses a switch on strings rather than integers which gets a little more complicated. At a low level, strings can't be switched on in the same way that integer values can so the C# compiler does some magic to make this work for you. If the switch statement is "small enough" (where the compiler does what it thinks is best automatically) switching on strings generates code that is the same as an if/else chain. switch(someString) { case "Foo": DoFoo(); break; case "Bar": DoBar(); break; default: DoOther; break;} is the same as: if(someString == "Foo") { DoFoo();} else if(someString == "Bar") { DoBar();} else { DoOther();} Once the list of items in the dictionary gets "big enough" the compiler will automatically create an internal dictionary that maps from the strings in the switch to an integer index and then a switch based on that index. It looks something like this (Just imagine more entries than I am going to bother to type) A static field is defined in a "hidden" location that is associated with the class containing the switch statement of type Dictionary<string, int> and given a mangled name //Make sure the dictionary is loadedif(theDictionary == null) { //This is simplified for clarity, the actual implementation is more complex // in order to ensure thread safety theDictionary = new Dictionary<string,int>(); theDictionary["Foo"] = 0; theDictionary["Bar"] = 1;}int switchIndex;if(theDictionary.TryGetValue(someString, out switchIndex)) { switch(switchIndex) { case 0: DoFoo(); break; case 1: DoBar(); break; }} else { DoOther();} In some quick tests that I just ran, the If/Else method is about 3x as fast as the switch for 3 different types (where the types are randomly distributed). At 25 types the switch is faster by a small margin (16%) at 50 types the switch is more than twice as fast. If you are going to be switching on a large number of types, I would suggest a 3rd method: private delegate void NodeHandler(ChildNode node);static Dictionary<RuntimeTypeHandle, NodeHandler> TypeHandleSwitcher = CreateSwitcher();private static Dictionary<RuntimeTypeHandle, NodeHandler> CreateSwitcher(){ var ret = new Dictionary<RuntimeTypeHandle, NodeHandler>(); ret[typeof(Bob).TypeHandle] = HandleBob; ret[typeof(Jill).TypeHandle] = HandleJill; ret[typeof(Marko).TypeHandle] = HandleMarko; return ret;}void HandleChildNode(ChildNode node){ NodeHandler handler; if (TaskHandleSwitcher.TryGetValue(Type.GetRuntimeType(node), out handler)) { handler(node); } else { //Unexpected type... }} This is similar to what Ted Elliot suggested, but the usage of runtime type handles instead of full type objects avoids the overhead of loading the type object through reflection. Here are some quick timings on my machine: Testing 3 iterations with 5,000,000 data elements (mode=Random) and 5 typesMethod Time % of optimalIf/Else 179.67 100.00TypeHandleDictionary 321.33 178.85TypeDictionary 377.67 210.20Switch 492.67 274.21Testing 3 iterations with 5,000,000 data elements (mode=Random) and 10 typesMethod Time % of optimalIf/Else 271.33 100.00TypeHandleDictionary 312.00 114.99TypeDictionary 374.33 137.96Switch 490.33 180.71Testing 3 iterations with 5,000,000 data elements (mode=Random) and 15 typesMethod Time % of optimalTypeHandleDictionary 312.00 100.00If/Else 369.00 118.27TypeDictionary 371.67 119.12Switch 491.67 157.59Testing 3 iterations with 5,000,000 data elements (mode=Random) and 20 typesMethod Time % of optimalTypeHandleDictionary 335.33 100.00TypeDictionary 373.00 111.23If/Else 462.67 137.97Switch 490.33 146.22Testing 3 iterations with 5,000,000 data elements (mode=Random) and 25 typesMethod Time % of optimalTypeHandleDictionary 319.33 100.00TypeDictionary 371.00 116.18Switch 483.00 151.25If/Else 562.00 175.99Testing 3 iterations with 5,000,000 data elements (mode=Random) and 50 typesMethod Time % of optimalTypeHandleDictionary 319.67 100.00TypeDictionary 376.67 117.83Switch 453.33 141.81If/Else 1,032.67 323.04 On my machine at least, the type handle dictionary approach beats all of the others for anything over 15 different types when the distributionof the types used as input to the method is random. If on the other hand, the input is composed entirely of the type that is checked first in the if/else chain that method is much faster: Testing 3 iterations with 5,000,000 data elements (mode=UniformFirst) and 50 typesMethod Time % of optimalIf/Else 39.00 100.00TypeHandleDictionary 317.33 813.68TypeDictionary 396.00 1,015.38Switch 403.00 1,033.33 Conversely, if the input is always the last thing in the if/else chain, it has the opposite effect: Testing 3 iterations with 5,000,000 data elements (mode=UniformLast) and 50 typesMethod Time % of optimalTypeHandleDictionary 317.67 100.00Switch 354.33 111.54TypeDictionary 377.67 118.89If/Else 1,907.67 600.52 If you can make some assumptions about your input, you might get the best performance from a hybrid approach where you perform if/else checks for the few types that are most common, and then fall back to a dictionary-driven approach if those fail.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/94305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1143/" ] }
94,331
I use the recent Ganymede release of Eclipse, specifically the distro for Java EE and web developers. I have installed a few additional plugins (e.g. Subclipse, Spring, FindBugs) and removed all the Mylyn plugins. I don't do anything particularly heavy-duty within Eclipse such as starting an app server or connecting to databases, yet for some reason, after several hours use I see that Eclipse is using close to 500MB of memory. Does anybody know why Eclipse uses so much memory (leaky?), and more importantly, if there's anything I can do to improve this?
I don't know about Eclipse specifically, I use IntelliJ which also suffers from memory growth (whether you're actively using it or not!). Anyway, in IntelliJ, I couldn't eliminate the problem, but I did slow down the memory growth by playing with the runtime VM options. You could try resetting these in Eclipse and see if they make a difference. You can edit the VM options in the eclipse.ini file in your eclipse folder. I found that (in IntelliJ) the garbage collector settings had the most effect on how fast the memory grows. My settings are: -Xms128m-Xmx512m-XX:MaxPermSize=120m-XX:MaxGCPauseMillis=10-XX:MaxHeapFreeRatio=70-XX:+UseConcMarkSweepGC-XX:+CMSIncrementalMode-XX:+CMSIncrementalPacing (See http://piotrga.wordpress.com/2006/12/12/intellij-and-garbage-collection/ for an explanation of the individual settings). As you can see, I'm more concerned with avoiding long pauses during editting than actuial memory usage but you could use this as a start.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ] }
94,342
I have a string which contain tags in the form < tag > . Is there an easy way for me to programmatically replace instances of these tags with special ascii characters? e.g. replace a tag like "< tab >" with the ascii equivelent of '/t' ?
string s = "...<tab>...";s = s.Replace("<tab>", "\t");
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ] }
94,361
What are the best practices for using Java's @Override annotation and why? It seems like it would be overkill to mark every single overridden method with the @Override annotation. Are there certain programming situations that call for using the @Override and others that should never use the @Override ?
Use it every time you override a method for two benefits. Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten. Additionally, in Java 1.6 you can use it to mark when a method implements an interface for the same benefits. I think it would be better to have a separate annotation (like @Implements ), but it's better than nothing.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/94361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6180/" ] }
94,382
I'm using gvim on Windows. In my _vimrc I've added: set shell=powershell.exeset shellcmdflag=-cset shellpipe=>set shellredir=>function! Test() echo system("dir -name")endfunctioncommand! -nargs=0 Test :call Test() If I execute this function (:Test) I see nonsense characters (non number/letter ASCII characters). If I use cmd as the shell, it works (without the -name), so the problem seems to be with getting output from powershell into vim. Interestingly, this works great: :!dir -name As does this: :r !dir -name UPDATE: confirming behavior mentioned by David If you execute the set commands mentioned above in the _vimrc, :Test outputs nonsense. However, if you execute them directly in vim instead of in the _vimrc, :Test works as expected. Also, I've tried using iconv in case it was an encoding problem: :echo iconv( system("dir -name"), "unicode", &enc ) But this didn't make any difference. I could be using the wrong encoding types though. Anyone know how to make this work?
It is a bit of a hack, but the following works in Vim 7.2. Notice, I am running Powershell within a CMD session. if has("win32") set shell=cmd.exe set shellcmdflag=/c\ powershell.exe\ -NoLogo\ -NoProfile\ -NonInteractive\ -ExecutionPolicy\ RemoteSigned set shellpipe=| set shellredir=>endiffunction! Test() echo system("dir -name")endfunction Tested with the following... :!dir -name :call Test()
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/94382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4407/" ] }
94,445
I'm generating a self-signed SSL certificate to protect my server's admin section, and I keep getting this message from OpenSSL: unable to write 'random state' What does this mean? This is on an Ubuntu server. I have upgraded libssl to fix the recent security vulnerability .
In practice, the most common reason for this happening seems to be that the .rnd file in your home directory is owned by root rather than your account. The quick fix: sudo rm ~/.rnd For more information, here's the entry from the OpenSSL FAQ : Sometimes the openssl command line utility does not abort with a "PRNG not seeded" error message, but complains that it is "unable to write 'random state'". This message refers to the default seeding file (see previous answer). A possible reason is that no default filename is known because neither RANDFILE nor HOME is set. (Versions up to 0.9.6 used file ".rnd" in the current directory in this case, but this has changed with 0.9.6a.) So I would check RANDFILE, HOME, and permissions to write to those places in the filesystem. If everything seems to be in order, you could try running with strace and see what exactly is going on.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/94445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17965/" ] }
94,456
I have an instance of a System.Drawing.Bitmap and would like to make it available to my WPF app in the form of a System.Windows.Media.Imaging.BitmapImage . What would be the best approach for this?
How about loading it from MemoryStream? using(MemoryStream memory = new MemoryStream()){ bitmap.Save(memory, ImageFormat.Png); memory.Position = 0; BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = memory; bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.EndInit();}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/94456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2723/" ] }
94,488
More specifically, when the exception contains custom objects which may or may not themselves be serializable. Take this example: public class MyException : Exception{ private readonly string resourceName; private readonly IList<string> validationErrors; public MyException(string resourceName, IList<string> validationErrors) { this.resourceName = resourceName; this.validationErrors = validationErrors; } public string ResourceName { get { return this.resourceName; } } public IList<string> ValidationErrors { get { return this.validationErrors; } }} If this Exception is serialized and de-serialized, the two custom properties ( ResourceName and ValidationErrors ) will not be preserved. The properties will return null . Is there a common code pattern for implementing serialization for custom exception?
Base implementation, without custom properties SerializableExceptionWithoutCustomProperties.cs: namespace SerializableExceptions{ using System; using System.Runtime.Serialization; [Serializable] // Important: This attribute is NOT inherited from Exception, and MUST be specified // otherwise serialization will fail with a SerializationException stating that // "Type X in Assembly Y is not marked as serializable." public class SerializableExceptionWithoutCustomProperties : Exception { public SerializableExceptionWithoutCustomProperties() { } public SerializableExceptionWithoutCustomProperties(string message) : base(message) { } public SerializableExceptionWithoutCustomProperties(string message, Exception innerException) : base(message, innerException) { } // Without this constructor, deserialization will fail protected SerializableExceptionWithoutCustomProperties(SerializationInfo info, StreamingContext context) : base(info, context) { } }} Full implementation, with custom properties Complete implementation of a custom serializable exception ( MySerializableException ), and a derived sealed exception ( MyDerivedSerializableException ). The main points about this implementation are summarized here: You must decorate each derived class with the [Serializable] attribute —This attribute is not inherited from the base class, and if it is not specified, serialization will fail with a SerializationException stating that "Type X in Assembly Y is not marked as serializable." You must implement custom serialization . The [Serializable] attribute alone is not enough — Exception implements ISerializable which means your derived classes must also implement custom serialization. This involves two steps: Provide a serialization constructor . This constructor should be private if your class is sealed , otherwise it should be protected to allow access to derived classes. Override GetObjectData() and make sure you call through to base.GetObjectData(info, context) at the end, in order to let the base class save its own state. SerializableExceptionWithCustomProperties.cs: namespace SerializableExceptions{ using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Security.Permissions; [Serializable] // Important: This attribute is NOT inherited from Exception, and MUST be specified // otherwise serialization will fail with a SerializationException stating that // "Type X in Assembly Y is not marked as serializable." public class SerializableExceptionWithCustomProperties : Exception { private readonly string resourceName; private readonly IList<string> validationErrors; public SerializableExceptionWithCustomProperties() { } public SerializableExceptionWithCustomProperties(string message) : base(message) { } public SerializableExceptionWithCustomProperties(string message, Exception innerException) : base(message, innerException) { } public SerializableExceptionWithCustomProperties(string message, string resourceName, IList<string> validationErrors) : base(message) { this.resourceName = resourceName; this.validationErrors = validationErrors; } public SerializableExceptionWithCustomProperties(string message, string resourceName, IList<string> validationErrors, Exception innerException) : base(message, innerException) { this.resourceName = resourceName; this.validationErrors = validationErrors; } [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] // Constructor should be protected for unsealed classes, private for sealed classes. // (The Serializer invokes this constructor through reflection, so it can be private) protected SerializableExceptionWithCustomProperties(SerializationInfo info, StreamingContext context) : base(info, context) { this.resourceName = info.GetString("ResourceName"); this.validationErrors = (IList<string>)info.GetValue("ValidationErrors", typeof(IList<string>)); } public string ResourceName { get { return this.resourceName; } } public IList<string> ValidationErrors { get { return this.validationErrors; } } [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } info.AddValue("ResourceName", this.ResourceName); // Note: if "List<T>" isn't serializable you may need to work out another // method of adding your list, this is just for show... info.AddValue("ValidationErrors", this.ValidationErrors, typeof(IList<string>)); // MUST call through to the base class to let it save its own state base.GetObjectData(info, context); } }} DerivedSerializableExceptionWithAdditionalCustomProperties.cs: namespace SerializableExceptions{ using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Security.Permissions; [Serializable] public sealed class DerivedSerializableExceptionWithAdditionalCustomProperty : SerializableExceptionWithCustomProperties { private readonly string username; public DerivedSerializableExceptionWithAdditionalCustomProperty() { } public DerivedSerializableExceptionWithAdditionalCustomProperty(string message) : base(message) { } public DerivedSerializableExceptionWithAdditionalCustomProperty(string message, Exception innerException) : base(message, innerException) { } public DerivedSerializableExceptionWithAdditionalCustomProperty(string message, string username, string resourceName, IList<string> validationErrors) : base(message, resourceName, validationErrors) { this.username = username; } public DerivedSerializableExceptionWithAdditionalCustomProperty(string message, string username, string resourceName, IList<string> validationErrors, Exception innerException) : base(message, resourceName, validationErrors, innerException) { this.username = username; } [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] // Serialization constructor is private, as this class is sealed private DerivedSerializableExceptionWithAdditionalCustomProperty(SerializationInfo info, StreamingContext context) : base(info, context) { this.username = info.GetString("Username"); } public string Username { get { return this.username; } } public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } info.AddValue("Username", this.username); base.GetObjectData(info, context); } }} Unit Tests MSTest unit tests for the three exception types defined above. UnitTests.cs: namespace SerializableExceptions{ using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class UnitTests { private const string Message = "The widget has unavoidably blooped out."; private const string ResourceName = "Resource-A"; private const string ValidationError1 = "You forgot to set the whizz bang flag."; private const string ValidationError2 = "Wally cannot operate in zero gravity."; private readonly List<string> validationErrors = new List<string>(); private const string Username = "Barry"; public UnitTests() { validationErrors.Add(ValidationError1); validationErrors.Add(ValidationError2); } [TestMethod] public void TestSerializableExceptionWithoutCustomProperties() { Exception ex = new SerializableExceptionWithoutCustomProperties( "Message", new Exception("Inner exception.")); // Save the full ToString() value, including the exception message and stack trace. string exceptionToString = ex.ToString(); // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { // "Save" object state bf.Serialize(ms, ex); // Re-use the same stream for de-serialization ms.Seek(0, 0); // Replace the original exception with de-serialized one ex = (SerializableExceptionWithoutCustomProperties)bf.Deserialize(ms); } // Double-check that the exception message and stack trace (owned by the base Exception) are preserved Assert.AreEqual(exceptionToString, ex.ToString(), "ex.ToString()"); } [TestMethod] public void TestSerializableExceptionWithCustomProperties() { SerializableExceptionWithCustomProperties ex = new SerializableExceptionWithCustomProperties(Message, ResourceName, validationErrors); // Sanity check: Make sure custom properties are set before serialization Assert.AreEqual(Message, ex.Message, "Message"); Assert.AreEqual(ResourceName, ex.ResourceName, "ex.ResourceName"); Assert.AreEqual(2, ex.ValidationErrors.Count, "ex.ValidationErrors.Count"); Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], "ex.ValidationErrors[0]"); Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], "ex.ValidationErrors[1]"); // Save the full ToString() value, including the exception message and stack trace. string exceptionToString = ex.ToString(); // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { // "Save" object state bf.Serialize(ms, ex); // Re-use the same stream for de-serialization ms.Seek(0, 0); // Replace the original exception with de-serialized one ex = (SerializableExceptionWithCustomProperties)bf.Deserialize(ms); } // Make sure custom properties are preserved after serialization Assert.AreEqual(Message, ex.Message, "Message"); Assert.AreEqual(ResourceName, ex.ResourceName, "ex.ResourceName"); Assert.AreEqual(2, ex.ValidationErrors.Count, "ex.ValidationErrors.Count"); Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], "ex.ValidationErrors[0]"); Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], "ex.ValidationErrors[1]"); // Double-check that the exception message and stack trace (owned by the base Exception) are preserved Assert.AreEqual(exceptionToString, ex.ToString(), "ex.ToString()"); } [TestMethod] public void TestDerivedSerializableExceptionWithAdditionalCustomProperty() { DerivedSerializableExceptionWithAdditionalCustomProperty ex = new DerivedSerializableExceptionWithAdditionalCustomProperty(Message, Username, ResourceName, validationErrors); // Sanity check: Make sure custom properties are set before serialization Assert.AreEqual(Message, ex.Message, "Message"); Assert.AreEqual(ResourceName, ex.ResourceName, "ex.ResourceName"); Assert.AreEqual(2, ex.ValidationErrors.Count, "ex.ValidationErrors.Count"); Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], "ex.ValidationErrors[0]"); Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], "ex.ValidationErrors[1]"); Assert.AreEqual(Username, ex.Username); // Save the full ToString() value, including the exception message and stack trace. string exceptionToString = ex.ToString(); // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { // "Save" object state bf.Serialize(ms, ex); // Re-use the same stream for de-serialization ms.Seek(0, 0); // Replace the original exception with de-serialized one ex = (DerivedSerializableExceptionWithAdditionalCustomProperty)bf.Deserialize(ms); } // Make sure custom properties are preserved after serialization Assert.AreEqual(Message, ex.Message, "Message"); Assert.AreEqual(ResourceName, ex.ResourceName, "ex.ResourceName"); Assert.AreEqual(2, ex.ValidationErrors.Count, "ex.ValidationErrors.Count"); Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], "ex.ValidationErrors[0]"); Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], "ex.ValidationErrors[1]"); Assert.AreEqual(Username, ex.Username); // Double-check that the exception message and stack trace (owned by the base Exception) are preserved Assert.AreEqual(exceptionToString, ex.ToString(), "ex.ToString()"); } }}
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/94488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5975/" ] }
94,502
I have a simple database table called "Entries": class CreateEntries < ActiveRecord::Migration def self.up create_table :entries do |t| t.string :firstName t.string :lastName #etc. t.timestamps end end def self.down drop_table :entries endend How do I write a handler that will return the contents of the Entries table as a CSV file (ideally in a way that it will automatically open in Excel)? class EntriesController < ApplicationController def getcsv @entries = Entry.find( :all ) # ??? NOW WHAT ???? endend
There is a plugin called FasterCSV that handles this wonderfully.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/94502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4540/" ] }
94,528
In other words may one use /<tag[^>]*>.*?<\/tag>/ regex to match the tag html element which does not contain nested tag elements? For example (lt.html): <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html> <head> <title>greater than sign in attribute value</title> </head> <body> <div>1</div> <div title=">">2</div> </body></html> Regex: $ perl -nE"say $1 if m~<div[^>]*>(.*?)</div>~" lt.html And screen-scraper: #!/usr/bin/env pythonimport sysimport BeautifulSoupsoup = BeautifulSoup.BeautifulSoup(sys.stdin)for div in soup.findAll('div'): print div.string$ python lt.py <lt.html Both give the same output: 1">2 Expected output: 12 w3c says: Attribute values are a mixture of text and character references, except with the additional restriction that the text cannot contain an ambiguous ampersand.
Yes, it is allowed (W3C Validator accepts it, only issues a warning). Unescaped < and > are also allowed inside comments, so such simple regexp can be fooled. If BeautifulSoup doesn't handle this, it could be a bug or perhaps a conscious design decision to make it more resilient to missing closing quotes in attributes.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279/" ] }
94,542
I have a handful of projects that all use one project for the data model. Each of these projects has its own applicationContext.xml file with a bunch of repetitive data stuff within it. I'd like to have a modelContext.xml file and another for my ui.xml, etc. Can I do this?
From the Spring Docs (v 2.5.5 Section 3.2.2.1.) : It can often be useful to split up container definitions into multiple XML files. One way to then load an application context which is configured from all these XML fragments is to use the application context constructor which takes multiple Resource locations. With a bean factory, a bean definition reader can be used multiple times to read definitions from each file in turn. Generally, the Spring team prefers the above approach, since it keeps container configuration files unaware of the fact that they are being combined with others. An alternate approach is to use one or more occurrences of the element to load bean definitions from another file (or files). Let's look at a sample: <import resource="services.xml"/><import resource="resources/messageSource.xml"/><import resource="/resources/themeSource.xml"/><bean id="bean1" class="..."/><bean id="bean2" class="..."/> In this example, external bean definitions are being loaded from 3 files, services.xml, messageSource.xml, and themeSource.xml. All location paths are considered relative to the definition file doing the importing, so services.xml in this case must be in the same directory or classpath location as the file doing the importing, while messageSource.xml and themeSource.xml must be in a resources location below the location of the importing file. As you can see, a leading slash is actually ignored, but given that these are considered relative paths, it is probably better form not to use the slash at all. The contents of the files being imported must be valid XML bean definition files according to the Spring Schema or DTD, including the top level element.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ] }
94,556
We've got a multiproject we're trying to run Cobertura test coverage reports on as part of our mvn site build. I can get Cobertura to run on the child projects, but it erroneously reports 0% coverage, even though the reports still highlight the lines of code that were hit by the unit tests. We are using mvn 2.0.8. I have tried running mvn clean site , mvn clean site:stage and mvn clean package site . I know the tests are running, they show up in the surefire reports (both the txt/xml and site reports). Am I missing something in the configuration? Does Cobertura not work right with multiprojects? This is in the parent .pom: <build> <pluginManagement> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <inherited>true</inherited> <executions> <execution> <id>clean</id> <goals> <goal>clean</goal> </goals> </execution> </executions> </plugin> </plugins> </pluginManagement></build><reporting> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <inherited>true</inherited> </plugin> </plugins></reporting> I've tried running it with and without the following in the child .poms: <reporting> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> </plugin> </plugins></reporting> I get this in the output of the build: ...[INFO] [cobertura:instrument][INFO] Cobertura 1.9 - GNU GPL License (NO WARRANTY) - See COPYRIGHT fileInstrumenting 3 files to C:\workspaces\sandbox\CommonJsf\target\generated-classes\coberturaCobertura: Saved information on 3 classes.Instrument time: 186ms[INFO] Instrumentation was successful....[INFO] Generating "Cobertura Test Coverage" report.[INFO] Cobertura 1.9 - GNU GPL License (NO WARRANTY) - See COPYRIGHT fileCobertura: Loaded information on 3 classes.Report time: 481ms[INFO] Cobertura Report generation was successful. And the report looks like this:
From the Spring Docs (v 2.5.5 Section 3.2.2.1.) : It can often be useful to split up container definitions into multiple XML files. One way to then load an application context which is configured from all these XML fragments is to use the application context constructor which takes multiple Resource locations. With a bean factory, a bean definition reader can be used multiple times to read definitions from each file in turn. Generally, the Spring team prefers the above approach, since it keeps container configuration files unaware of the fact that they are being combined with others. An alternate approach is to use one or more occurrences of the element to load bean definitions from another file (or files). Let's look at a sample: <import resource="services.xml"/><import resource="resources/messageSource.xml"/><import resource="/resources/themeSource.xml"/><bean id="bean1" class="..."/><bean id="bean2" class="..."/> In this example, external bean definitions are being loaded from 3 files, services.xml, messageSource.xml, and themeSource.xml. All location paths are considered relative to the definition file doing the importing, so services.xml in this case must be in the same directory or classpath location as the file doing the importing, while messageSource.xml and themeSource.xml must be in a resources location below the location of the importing file. As you can see, a leading slash is actually ignored, but given that these are considered relative paths, it is probably better form not to use the slash at all. The contents of the files being imported must be valid XML bean definition files according to the Spring Schema or DTD, including the top level element.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/765/" ] }
94,591
I can never remember the number. I need a memory rule.
It's 2,147,483,647. Easiest way to memorize it is via a tattoo.
{ "score": 13, "source": [ "https://Stackoverflow.com/questions/94591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15054/" ] }
94,610
I have a Silverlight 2 application that is consuming a WCF service. As such, it uses asynchronous callbacks for all the calls to the methods of the service. If the service is not running, or it crashes, or the network goes down, etc before or during one of these calls, an exception is generated as you would expect. The problem is, I don't know how to catch this exception. Because it is an asynchronous call, I can't wrap my begin call with a try/catch block and have it pick up an exception that happens after the program has moved on from that point. Because the service proxy is automatically generated, I can't put a try/catch block on each and every generated function that calls EndInvoke (where the exception actually shows up). These generated functions are also surrounded by External Code in the call stack, so there's nowhere else in the stack to put a try/catch either. I can't put the try/catch in my callback functions, because the exception occurs before they would get called. There is an Application_UnhandledException function in my App.xaml.cs, which captures all unhandled exceptions. I could use this, but it seems like a messy way to do it. I'd rather reserve this function for the truly unexpected errors (aka bugs) and not end up with code in this function for every circumstance I'd like to deal with in a specific way. Am I missing an obvious solution? Or am I stuck using Application_UnhandledException? [Edit] As mentioned below, the Error property is exactly what I was looking for. What is throwing me for a loop is that the fact that the exception is thrown and appears to be uncaught, yet execution is able to continue. It triggers the Application_UnhandledException event and causes VS2008 to break execution, but continuing in the debugger allows execution to continue. It's not really a problem, it just seems odd.
I check the Error property of the event args in the service method completed event handler. I haven't had issues with the event handler not being called. In the case where the server goes down, the call takes a few seconds then comes back with a ProtocolException in the Error property. Assuming you have tried this and your callback really never gets called, you might look into customizing the generated proxy class. See this article .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17986/" ] }
94,674
How come this doesn't work (operating on an empty select list <select id="requestTypes"></select> $(function() { $.getJSON("/RequestX/GetRequestTypes/", showRequestTypes); } ); function showRequestTypes(data, textStatus) { $.each(data, function() { var option = new Option(this.RequestTypeName, this.RequestTypeID); // Use Jquery to get select list element var dropdownList = $("#requestTypes"); if ($.browser.msie) { dropdownList.add(option); } else { dropdownList.add(option, null); } } ); } But this does: Replace: var dropdownList = $("#requestTypes"); With plain old javascript: var dropdownList = document.getElementById("requestTypes");
$("#requestTypes") returns a jQuery object that contains all the selected elements. You are attempting to call the add() method of an individual element, but instead you are calling the add() method of the jQuery object, which does something very different. In order to access the DOM element itself, you need to treat the jQuery object as an array and get the first item out of it, by using $("#requestTypes")[0] .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17729/" ] }
94,696
I know it happens sometime before Load, but during what event exactly?
It's loaded into memory between init and load. See t his article for a full break down of the page lifecycle.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/94696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9991/" ] }
94,767
I'm attempting to debug my web application with FireFox3. However, when a JSON feed comes from my application, Firefox wants to open up the "application/json" in a new program. Is there a way to configure FireFox3 to handle JSON like regular text files and open up the JSON in the current tab? Thanks.
Try the Open in browser extension . [edit 30.05.2010 - updated the link]
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ] }
94,779
I am working on a client proposal and they will need to upgrade their network infrastructure to support hosting an ASP.NET application. Essentially, I need to estimate peak usage for a system with a known quantity of users (currently 250). A simple answer like "you'll need a dedicated T1 line" would probably suffice, but I'd like to have data to back it up. Another question referenced NetLimiter, which looks pretty slick for getting a sense of what's being used. My general thought is that I'll fire the web app up and use the system like I would anticipate it be used at the customer, really at a leisurely pace, over a certain time span, and then multiply the bandwidth usage by the number of users and divide by the time. This doesn't seem very scientific. It may be good enough for a proposal, but I'd like to see if there's a better way. I know there are load tools available for testing web application performance, but it seems like these would not accurately simulate peak user load for bandwidth testing purposes (too much at once). The platform is Windows/ASP.NET and the application is hosted within SharePoint (MOSS 2007).
Try the Open in browser extension . [edit 30.05.2010 - updated the link]
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7301/" ] }
94,792
I've been using Lisp on and off for a while but I'm starting to get more serious about doing some "real" work in Lisp. I'm a huge Vim fan and was wondering how I can be most productive using Vim as my editor for Lisp development. Plugins, work flow suggestions, etc. are all welcome. Please don't say "use emacs" as I've already ramped up on Vim and I'm really enjoying it as an editor.
Limp aims to be a fully featured Common Lisp IDE for Vim. It defaults to SBCL, but can be changed to support most other implementations by replacing "sbcl" for your favourite lisp, in the file /usr/local/limp/latest/bin/lisp.sh When discussing Lisp these days, it is commonly assumed to be Common Lisp, the language standardized by ANSI X3J13 (see the HyperSpec , and Practical Common Lisp for a good textbook) with implementations such as GNU Clisp, SBCL, CMUCL, AllegroCL, and many others. Back to Limp. There are other solutions that are more light-weight, or try to do other things, but I believe in providing an environment that gives you things like bracket matching, highlighting, documentation lookup, i.e. making it a turn-key solution as much as possible. In the Limp repository you'll find some of the previous work of the SlimVim project, namely the ECL (Embeddable Common Lisp) interface, merged with later releases (7.1); Simon has also made patches to 7.2 available yet to be merged. The ECL interface is documented in if_ecl.txt . Short-term work is to do said merging with 7.2 and submit a patch to vim_dev to get it merged into the official Vim tree. Which leads us to the long-term plans: having Lisp directly in Vim will make it convenient to start working on a SWANK front-end (the part of SLIME that runs in your Lisp, with slime.el being the part that runs in the editor - the frontend). And somewhere in between, it is likely that all of Limp will be rewritten in Common Lisp using the ECL interface, making Limp easier to maintain (VimScript isn't my favourite) and being easier for users to customize. The official Limp site goes down from time to time, but as pointed out, the download at Vim.org should always work, and the support groups limp-devel and limp-user are hosted with Google Groups. Don't hesitate to join if you feel you need a question answered, or perhaps even want to join in on development. Most of the discussion takes place on the limp-devel list. If you're into IRC, I'm in #limp on irc.freenode.net as 'tic'. Good luck!
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/94792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9434/" ] }
94,794
Compared to Simple memory access Disk access Memory access on another computer(on the same network) Disk access on another computer(on the same network) in C++ on windows.
relative timings (shouldn't be off by more than a factor of 100 ;-) memory-access in cache = 1 function call/return in cache = 2 memory-access out of cache = 10 .. 300 disk access = 1000 .. 1e8 (amortized depends upon the number of bytes transferred) depending mostly upon seek times the transfer itself can be pretty fast involves at least a few thousand ops, since the user/system threshold must be crossed at least twice; an I/O request must be scheduled, the result must be written back; possibly buffers are allocated... network calls = 1000 .. 1e9 (amortized depends upon the number of bytes transferred) same argument as with disk i/o the raw transfer speed can be quite high, but some process on the other computer must do the actual work
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/94794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15054/" ] }
94,875
I've recently come across a problem which requires at least a basic degree of image processing, can I do this in Python, and if so, with what?
The best-known library is PIL . However if you are simply doing basic manipulation, you are probably better off with the Python bindings for ImageMagick , which will be a good deal more efficient than writing the transforms in Python.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/94875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145/" ] }
94,884
The system I work on here was written before .net 2.0 and didn't have the benefit of generics. It was eventually updated to 2.0, but none of the code was refactored due to time constraints. There are a number of places where the code uses ArraysLists etc. that store things as objects. From performance perspective, how important change the code to using generics? I know from a perfomance perspective, boxing and unboxing etc., it is inefficient, but how much of a performance gain will there really be from changing it? Are generics something to use on a go forward basis, or it there enough of a performance change that a conscience effort should be made to update old code?
Technically the performance of generics is, as you say, better. However, unless performance is hugely important AND you've already optimised in other areas you're likely to get MUCH better improvements by spending your time elsewhere. I would suggest: use generics going forward. if you have solid unit tests then refactor to generics as you touch code spend other time doing refactorings/measurement that will significantly improve performance (database calls, changing data structures, etc) rather than a few milliseconds here and there. Of course there's reasons other than performance to change to generics: less error prone, since you have compile-time checking of types more readable, you don't need to cast all over the place and it's obvious what type is stored in a collection if you're using generics going forward, then it's cleaner to use them everywhere
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1942/" ] }
94,906
I'm running a SQL query on SQL Server 2005, and in addition to 2 columns being queried from the database, I'd also like to return 1 column of random numbers along with them. I tried this: select column1, column2, floor(rand() * 10000) as column3 from table1 Which kinda works, but the problem is that this query returns the same random number on every row. It's a different number each time you run the query, but it doesn't vary from row to row. How can I do this and get a new random number for each row?
I realize this is an older post... but you don't need a view. select column1, column2, ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 10000 as column3 from table1
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/94906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8409/" ] }
94,932
Our CF server occasionally stops processing mail. This is problematic, as many of our clients depend on it. We found suggestions online that mention zero-byte files in the undeliverable folder, so I created a task that removes them every three minutes. However, the stoppage has occurred again. I am looking for suggestions for diagnosing and fixing this issue. CF 8 standard Win2k3 Added: There are no errors in the mail log at the time the queue fails We have not tried to run this without using the queue, due to the large amount of mail we send Added 2: It does not seem to be a problem with any of the files in the spool folder. When we restart the mail queue, they all seem to process correctly. Added 3: We are not using attachments.
What we ended up doing: I wrote two scheduled tasks. The first checked to see if there were any messages in the queue folder older than n minues (currently set to 30). The second reset the queue every night during low usage. Unfortunately, we never really discovered why the queue would come off the rails, but it only seems to happen when we use Exchange -- other mail servers we've tried do not have this issue. Edit: I was asked to post my code, so here's the one to restart when old mail is found: <cfdirectory action="list" directory="c:\coldfusion8\mail\spool\" name="spool" sort="datelastmodified"><cfset restart = 0><cfif datediff('n', spool.datelastmodified, now()) gt 30> <cfset restart = 1></cfif><cfif restart> <cfset sFactory = CreateObject("java","coldfusion.server.ServiceFactory")> <cfset MailSpoolService = sFactory.mailSpoolService> <cfset MailSpoolService.stop()> <cfset MailSpoolService.start()></cfif>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12267/" ] }
94,935
Apparently xrange is faster but I have no idea why it's faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about for i in range(0, 20):for i in xrange(0, 20):
In Python 2.x: range creates a list, so if you do range(1, 10000000) it creates a list in memory with 9999999 elements. xrange is a sequence object that evaluates lazily. In Python 3: range does the equivalent of Python 2's xrange . To get the list, you have to explicitly use list(range(...)) . xrange no longer exists.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/94935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ] }
94,977
In C# and in Java (and possibly other languages as well), variables declared in a "try" block are not in scope in the corresponding "catch" or "finally" blocks. For example, the following code does not compile: try { String s = "test"; // (more code...)}catch { Console.Out.WriteLine(s); //Java fans: think "System.out.println" here instead} In this code, a compile-time error occurs on the reference to s in the catch block, because s is only in scope in the try block. (In Java, the compile error is "s cannot be resolved"; in C#, it's "The name 's' does not exist in the current context".) The general solution to this issue seems to be to instead declare variables just before the try block, instead of within the try block: String s;try { s = "test"; // (more code...)}catch { Console.Out.WriteLine(s); //Java fans: think "System.out.println" here instead} However, at least to me, (1) this feels like a clunky solution, and (2) it results in the variables having a larger scope than the programmer intended (the entire remainder of the method, instead of only in the context of the try-catch-finally). My question is, what were/are the rationale(s) behind this language design decision (in Java, in C#, and/or in any other applicable languages)?
Two things: Generally, Java has just 2 levels of scope: global and function. But, try/catch is an exception (no pun intended). When an exception is thrown and the exception object gets a variable assigned to it, that object variable is only available within the "catch" section and is destroyed as soon as the catch completes. (and more importantly). You can't know where in the try block the exception was thrown. It may have been before your variable was declared. Therefore it is impossible to say what variables will be available for the catch/finally clause. Consider the following case, where scoping is as you suggested: try{ throw new ArgumentException("some operation that throws an exception"); string s = "blah";}catch (e as ArgumentException){ Console.Out.WriteLine(s);} This clearly is a problem - when you reach the exception handler, s will not have been declared. Given that catches are meant to handle exceptional circumstances and finallys must execute, being safe and declaring this a problem at compile time is far better than at runtime.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/94977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12484/" ] }
94,997
Suppose you have a program which reads from a socket. How do you keep the download rate below a certain given threshold?
At the application layer (using a Berkeley socket style API) you just watch the clock, and read or write data at the rate you want to limit at. If you only read 10kbps on average, but the source is sending more than that, then eventually all the buffers between it and you will fill up. TCP/IP allows for this, and the protocol will arrange for the sender to slow down (at the application layer, probably all you need to know is that at the other end, blocking write calls will block, nonblocking writes will fail, and asynchronous writes won't complete, until you've read enough data to allow it). At the application layer you can only be approximate - you can't guarantee hard limits such as "no more than 10 kb will pass a given point in the network in any one second". But if you keep track of what you've received, you can get the average right in the long run.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/94997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9107/" ] }
95,007
I've been mystified by the R quantile function all day. I have an intuitive notion of how quantiles work, and an M.S. in stats, but boy oh boy, the documentation for it is confusing to me. From the docs: Q[i](p) = (1 - gamma) x[j] + gamma x[j+1], I'm with it so far. For a type i quantile, it's an interpolation between x[j] and x [j+1], based on some mysterious constant gamma where 1 <= i <= 9, (j-m)/n <= p < (j-m+1)/ n, x[j] is the jth order statistic, n is the sample size, and m is a constant determined by the sample quantile type. Here gamma depends on the fractional part of g = np+m-j. So, how calculate j? m? For the continuous sample quantile types (4 through 9), the sample quantiles can be obtained by linear interpolation between the kth order statistic and p(k): p(k) = (k - alpha) / (n - alpha - beta + 1), where α and β are constants determined by the type. Further, m = alpha + p(1 - alpha - beta), and gamma = g. Now I'm really lost. p, which was a constant before, is now apparently a function. So for Type 7 quantiles, the default... Type 7 p(k) = (k - 1) / (n - 1). In this case, p(k) = mode[F(x[k])]. This is used by S. Anyone want to help me out? In particular I'm confused by the notation of p being a function and a constant, what the heck m is, and now to calculate j for some particular p . I hope that based on the answers here, we can submit some revised documentation that better explains what is going on here. quantile.R source code or type: quantile.default
You're understandably confused. That documentation is terrible. I had to go back to the paper its based on (Hyndman, R.J.; Fan, Y. (November 1996). "Sample Quantiles in Statistical Packages". American Statistician 50 (4): 361–365. doi:10.2307/2684934 ) to get an understanding. Let's start with the first problem. where 1 <= i <= 9, (j-m)/n <= p < (j-m+1)/ n, x[j] is the jth order statistic, n is the sample size, and m is a constant determined by the sample quantile type. Here gamma depends on the fractional part of g = np+m-j. The first part comes straight from the paper, but what the documentation writers omitted was that j = int(pn+m) . This means Q[i](p) only depends on the two order statistics closest to being p fraction of the way through the (sorted) observations. (For those, like me, who are unfamiliar with the term, the "order statistics" of a series of observations is the sorted series.) Also, that last sentence is just wrong. It should read Here gamma depends on the fractional part of np+m, g = np+m-j As for m that's straightforward. m depends on which of the 9 algorithms was chosen. So just like Q[i] is the quantile function, m should be considered m[i] . For algorithms 1 and 2, m is 0, for 3, m is -1/2, and for the others, that's in the next part. For the continuous sample quantile types (4 through 9), the sample quantiles can be obtained by linear interpolation between the kth order statistic and p(k): p(k) = (k - alpha) / (n - alpha - beta + 1), where α and β are constants determined by the type. Further, m = alpha + p(1 - alpha - beta), and gamma = g. This is really confusing. What the documentation calls p(k) is not the same as the p from before. p(k) is the plotting position . In the paper, the authors write it as p k , which helps. Especially since in the expression for m , the p is the original p , and the m = alpha + p * (1 - alpha - beta) . Conceptually, for algorithms 4-9, the points ( p k , x[k] ) are interpolated to get the solution ( p , Q[i](p) ). Each algorithm only differs in the algorithm for the p k . As for the last bit, R is just stating what S uses. The original paper gives a list of 6 "desirable properties for a sample quantile" function, and states a preference for #8 which satisfies all by 1. #5 satisfies all of them, but they don't like it on other grounds (it's more phenomenological than derived from principles). #2 is what non-stat geeks like myself would consider the quantiles and is what's described in wikipedia. BTW, in response to dreeves answer , Mathematica does things significantly differently. I think I understand the mapping. While Mathematica's is easier to understand, (a) it's easier to shoot yourself in the foot with nonsensical parameters, and (b) it can't do R's algorithm #2. (Here's Mathworld's Quantile page , which states Mathematica can't do #2, but gives a simpler generalization of all the other algorithms in terms of four parameters.)
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/95007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15842/" ] }
95,055
I am trying to write a simple networked chat program in Java. I have almost no networking experience. I was wondering what resources I should begin looking at (beside here of course). Sticking with the core Java API would be best for now.
I found a great tutorial into networking and java from sun's own website: http://download.oracle.com/javase/tutorial/networking/TOC.html The socket section even has you write a mini client / server chat demo.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/95055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ] }
95,098
Using the method Application.Restart() in C# should restart the current application: but it seems that this is not always working. Is there a reason for this Issue, can somebody tell me, why it doesn't work all the time?
There could be a lot of reasons for this. It's not that the method doesn't work; rather, many times programmers forget that they've put something in their code that would stop the application from automatically shutting down, or starting up. Two examples: The Closing event on a form can stop an app's shutdown If you're doing checking for an already-running process, the old one may not be closing fast enough to allow the new one to start up. Check your code for gotchas like that. If you're seeing this behaviour within a blank application, then that's more likely to be a problem with the actual function than your code. Check Microsoft's sourcecode of application restart .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/95098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17558/" ] }
95,112
I have a long running process in VB6 that I want to finish before executing the next line of code. How can I do that? Built-in function? Can I control how long to wait? Trivial example: Call ExternalLongRunningProcessCall DoOtherStuff How do I delay 'DoOtherStuff'?
VB.Net: I would use a WaitOne event handle. VB 6.0: I've seen a DoEvents Loop. Do If isSomeCheckCondition() Then Exit Do DoEventsLoop Finally, You could just sleep: Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)Sleep 10000
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/95112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ] }
95,163
I'm new to .Net and I'm trying to understand the basics first. What is the difference between MSIL and Java bytecode?
First off let me say that I don't think that the subtle differences between Java bytecode and MSIL is something that should bother a novice .NET developer. They both serve the same purpose of defining an abstract target machine which is a layer above the physical machine being used in the end. MSIL and Java bytecode are very similar, in fact there is was a tool called Grasshopper which translates MSIL to Java bytecode, I was part of the development team for Grasshopper so I can share a bit of my (faded) knowledge.Please note that I stopped working on this around when .NET framework 2.0 came out so some of these things may not be true any more (if so please leave a comment and I'll correct it). .NET allows user defined types that have value semantics as apposed to the regular reference semantics ( struct ). .NET supports unsigned types, this makes the instruction set a bit richer. Java includes the exception specification of methods in the bytecode. Although exception specification is usually only enforced by the compiler, it may be enforced by the JVM if a class loader other than the default one is used. .NET generics are expressed in IL while Java generics only use type erasure . .NET attributes have no equivalent in Java (is this still true?). .NET enums are not much more than wrappers around integer types while Java enums are pretty much fully fledged classes (thanks to Internet Friend for commenting). .NET has out and ref parameters. There are other language differences but most of them are not expressed at the byte code level, for example, if memory serves, Java's non- static inner classes (which do not exist in .NET) are not a bytecode feature, the compiler generates an additional argument to the inner class's constructor and passes the outer object. The same is true for .NET lambda expressions.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/95163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18055/" ] }
95,181
I have: class MyClass extends MyClass2 implements Serializable { //...} In MyClass2 is a property that is not serializable. How can I serialize (and de-serialize) this object? Correction: MyClass2 is, of course, not an interface but a class.
As someone else noted, chapter 11 of Josh Bloch's Effective Java is an indispensible resource on Java Serialization. A couple points from that chapter pertinent to your question: assuming you want to serialize the state of the non-serializable field in MyClass2, that field must be accessible to MyClass, either directly or through getters and setters. MyClass will have to implement custom serialization by providing readObject and writeObject methods. the non-serializable field's Class must have an API to allow getting it's state (for writing to the object stream) and then instantiating a new instance with that state (when later reading from the object stream.) per Item 74 of Effective Java, MyClass2 must have a no-arg constructor accessible to MyClass, otherwise it is impossible for MyClass to extend MyClass2 and implement Serializable. I've written a quick example below illustrating this. class MyClass extends MyClass2 implements Serializable{ public MyClass(int quantity) { setNonSerializableProperty(new NonSerializableClass(quantity)); } private void writeObject(java.io.ObjectOutputStream out) throws IOException{ // note, here we don't need out.defaultWriteObject(); because // MyClass has no other state to serialize out.writeInt(super.getNonSerializableProperty().getQuantity()); } private void readObject(java.io.ObjectInputStream in) throws IOException { // note, here we don't need in.defaultReadObject(); // because MyClass has no other state to deserialize super.setNonSerializableProperty(new NonSerializableClass(in.readInt())); }}/* this class must have no-arg constructor accessible to MyClass */class MyClass2 { /* this property must be gettable/settable by MyClass. It cannot be final, therefore. */ private NonSerializableClass nonSerializableProperty; public void setNonSerializableProperty(NonSerializableClass nonSerializableProperty) { this.nonSerializableProperty = nonSerializableProperty; } public NonSerializableClass getNonSerializableProperty() { return nonSerializableProperty; }}class NonSerializableClass{ private final int quantity; public NonSerializableClass(int quantity){ this.quantity = quantity; } public int getQuantity() { return quantity; }}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/95181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12860/" ] }
95,183
How do I create an index on the date part of DATETIME field? mysql> SHOW COLUMNS FROM transactionlist;+-------------------+------------------+------+-----+---------+----------------+| Field | Type | Null | Key | Default | Extra |+-------------------+------------------+------+-----+---------+----------------+| TransactionNumber | int(10) unsigned | NO | PRI | NULL | auto_increment || WagerId | int(11) | YES | MUL | 0 | || TranNum | int(11) | YES | MUL | 0 | || TranDateTime | datetime | NO | | NULL | || Amount | double | YES | | 0 | || Action | smallint(6) | YES | | 0 | || Uid | int(11) | YES | | 1 | || AuthId | int(11) | YES | | 1 | |+-------------------+------------------+------+-----+---------+----------------+8 rows in set (0.00 sec) TranDateTime is used to save the date and time of a transaction as it happens My Table has over 1,000,000 records in it and the statement SELECT * FROM transactionlist where date(TranDateTime) = '2008-08-17' takes a long time. EDIT: Have a look at this blog post on " Why MySQL’s DATETIME can and should be avoided "
If I remember correctly, that will run a whole table scan because you're passing the column through a function. MySQL will obediently run the function for each and every column, bypassing the index since the query optimizer can't really know the results of the function. What I would do is something like: SELECT * FROM transactionlist WHERE TranDateTime BETWEEN '2008-08-17' AND '2008-08-17 23:59:59.999999'; That should give you everything that happened on 2008-08-17.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/95183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17560/" ] }
95,213
Simple example: I want to have some items on a page (like divs or table rows), and I want to let the user click on them to select them. That seems easy enough in jQuery. To save which items a user clicks on with no server-side post backs, I was thinking a cookie would be a simple way to get this done. Is this assumption that a cookie is OK in this case, correct? If it is correct, does the jQuery API have some way to read/write cookie information that is nicer than the default JavaScript APIs?
The default JavaScript "API" for setting a cookie is as easy as: document.cookie = 'mycookie=valueOfCookie;expires=DateHere;path=/' Use the jQuery cookie plugin like: $.cookie('mycookie', 'valueOfCookie')
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/95213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5619/" ] }
95,222
I found this link http://artis.imag.fr/~Xavier.Decoret/resources/glsl-mode/ , but there isn't a lot of description around it, aside that it's "simple". Ideally, I'd like an extension to CcMode that can do it, or at least a mode that can handle auto-styling and has similar shortcuts to CcMode. If there isn't one, any good elisp references to help me get started writing it myself would be greatly appreciated. EDIT: David's response prompted me to take a closer look at glsl-mode.el, and it is in fact based on cc-mode, so it's exactly what I was looking for in the first place.
Add the following code to your ~/.emacs file. (autoload 'glsl-mode "glsl-mode" nil t)(add-to-list 'auto-mode-alist '("\\.vert\\'" . glsl-mode))(add-to-list 'auto-mode-alist '("\\.frag\\'" . glsl-mode)) Put the file http://artis.imag.fr/~Xavier.Decoret/resources/glsl-mode/glsl-mode.el somewhere on your emacs path. You can eval (print load-path) in your scratch buffer to get the list of possible locations. If you don't have write access to any of those, you can append another location to load-paths by adding (setq load-path (cons "~/.emacs.d" load-path)) to your ~/.emacs file.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/95222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13894/" ] }
95,257
I just want a quick way (and preferably not using a while loop)of createing a table of every date between date @x and date @y so I can left outer join to some stats tables, some of which will have no records for certain days in between, allowing me to mark missing days with a 0
Strictly speaking this doesn't exactly answer your question, but its pretty neat. Assuming you can live with specifying the number of days after the start date, then using a Common Table Expression gives you: WITH numbers ( n ) AS ( SELECT 1 UNION ALL SELECT 1 + n FROM numbers WHERE n < 500 ) SELECT DATEADD(day,n-1,'2008/11/01') FROM numbers OPTION ( MAXRECURSION 500 )
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/95257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5055/" ] }
95,286
I have the following configuration, but I have not able to find any documentation on how to set a maximum backup files on date rolling style. I know that you can do this with size rolling style by using the maxSizeRollBackups. <appender name="AppLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="mylog.log" /> <appendToFile value="true" /> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <rollingStyle value="Date" /> <datePattern value=".yyMMdd.'log'" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%d %-5p %c - %m%n" /> </layout></appender>
You can't. from log4net SDK Reference RollingFileAppender Class CAUTION A maximum number of backup files when rolling on date/time boundaries is not supported.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/95286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4191/" ] }
95,419
Had a conversation with a coworker the other day about this. There's the obvious using a constructor, but what are the other ways there?
There are four different ways to create objects in java: A . Using new keyword This is the most common way to create an object in java. Almost 99% of objects are created in this way. MyObject object = new MyObject(); B . Using Class.forName() If we know the name of the class & if it has a public default constructor we can create an object in this way. MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance(); C . Using clone() The clone() can be used to create a copy of an existing object. MyObject anotherObject = new MyObject();MyObject object = (MyObject) anotherObject.clone(); D . Using object deserialization Object deserialization is nothing but creating an object from its serialized form. ObjectInputStream inStream = new ObjectInputStream(anInputStream );MyObject object = (MyObject) inStream.readObject(); You can read them from here .
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/95419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1247/" ] }
95,492
Given a date/time as an array of (year, month, day, hour, minute, second), how would you convert it to epoch time, i.e., the number of seconds since 1970-01-01 00:00:00 GMT? Bonus question: If given the date/time as a string, how would you first parse it into the (y,m,d,h,m,s) array?
This is the simplest way to get unix time: use Time::Local;timelocal($second,$minute,$hour,$day,$month-1,$year); Note the reverse order of the arguments and that January is month 0.For many more options, see the DateTime module from CPAN. As for parsing, see the Date::Parse module from CPAN. If you really need to get fancy with date parsing, the Date::Manip may be helpful, though its own documentation warns you away from it since it carries a lot of baggage (it knows things like common business holidays, for example) and other solutions are much faster. If you happen to know something about the format of the date/times you'll be parsing then a simple regular expression may suffice but you're probably better off using an appropriate CPAN module. For example, if you know the dates will always be in YMDHMS order, use the CPAN module DateTime::Format::ISO8601 . For my own reference, if nothing else, below is a function I use for an application where I know the dates will always be in YMDHMS order with all or part of the "HMS" part optional. It accepts any delimiters (eg, "2009-02-15" or "2009.02.15"). It returns the corresponding unix time (seconds since 1970-01-01 00:00:00 GMT) or -1 if it couldn't parse it (which means you better be sure you'll never legitimately need to parse the date 1969-12-31 23:59:59). It also presumes two-digit years XX up to "69" refer to "20XX", otherwise "19XX" (eg, "50-02-15" means 2050-02-15 but "75-02-15" means 1975-02-15). use Time::Local;sub parsedate { my($s) = @_; my($year, $month, $day, $hour, $minute, $second); if($s =~ m{^\s*(\d{1,4})\W*0*(\d{1,2})\W*0*(\d{1,2})\W*0* (\d{0,2})\W*0*(\d{0,2})\W*0*(\d{0,2})}x) { $year = $1; $month = $2; $day = $3; $hour = $4; $minute = $5; $second = $6; $hour |= 0; $minute |= 0; $second |= 0; # defaults. $year = ($year<100 ? ($year<70 ? 2000+$year : 1900+$year) : $year); return timelocal($second,$minute,$hour,$day,$month-1,$year); } return -1;}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/95492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4234/" ] }
95,500
While refactoring code and ridding myself of all those #defines that we're now taught to hate, I came across this beauty used to calculate the number of elements in a structure: #define STRUCTSIZE(s) (sizeof(s) / sizeof(*s)) Very useful as it is but can it be converted into an inline function or template? OK, ARRAYSIZE would be a better name but this is legacy code (no idea where it came from, it's at least 15 years old) so I pasted it 'as is'.
As been stated, the code actually work out the number of elements in an array, not struct. I would just write out the sizeof() division explicitly when I want it. If I were to make it a function, I would want to make it clear in its definition that it's expecting an array. template<typename T,int SIZE>inline size_t array_size(const T (&array)[SIZE]){ return SIZE;} The above is similar to xtofl's , except it guards against passing a pointer to it (that says point to a dynamically allocated array) and getting the wrong answer by mistake. EDIT : Simplified as per JohnMcG . EDIT : inline. Unfortunately, the above does not provide a compile time answer (even if the compiler does inline & optimize it to be a constant under the hood), so cannot be used as a compile time constant expression. i.e. It cannot be used as size to declare a static array. Under C++0x, this problem go away if one replaces the keyword inline by constexpr (constexpr is inline implicitly). constexpr size_t array_size(const T (&array)[SIZE]) jwfearn's solution work for compile time, but involve having a typedef which effectively "saved" the array size in the declaration of a new name. The array size is then worked out by initialising a constant via that new name. In such case, one may as well simply save the array size into a constant from the start. Martin York's posted solution also work under compile time, but involve using the non-standard typeof() operator. The work around to that is either wait for C++0x and use decltype (by which time one wouldn't actually need it for this problem as we'll have constexpr ). Another alternative is to use Boost.Typeof, in which case we'll end up with #include <boost/typeof/typeof.hpp>template<typename T>struct ArraySize{ private: static T x; public: enum { size = sizeof(T)/sizeof(*x)};};template<typename T>struct ArraySize<T*> {}; and is used by writing ArraySize<BOOST_TYPEOF(foo)>::size where foo is the name of an array.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/95500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ] }
95,510
I need my application to behave differently depending on whether Vista UAC is enabled or not. How can my application detect the state of UAC on the user's computer?
This registry key should tell you: HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System Value EnableLUA (DWORD) 1 enabled / 0 or missing disabled But that assumes you have the rights to read it. Programmatically you can try to read the user's token and guess if it's an admin running with UAC enabled (see here ). Not foolproof, but it may work. The issue here is more of a "why do you need to know" - it has bearing on the answer. Really, there is no API because from a OS behavior point of view, what matters is if the user is an administrator or not - how they choose to protect themselves as admin is their problem.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/95510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17037/" ] }
95,547
Should I catch exceptions for logging purposes? public foo(..){ try { ... } catch (Exception ex) { Logger.Error(ex); throw; }} If I have this in place in each of my layers (DataAccess, Business and WebService) it means the exception is logged several times. Does it make sense to do so if my layers are in separate projects and only the public interfaces have try/catch in them? Why? Why not? Is there a different approach I could use?
Definitely not. You should find the correct place to handle the exception (actually do something, like catch-and-not-rethrow), and then log it. You can and should include the entire stack trace of course, but following your suggestion would litter the code with try-catch blocks.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/95547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15771/" ] }
95,554
I want to override the JSON MIME type ("application/json") in Rails to ("text/x-json"). I tried to register the MIME type again in mime_types.rb but that didn't work. Any suggestions? Thanks.
This should work (in an initializer, plugin, or some similar place): Mime.send(:remove_const, :JSON)Mime::Type.register "text/x-json", :json
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/95554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ] }
95,578
I have an Oracle database backup file (.dmp) that was created with expdp . The .dmp file was an export of an entire database. I need to restore 1 of the schemas from within this dump file. I don't know the names of the schemas inside this dump file. To use impdp to import the data I need the name of the schema to load. So, I need to inspect the .dmp file and list all of the schemas in it, how do I do that? Update (2008-09-18 13:02) - More detailed information: The impdp command i'm current using is: impdp user/password@database directory=DPUMP_DIR dumpfile=EXPORT.DMP logfile=IMPORT.LOG And the DPUMP_DIR is correctly configured. SQL> SELECT directory_path2 FROM dba_directories3 WHERE directory_name = 'DPUMP_DIR';DIRECTORY_PATH-------------------------D:\directory_path\dpump_dir\ And yes, the EXPORT.DMP file is in fact in that folder. The error message I get when I run the impdp command is: Connected to: Oracle Database 10g Enterprise Edition ...ORA-31655: no data or metadata objects selected for the jobORA-39154: Objects from foreign schemas have been removed from import This error message is mostly expected. I need the impdp command be: impdp user/password@database directory=DPUMP_DIR dumpfile=EXPORT.DMP SCHEMAS=SOURCE_SCHEMA REMAP_SCHEMA=SOURCE_SCHEMA:MY_SCHEMA But to do that, I need the source schema.
impdp exports the DDL of a dmp backup to a file if you use the SQLFILE parameter . For example, put this into a text file impdp '/ as sysdba' dumpfile=<your .dmp file> logfile=import_log.txt sqlfile=ddl_dump.txt Then check ddl_dump.txt for the tablespaces, users, and schemas in the backup. According to the documentation, this does not actually modify the database: The SQL is not actually executed, and the target system remains unchanged.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/95578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12923/" ] }
95,600
The documentation indicates that the error: option function will make available: XHR instance, a status message string (in this case always error) and an optional exception object returned from the XHR instance (Book: JQuery in Action) Using the following (in the $.ajax call) I was able to determine I had a "parsererror" and a "timeout" (since I added the timeout: option) error error: function(request, error){} What are other things you evaluate in the error option? do you include the optional exception object? EDIT: one of the answers indicates all the return errors...learning more about what is of value (for debugging) in the XHR instance and exception object would be helpful This is a complete $.ajax call: $.ajax({ type: "post", url: "http://myServer/cgi-bin/broker" , dataType: "text", data: { '_service' : 'myService', '_program' : 'myProgram', 'start' : start, 'end' : end }, beforeSend: function() { $("#loading").removeClass("hide"); }, timeout: 5000, error: function(request,error) { $("#loading").addClass("hide"); if (error == "timeout") { $("#error").append("The request timed out, please resubmit"); } else { $("#error").append("ERROR: " + error); } }, success: function(request) { $("#loading").addClass("hide"); var t = eval( "(" + request + ")" ) ; } // End success}); // End ajax method Thanks for the input
Looking at the jQuery source code, there are four returned statuses, in additon to success : timeout - when your specifiedtimeout is exceeded error - http error, like 404 notmodified - when requestedresource was not modified since lastrequest parsererror - when an xml/json response isbad
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/95600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ] }
95,631
Suppose I want to open a file in an existing Emacs session using su or sudo , without dropping down to a shell and doing sudoedit or sudo emacs . One way to do this is C-x C-f /sudo::/path/to/file but this requires an expensive round-trip through SSH . Is there a more direct way? [EDIT] @JBB is right. I want to be able to invoke su / sudo to save as well as open. It would be OK (but not ideal) to re-authorize when saving. What I'm looking for is variations of find-file and save-buffer that can be "piped" through su / sudo .
The nice thing about Tramp is that you only pay for that round-trip to SSH when you open the first file. Sudo then caches your credentials, and Emacs saves a handle, so that subsequent sudo-opened files take much less time. I haven't found the extra time it takes to save burdening, either. It's fast enough, IMO.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/95631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ] }
95,635
What does a JIT compiler specifically do as opposed to a non-JIT compiler? Can someone give a succinct and easy to understand description?
A JIT compiler runs after the program has started and compiles the code (usually bytecode or some kind of VM instructions) on the fly (or just-in-time, as it's called) into a form that's usually faster, typically the host CPU's native instruction set. A JIT has access to dynamic runtime information whereas a standard compiler doesn't and can make better optimizations like inlining functions that are used frequently. This is in contrast to a traditional compiler that compiles all the code to machine language before the program is first run. To paraphrase, conventional compilers build the whole program as an EXE file BEFORE the first time you run it. For newer style programs, an assembly is generated with pseudocode (p-code). Only AFTER you execute the program on the OS (e.g., by double-clicking on its icon) will the (JIT) compiler kick in and generate machine code (m-code) that the Intel-based processor or whatever will understand.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/95635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6264/" ] }
95,642
Long story short, I have a substantial Python application that, among other things, does outcalls to "losetup", "mount", etc. on Linux. Essentially consuming system resources that must be released when complete. If my application crashes, I want to ensure these system resources are properly released. Does it make sense to do something like the following? def main(): # TODO: main application entry point passdef cleanup(): # TODO: release system resources here passif __name__ == "__main__": try: main() except: cleanup() raise Is this something that is typically done? Is there a better way? Perhaps the destructor in a singleton class?
I like top-level exception handlers in general (regardless of language). They're a great place to cleanup resources that may not be immediately related to resources consumed inside the method that throws the exception. It's also a fantastic place to log those exceptions if you have such a framework in place. Top-level handlers will catch those bizarre exceptions you didn't plan on and let you correct them in the future, otherwise, you may never know about them at all. Just be careful that your top-level handler doesn't throw exceptions!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/95642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9188/" ] }
95,655
There are various ways to maintain user state using in web development. These are the ones that I can think of right now: Query String Cookies Form Methods (Get and Post) Viewstate (ASP.NET only I guess) Session (InProc Web server) Session (Dedicated web server) Session (Database) Local Persistence (Google Gears) (thanks Steve Moyer)etc. I know that each method has its own advantages and disadvantages like cookies not being secure and QueryString having a length limit and being plain ugly to look at! ;) But, when designing a web application I am always confused as to what methods to use for what application or what methods to avoid. What I would like to know is what method(s) do you generally use and would recommend or more interestingly which of these methods would you like to avoid in certain scenarios and why?
While this is a very complicated question to answer, I have a few quick-bite things I think about when considering implementing state. Query string state is only useful for the most basic tasks -- e.g., maintaining the position of a user within a wizard, perhaps, or providing a path to redirect the user to after they complete a given task (e.g., logging in). Otherwise, query string state is horribly insecure, difficult to implement, and in order to do it justice, it needs to be tied to some server-side state machine by containing a key to tie the client to the server's maintained state for that client. Cookie state is more or less the same -- it's just fancier than query string state. But it's still totally maintained on the client side unless the data in the cookie is a key to tie the client to some server-side state machine. Form method state is again similar -- it's useful for hiding fields that tie a given form to some bit of data on the back end (e.g., "this user is editing record #512, so the form will contain a hidden input with the value 512"). It's not useful for much else, and again, is just another implementation of the same idea behind query string and cookie state. Session state (any of the ways you describe) are all great, since they're infinitely extensible and can handle anything your chosen programming language can handle. The first caveat is that there needs to be a key in the client's hand to tie that client to its state being stored on the server; this is where most web frameworks provide either a cookie-based or query string-based key back to the client. (Almost every modern one uses cookies, but falls back on query strings if cookies aren't enabled.) The second caveat is that you need to put some though into how you're storing your state... will you put it in a database? Does your web framework handle it entirely for you? Again, most modern web frameworks take the work out of this, and for me to go about implementing my own state machine, I need a very good reason... otherwise, I'm likely to create security holes and functionality breakage that's been hashed out over time in any of the mature frameworks. So I guess I can't really imagine not wanting to use session-based state for anything but the most trivial reason.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/95655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384/" ] }
95,683
I have a .NET 3.5 (target framework) web application. I have some code that looks like this: public string LogPath { get; private set; }public string ErrorMsg { get; private set; } It's giving me this compilation error for these lines: "must declare a body because it is not marked abstract or extern." Any ideas? My understanding was that this style of property was valid as of .NET 3.0. Thanks! The problem turned out to be in my .sln file itself. Although I was changing the target version in my build options, in the .sln file, I found this: TargetFramework = "3.0" Changing that to "3.5" solved it. Thanks, guys!
add to web.config <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4"> <providerOption name="CompilerVersion" value="v3.5" /> <providerOption name="WarnAsError" value="false" /> </compiler> </compilers></system.codedom>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/95683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13348/" ] }
95,724
I am a .Net developer that has been tasked with upgrading a classic asp website to asp.net. The website is currently running on luck and bubble gum but there is not enough time or money to stop progress and do a full rewrite. Of course I will still need to be able to deliver new features while I am upgrading. What strategies should I use to make a smooth gradual change to asp.net? Should I convert to a single tier .net solution and then refactor to a proper multi-tier solution or should I design my business and data layers now? Should I go straight to 3.5 or is it easier to just get to 1.1 and upgrade to 2.0 or 3.5 after? A full conversion would probably take 3-5 months. There is also some existing 1.1 code, which is why I am considering using that as a jumping off point.
Having been a longtime classic asp programmer, and now an ASP.NET dev, I would take the time and architect it properly in the 2.0 framework (3.5 if you want/need the features). My last job we had a large handful of very badly build classic asp apps that we were rebuilding, and the "nuke and pave" approach was the most successful. Use the existing classic app as your functional spec and wireframes, and build your tasks and tech specs off of that.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/95724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16591/" ] }
95,727
Let's say we have 0.33 , we need to output 1/3 . If we have 0.4 , we need to output 2/5 . The idea is to make it human-readable to make the user understand " x parts out of y " as a better way of understanding data. I know that percentages is a good substitute but I was wondering if there was a simple way to do this?
I have found David Eppstein's find rational approximation to given real number C code to be exactly what you are asking for. Its based on the theory of continued fractions and very fast and fairly compact. I have used versions of this customized for specific numerator and denominator limits. /*** find rational approximation to given real number** David Eppstein / UC Irvine / 8 Aug 1993**** With corrections from Arno Formella, May 2008**** usage: a.out r d** r is real number to approx** d is the maximum denominator allowed**** based on the theory of continued fractions** if x = a1 + 1/(a2 + 1/(a3 + 1/(a4 + ...)))** then best approximation is found by truncating this series** (with some adjustments in the last term).**** Note the fraction can be recovered as the first column of the matrix** ( a1 1 ) ( a2 1 ) ( a3 1 ) ...** ( 1 0 ) ( 1 0 ) ( 1 0 )** Instead of keeping the sequence of continued fraction terms,** we just keep the last partial product of these matrices.*/#include <stdio.h>main(ac, av)int ac;char ** av;{ double atof(); int atoi(); void exit(); long m[2][2]; double x, startx; long maxden; long ai; /* read command line arguments */ if (ac != 3) { fprintf(stderr, "usage: %s r d\n",av[0]); // AF: argument missing exit(1); } startx = x = atof(av[1]); maxden = atoi(av[2]); /* initialize matrix */ m[0][0] = m[1][1] = 1; m[0][1] = m[1][0] = 0; /* loop finding terms until denom gets too big */ while (m[1][0] * ( ai = (long)x ) + m[1][1] <= maxden) { long t; t = m[0][0] * ai + m[0][1]; m[0][1] = m[0][0]; m[0][0] = t; t = m[1][0] * ai + m[1][1]; m[1][1] = m[1][0]; m[1][0] = t; if(x==(double)ai) break; // AF: division by zero x = 1/(x - (double) ai); if(x>(double)0x7FFFFFFF) break; // AF: representation failure } /* now remaining x is between 0 and 1/ai */ /* approx as either 0 or 1/m where m is max that will fit in maxden */ /* first try zero */ printf("%ld/%ld, error = %e\n", m[0][0], m[1][0], startx - ((double) m[0][0] / (double) m[1][0])); /* now try other possibility */ ai = (maxden - m[1][1]) / m[1][0]; m[0][0] = m[0][0] * ai + m[0][1]; m[1][0] = m[1][0] * ai + m[1][1]; printf("%ld/%ld, error = %e\n", m[0][0], m[1][0], startx - ((double) m[0][0] / (double) m[1][0]));}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/95727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4869/" ] }
95,731
Ran into this problem today, posting in case someone else has the same issue. var execBtn = document.createElement('input');execBtn.setAttribute("type", "button");execBtn.setAttribute("id", "execBtn");execBtn.setAttribute("value", "Execute");execBtn.setAttribute("onclick", "runCommand();"); Turns out to get IE to run an onclick on a dynamically generated element, we can't use setAttribute. Instead, we need to set the onclick property on the object with an anonymous function wrapping the code we want to run. execBtn.onclick = function() { runCommand() }; BAD IDEAS: You can do execBtn.setAttribute("onclick", function() { runCommand() }); but it will break in IE in non-standards mode according to @scunliffe. You can't do this at all execBtn.setAttribute("onclick", runCommand() ); because it executes immediately, and sets the result of runCommand() to be the onClick attribute value, nor can you do execBtn.setAttribute("onclick", runCommand);
to make this work in both FF and IE you must write both ways: button_element.setAttribute('onclick','doSomething();'); // for FF button_element.onclick = function() {doSomething();}; // for IE thanks to this post . UPDATE : This is to demonstrate that sometimes it is necessary to use setAttribute! This method works if you need to take the original onclick attribute from the HTML and add it to the onclick event, so that it doesn't get overridden: // get old onclick attributevar onclick = button_element.getAttribute("onclick"); // if onclick is not a function, it's not IE7, so use setAttributeif(typeof(onclick) != "function") { button_element.setAttribute('onclick','doSomething();' + onclick); // for FF,IE8,Chrome// if onclick is a function, use the IE7 method and call onclick() in the anonymous function} else { button_element.onclick = function() { doSomething(); onclick(); }; // for IE7}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/95731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13289/" ] }
95,760
In order to distribute a function I've written that depends on other functions I've written that have their own dependencies and so on without distributing every m-file I have ever written, I need to figure out what the full list of dependencies is for a given m-file. Is there a built-in/freely downloadable way to do this? Specifically I am interested in solutions for MATLAB 7.4.0 (R2007a), but if there is a different way to do it in older versions, by all means please add them here.
For newer releases of Matlab (eg 2007 or 2008) you could use the built in functions: mlint dependency report and coverage report Another option is to use Matlab's profiler. The command is profile, it can also be used to track dependencies. To use profile, you could do >> profile on % turn profiling on>> foo; % entry point to your matlab function or script>> profile off % turn profiling off>> profview % view the report If profiler is not available, then perhaps the following two functions are (for pre-MATLAB 2015a): depfun depdir For example, >> deps = depfun('foo'); gives a structure, deps, that contains all the dependencies of foo.m. From answers 2 , and 3 , newer versions of MATLAB (post 2015a) use matlab.codetools.requiredFilesAndProducts instead. See answers EDIT: Caveats thanks to @Mike Katz comments Remember that the Profiler will only show you files that were actually used in those runs, so if you don't go through every branch, you may have additional dependencies. The dependency report is a good tool, but only resolves static dependencies on the path and just for the files in a single directory. Depfun is more reliable but gives you every possible thing it can think of, and still misses LOAD's and EVAL's.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/95760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17231/" ] }
95,800
I'm using Eclipse PHP Development Tools. What would be the easiest way to access a file or maybe create a remote project trough FTP and maybe SSH and SFTP?.
Eclipse natively supports FTP and SSH. Aptana is not necessary. Native FTP and SSH support in Eclipse is in the "Remote System Explorer End-User Runtime" Plugin. Install it through Eclipse itself. These instructions may vary slightly with your version of Eclipse: Go to 'Help' -> 'Install New Software' (in older Eclipses, this is called something a bit different) In the 'Work with:' drop-down, select your version's plugin release site. Example: for Kepler, this is Kepler - http://download.eclipse.org/releases/kepler In the filter field, type 'remote'. Check the box next to 'Remote System Explorer End-User Runtime' Click 'Next', and accept the terms. It should now download and install. After install, Eclipse may want to restart. Using it, in Eclipse: Window -> Open Perspective -> (perhaps select 'Other') -> Remote System Explorer File -> New -> Other -> Remote System Explorer (folder) -> Connection (or type Connection into the filter field) Choose FTP from the 'Select Remote System Type' panel. Fill in your FTP host info in the next panel (username and password come later). In the Remote Systems panel, right-click the hostname and click 'connect'. Enter username + password and you're good! Well, not exactly 'good'. The RSE system is fairly unusual, but you're connected. And you're one smart cookie! You'll figure out the rest. Edit: To change the default port, follow the instructions on this page: http://ikool.wordpress.com/2008/07/25/tips-to-access-ftpssh-on-different-ports-using-eclipse-rse/
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/95800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7946/" ] }
95,820
Let's say I have an array, and I know I'm going to be doing a lot of "Does the array contain X?" checks. The efficient way to do this is to turn that array into a hash, where the keys are the array's elements, and then you can just say if($hash{X}) { ... } Is there an easy way to do this array-to-hash conversion? Ideally, it should be versatile enough to take an anonymous array and return an anonymous hash.
%hash = map { $_ => 1 } @array; It's not as short as the "@hash{@array} = ..." solutions, but those ones require the hash and array to already be defined somewhere else, whereas this one can take an anonymous array and return an anonymous hash. What this does is take each element in the array and pair it up with a "1". When this list of (key, 1, key, 1, key 1) pairs get assigned to a hash, the odd-numbered ones become the hash's keys, and the even-numbered ones become the respective values.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/95820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ] }
95,821
I have been playing with Haml recently and really like the way the resulting code looks to me...the developer. I'm also not too worried about a designer being able to consume or change it...we're a small team. That said, beginning work on a project we believe will generate quite a bit of traffic (who doesn't?). I'm concerned that there are things I just don't know about haml. Is there anything erb can do that haml can't? Does haml have a negative effect as a project grows? Are there other things that should be considered? And finally...how does Haml compare speedwise to erubis? I see that it supposedly beats erb and eruby now... Thanks!
Haml rocks. I haven't seen any recent performance numbers but it is pretty close to erb these days. I think that it might be faster than erb if you turn on ugly mode (which prevents the pretty indentation) We're doing 2.8 million pageviews a day with Haml. There is a benchmarker checked into the Haml source tree: http://github.com/nex3/haml/tree/master/test Update November 2009 Nathan (Haml's main developer) published some Haml 2.2 benchmarks on his blog. You can see the exact numbers there but in short: Normal (pretty printing) mode = 2.8 times slower than ERB Ugly mode (no pretty tabs added) = equal to ERB You can enable ugly mode by placing Haml::Template::options[:ugly] = true in an initializer or environment file. Note that ugly mode isn't really that ugly - the resulting HTML is actually much prettier than ERB - it's just not indented nicely.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/95821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
95,875
How do I see if a certain object has been loaded, and if not, how can it be loaded, like the following? if (!isObjectLoaded(someVar)) { someVar= loadObject();}
If it is an object then you should just be able to check to see if it is null or undefined and then load it if it is. if (myObject === null || myObject === undefined) { myObject = loadObject();} Using the typeof function is also an option as it returns the type of the object provided. However, it will return null or undefined if the object has not been loaded so it might boil down a bit to personal preference in regards to readability.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/95875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ] }