source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
58,510
I am looking for a simple way to get a mime type where the file extension is incorrect or not given, something similar to this question only in .Net.
I did use urlmon.dll in the end. I thought there would be an easier way but this works. I include the code to help anyone else and allow me to find it again if I need it. using System.Runtime.InteropServices; ... [DllImport(@"urlmon.dll", CharSet = CharSet.Auto)] private extern static System.UInt32 FindMimeFromData( System.UInt32 pBC, [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl, [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer, System.UInt32 cbSize, [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed, System.UInt32 dwMimeFlags, out System.UInt32 ppwzMimeOut, System.UInt32 dwReserverd ); public static string getMimeFromFile(string filename) { if (!File.Exists(filename)) throw new FileNotFoundException(filename + " not found"); byte[] buffer = new byte[256]; using (FileStream fs = new FileStream(filename, FileMode.Open)) { if (fs.Length >= 256) fs.Read(buffer, 0, 256); else fs.Read(buffer, 0, (int)fs.Length); } try { System.UInt32 mimetype; FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0); System.IntPtr mimeTypePtr = new IntPtr(mimetype); string mime = Marshal.PtrToStringUni(mimeTypePtr); Marshal.FreeCoTaskMem(mimeTypePtr); return mime; } catch (Exception e) { return "unknown/unknown"; } }
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/58510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2674/" ] }
58,513
How do I Unit Test a MVC redirection? public ActionResult Create(Product product){ _productTask.Save(product); return RedirectToAction("Success"); }public ActionResult Success(){ return View();} Is Ayende's approach still the best way to go, with preview 5: public static void RenderView(this Controller self, string action) { typeof(Controller).GetMethod("RenderView").Invoke(self,new object[] { action} ); } Seems odd to have to do this, especially as the MVC team have said they are writing the framework to be testable.
[TestFixture]public class RedirectTester{ [Test] public void Should_redirect_to_success_action() { var controller = new RedirectController(); var result = controller.Index() as RedirectToRouteResult; Assert.That(result, Is.Not.Null); Assert.That(result.Values["action"], Is.EqualTo("success")); }}public class RedirectController : Controller{ public ActionResult Index() { return RedirectToAction("success"); }}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/58513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ] }
58,517
Is there a way to combine Enums in VB.net?
I believe what you want is a flag type enum. You need to add the Flags attribute to the top of the enum, and then you can combine enums with the 'Or' keyword. Like this: <Flags()> _Enum CombinationEnums As Integer HasButton = 1 TitleBar = 2 [ReadOnly] = 4 ETC = 8End Enum Note: The numbers to the right are always twice as big (powers of 2) - this is needed to be able to separate the individual flags that have been set. Combine the desired flags using the Or keyword: Dim settings As CombinationEnumssettings = CombinationEnums.TitleBar Or CombinationEnums.Readonly This sets TitleBar and Readonly into the enum To check what's been set: If (settings And CombinationEnums.TitleBar) = CombinationEnums.TitleBar Then Window.TitleBar = TrueEnd If
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/58517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5055/" ] }
58,538
I'm creating an installer for a website that uses a custom event log source. I would like our WiX based installer to create that event log source during installation. Does anyone know the best way to do this using the WiX framework.
Wix has out-of-the-box support for creating event log sources. Assuming you use Wix 3, you first need to add a reference to WixUtilExtension to either your Votive project or the command line. You can then add an EventSource element under a component : <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi" xmlns:util="http://schemas.microsoft.com/wix/UtilExtension"> <Component ...> ... <util:EventSource Log="Application" Name="*source name*" EventMessageFile="*path to message file*"/> ... </Component> If this is a .NET project, you can use EventLogMessages.dll in the framework directory as the message file.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/58538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5182/" ] }
58,540
When trying to enter a SQL query with parameters using the Oracle OLE DB provider I get the following error: Parameters cannot be extracted from the SQL command. The provider might not help to parse parameter information from the command. In that case, use the "SQL command from variable" access mode, in which the entire SQL command is stored in a variable. ADDITIONAL INFORMATION: Provider cannot derive parameter information and SetParameterInfo has not been called. (Microsoft OLE DB Provider for Oracle) I have tried following the suggestion here but don't quite understand what is required: Parameterized queries against Oracle Any ideas?
To expand on the link given in the question: Create a package variable Double click on the package variable name. (This allows you to access the properties of the variable) Set the property 'EvaluateAsExpression' to true Enter the query in the expression builder. Set the OLE DB source query to SQL Command from Variable The expression builder can dynamically create expressions using variable to create 'parametised queries'. So the following 'normal' query: select * from book where book.BOOK_ID = ? Can be written in the expression builder as: "select * from book where book.BOOK_ID = " + @[User::BookID] You can then do null handling and data conversion using the expression builder.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/58540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1281/" ] }
58,561
I'm trying to get only the list of id of object bob for example instead of the list of bob. It's ok with a HQL request, but I would know if it's possible using criteria ? An example : final StringBuilder hql = new StringBuilder();hql.append( "select bob.id from " ) .append( bob.class.getName() ).append( " bob " ) .append( "where bob.id > 10");final Query query = session.createQuery( hql.toString() );return query.list();
I think you could do that with Projections, something like Criteria.forClass(bob.class.getName()) .add(Restrictions.gt("id", 10)) .setProjection(Projections.property("id")) );
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/58561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
58,584
Selecting a large amount of text that extends over many screens in an IDE like Eclipse is fairly easy since you can use the mouse, but what is the best way to e.g. select and delete multiscreen blocks of text or write e.g. three large methods out to another file and then delete them for testing purposes in Vim when using it via putty/ssh where you cannot use the mouse? I can easily yank-to-the-end-of-line or yank-to-the-end-of-code-block but if the text extends over many screens, or has lots of blank lines in it, I feel like my hands are tied in Vim. Any solutions? And a related question: is there a way to somehow select 40 lines, and then comment them all out (with "#" or "//"), as is common in most IDEs?
Well, first of all, you can set vim to work with the mouse, which would allow you to select text just like you would in Eclipse . You can also use the Visual selection - v , by default. Once selected, you can yank , cut , etc. As far as commenting out the block, I usually select it with VISUAL , then do :'<,'>s/^/# / Replacing the beginning of each line with a # . (The '< and '> markers are the beginning and and of the visual selection.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/58584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ] }
58,621
How do I make an MD5 hash of a string with Delphi?
If you want an MD5 digest and have the Indy components installed, you can do this: uses SysUtils, IdGlobal, IdHash, IdHashMessageDigest;with TIdHashMessageDigest5.Create dotry Result := TIdHash128.AsHex(HashValue('Hello, world'));finally Free;end; Most popular algorithms are supported in the Delphi Cryptography Package : Haval MD4, MD5 RipeMD-128, RipeMD-160 SHA-1, SHA-256, SHA-384, SHA-512, Tiger Update DCPCrypt is now maintained by Warren Postma and source can be found here .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/58621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3366/" ] }
58,622
I like Doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have /* .. */ comments, and also has its own self-documentation facility which seems to be the pythonic way to document. Since I'm familiar with Doxygen, how can I use it to produce my Python documentation? Is there anything in particular that I need to be aware of?
This is documented on the doxygen website , but to summarize here: You can use doxygen to document your Python code. You can either use the Python documentation string syntax: """@package docstringDocumentation for this module.More details."""def func(): """Documentation for a function. More details. """ pass In which case the comments will be extracted by doxygen, but you won't be able to use any of the special doxygen commands . Or you can (similar to C-style languages under doxygen) double up the comment marker ( # ) on the first line before the member: ## @package pyexample# Documentation for this module.## More details.## Documentation for a function.## More details.def func(): pass In that case, you can use the special doxygen commands. There's no particular Python output mode, but you can apparently improve the results by setting OPTMIZE_OUTPUT_JAVA to YES . Honestly, I'm a little surprised at the difference - it seems like once doxygen can detect the comments in ## blocks or """ blocks, most of the work would be done and you'd be able to use the special commands in either case. Maybe they expect people using """ to adhere to more Pythonic documentation practices and that would interfere with the special doxygen commands?
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/58622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ] }
58,649
I would like to write a small program in C# which goes through my jpeg photos and, for example, sorts them into dated folders (using MY dating conventions, dammit...). Does anyone know a relatively easy way to get at the EXIF data such as Date And Time or Exposure programatically?Thanks!
Check out this metadata extractor . It is written in Java but has also been ported to C#. I have used the Java version to write a small utility to rename my jpeg files based on the date and model tags. Very easy to use. EDIT metadata-extractor supports .NET too. It's a very fast and simple library for accessing metadata from images and videos. It fully supports Exif, as well as IPTC, XMP and many other types of metadata from file types including JPEG, PNG, GIF, PNG, ICO, WebP, PSD, ... var directories = ImageMetadataReader.ReadMetadata(imagePath);// print out all metadataforeach (var directory in directories)foreach (var tag in directory.Tags) Console.WriteLine($"{directory.Name} - {tag.Name} = {tag.Description}");// access the date timevar subIfdDirectory = directories.OfType<ExifSubIfdDirectory>().FirstOrDefault();var dateTime = subIfdDirectory?.GetDateTime(ExifDirectoryBase.TagDateTime); It's available via NuGet and the code's on GitHub .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/58649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6091/" ] }
58,730
I want to be able to generate PDF output from my (native) C++ Windows application. Are there any free/open source libraries available to do this? I looked at the answers to this question , but they mostly relate to .Net.
LibHaru Haru is a free, cross platform, open-sourced software library for generating PDF written in ANSI-C. It can work as both a static-library (.a, .lib) and a shared-library (.so, .dll). Didn't try it myself, but maybe it can help you
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/58730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3853/" ] }
58,739
What should every WPF developer know? Entry Level Strong .NET 2.0 Background & willing to learn! Explain dependency properties? What's a style? What's a template? Binding Differences between base classes: Visual, UIElement, FrameworkElement, Control Visual vs Logical tree? Property Change Notification (INotifyPropertyChange and ObservableCollection) ResourceDictionary - Added by a7an UserControls - Added by a7an difference between bubble and tunnel routing strategies - added by Carlo Why did Microsoft introduce yet another markup language? XAML Mid-level Routed Events & Commands Converters - Added by Artur Carvalho Explain WPF's 2-pass layout engine? How to implement a panel? Interoperability (WPF/WinForms) Blend / Cider - Added by a7an Animations and Storyboarding ClickOnce Deployment Skinning/Themeing Custom Controls How can worker threads update the UI? DataTemplate vs HierarchicalDataTemplate ItemsControl vs ItemsPresenter vs ContentControl vs ContentPresenter Different types of Triggers Senior Example of attached behavior? What is PRISM,CAL & CAG? How can worker threads update the UI? WPF 3D - Added by a7an Differences between Silverlight 2 and WPF MVVM/MVP - Added by a7an WPF Performance tuning Pixel Shaders Purpose of Freezables Any other "trick" questions to ask? Do you expect your WPF developer to know blend?
I'd put binding and converters at entry level, since that is how you spend a lot of time in WPF.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/58739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5147/" ] }
58,743
As an example take the following code: public enum ExampleEnum { FooBar, BarFoo }public class ExampleClass : INotifyPropertyChanged{ private ExampleEnum example; public ExampleEnum ExampleProperty { get { return example; } { /* set and notify */; } }} I want a to databind the property ExampleProperty to a ComboBox, so that it shows the options "FooBar" and "BarFoo" and works in mode TwoWay. Optimally I want my ComboBox definition to look something like this: <ComboBox ItemsSource="What goes here?" SelectedItem="{Binding Path=ExampleProperty}" /> Currently I have handlers for the ComboBox.SelectionChanged and ExampleClass.PropertyChanged events installed in my Window where I do the binding manually. Is there a better or some kind of canonical way? Would you usually use Converters and how would you populate the ComboBox with the right values? I don't even want to get started with i18n right now. Edit So one question was answered: How do I populate the ComboBox with the right values. Retrieve Enum values as a list of strings via an ObjectDataProvider from the static Enum.GetValues method: <Window.Resources> <ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type sys:Enum}" x:Key="ExampleEnumValues"> <ObjectDataProvider.MethodParameters> <x:Type TypeName="ExampleEnum" /> </ObjectDataProvider.MethodParameters> </ObjectDataProvider></Window.Resources> This I can use as an ItemsSource for my ComboBox: <ComboBox ItemsSource="{Binding Source={StaticResource ExampleEnumValues}}"/>
You can create a custom markup extension. Example of usage: enum Status{ [Description("Available.")] Available, [Description("Not here right now.")] Away, [Description("I don't have time right now.")] Busy} At the top of your XAML: xmlns:my="clr-namespace:namespace_to_enumeration_extension_class and then... <ComboBox ItemsSource="{Binding Source={my:Enumeration {x:Type my:Status}}}" DisplayMemberPath="Description" SelectedValue="{Binding CurrentStatus}" SelectedValuePath="Value" /> And the implementation... public class EnumerationExtension : MarkupExtension { private Type _enumType; public EnumerationExtension(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); EnumType = enumType; } public Type EnumType { get { return _enumType; } private set { if (_enumType == value) return; var enumType = Nullable.GetUnderlyingType(value) ?? value; if (enumType.IsEnum == false) throw new ArgumentException("Type must be an Enum."); _enumType = value; } } public override object ProvideValue(IServiceProvider serviceProvider) // or IXamlServiceProvider for UWP and WinUI { var enumValues = Enum.GetValues(EnumType); return ( from object enumValue in enumValues select new EnumerationMember{ Value = enumValue, Description = GetDescription(enumValue) }).ToArray(); } private string GetDescription(object enumValue) { var descriptionAttribute = EnumType .GetField(enumValue.ToString()) .GetCustomAttributes(typeof (DescriptionAttribute), false) .FirstOrDefault() as DescriptionAttribute; return descriptionAttribute != null ? descriptionAttribute.Description : enumValue.ToString(); } public class EnumerationMember { public string Description { get; set; } public object Value { get; set; } } }
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/58743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1733/" ] }
58,744
I want to copy the entire contents of a directory from one location to another in C#. There doesn't appear to be a way to do this using System.IO classes without lots of recursion. There is a method in VB that we can use if we add a reference to Microsoft.VisualBasic : new Microsoft.VisualBasic.Devices.Computer(). FileSystem.CopyDirectory( sourceFolder, outputFolder ); This seems like a rather ugly hack. Is there a better way?
Much easier private static void CopyFilesRecursively(string sourcePath, string targetPath){ //Now Create all of the directories foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories)) { Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath)); } //Copy all the files & Replaces any files with the same name foreach (string newPath in Directory.GetFiles(sourcePath, "*.*",SearchOption.AllDirectories)) { File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true); }}
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/58744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ] }
58,750
Is it possible to obtain raw logs from Google Analytic? Is there any tool that can generate the raw logs from GA?
No you can't get the raw logs, but there's nothing stopping you from getting the exact same data logged to your own web server logs. Have a look at the Urchin code and borrow that, changing the following two lines to point to your web server instead. var _ugifpath2="http://www.google-analytics.com/__utm.gif";if (_udl.protocol=="https:") _ugifpath2="https://ssl.google-analytics.com/__utm.gif"; You'll want to create a __utm.gif file so that they don't show up in the logs as 404s. Obviously you'll need to parse the variables out of the hits into your web server logs. The log line in Apache looks something like this. You'll have lots of "fun" parsing out all the various stuff you want from that, but everything Google Analytics gets from the basic JavaScript tagging comes in like this. 127.0.0.1 - - [02/Oct/2008:10:17:18 +1000] "GET /__utm.gif?utmwv=1.3&utmn=172543292&utmcs=ISO-8859-1&utmsr=1280x1024&utmsc=32-bit&utmul=en-us&utmje=1&utmfl=9.0%20%20r124&utmdt=My%20Web%20Page&utmhn=www.mydomain.com&utmhid=979599568&utmr=-&utmp=/urlgoeshere/&utmac=UA-1715941-2&utmcc=__utma%3D113887236.511203954.1220404968.1222846275.1222906638.33%3B%2B__utmz%3D113887236.1222393496.27.2.utmccn%3D(organic)%7Cutmcsr%3Dgoogle%7Cutmctr%3Dsapphire%2Btechnologies%2Bsite%253Arumble.net%7Cutmcmd%3Dorganic%3B%2B HTTP/1.0" 200 35 "http://www.mydomain.com/urlgoeshere/" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.2.153.1 Safari/525.19"
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/58750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/370899/" ] }
58,774
I want to paste something I have cut from my desktop into a file open in Vi. But if I paste the tabs embed on top of each other across the page. I think it is some sort of visual mode change but can't find the command.
If you're using plain vi: You probably have autoindent on. To turn it off while pasting: <Esc> :set noai<paste all you want><Esc> :set ai I have in my .exrc the following shortcuts: map ^P :set noai^Mmap ^N :set ai^M Note that these have to be the actual control characters - insert them using Ctrl - V Ctrl - P and so on. If you're using vim: Use the paste option. In addition to disabling autoindent it will also set other options such as textwidth and wrapmargin to paste-friendly defaults: <Esc> :set paste<paste all you want><Esc> :set nopaste You can also set a key to toggle the paste mode. My .vimrc has the following line: set pastetoggle=<C-P> " Ctrl-P toggles paste mode
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/58774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6096/" ] }
58,782
I need to copy files using Windows command-line (available on XP Pro or later by default) and show progress during the process. The progress indicator could be in a terminal or a GUI window. It is intended to be used during batch file scripting.
I used the copy command with the /z switch for copying over network drives. Also works for copying between local drives. Tested on XP Home edition.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/58782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
58,825
Has anyone else found VIM's syntax highlighting of Javascript sub-optimal? I'm finding that sometimes I need to scroll around in order to get the syntax highlighting adjusted, as sometimes it mysteriously drops all highlighting. Are there any work-arounds or ways to fix this? I'm using vim 7.1.
You might like to try this improved Javascript syntax highlighter rather than the one that ships with VIMRUNTIME.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/58825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1693/" ] }
58,827
OK, I am not sure if the title it completely accurate, open to suggestions! I am in the process of creating an ASP.NET custom control, this is something that is still relatively new to me, so please bear with me. I am thinking about the event model. Since we are not using Web Controls there are no events being fired from buttons, rather I am manually calling __doPostBack with the appropriate arguments. However this can obviously mean that there are a lot of postbacks occuring when say, selecting options (which render differently when selected). In time, I will need to make this more Ajax-y and responsive, so I will need to change the event binding to call local Javascript. So, I was thinking I should be able to toggle the "mode" of the control, it can either use postback and handlle itself, or you can specify the Javascript function names to call instead of the doPostBack. What are your thoughts on this? Am I approaching the raising of the events from the control in the wrong way? (totally open to suggestions here!) How would you approach a similar problem? Edit - To Clarify I am creating a custom rendered control (i.e. inherits from WebControl). We are not using existnig Web Controls since we want complete control over the rendered output. AFAIK the only way to get a server side event to occur from a custom rendered control is to call doPostBack from the rendered elements (please correct if wrong!). ASP.NET MVC is not an option.
You might like to try this improved Javascript syntax highlighter rather than the one that ships with VIMRUNTIME.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/58827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ] }
58,841
How can I get precompiled headers working with GCC? I have had no luck in my attempts and I haven't seen many good examples for how to set it up. I've tried on Cygwin GCC 3.4.4 and using 4.0 on Ubuntu .
Firstly, see the documentation here . You compile headers just like any other file but you put the output inside a file with a suffix of .gch . So for example if you precompile stdafx.h you will have a precompiled header that will be automatically searched for called stdafx.h.gch anytime you include stdafx.h Example: stdafx.h: #include <string>#include <stdio.h> a.cpp: #include "stdafx.h"int main(int argc, char**argv){ std::string s = "Hi"; return 0;} Then compile as: > g++ -c stdafx.h -o stdafx.h.gch > g++ a.cpp > ./a.out Your compilation will work even if you remove stdafx.h after step 1.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/58841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5200/" ] }
58,851
I am running an application through gdb and I want to set a breakpoint for any time a specific variable is accessed / changed. Is there a good method for doing this? I would also be interested in other ways to monitor a variable in C/C++ to see if/when it changes.
watch only breaks on write, rwatch let you break on read, and awatch let you break on read/write. You can set read watchpoints on memory locations: gdb$ rwatch *0xfeedfaceHardware read watchpoint 2: *0xfeedface but one limitation applies to the rwatch and awatch commands; you can't use gdb variablesin expressions: gdb$ rwatch $ebx+0xec1a04fExpression cannot be implemented with read/access watchpoint. So you have to expand them yourself: gdb$ print $ebx $13 = 0x135700gdb$ rwatch *0x135700+0xec1a04fHardware read watchpoint 3: *0x135700 + 0xec1a04fgdb$ cHardware read watchpoint 3: *0x135700 + 0xec1a04fValue = 0xec34daf0x9527d6e7 in objc_msgSend () Edit: Oh, and by the way. You need either hardware or software support . Software is obviously much slower. To find out if your OS supports hardware watchpoints you can see the can-use-hw-watchpoints environment setting. gdb$ show can-use-hw-watchpointsDebugger's willingness to use watchpoint hardware is 1.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/58851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3022/" ] }
58,872
I've read in several places that the rectangle functions in emacs are very useful. I've read a bit about them, and I can't quite figure why. I mean, when you want to kill a paragraph, you mark the first row/column and then the last one, and that's actually a rectangle, right? But you can still use the normal kill... So what kind of transformations would you do with them?
If you have data in columns in a text file with M-x delete-rectangle or M-x kill-rectangle you can delete a single column of data. Similarly, M-x yank-rectangle will paste in a column of text. For example, take the following text: 1. alligator alphorn2. baboon bugle3. crocodile cornet4. dog didgeridoo5. elephant euphonium 6. fish flugelhorn 7. gopher guitar Select from the a of alligator to the g of guitar. The beginning and end of the selection mark out two opposite corners of the rectangle. Enter M-x kill-rectangle and you immediately have: 1. alphorn2. bugle3. cornet4. didgeridoo5. euphonium 6. flugelhorn7. guitar Next put the mark at the end of the top line, add a few spaces if required and enter M-x yank-rectangle and ta-da! You have re-ordered the columns: 1. alphorn alligator 2. bugle baboon 3. cornet crocodile 4. didgeridoo dog 5. euphonium elephant 6. flugelhorn fish 7. guitar gopher
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/58872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3785/" ] }
58,874
I can't seem to find that option. Surely it's in there?
That would be Tools > Options Text Editor > All Languages > Line Numbers (at the bottom right)
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/58874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ] }
58,910
I've been trying to convert SVG images to PNG using C#, without having to write too much code. Can anyone recommend a library or example code for doing this?
You can call the command-line version of inkscape to do this: http://harriyott.com/2008/05/converting-svg-images-to-png-in-c.aspx Also there is a C# SVG rendering engine, primarily designed to allow SVG files to be used on the web on codeplex that might suit your needs if that is your problem: Original Project http://www.codeplex.com/svg Fork with fixes and more activity: (added 7/2013) https://github.com/vvvv/SVG
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/58910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5744/" ] }
58,925
I have any ASP.NET control. I want the HTML string how to do I get the HTML string of the control?
This appears to work. public string RenderControlToHtml(Control ControlToRender){ System.Text.StringBuilder sb = new System.Text.StringBuilder(); System.IO.StringWriter stWriter = new System.IO.StringWriter(sb); System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter); ControlToRender.RenderControl(htmlWriter); return sb.ToString();}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/58925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2469/" ] }
58,939
I'm trying to get an event to fire whenever a choice is made from a JComboBox . The problem I'm having is that there is no obvious addSelectionListener() method. I've tried to use actionPerformed() , but it never fires. Short of overriding the model for the JComboBox , I'm out of ideas. How do I get notified of a selection change on a JComboBox ?** Edit: I have to apologize. It turns out I was using a misbehaving subclass of JComboBox , but I'll leave the question up since your answer is good.
It should respond to ActionListeners , like this: combo.addActionListener (new ActionListener () { public void actionPerformed(ActionEvent e) { doSomething(); }}); @John Calsbeek rightly points out that addItemListener() will work, too. You may get 2 ItemEvents , though, one for the deselection of the previously selected item, and another for the selection of the new item. Just don't use both event types!
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/58939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ] }
58,940
I'm using SQL Server 2005, and I would like to know how to access different result sets from within transact-sql. The following stored procedure returns two result sets, how do I access them from, for example, another stored procedure? CREATE PROCEDURE getOrder (@orderId as numeric) ASBEGIN select order_address, order_number from order_table where order_id = @orderId select item, number_of_items, cost from order_line where order_id = @orderIdEND I need to be able to iterate through both result sets individually. EDIT: Just to clarify the question, I want to test the stored procedures. I have a set of stored procedures which are used from a VB.NET client, which return multiple result sets. These are not going to be changed to a table valued function, I can't in fact change the procedures at all. Changing the procedure is not an option. The result sets returned by the procedures are not the same data types or number of columns.
The short answer is: you can't do it. From T-SQL there is no way to access multiple results of a nested stored procedure call, without changing the stored procedure as others have suggested. To be complete, if the procedure were returning a single result, you could insert it into a temp table or table variable with the following syntax: INSERT INTO #Table (...columns...)EXEC MySproc ...parameters... You can use the same syntax for a procedure that returns multiple results, but it will only process the first result, the rest will be discarded.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/58940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1836/" ] }
58,976
How do I find out whether or not Caps Lock is activated, using VB.NET? This is a follow-up to my earlier question .
Control.IsKeyLocked(Keys) Method - MSDN Imports SystemImports System.Windows.FormsImports Microsoft.VisualBasicPublic Class CapsLockIndicator Public Shared Sub Main() if Control.IsKeyLocked(Keys.CapsLock) Then MessageBox.Show("The Caps Lock key is ON.") Else MessageBox.Show("The Caps Lock key is OFF.") End If End Sub 'MainEnd Class 'CapsLockIndicator C# version: using System;using System.Windows.Forms;public class CapsLockIndicator{ public static void Main() { if (Control.IsKeyLocked(Keys.CapsLock)) { MessageBox.Show("The Caps Lock key is ON."); } else { MessageBox.Show("The Caps Lock key is OFF."); } }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/58976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133/" ] }
58,988
The Interface Segregation Principle (ISP) says that many client specific interfaces are better than one general purpose interface. Why is this important?
ISP states that: Clients should not be forced to depend on methods that they do not use. ISP relates to important characteristics - cohesion and coupling . Ideally your components must be highly tailored. It improves code robustness and maintainability. Enforcing ISP gives you following bonuses: High cohesion - better understandability, robustness Low coupling - better maintainability, high resistance to changes If you want to learn more about software design principles, get a copyof Agile Software Development, Principles, Patterns, and Practices book.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/58988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3012/" ] }
59,016
The Open/Closed Principle states that software entities (classes, modules, etc.) should be open for extension, but closed for modification. What does this mean, and why is it an important principle of good object-oriented design?
It means that you should put new code in new classes/modules. Existing code should be modified only for bug fixing. New classes can reuse existing code via inheritance. Open/closed principle is intended to mitigate risk when introducing new functionality. Since you don't modify existing code you can be assured that it wouldn't be broken. It reduces maintenance cost and increases product stability.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/59016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3012/" ] }
59,022
We are currently storing plain text passwords for a web app that we have. I keep advocating moving to a password hash but another developer said that this would be less secure -- more passwords could match the hash and a dictionary/hash attack would be faster. Is there any truth to this argument?
Absolutely none. But it doesn't matter. I've posted a similar response before: It's unfortunate, but people, even programmers, are just too emotional to be easily be swayed by argument. Once he's invested in his position (and, if you're posting here, he is) you're not likely to convince him with facts alone. What you need to do is switch the burden of proof. You need to get him out looking for data that he hopes will convince you, and in so doing learn the truth. Unfortunately, he has the benefit of the status quo, so you've got a tough road there.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5882/" ] }
59,044
Question is pretty self explanitory. I want to do a simple find and replace, like you would in a text editor on the data in a column of my database (which is MsSQL on MS Windows server 2003)
The following query replace each and every a character with a b character. UPDATE YourTableSET Column1 = REPLACE(Column1,'a','b')WHERE Column1 LIKE '%a%' This will not work on SQL server 2003.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/59044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2908/" ] }
59,075
How do I save each sheet in an Excel workbook to separate CSV files with a macro? I have an excel with multiple sheets and I was looking for a macro that will save each sheet to a separate CSV (comma separated file) . Excel will not allow you to save all sheets to different CSV files.
Here is one that will give you a visual file chooser to pick the folder you want to save the files to and also lets you choose the CSV delimiter (I use pipes '|' because my fields contain commas and I don't want to deal with quotes): ' ---------------------- Directory Choosing Helper Functions -----------------------' Excel and VBA do not provide any convenient directory chooser or file chooser' dialogs, but these functions will provide a reference to a system DLL' with the necessary capabilitiesPrivate Type BROWSEINFO ' used by the function GetFolderName hOwner As Long pidlRoot As Long pszDisplayName As String lpszTitle As String ulFlags As Long lpfn As Long lParam As Long iImage As LongEnd TypePrivate Declare Function SHGetPathFromIDList Lib "shell32.dll" _ Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As LongPrivate Declare Function SHBrowseForFolder Lib "shell32.dll" _ Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As LongFunction GetFolderName(Msg As String) As String ' returns the name of the folder selected by the user Dim bInfo As BROWSEINFO, path As String, r As Long Dim X As Long, pos As Integer bInfo.pidlRoot = 0& ' Root folder = Desktop If IsMissing(Msg) Then bInfo.lpszTitle = "Select a folder." ' the dialog title Else bInfo.lpszTitle = Msg ' the dialog title End If bInfo.ulFlags = &H1 ' Type of directory to return X = SHBrowseForFolder(bInfo) ' display the dialog ' Parse the result path = Space$(512) r = SHGetPathFromIDList(ByVal X, ByVal path) If r Then pos = InStr(path, Chr$(0)) GetFolderName = Left(path, pos - 1) Else GetFolderName = "" End IfEnd Function'---------------------- END Directory Chooser Helper Functions ----------------------Public Sub DoTheExport() Dim FName As Variant Dim Sep As String Dim wsSheet As Worksheet Dim nFileNum As Integer Dim csvPath As String Sep = InputBox("Enter a single delimiter character (e.g., comma or semi-colon)", _ "Export To Text File") 'csvPath = InputBox("Enter the full path to export CSV files to: ") csvPath = GetFolderName("Choose the folder to export CSV files to:") If csvPath = "" Then MsgBox ("You didn't choose an export directory. Nothing will be exported.") Exit Sub End If For Each wsSheet In Worksheets wsSheet.Activate nFileNum = FreeFile Open csvPath & "\" & _ wsSheet.Name & ".csv" For Output As #nFileNum ExportToTextFile CStr(nFileNum), Sep, False Close nFileNum Next wsSheetEnd SubPublic Sub ExportToTextFile(nFileNum As Integer, _ Sep As String, SelectionOnly As Boolean) Dim WholeLine As String Dim RowNdx As Long Dim ColNdx As Integer Dim StartRow As Long Dim EndRow As Long Dim StartCol As Integer Dim EndCol As Integer Dim CellValue As String Application.ScreenUpdating = False On Error GoTo EndMacro: If SelectionOnly = True Then With Selection StartRow = .Cells(1).Row StartCol = .Cells(1).Column EndRow = .Cells(.Cells.Count).Row EndCol = .Cells(.Cells.Count).Column End With Else With ActiveSheet.UsedRange StartRow = .Cells(1).Row StartCol = .Cells(1).Column EndRow = .Cells(.Cells.Count).Row EndCol = .Cells(.Cells.Count).Column End With End If For RowNdx = StartRow To EndRow WholeLine = "" For ColNdx = StartCol To EndCol If Cells(RowNdx, ColNdx).Value = "" Then CellValue = "" Else CellValue = Cells(RowNdx, ColNdx).Value End If WholeLine = WholeLine & CellValue & Sep Next ColNdx WholeLine = Left(WholeLine, Len(WholeLine) - Len(Sep)) Print #nFileNum, WholeLine Next RowNdxEndMacro: On Error GoTo 0 Application.ScreenUpdating = TrueEnd Sub
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/59075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5790/" ] }
59,083
Question Alright, I'm confused by all the buzzwords and press release bingo going on. What is the relationship between flash and flex: Replace flash (not really compatible) Enhance flash The next version of flash but still basically compatible Separate technology altogether ??? If I'm starting out in Flash now, should I just skip to Flex? Follow up Ok, so what I'm hearing is that there's three different parts to the puzzle: Flash The graphical editor used to make "Flash Movies", ie it's an IDE that focuses on the visual aspect of "Flash" (Officially Flash CS3?) The official name for the display plugins (ie, "Download Flash Now!") A general reference to the entire technology stack In terms of the editor, it's a linear timeline based editor, best used for animations with complex interactivity. Actionscript The "Flash" programming language Flex An Adobe Flash IDE that focuses on the coding/programming aspect of "Flash" (Flex Builder?) A Flash library that enhances Flash and makes it easier to program for (Flex SDK?) Is not bound to a timeline (as the Flash IDE is) and so "standard" applications are more easily accomplished. Is this correct? -Adam
The term Flash can include any of the other terms defined below, and I find that saying "Flash" without specifying exactly what you mean can be confusing and misleading. Case in point: I'm not sure what you specifically mean when you say "Flash" in your question. Is it Flash Player? The authoring tool? Or the whole collection of technologies that fall under what Adobe calls the "Flash Platform"? To help clear all this up, let me define the technologies involved in creating Flash and Flex content so that we're all using the same terminology here: Flash Player is a runtime for rich media content in the browser. There is also Flash Lite to run Flash content on older or low-end mobile devices, and Adobe AIR extends Flash Player to allow content authors to publish native desktop and mobile applications that can integrate with things like the file system, windowing systems, and device sensors like the accelerometer and camera. Collectively, Adobe refers to these as the Flash runtimes . Flash Professional (often called the Flash authoring tool or the Flash IDE ) has traditionally been the primary application used to create content that runs on Flash Player. It is very designer oriented with timelines, layers, and visual drawing tools. Software developers may find this application disorienting and limited compared to other development tools that focus more on code, like Flash Builder (see below). When someone says, "I built something with Flash", they often mean the Flash authoring tool, but that's not always the case. For that reason, it's good to always clarify to avoid any confusion. ActionScript is the primary programming language supported by Adobe to target Flash runtimes. The current version is ActionScript 3 (abbreviated as AS3 ), which has been supported since Flash Player 9. Content created with older versions of ActionScript can still be run in the latest versions Flash Player, but new features are only supported when using ActionScript 3 to create new content. Flex is a collection of technologies designed to create rich applications that target the Adobe's Flash runtimes. Though saying "Flex" previously had the same ambiguity as "Flash", the Flex brand name is becoming more and more focused on the Flex framework and SDK, described below. The Flex SDK consists of compilers, a command-line debugger, and the Flex framework. The included compilers are:1. MXMLC, an ActionScript and MXML compiler to output the final SWF file for deployment to Flash Player.2. COMPC, a static library compiler for ActionScript that outputs SWC files.3. ASDOC, a documentation generator built on the compiler technology. The Flex framework is a collection of ActionScript classes designed to build Rich Internet Applications. It includes things like user interface controls, web services and other connectivity classes, formatters and validators, drag and drop, modal windowing, and component states. These classes are in the mx.* package. Generally, when developers say "Flex" without any clarifying information, they mean the Flex framework and not the product formerly known as Flex Builder. In 2011, Adobe donated the Flex SDK to the Apache Software Foundation. It is now called Apache Flex and it is fully managed by the community rather than Adobe. However, Adobe employees continue to contribute to the project, and Flash Builder (see below) continues to support new SDKs released by the Apache Flex project. MXML is an XML-based markup language used by the Flex compilers to make layout and placing components into containers easier. The tree-like structure of XML make the containment hierarchy easier to visualize. MXML is actually converted to ActionScript during the compilation process. Flash Builder (formerly known as Flex Builder ) is a development environment that allows developers to build different project types to create SWF files that are deployed to Flash runtimes. It is built on the Eclipse platform and is more familiar to software engineers. Flash Builder supports projects built with Flex or pure ActionScript. Flex projects include the Flex framework. ActionScript projects are the most basic you can work with, starting with a single class and an empty canvas, and the Flex framework is not included. Flash Builder does not replace Flash Professional. Some people who have traditionally used Flash Professional may now choose to use Flash Builder instead. Often, these are software engineers who appreciate or require the advanced development tools offered by Flash Builder or don't work heavily with assets designed in a visual tool. Some developers may write their code in Flash Builder, while choosing to compile their projects in the Flash authoring tool. Often, these developers are also designers, or they are working with other people who are designers. In this situation, there may be many graphical assets created in the Flash authoring tool, and it could be difficult or simply inappropriate to bring them into another environment. The Flex framework is specifically designed to build applications. It includes many traditional form controls (buttons, lists, datagrids, etc) and much of the code runs on an advanced component framework written in ActionScript. Not everyone is building the sort of content that Flex is designed to create, and Flex does not replace traditional Flash development practices for everyone. It is a better approach for some developers, but may not be right for others. More design-heavy websites, such as those created for movies, music, energy drinks, advertising campaigns, and things like that probably shouldn't use the Flex framework. These types of content might be better suited to Flash Professional or a pure ActionScript project in Flash Builder. Similarly, little widgets you put into the sidebar of your website or on your profile in a social networking website may need to be built with pure ActionScript (without the Flex framework) because they require a smaller file size and they probably don't need a big complex component architecture designed for larger applications. When targeting Flash runtimes, your development environment, frameworks, and workflow should be chosen based on your project's requirements and goals.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/59083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ] }
59,099
Visually both of the following snippets produce the same UI. So why are there 2 controls.. Snippet1 <TextBlock>Name:</TextBlock><TextBox Name="nameTextBox" /> Snippet2 <Label>Name:</Label><TextBox Name="nameTextBox" /> ( Well I am gonna answer this myself... thought this is a useful tidbit I learnt today from Programming WPF )
The WPF Textblock inherits from FrameworkElement instead of deriving from System.Windows.Control like the Label Control. This means that the Textblock is much more lightweight. The downside of using a textblock is no support for Access/Accerelator Keys and there is no link to other controls as target. When you want to display text by itself use the TextBlock . The benefit is a light, performant way to display text. When you want to associate text with another control like a TextBox use the Label control . The benefits are access keys and references to target control.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/59099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ] }
59,102
Let's say that I'm writing a function to convert between temperature scales. I want to support at least Celsius, Fahrenheit, and Kelvin. Is it better to pass the source scale and target scale as separate parameters of the function, or some sort of combined parameter? Example 1 - separate parameters:function convertTemperature("celsius", "fahrenheit", 22) Example 2 - combined parameter:function convertTemperature("c-f", 22) The code inside the function is probably where it counts. With two parameters, the logic to determine what formula we're going to use is slightly more complicated, but a single parameter doesn't feel right somehow. Thoughts?
Go with the first option, but rather than allow literal strings (which are error prone), take constant values or an enumeration if your language supports it, like this: convertTemperature (TempScale.CELSIUS, TempScale.FAHRENHEIT, 22)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6126/" ] }
59,107
I'm converting an application to use Java 1.5 and have found the following method: /** * Compare two Comparables, treat nulls as -infinity. * @param o1 * @param o2 * @return -1 if o1&lt;o2, 0 if o1==o2, 1 if o1&gt;o2 */ protected static int nullCompare(Comparable o1, Comparable o2) { if (o1 == null) { if (o2 == null) { return 0; } else { return -1; } } else if (o2 == null) { return 1; } else { return o1.compareTo(o2); } } Ideally I would like to make the method take two Comparables of the same type, is it possible to convert this and how? I thought the following would do the trick: protected static <T extends Comparable> int nullCompare(T o1, T o2) { but it has failed to get rid of a warning in IntelliJ "Unchecked call to 'compareTo(T)' as a member of raw type 'java.lang.Comparable'" on the line: return o1.compareTo(o2);
Change it to: protected static <T extends Comparable<T>> int nullCompare(T o1, T o2) { You need that because Comparable is itself a generic type.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4389/" ] }
59,120
I am getting this error now that I hit version number 1.256.0:Error 4 Invalid product version '1.256.0'. Must be of format '##.##.####' The installer was fine with 1.255.0 but something with 256 (2^8) it doesn't like. I found this stated on msdn.com:The Version property must be formatted as N.N.N, where each N represents at least one and no more than four digits. ( http://msdn.microsoft.com/en-us/library/d3ywkte8(VS.80).aspx ) Which would make me believe there is nothing wrong 1.256.0 because it meets the rules stated above. Does anyone have any ideas on why this would be failing now?
Change it to: protected static <T extends Comparable<T>> int nullCompare(T o1, T o2) { You need that because Comparable is itself a generic type.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5967/" ] }
59,130
I'm writing an asp.net application that will need to be localized to several regions other than North America. What do I need to do to prepare for this globalization? What are your top 1 to 2 resources for learning how to write a world ready application.
A couple of things that I've learned: Absolutely and brutally minimize the number of images you have that contain text. Doing so will make your life a billion percent easier since you won't have to get a new set of images for every friggin' language. Be very wary of css positioning that relies on things always remaining the same size. If those things contain text, they will not remain the same size, and you will then need to go back and fix your designs. If you use character types in your sql tables, make sure that any of those that might receive international input are unicode (nchar, nvarchar, ntext). For that matter, I would just standardize on using the unicode versions. If you're building SQL queries dynamically, make sure that you include the N prefix before any quoted text if there's any chance that text might be unicode. If you end up putting garbage in a SQL table, check to see if that's there. Make sure that all your web pages definitively state that they are in a unicode format. See Joel's article, mentioned above. You're going to be using resource files a lot for this project. That's good - ASP.NET 2.0 has great support for such. You'll want to look into the App_LocalResources and App_GlobalResources folder as well as GetLocalResourceObject, GetGlobalResourceObject, and the concept of meta:resourceKey. Chapter 30 of Professional ASP.NET 2.0 has some great content regarding that. The 3.5 version of the book may well have good content there as well, but I don't own it. Think about fonts. Many of the standard fonts you might want to use aren't unicode capable. I've always had luck with Arial Unicode MS, MS Gothic, MS Mincho. I'm not sure about how cross-platform these are, though. Also, note that not all fonts support all of the Unicode character definition. Again, test, test, test. Start thinking now about how you're going to get translations into this system. Go talk to whoever is your translation vendor about how they want data passed back and forth for translation. Think about the fact that, through your local resource files, you will likely be repeating some commonly used strings through the system. Do you normalize those into global resource files, or do you have some sort of database layer where only one copy of each text used is generated. In our recent project, we used resource files which were generated from a database table that contained all the translations and the original, english version of the resource files. Test. Generally speaking I will test in German, Polish, and an Asian language (Japanese, Chinese, Korean). German and Polish are wordy and nearly guaranteed to stretch text areas, Asian languages use an entirely different set of characters which tests your unicode support.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1642688/" ] }
59,148
Which standalone Windows GUI application do you recommend for use for accessing a Subversion repository? Edit: A lot of people are mentioning Tortoise, however I am looking for an application not a shell extension. Also people are questioning my reasoning behind not wanting to use a shell extension. In our environment we rather interact with the repository (when not using an IDE plugin) through a management application and not navigate the files through Windows Explorer.
Standalone Clients For total stand alone Synchro SVN is a powerful and cross platform solution. It looks like the most native application on each of the platforms. The Subversion website includes a listing of other standalone SVN Clients (most are cross platform). [Copied list below from http://subversion.tigris.org/links.html#clients] eSvn - cross-platform QT-based GUI frontend to Subversion http://sourceforge.net/projects/esvn FSVS - fast subversion command-line client centered around software deployment http://fsvs.tigris.org/ KDESvn - A Subversion client for KDE http://www.alwins-world.de/wiki/programs/kdesvn QSvn - A cross-platform GUI Subversion client http://ar.oszine.de/projects/qsvn/ RapidSVN - A cross-platform GUI front-end for Subversion http://rapidsvn.tigris.org/ RSVN - Python script which allows multiple repository-side operations in a single, atomic transaction. https://opensvn.csie.org/traccgi/rsvn/trac.cgi/wiki SmartSVN - A cross-platform GUI client for Subversion(Not open source. Available in a free and a commercial version.) https://www.smartsvn.com/ Subcommander - A cross-platform Subversion GUI client including a visual text merge tool. http://subcommander.tigris.org/ SvnX - A Mac OS X Panther GUI client. http://www.lachoseinteractive.net/en/community/subversion/svnx/ Syncro SVN Client - Cross-platform graphical Subversion client.(Not open source. Free trial versions available for Mac OS X, Windows and Linux.) http://www.syncrosvnclient.com WorkBench - Cross platform software development GUI built on Subversion written in Python http://pysvn.tigris.org/ Versions - A GUI Subversion client for Mac OS X.(Not open source; requires commercial license.) http://www.versionsapp.com/ ZigVersion - a Subversion Interface for Mac OS X. Aims to design an interface around the typical workflows of programmers.(Note that this is not open source.) http://zigversion.com/ Integrated Clients TortoiseSVN is the best general use system [An integrated system is not standalone - Thanks Martin Kenny]. It integrates itself into Windows Explorer (You can use it in explorer or any shell dialog) so it works extremely well and gives you the full power of SVN. Ankhsvn is a good solution that integrates into Visual Studios (Except Express Editions). SVN Notifier monitors your repositories and will notify you when anything changes. It integrates with TortoiseSVN to show you diffs and commit logs. Very handy when working in a team environment.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/59148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3111/" ] }
59,154
When I press F5 in Visual Studio 2008, I want Google Chrome launched as the browser that my ASP.NET app runs in. May I know how this can be done?
Right click on an .aspx file and click "Browse with..." then select Chrome and click "Set as Default." You can select more than one browser in the list if you want. There's also this really great WoVS Default Browser Switcher Visual Studio extension .
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/59154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ] }
59,166
So I have an object which has some fields, doesn't really matter what.I have a generic list of these objects. List<MyObject> myObjects = new List<MyObject>();myObjects.Add(myObject1);myObjects.Add(myObject2);myObjects.Add(myObject3); So I want to remove objects from my list based on some criteria.For instance, myObject.X >= 10. I would like to use the RemoveAll(Predicate<T> match) method for to do this. I know I can define a delegate which can be passed into RemoveAll, but I would like to know how to define this inline with an anonymous delegate, instead of creating a bunch of delegate functions which are only used in once place.
There's two options, an explicit delegate or a delegate disguised as a lamba construct: explicit delegate myObjects.RemoveAll(delegate (MyObject m) { return m.X >= 10; }); lambda myObjects.RemoveAll(m => m.X >= 10); Performance wise both are equal. As a matter of fact, both language constructs generate the same IL when compiled. This is because C# 3.0 is basically an extension on C# 2.0, so it compiles to C# 2.0 constructs
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/59166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/454247/" ] }
59,181
I have a WCF service that gets called from client side JavaScript. The call fails with a Service is null JavaScript error. WebDevelopment helper trace shows that the calls to load the jsdebug support file results in a 404 (file not found) error. Restarting IIS or clearing out the Temp ASP.Net files or setting batch="false" on the compilation tag in web.config does not resolve the problem From the browser https://Myserver/MyApp/Services/MyService.svc displays the service metadata however https://Myserver/MyApp/Services/MyService.svc/jsdebug results in a 404. The issue seems to be with the https protocol. With http /jsdebug downloads the supporting JS file. Any ideas? TIA
Figured it out! Here is the services configuration section from web.config Look at the bindingConfiguration attribute on the endpoint. The value "webBinding" points to the binding name="webBinding" tag in the bindings and that is what tells the service to use Transport level security it HTTPS. In my case the attribute value was empty causing the webservice request to the /js or /jsdebug file over HTTPS to fail and throw a 404 error. <services> <service name="MyService"> <endpoint address="" behaviorConfiguration="MyServiceAspNetAjaxBehavior" binding="webHttpBinding" bindingConfiguration="webBinding" contract="Services.MyService" /> </service> </services> <bindings> <webHttpBinding> <binding name="webBinding"> <security mode="Transport"> </security> </binding> </webHttpBinding> </bindings> Note that the bindingConfiguration attribute should be empty ("") if the service is accessed via http instead of https (when testing on local machine with no certs) Hope this helps someone.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3635/" ] }
59,195
When I originally was introduced to Mocks I felt the primary purpose was to mock up objects that come from external sources of data. This way I did not have to maintain an automated unit testing test database, I could just fake it. But now I am starting to think of it differently. I am wondering if Mocks are more effective used to completely isolate the tested method from anything outside of itself. The image that keeps coming to mind is the backdrop you use when painting. You want to keep the paint from getting all over everything. I am only testing that method, and I only want to know how it reacts to these faked up external factors? It seems incredibly tedious to do it this way but the advantage I am seeing is when the test fails it is because it is screwed up and not 16 layers down. But now I have to have 16 tests to get the same testing coverage because each piece would be tested in isolation. Plus each test becomes more complicated and more deeply tied to the method it is testing. It feels right to me but it also seems brutal so I kind of want to know what others think.
I recommend you take a look at Martin Fowler's article Mocks Aren't Stubs for a more authoritative treatment of Mocks than I can give you. The purpose of mocks is to unit test your code in isolation of dependencies so you can truly test a piece of code at the "unit" level. The code under test is the real deal, and every other piece of code it relies on (via parameters or dependency injection, etc) is a "Mock" (an empty implementation that always returns expected values when one of its methods is called.) Mocks may seem tedious at first, but they make Unit Testing far easier and more robust once you get the hang of using them. Most languages have Mock libraries which make mocking relatively trivial. If you are using Java, I'll recommend my personal favorite: EasyMock. Let me finish with this thought: you need integration tests too, but having a good volume of unit tests helps you find out which component contains a bug, when one exists.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5551/" ] }
59,217
Is there a built in function in .NET 2.0 that will take two arrays and merge them into one array? The arrays are both of the same type. I'm getting these arrays from a widely used function within my code base and can't modify the function to return the data in a different format. I'm looking to avoid writing my own function to accomplish this if possible.
In C# 3.0 you can use LINQ's Concat method to accomplish this easily: int[] front = { 1, 2, 3, 4 };int[] back = { 5, 6, 7, 8 };int[] combined = front.Concat(back).ToArray(); In C# 2.0 you don't have such a direct way, but Array.Copy is probably the best solution: int[] front = { 1, 2, 3, 4 };int[] back = { 5, 6, 7, 8 };int[] combined = new int[front.Length + back.Length];Array.Copy(front, combined, front.Length);Array.Copy(back, 0, combined, front.Length, back.Length); This could easily be used to implement your own version of Concat .
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/59217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3058/" ] }
59,220
I'm writing a utility for myself, partly as an exercise in learning C# Reflection and partly because I actually want the resulting tool for my own use. What I'm after is basically pointing the application at an assembly and choosing a given class from which to select properties that should be included in an exported HTML form as fields. That form will be then used in my ASP.NET MVC app as the beginning of a View. As I'm using Subsonic objects for the applications where I want to use, this should be reasonable and I figured that, by wanting to include things like differing output HTML depending on data type, Reflection was the way to get this done. What I'm looking for, however, seems to be elusive. I'm trying to take the DLL/EXE that's chosen through the OpenFileDialog as the starting point and load it: String FilePath = Path.GetDirectoryName(FileName);System.Reflection.Assembly o = System.Reflection.Assembly.LoadFile(FileName); That works fine, but because Subsonic-generated objects actually are full of object types that are defined in Subsonic.dll, etc., those dependent objects aren't loaded. Enter: AssemblyName[] ReferencedAssemblies = o.GetReferencedAssemblies(); That, too, contains exactly what I would expect it to. However, what I'm trying to figure out is how to load those assemblies so that my digging into my objects will work properly. I understand that if those assemblies were in the GAC or in the directory of the running executable, I could just load them by their name, but that isn't likely to be the case for this use case and it's my primary use case. So, what it boils down to is how do I load a given assembly and all of its arbitrary assemblies starting with a filename and resulting in a completely Reflection-browsable tree of types, properties, methods, etc. I know that tools like Reflector do this, I just can't find the syntax for getting at it.
Couple of options here: Attach to AppDomain.AssemblyResolve and do another LoadFile based on the requested assembly. Spin up another AppDomain with the directory as its base and load the assemblies in that AppDomain . I'd highly recommend pursuing option 2, since that will likely be cleaner and allow you to unload all those assemblies after. Also, consider loading assemblies in the reflection-only context if you only need to reflect over them (see Assembly.ReflectionOnlyLoad ).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1124/" ] }
59,221
I am using ActiveScaffold in a Ruby on Rails app, and to save space in the table I have replaced the default "actions" text in the table (ie. "edit", "delete", "show") with icons using CSS. I have also added a couple of custom actions with action_link.add ("move" and "copy"). For clarity, I would like to have a tooltip pop up with the related action (ie. "edit", "copy") when I hover the mouse over the icon. I thought I could do this by adding a simple "alt" definition to the tag, but that doesn't appear to work. Can somebody point me in the right direction?
The alt attribute is to be used as an alternative to the image, in the case of the image missing, or in a text only browser. IE got it wrong, when they made alt appear as a tooltip. It was never meant to be that. The correct attribute for this is title , which of course doesn't do a tooltip in IE. So, to do have a tooltip show up in both IE, and FireFox/Safari/Chrome/Opera, use both an alt attribute and a title attribute.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3764/" ] }
59,232
What's the simplest SQL statement that will return the duplicate values for a given column and the count of their occurrences in an Oracle database table? For example: I have a JOBS table with the column JOB_NUMBER . How can I find out if I have any duplicate JOB_NUMBER s, and how many times they're duplicated?
Aggregate the column by COUNT, then use a HAVING clause to find values that appear greater than one time. SELECT column_name, COUNT(column_name)FROM table_nameGROUP BY column_nameHAVING COUNT(column_name) > 1;
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/59232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5662/" ] }
59,267
Starting from ASP.NET MVC Preview 3, HTML.Button ( and other related HTML controls) are no longer supported. The question is, what is the equivalent for them? I've an app that was built using Preview 2, now I have to make it compatible with the latest CTP releases.
I figured it out. It goes something like this: <form method="post" action="<%= Html.AttributeEncode(Url.Action("CastUpVote")) %>"><input type="submit" value="<%=ViewData.Model.UpVotes%> up votes" /></form>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ] }
59,294
I have the following query: select column_name, count(column_name)from tablegroup by column_namehaving count(column_name) > 1; What would be the difference if I replaced all calls to count(column_name) to count(*) ? This question was inspired by How do I find duplicate values in a table in Oracle? . To clarify the accepted answer (and maybe my question), replacing count(column_name) with count(*) would return an extra row in the result that contains a null and the count of null values in the column.
count(*) counts NULLs and count(column) does not [edit] added this code so that people can run it create table #bla(id int,id2 int)insert #bla values(null,null)insert #bla values(1,null)insert #bla values(null,1)insert #bla values(1,null)insert #bla values(null,1)insert #bla values(1,null)insert #bla values(null,null)select count(*),count(id),count(id2)from #bla results7 3 2
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/59294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ] }
59,297
When setting up foreign keys in SQL Server, under what circumstances should you have it cascade on delete or update, and what is the reasoning behind it? This probably applies to other databases as well. I'm looking most of all for concrete examples of each scenario, preferably from someone who has used them successfully.
Summary of what I've seen so far: Some people don't like cascading at all. Cascade Delete Cascade Delete may make sense when the semantics of the relationship can involve an exclusive "is part of " description. For example, an OrderLine record is part of its parent order, and OrderLines will never be shared between multiple orders. If the Order were to vanish, the OrderLine should as well, and a line without an Order would be a problem. The canonical example for Cascade Delete is SomeObject and SomeObjectItems, where it doesn't make any sense for an items record to ever exist without a corresponding main record. You should not use Cascade Delete if you are preserving history or using a "soft/logical delete" where you only set a deleted bit column to 1/true. Cascade Update Cascade Update may make sense when you use a real key rather than a surrogate key (identity/autoincrement column) across tables. The canonical example for Cascade Update is when you have a mutable foreign key, like a username that can be changed. You should not use Cascade Update with keys that are Identity/autoincrement columns. Cascade Update is best used in conjunction with a unique constraint. When To Use Cascading You may want to get an extra strong confirmation back from the user before allowing an operation to cascade, but it depends on your application. Cascading can get you into trouble if you set up your foreign keys wrong. But you should be okay if you do that right. It's not wise to use cascading before you understand it thoroughly. However, it is a useful feature and therefore worth taking the time to understand.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/59297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ] }
59,309
What is the best way to vertically center the content of a div when the height of the content is variable. In my particular case, the height of the container div is fixed, but it would be great if there were a solution that would work in cases where the container has a variable height as well. Also, I would love a solution with no, or very little use of CSS hacks and/or non-semantic markup.
Just add position: relative;top: 50%;transform: translateY(-50%); to the inner div. What it does is moving the inner div's top border to the half height of the outer div ( top: 50%; ) and then the inner div up by half its height ( transform: translateY(-50%) ). This will work with position: absolute or relative . Keep in mind that transform and translate have vendor prefixes which are not included for simplicity. Codepen: http://codepen.io/anon/pen/ZYprdb
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/59309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5651/" ] }
59,322
I have the following code: SELECT <column>, count(*)FROM <table>GROUP BY <column> HAVING COUNT(*) > 1; Is there any difference to the results or performance if I replace the COUNT(*) with COUNT('x')? (This question is related to a previous one )
To say that SELECT COUNT(*) vs COUNT(1) results in your DBMS returning "columns" is pure bunk. That may have been the case long, long ago but any self-respecting query optimizer will choose some fast method to count the rows in the table - there is NO performance difference between SELECT COUNT(*), COUNT(1), COUNT('this is a silly conversation') Moreover, SELECT(1) vs SELECT(*) will NOT have any difference in INDEX usage -- most DBMS will actually optimize SELECT( n ) into SELECT(*) anyway. See the ASK TOM: Oracle has been optimizing SELECT(n) into SELECT(*) for the better part of a decade, if not longer: http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1156151916789 problem is in count(col) to count( ) conversion **03/23/00 05:46 pm *** one workaround is to set event 10122 to turn off count(col) ->count( ) optimization. Another work around is to change the count(col) to count( ), it means the same, when the col has a NOT NULL constraint. The bug number is 1215372. One thing to note - if you are using COUNT(col) (don't!) and col is marked NULL, then it will actually have to count the number of occurrences in the table (either via index scan, histogram, etc. if they exist, or a full table scan otherwise). Bottom line: if what you want is the count of rows in a table, use COUNT(*)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5662/" ] }
59,327
So I'm getting really sick of E*TRADE and, being a developer, would love to find an online broker that offers an API. It would be great to be able to write my own trading tools, and maybe even modify existing ones. Based on my research so far, I've only found one option. Interactive Brokers offers a multi-language API (Java/C++/ActiveX/DDE) and has some fairly decent commission rates to boot. I want to make sure there aren't any other options out there I should be considering. Any ideas? Update: Based on answers so far, here's a quick list... Interactive Brokers Java C++ ActiveX DDE for Excel Pinnacle Trading C++ Perl VB.NET Excel MB Trading
I vote for IB(Interactive Brokers). I've used them in the past as was quite happy. Pinnacle Capital Markets trading also has an API (pcmtrading.com) but I haven't used them. Interactive Brokers: https://www.interactivebrokers.com/en/?f=%2Fen%2Fsoftware%2Fibapi.php Pinnacle Capital Markets: http://www.pcmtrading.com/es/technology/api.html
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/59327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ] }
59,331
Suppose I have fileA.h which declares a class classA with template function SomeFunc<T>() . This function is implemented directly in the header file (as is usual for template functions). Now I add a specialized implementation of SomeFunc() (like for SomeFunc<int>() ) in fileA.C (ie. not in the header file). If I now call SomeFunc<int>() from some other code (maybe also from another library), would it call the generic version, or the specialization? I have this problem right now, where the class and function live in a library which is used by two applications. And one application correctly uses the specialization, while another app uses the generic form (which causes runtime problems later on). Why the difference? Could this be related to linker options etc? This is on Linux, with g++ 4.1.2.
It is an error to have a specialization for a template which is not visible at the point of call. Unfortunately, compilers are not required to diagnose this error, and can then do what they like with your code (in standardese it is "ill formed, no diagnostic required"). Technically, you need to define the specialization in the header file, but just about every compiler will handle this as you might expect: this is fixed in C++11 with the new "extern template" facility: extern template<> SomeFunc<int>(); This explicitly declares that the particular specialization is defined elsewhere. Many compilers support this already, some with and some without the extern .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2148773/" ] }
59,392
I'm a single developer looking to get off of Visual Source Safe and move to svn. A quick search brings up several tools, but I don't see a clear winner and I can't afford to spend a lot of time testing different tools. Has anyone done this successfully, and can recommend a method?
I recommend just adding your code to a new Subversion repository rather than importing from VSS. VSS has a convoluted version control model that doesn't translate well to many other systems, and just starting fresh is usually the best way to avoid taking that clutter with you. If you need to keep the history around, make your VSS repository read-only.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/59392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1204/" ] }
59,422
Is accessing a bool field atomic in C#? In particular, do I need to put a lock around: class Foo{ private bool _bar; //... in some function on any thread (or many threads) _bar = true; //... same for a read if (_bar) { ... }}
Yes. Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types. as found in C# Language Spec . Edit: It's probably also worthwhile understanding the volatile keyword.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/59422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/838/" ] }
59,428
I've been making my way through The Little Schemer and I was wondering what environment, IDE or interpreter would be best to use in order to test any of the Scheme code I jot down for myself.
Racket ( formerly Dr Scheme ) has a nice editor, several different Scheme dialects, an attempt at visual debugging, lots of libraries, and can run on most platforms. It even has some modes specifically geared around learning the language.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/59428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64/" ] }
59,436
As much as we would all like to say it is a benefit to programmers to be language agnostic, is it really feasible to support multiple enterprise Web applications of the same type all written in different languages? Think about how complicated a CMS or e-commerce system can be -- now imagine supporting three different CMS platforms all written in different languages. I would hate to be known as a .NET or Java or PHP shop, but I also don't want to be the vendor who says they can support a solution they have never worked with, upsetting a client who wonders why we can't get something done right on time. Can anyone speak from experience on this? Does your company usually just suck it up, and try and to learn a new platform on the fly? Do you bill up-to-speed, or eat those costs?
Racket ( formerly Dr Scheme ) has a nice editor, several different Scheme dialects, an attempt at visual debugging, lots of libraries, and can run on most platforms. It even has some modes specifically geared around learning the language.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/59436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
59,444
Is there a system stored procedure to get the version #?
Try SELECT @@VERSION or for SQL Server 2000 and above the following is easier to parse :) SELECT SERVERPROPERTY('productversion') , SERVERPROPERTY('productlevel') , SERVERPROPERTY('edition') From: http://support.microsoft.com/kb/321185
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/59444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ] }
59,451
How do I create a silverlight data template in code? I've seen plenty of examples for WPF, but nothing for Silverlight. Edit: Here's the code I'm now using this for, based on the answer from Santiago below. public DataTemplate Create(Type type){ return (DataTemplate)XamlReader.Load( @"<DataTemplate xmlns=""http://schemas.microsoft.com/client/2007""> <" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/> </DataTemplate>" );} This works really nicely and allows me to change the binding on the fly.
Although you cannot programatically create it, you can load it from a XAML string in code like this: public static DataTemplate Create(Type type) { return (DataTemplate) XamlReader.Load( @"<DataTemplate xmlns=""http://schemas.microsoft.com/client/2007""> <" + type.Name + @"/> </DataTemplate>" ); } The snippet above creates a data template containing a single control, which may be a user control with the contents you need.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/59451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5932/" ] }
59,482
A former coworker insisted that a database with more tables with fewer columns each is better than one with fewer tables with more columns each. For example rather than a customer table with name, address, city, state, zip, etc. columns, you would have a name table, an address table, a city table, etc. He argued this design was more efficient and flexible. Perhaps it is more flexible, but I am not qualified to comment on its efficiency. Even if it is more efficient, I think those gains may be outweighed by the added complexity. So, are there any significant benefits to more tables with fewer columns over fewer tables with more columns?
I have a few fairly simple rules of thumb I follow when designing databases, which I think can be used to help make decisions like this.... Favor normalization. Denormalization is a form of optimization, with all the requisite tradeoffs, and as such it should be approached with a YAGNI attitude. Make sure that client code referencing the database is decoupled enough from the schema that reworking it doesn't necessitate a major redesign of the client(s). Don't be afraid to denormalize when it provides a clear benefit to performance or query complexity. Use views or downstream tables to implement denormalization rather than denormalizing the core of the schema, when data volume and usage scenarios allow for it . The usual result of these rules is that the initial design will favor tables over columns, with a focus on eliminating redundancy. As the project progresses and denormalization points are identified, the overall structure will evolve toward a balance that compromises with limited redundancy and column proliferation in exchange for other valuable benefits.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/59482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4228/" ] }
59,515
I am new to all the anonymous features and need some help. I have gotten the following to work: public void FakeSaveWithMessage(Transaction t){ t.Message = "I drink goats blood";}public delegate void FakeSave(Transaction t);public void SampleTestFunction(){ Expect.Call(delegate { _dao.Save(t); }).Do(new FakeSave(FakeSaveWithMessage));} But this is totally ugly and I would like to have the inside of the Do to be an anonymous method or even a lambda if it is possible. I tried: Expect.Call(delegate { _dao.Save(t); }).Do(delegate(Transaction t2) { t2.Message = "I drink goats blood"; }); and Expect.Call(delegate { _dao.Save(t); }).Do(delegate { t.Message = "I drink goats blood"; }); but these give me Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type** compile errors. What am I doing wrong? Because of what Mark Ingram posted, seems like the best answer, though nobody's explicitly said it, is to do this: public delegate void FakeSave(Transaction t);Expect.Call(delegate { _dao.Save(t); }).Do( new FakeSave(delegate(Transaction t2) { t.Message = expected_msg; }));
That's a well known error message. Check the link below for a more detailed discussion. http://staceyw1.wordpress.com/2007/12/22/they-are-anonymous-methods-not-anonymous-delegates/ Basically you just need to put a cast in front of your anonymous delegate (your lambda expression). In case the link ever goes down, here is a copy of the post: They are Anonymous Methods, not Anonymous Delegates. Posted on December 22, 2007 by staceyw1 It is not just a talking point because we want to be difficult. It helps us reason about what exactly is going on. To be clear, there is *no such thing as an anonymous delegate. They don’t exist (not yet). They are "Anonymous Methods" – period. It matters in how we think of them and how we talk about them. Lets take a look at the anonymous method statement "delegate() {…}". This is actually two different operations and when we think of it this way, we will never be confused again. The first thing the compiler does is create the anonymous method under the covers using the inferred delegate signature as the method signature. It is not correct to say the method is "unnamed" because it does have a name and the compiler assigns it. It is just hidden from normal view. The next thing it does is create a delegate object of the required type to wrap the method. This is called delegate inference and can be the source of this confusion. For this to work, the compiler must be able to figure out (i.e. infer) what delegate type it will create. It has to be a known concrete type. Let write some code to see why. private void MyMethod(){} Does not compile: 1) Delegate d = delegate() { }; // Cannot convert anonymous method to type ‘System.Delegate’ because it is not a delegate type2) Delegate d2 = MyMethod; // Cannot convert method group ‘MyMethod’ to non-delegate type ‘System.Delegate’3) Delegate d3 = (WaitCallback)MyMethod; // No overload for ‘MyMethod’ matches delegate ‘System.Threading.WaitCallback’ Line 1 does not compile because the compiler can not infer any delegate type. It can plainly see the signature we desire, but there is no concrete delegate type the compiler can see. It could create an anonymous type of type delegate for us, but it does not work like that. Line 2 does not compile for a similar reason. Even though the compiler knows the method signature, we are not giving it a delegate type and it is not just going to pick one that would happen to work (not what side effects that could have). Line 3 does not work because we purposely mismatched the method signature with a delegate having a different signature (as WaitCallback takes and object). Compiles: 4) Delegate d4 = (MethodInvoker)MyMethod; // Works because we cast to a delegate type of the same signature.5) Delegate d5 = (Action)delegate { }; // Works for same reason as d4.6) Action d6 = MyMethod; // Delegate inference at work here. New Action delegate is created and assigned. In contrast, these work. Line 1 works because we tell the compiler what delegate type to use and they match, so it works. Line 5 works for the same reason. Note we used the special form of "delegate" without the parens. The compiler infers the method signature from the cast and creates the anonymous method with the same signature as the inferred delegate type. Line 6 works because the MyMethod() and Action use same signature. I hope this helps. Also see: http://msdn.microsoft.com/msdnmag/issues/04/05/C20/
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/59515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ] }
59,537
Service Oriented Architecture seems to be more and more of a hot quote these days, but after asking around the office I have found that I seem to get many different definitions for it. How would you guys define SOA? What would you consider the official definition?
As Martin Fowler says, it means different things to different people. His article on the topic is pretty good although it isn't quite a definition. http://martinfowler.com/bliki/ServiceOrientedAmbiguity.html It may explain, the difficulty coming up with a concrete definition.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/59537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2328/" ] }
59,547
I maintain an old PC-only application written in Delphi 7. Although Delphi has served me very well in the past I now only use it for this one application and find my skills with the language diminishing. Its syntax is too different from my 'day job' languages of Java/Ruby so it takes me longer to get into the groove of writing new code, plus it is so old I have not used many interface s so the code is not managed which seems ancient to me now! Many of my users are moving to Vista which may run the app in compatibility mode or may have GPF problems depending on how their PC is configured by their IT department, so I have to do some maintenance on the application. I'm wondering if I should jump to a more familiar stack. Is there an automated tool that will do the legwork of converting the code base to C#, leaving me to concentrate on the conversion on any non-standard components? I'm using an embedded database component called AbsoluteDatabase which is BDE compatible and using standard SQL throughout, and a native Delphi HTML browser component which can be swapped out with something from the Microsoft world. How good are these conversion tools?
I am not aware of any automated tools for making that conversion. Personally I would suggest you stick with Delphi, maybe just upgrade to a new version. I have seen a couple code DOM's that attempt to convert from Delphi to C#, but that doesn't address the library issue. CodeGear (formally Borland) has a tool for going from C# to Delphi that works OK. I would assume the tools that go the other direction will work the same (requiring a lot of editing). Here is a Swedish tool that works on the same CodeDOM principle to go from Delphi to C# (and a number of other languages). There are others, I just can't find them right now. Another option would be to upgrade to a more resent version of Delphi for .NET and port your code to .NET that way. Once you get it working in Delphi for .NET (which will be pretty easy, except for the embedded DB, unless they have a .NET version) you can use .NET Reflector and File Disassembler reverse the IL to C#. You will still be using the VCL, but you can use C# instead of Object pascal. Another similar solution would be to port it to Oxygene by RemObjects . I believe they have a Delphi Win32 migration path to WinForms. Then use .NET Reflector and File Disassembler reverse the IL to C#. In short, no easy answers. Language migration is easier then library migration. A lot of it depends on what 3rd party components you used (beyond AbsoluteDatabase) and if you made any Windows API calls directly in your application. Another completely different option would be too look for an off shore team to maintain the application. They can probably do so cheaply. You could find someone domestically, but it would cost you more no doubt (although with the sagging dollar and poor job market you never know . . . ) Good luck!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3366/" ] }
59,560
Of all the forms of CAPTCHA available, which one is the "least crackable" while remaining fairly human readable?
I agree with Thomas. Captcha is on its way out. But if you must use it, reCAPTCHA is a pretty good provider with a simple API.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5287/" ] }
59,590
I understand the main function of the lock key word from MSDN lock Statement (C# Reference) The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock. When should the lock be used? For instance it makes sense with multi-threaded applications because it protects the data. But is it necessary when the application does not spin off any other threads? Is there performance issues with using lock? I have just inherited an application that is using lock everywhere, and it is single threaded and I want to know should I leave them in, are they even necessary? Please note this is more of a general knowledge question, the application speed is fine, I want to know if that is a good design pattern to follow in the future or should this be avoided unless absolutely needed.
When should the lock be used? A lock should be used to protect shared resources in multithreaded code. Not for anything else. But is it necessary when the application does not spin off any other threads? Absolutely not. It's just a time waster. However do be sure that you're not implicitly using system threads. For example if you use asynchronous I/O you may receive callbacks from a random thread, not your original thread. Is there performance issues with using lock? Yes. They're not very big in a single-threaded application, but why make calls you don't need? ...if that is a good design pattern to follow in the future[?] Locking everything willy-nilly is a terrible design pattern. If your code is cluttered with random locking and then you do decide to use a background thread for some work, you're likely to run into deadlocks. Sharing a resource between multiple threads requires careful design, and the more you can isolate the tricky part, the better.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/59590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2469/" ] }
59,635
Since our switch from Visual Studio 6 to Visual Studio 2008, we've been using the MFC90.dll and msvc[pr]90.dlls along with the manifest files in a private side-by-side configuration so as to not worry about versions or installing them to the system. Pre-SP1, this was working fine (and still works fine on our developer machines). Now that we've done some testing post-SP1 I've been pulling my hair out since yesterday morning. First off, our NSIS installer script pulls the dlls and manifest files from the redist folder. These were no longer correct, as the app still links to the RTM version. So I added the define for _BIND_TO_CURRENT_VCLIBS_VERSION=1 to all of our projects so that they will use the SP1 DLLs in the redist folder (or subsequent ones as new service packs come out). It took me hours to find this. I've double checked the generated manifest files in the intermediate files folder from the compilation, and they correctly list the 9.0.30729.1 SP1 versions. I've double and triple checked depends on a clean machine: it all links to the local dlls with no errors. Running the app still gets the following error: The application failed to initialize properly (0xc0150002). Click on OK to terminate the application. None of the searches I've done on google or microsoft have come up with anything that relates to my specific issues (but there are hits back to 2005 with this error message). Any one had any similar problem with SP1? Options: Find the problem and fix it so it works as it should (preferred) Install the redist dig out the old RTM dlls and manifest files and remove the #define to use the current ones. (I've got them in an earlier installer build, since Microsoft blasts them out of your redist folder!) Edit: I've tried re-building with the define turned off (link to RTM dlls), and that works as long as the RTM dlls are installed in the folder. If the SP1 dlls are dropped in, it gets the following error: c:\Program Files\...\...\X.exe This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. Has no-one else had to deal with this issue? Edit: Just for grins, I downloaded and ran the vcredist_x86.exe for VS2008SP1 on my test machine. It works. With the SP1 DLLs. And my RTM linked app. But NOT in a private side-by-side distribution that worked pre-SP1.
I have battled this problem myself last week and consider myself somewhat of an expert now ;) I'm 99% sure that not all dlls and static libraries were recompiled with the SP1 version. You need to put #define _BIND_TO_CURRENT_MFC_VERSION 1#define _BIND_TO_CURRENT_CRT_VERSION 1 into every project you're using. For every project of a real-world size, it's very easy to forget some small lib that wasn't recompiled. There are more flags that define what versions to bind to; it's documented on http://msdn.microsoft.com/en-us/library/cc664727%28v=vs.90%29.aspx . As an alternative to the lines above, you can also put #define _BIND_TO_CURRENT_VCLIBS_VERSION 1 which will bind to the latest version of all VC libs (CRT, MFC, ATL, OpenMP). Then, check what the embedded manifest says. Download XM Resource Editor: http://www.wilsonc.demon.co.uk/d10resourceeditor.htm . Open every dll and exe in your solution. Look under 'XP Theme Manifest'. Check that the 'version' attribute on the right-hand side is '9.0.30729.1'. If it's '9.0.21022', some static library is pulling in the manifest for the old version. What I found is that in many cases, both versions were included in the manifest. This means that some libraries use the sp1 version and others don't. A great way to debug which libraries don't have the preprocessor directives set: temporarily modify your platform headers so that compilation stops when it tries to embed the old manifest. Open C:\Program Files\Microsoft Visual Studio 9.0\VC\crt\include\crtassem.h. Search for the '21022' string. In that define, put something invalid (change 'define' to 'blehbleh' or so). This way, when you're compiling a project where the _BIND_TO_CURRENT_CRT_VERSION preprocessor flag is not set, your compilation will stop and you'll know that you need to add them or made sure that it's applied everywhere. Also make sure to use Dependency Walker so that you know what dlls are being pulled in. It's easiest to install a fresh Windows XP copy with no updates (only SP2) on a virtual machine. This way you know for sure that there is nothing in the SxS folder that is being used instead of the side-by-side dlls that you supplied.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/59635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1441/" ] }
59,642
What's the best way to determine which version of the .NET Compact Frameworks (including Service Packs) is installed on a device through a .NET application.
I have battled this problem myself last week and consider myself somewhat of an expert now ;) I'm 99% sure that not all dlls and static libraries were recompiled with the SP1 version. You need to put #define _BIND_TO_CURRENT_MFC_VERSION 1#define _BIND_TO_CURRENT_CRT_VERSION 1 into every project you're using. For every project of a real-world size, it's very easy to forget some small lib that wasn't recompiled. There are more flags that define what versions to bind to; it's documented on http://msdn.microsoft.com/en-us/library/cc664727%28v=vs.90%29.aspx . As an alternative to the lines above, you can also put #define _BIND_TO_CURRENT_VCLIBS_VERSION 1 which will bind to the latest version of all VC libs (CRT, MFC, ATL, OpenMP). Then, check what the embedded manifest says. Download XM Resource Editor: http://www.wilsonc.demon.co.uk/d10resourceeditor.htm . Open every dll and exe in your solution. Look under 'XP Theme Manifest'. Check that the 'version' attribute on the right-hand side is '9.0.30729.1'. If it's '9.0.21022', some static library is pulling in the manifest for the old version. What I found is that in many cases, both versions were included in the manifest. This means that some libraries use the sp1 version and others don't. A great way to debug which libraries don't have the preprocessor directives set: temporarily modify your platform headers so that compilation stops when it tries to embed the old manifest. Open C:\Program Files\Microsoft Visual Studio 9.0\VC\crt\include\crtassem.h. Search for the '21022' string. In that define, put something invalid (change 'define' to 'blehbleh' or so). This way, when you're compiling a project where the _BIND_TO_CURRENT_CRT_VERSION preprocessor flag is not set, your compilation will stop and you'll know that you need to add them or made sure that it's applied everywhere. Also make sure to use Dependency Walker so that you know what dlls are being pulled in. It's easiest to install a fresh Windows XP copy with no updates (only SP2) on a virtual machine. This way you know for sure that there is nothing in the SxS folder that is being used instead of the side-by-side dlls that you supplied.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/59642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2723/" ] }
59,655
Given a controller method like: def show @model = Model.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => model } endend What's the best way to write an integration test that asserts that the return has the expected XML?
A combination of using the format and assert_select in an integration test works great: class ProductsTest < ActionController::IntegrationTest def test_contents_of_xml get '/index/1.xml' assert_select 'product name', /widget/ endend For more details check out assert_select in the Rails docs.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4748/" ] }
59,656
Erasing programs such as Eraser recommend overwriting data maybe 36 times. As I understand it all data is stored on a hard drive as 1s or 0s. If an overwrite of random 1s and 0s is carried out once over the whole file then why isn't that enough to remove all traces of the original file?
A hard drive bit which used to be a 0, and is then changed to a '1', has a slightly weaker magnetic field than one which used to be a 1 and was then written to 1 again. With sensitive equipment the previous contents of each bit can be discerned with a reasonable degree of accuracy, by measuring the slight variances in strength. The result won't be exactly correct and there will be errors, but a good portion of the previous contents can be retrieved. By the time you've scribbled over the bits 35 times, it is effectively impossible to discern what used to be there. Edit: A modern analysis shows that a single overwritten bit can be recovered with only 56% accuracy. Trying to recover an entire byte is only accurate 0.97% of the time. So I was just repeating an urban legend. Overwriting multiple times might have been necessary when working with floppy disks or some other medium, but hard disks do not need it.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/59656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6164/" ] }
59,667
I realize that CHAR is recommended if all my values are fixed-width. But, so what? Why not just pick VARCHAR for all text fields just to be safe.
The general rule is to pick CHAR if all rows will have close to the same length . Pick VARCHAR (or NVARCHAR ) when the length varies significantly. CHAR may also be a bit faster because all the rows are of the same length. It varies by DB implementation, but generally, VARCHAR (or NVARCHAR ) uses one or two more bytes of storage (for length or termination) in addition to the actual data. So (assuming you are using a one-byte character set) storing the word "FooBar" CHAR(6) = 6 bytes (no overhead) VARCHAR(100) = 8 bytes (2 bytes of overhead) CHAR(10) = 10 bytes (4 bytes of waste) The bottom line is CHAR can be faster and more space-efficient for data of relatively the same length (within two characters length difference). Note : Microsoft SQL has 2 bytes of overhead for a VARCHAR. This may vary from DB to DB, but generally, there is at least 1 byte of overhead needed to indicate length or EOL on a VARCHAR. As was pointed out by Gaven in the comments: Things change when it comes to multi-byte characters sets, and is a is case where VARCHAR becomes a much better choice. A note about the declared length of the VARCHAR : Because it stores the length of the actual content, then you don't waste unused length. So storing 6 characters in VARCHAR(6), VARCHAR(100), or VARCHAR(MAX) uses the same amount of storage. Read more about the differences when using VARCHAR(MAX) . You declare a maximum size in VARCHAR to limit how much is stored. In the comments AlwaysLearning pointed out that the Microsoft Transact-SQL docs seem to say the opposite. I would suggest that is an error or at least the docs are unclear.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/59667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5592/" ] }
59,670
I'm working on an exceedingly large codebase, and recently upgraded to GCC 4.3, which now triggers this warning: warning: deprecated conversion from string constant to ‘char*’ Obviously, the correct way to fix this is to find every declaration like char *s = "constant string"; or function call like: void foo(char *s);foo("constant string"); and make them const char pointers. However, that would mean touching 564 files, minimum, which is not a task I wish to perform at this point in time. The problem right now is that I'm running with -Werror , so I need some way to stifle these warnings. How can I do that?
I believe passing -Wno-write-strings to GCC will suppress this warning.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/59670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3830/" ] }
59,677
Would using WSDualHttpBinding for duplex callbacks work in real-world scenarios? Say, I have a .NET application that uses a random port, would the service be able to resolve the client's base addresses and port for callbacks?
A complete answer to your question depends on the "real-world scenario" being either an Intranet or an Internet scenario. Although WSDualHttpBinding works in both scenarios there are specifics to be aware of: Intranet WSDualHttpBinding will work with your .NET application using a preconfigured custom port in an Intranet scenario and "Yes" the service will be able to resolve the client's base addresses and port for callbacks: exactly how is explained below. The reason it's explained below is that WSDualHttpBinding is primarily designed to be used over the Internet. Duplex callbacks in an Intranet scenario when you can use WCF on both client and server is best achieved by using NetTcpBinding or NetNamedPipeBinding. These bindings use TCP and ICP respectively as transport (rather than HTTP) and a custom binary encoding which is why WCF is required on both sides. For calls-back to the client the same channel used to connect to the Service via the Binding is re-used without requiring a new port to be opened. Internet In an Internet scenario valid HTTP requests and responses only travel in one direction, HTTP is designed as a one-way protocol. When using the WSDualHttpBinding WCF therefore creates a seperate HTTP channel for callbacks. In answer to your second question: the destination address for this call-back to the client is composed of the client machine hostname and port 80 by default. If the client is a development machine for example and has IIS installed, port 80 will be exclusively reserved in some scenarios which will cause conflicts with your prototype application. This is what this blog post presents a solution for and what the ClientBaseAddress property is designed to help with. Regardless of which port you go with - the default or a custom one, you must ensure all firewalls and routers on both sides are configured correctly to allow both the outgoing channel and the seperate callback channel to be established. A .NET application can also denote a Silverlight application. Because of the fact that a Silverlight application running in a browser cannot accept new incoming HTTP connections, WSDualHttpBinding with it's seperate back channel will not work. Hence PollingDuplexHttpBinding was created firstly in Silverlight 2 which can be thought of as a clever 'trick' to get around the fact that HTTP is unidirectional by keeping the request channel open for a long time (long polling) and using it as a back channel for calls back to the client. This has a number of implications on both the client and server side particularly relevant to scaling, for more detail please see this post from my blog . With an idea of your particular "real-world scenario" and your use-cases hopefully this will help you work out the correct binding to use for duplex callbacks.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/59677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5563/" ] }
59,719
I need to run a JavaScript function onLoad(), but only do it if the page loaded the first time (i.e. is not the result of a postback). Basically, I need to check for IsPostBack in JavaScript. Thank you.
Server-side, write: if(IsPostBack){ // NOTE: the following uses an overload of RegisterClientScriptBlock() // that will surround our string with the needed script tags ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true);} Then, in your script which runs for the onLoad, check for the existence of that variable: if(isPostBack) { // do your thing} You don't really need to set the variable otherwise, like Jonathan's solution. The client-side if statement will work fine because the "isPostBack" variable will be undefined, which evaluates as false in that if statement.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/59719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3661/" ] }
59,743
How many possible combinations of the variables a,b,c,d,e are possible if I know that: a+b+c+d+e = 500 and that they are all integers and >= 0, so I know they are finite.
@Torlack, @Jason Cohen: Recursion is a bad idea here, because there are "overlapping subproblems." I.e., If you choose a as 1 and b as 2 , then you have 3 variables left that should add up to 497; you arrive at the same subproblem by choosing a as 2 and b as 1 . (The number of such coincidences explodes as the numbers grow.) The traditional way to attack such a problem is dynamic programming : build a table bottom-up of the solutions to the sub-problems (starting with "how many combinations of 1 variable add up to 0?") then building up through iteration (the solution to "how many combinations of n variables add up to k ?" is the sum of the solutions to "how many combinations of n-1 variables add up to j ?" with 0 <= j <= k ). public static long getCombos( int n, int sum ) { // tab[i][j] is how many combinations of (i+1) vars add up to j long[][] tab = new long[n][sum+1]; // # of combos of 1 var for any sum is 1 for( int j=0; j < tab[0].length; ++j ) { tab[0][j] = 1; } for( int i=1; i < tab.length; ++i ) { for( int j=0; j < tab[i].length; ++j ) { // # combos of (i+1) vars adding up to j is the sum of the # // of combos of i vars adding up to k, for all 0 <= k <= j // (choosing i vars forces the choice of the (i+1)st). tab[i][j] = 0; for( int k=0; k <= j; ++k ) { tab[i][j] += tab[i-1][k]; } } } return tab[n-1][sum];} $ time java Combos2656615626real 0m0.151suser 0m0.120ssys 0m0.012s
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1815/" ] }
59,761
I need to disable specific keys (Ctrl and Backspace) in Internet Explorer 6. Is there a registry hack to do this. It has to be IE6. Thanks. Long Edit: @apandit: Whoops. I need to more specific about the backspace thing. When I say disable backspace, I mean disable the ability for Backspace to mimic the Back browser button. In IE, pressing Backspace when the focus is not in a text entry field is equivalent to pressing Back (browsing to the previous page). As for the Ctrl key. There are some pages which have links which create new IE windows. I have the popup blocker turned on, which block this. But, Ctrl clicking result in the new window being launched. This is for a kiosk application, which is currently a web based application. Clients do not have the funds at this time to make their site kiosk friendly. Things like URL filtering and disabling the URL entry field is already done. Thanks.
@Torlack, @Jason Cohen: Recursion is a bad idea here, because there are "overlapping subproblems." I.e., If you choose a as 1 and b as 2 , then you have 3 variables left that should add up to 497; you arrive at the same subproblem by choosing a as 2 and b as 1 . (The number of such coincidences explodes as the numbers grow.) The traditional way to attack such a problem is dynamic programming : build a table bottom-up of the solutions to the sub-problems (starting with "how many combinations of 1 variable add up to 0?") then building up through iteration (the solution to "how many combinations of n variables add up to k ?" is the sum of the solutions to "how many combinations of n-1 variables add up to j ?" with 0 <= j <= k ). public static long getCombos( int n, int sum ) { // tab[i][j] is how many combinations of (i+1) vars add up to j long[][] tab = new long[n][sum+1]; // # of combos of 1 var for any sum is 1 for( int j=0; j < tab[0].length; ++j ) { tab[0][j] = 1; } for( int i=1; i < tab.length; ++i ) { for( int j=0; j < tab[i].length; ++j ) { // # combos of (i+1) vars adding up to j is the sum of the # // of combos of i vars adding up to k, for all 0 <= k <= j // (choosing i vars forces the choice of the (i+1)st). tab[i][j] = 0; for( int k=0; k <= j; ++k ) { tab[i][j] += tab[i-1][k]; } } } return tab[n-1][sum];} $ time java Combos2656615626real 0m0.151suser 0m0.120ssys 0m0.012s
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78/" ] }
59,766
I thought jQuery Intellisense was supposed to be improved with SP1. I even downloaded an annotated version of jQuery 1.2.6, but intellisense will not work in a separate jscript file. I have the jQuery library referenced first on my web page in the <head> tag. Am I doing anything wrong?
At the top of your external JavaScript file, add the following: /// <reference path="jQuery.js"/> Make sure the path is correct, relative to the file's position in the folder structure, etc. Also, any references need to be at the top of the file, before any other text, including comments - literally, the very first thing in the file. Hopefully future version of Visual Studio will work regardless of where it is in the file, or maybe they will do something altogether different... Once you have done that and saved the file , hit Ctrl + Shift + J to force Visual Studio to update Intellisense.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/59766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ] }
59,819
I would like to be able to define and use a custom type in some of my PowerShell scripts. For example, let's pretend I had a need for an object that had the following structure: Contact{ string First string Last string Phone} How would I go about creating this so that I could use it in function like the following: function PrintContact{ param( [Contact]$contact ) "Customer Name is " + $contact.First + " " + $contact.Last "Customer Phone is " + $contact.Phone } Is something like this possible, or even recommended in PowerShell?
Prior to PowerShell 3 PowerShell's Extensible Type System didn't originally let you create concrete types you can test against the way you did in your parameter. If you don't need that test, you're fine with any of the other methods mentioned above. If you want an actual type that you can cast to or type-check with, as in your example script ... it cannot be done without writing it in C# or VB.net and compiling. In PowerShell 2, you can use the "Add-Type" command to do it quite simmple: add-type @"public struct contact { public string First; public string Last; public string Phone;}"@ Historical Note : In PowerShell 1 it was even harder. You had to manually use CodeDom, there is a very old function new-struct script on PoshCode.org which will help. Your example becomes: New-Struct Contact @{ First=[string]; Last=[string]; Phone=[string];} Using Add-Type or New-Struct will let you actually test the class in your param([Contact]$contact) and make new ones using $contact = new-object Contact and so on... In PowerShell 3 If you don't need a "real" class that you can cast to, you don't have to use the Add-Member way that Steven and others have demonstrated above. Since PowerShell 2 you could use the -Property parameter for New-Object: $Contact = New-Object PSObject -Property @{ First=""; Last=""; Phone="" } And in PowerShell 3, we got the ability to use the PSCustomObject accelerator to add a TypeName: [PSCustomObject]@{ PSTypeName = "Contact" First = $First Last = $Last Phone = $Phone} You're still only getting a single object, so you should make a New-Contact function to make sure that every object comes out the same, but you can now easily verify a parameter "is" one of those type by decorating a parameter with the PSTypeName attribute: function PrintContact{ param( [PSTypeName("Contact")]$contact ) "Customer Name is " + $contact.First + " " + $contact.Last "Customer Phone is " + $contact.Phone } In PowerShell 5 In PowerShell 5 everything changes, and we finally got class and enum as language keywords for defining types (there's no struct but that's ok): class Contact{ # Optionally, add attributes to prevent invalid values [ValidateNotNullOrEmpty()][string]$First [ValidateNotNullOrEmpty()][string]$Last [ValidateNotNullOrEmpty()][string]$Phone # optionally, have a constructor to # force properties to be set: Contact($First, $Last, $Phone) { $this.First = $First $this.Last = $Last $this.Phone = $Phone }} We also got a new way to create objects without using New-Object : [Contact]::new() -- in fact, if you kept your class simple and don't define a constructor, you can create objects by casting a hashtable (although without a constructor, there would be no way to enforce that all properties must be set): class Contact{ # Optionally, add attributes to prevent invalid values [ValidateNotNullOrEmpty()][string]$First [ValidateNotNullOrEmpty()][string]$Last [ValidateNotNullOrEmpty()][string]$Phone}$C = [Contact]@{ First = "Joel" Last = "Bennett"}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/59819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4916/" ] }
59,825
Suppose the following: >>> s = set([1, 2, 3]) How do I get a value (any value) out of s without doing s.pop() ? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host. Quick and dirty: >>> elem = s.pop()>>> s.add(elem) But do you know of a better way? Ideally in constant time.
Two options that don't require copying the whole set: for e in s: break# e is now an element from s Or... e = next(iter(s)) But in general, sets don't support indexing or slicing.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/59825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260/" ] }
59,838
What command checks if a directory exists or not within a Bash shell script?
To check if a directory exists: if [ -d "$DIRECTORY" ]; then echo "$DIRECTORY does exist."fi To check if a directory does not exist: if [ ! -d "$DIRECTORY" ]; then echo "$DIRECTORY does not exist."fi However, as Jon Ericson points out, subsequent commands may not work as intended if you do not take into account that a symbolic link to a directory will also pass this check.E.g. running this: ln -s "$ACTUAL_DIR" "$SYMLINK"if [ -d "$SYMLINK" ]; then rmdir "$SYMLINK" fi Will produce the error message: rmdir: failed to remove `symlink': Not a directory So symbolic links may have to be treated differently, if subsequent commands expect directories: if [ -d "$LINK_OR_DIR" ]; then if [ -L "$LINK_OR_DIR" ]; then # It is a symlink! # Symbolic link specific commands go here. rm "$LINK_OR_DIR" else # It's a directory! # Directory command goes here. rmdir "$LINK_OR_DIR" fifi Take particular note of the double-quotes used to wrap the variables. The reason for this is explained by 8jean in another answer . If the variables contain spaces or other unusual characters it will probably cause the script to fail.
{ "score": 13, "source": [ "https://Stackoverflow.com/questions/59838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4120/" ] }
59,850
I'd like to create a spring bean that holds the value of a double. Something like: <bean id="doubleValue" value="3.7"/>
Declare it like this: <bean id="doubleValue" class="java.lang.Double"> <constructor-arg index="0" value="3.7"/></bean> And use like this: <bean id="someOtherBean" ...> <property name="value" ref="doubleValue"/></bean>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6180/" ] }
59,857
Should I use a dedicated network channel between the database and the application server? ...or... Connecting both in the switch along with all other computer nodes makes no diference at all? The matter is performance!
Declare it like this: <bean id="doubleValue" class="java.lang.Double"> <constructor-arg index="0" value="3.7"/></bean> And use like this: <bean id="someOtherBean" ...> <property name="value" ref="doubleValue"/></bean>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1100/" ] }
59,880
Conventional wisdom states that stored procedures are always faster. So, since they're always faster, use them ALL THE TIME . I am pretty sure this is grounded in some historical context where this was once the case. Now, I'm not advocating that Stored Procs are not needed, but I want to know in what cases stored procedures are necessary in modern databases such as MySQL, SQL Server, Oracle, or < Insert_your_DB_here >. Is it overkill to have ALL access through stored procedures?
NOTE that this is a general look at stored procedures not regulated to a specific DBMS. Some DBMS (and even, different versions of the same DBMS!) may operate contrary to this, so you'll want to double-check with your target DBMS before assuming all of this still holds. I've been a Sybase ASE, MySQL, and SQL Server DBA on-and off since for almost a decade (along with application development in C, PHP, PL/SQL, C#.NET, and Ruby). So, I have no particular axe to grind in this (sometimes) holy war. The historical performance benefit of stored procs have generally been from the following (in no particular order): Pre-parsed SQL Pre-generated query execution plan Reduced network latency Potential cache benefits Pre-parsed SQL -- similar benefits to compiled vs. interpreted code, except on a very micro level. Still an advantage? Not very noticeable at all on the modern CPU, but if you are sending a single SQL statement that is VERY large eleventy-billion times a second, the parsing overhead can add up. Pre-generated query execution plan . If you have many JOINs the permutations can grow quite unmanageable (modern optimizers have limits and cut-offs for performance reasons). It is not unknown for very complicated SQL to have distinct, measurable (I've seen a complicated query take 10+ seconds just to generate a plan, before we tweaked the DBMS) latencies due to the optimizer trying to figure out the "near best" execution plan. Stored procedures will, generally, store this in memory so you can avoid this overhead. Still an advantage? Most DBMS' (the latest editions) will cache the query plans for INDIVIDUAL SQL statements, greatly reducing the performance differential between stored procs and ad hoc SQL. There are some caveats and cases in which this isn't the case, so you'll need to test on your target DBMS. Also, more and more DBMS allow you to provide optimizer path plans (abstract query plans) to significantly reduce optimization time (for both ad hoc and stored procedure SQL!!). WARNING Cached query plans are not a performance panacea. Occasionally the query plan that is generated is sub-optimal. For example, if you send SELECT * FROM table WHERE id BETWEEN 1 AND 99999999 , the DBMS may select a full-table scan instead of an index scan because you're grabbing every row in the table (so sayeth the statistics). If this is the cached version, then you can get poor performance when you later send SELECT * FROM table WHERE id BETWEEN 1 AND 2 . The reasoning behind this is outside the scope of this posting, but for further reading see: http://www.microsoft.com/technet/prodtechnol/sql/2005/frcqupln.mspx and http://msdn.microsoft.com/en-us/library/ms181055.aspx and http://www.simple-talk.com/sql/performance/execution-plan-basics/ "In summary, they determined that supplying anything other than the common values when a compile or recompile was performed resulted in the optimizer compiling and caching the query plan for that particular value. Yet, when that query plan was reused for subsequent executions of the same query for the common values (‘M’, ‘R’, or ‘T’), it resulted in sub-optimal performance. This sub-optimal performance problem existed until the query was recompiled. At that point, based on the @P1 parameter value supplied, the query might or might not have a performance problem." Reduced network latency A) If you are running the same SQL over and over -- and the SQL adds up to many KB of code -- replacing that with a simple "exec foobar" can really add up.B) Stored procs can be used to move procedural code into the DBMS. This saves shuffling large amounts of data off to the client only to have it send a trickle of info back (or none at all!). Analogous to doing a JOIN in the DBMS vs. in your code (everyone's favorite WTF!) Still an advantage? A) Modern 1Gb (and 10Gb and up!) Ethernet really make this negligible. B) Depends on how saturated your network is -- why shove several megabytes of data back and forth for no good reason? Potential cache benefits Performing server-side transforms of data can potentially be faster if you have sufficient memory on the DBMS and the data you need is in memory of the server. Still an advantage? Unless your app has shared memory access to DBMS data, the edge will always be to stored procs. Of course, no discussion of Stored Procedure optimization would be complete without a discussion of parameterized and ad hoc SQL. Parameterized / Prepared SQL Kind of a cross between stored procedures and ad hoc SQL, they are embedded SQL statements in a host language that uses "parameters" for query values, e.g.: SELECT .. FROM yourtable WHERE foo = ? AND bar = ? These provide a more generalized version of a query that modern-day optimizers can use to cache (and re-use) the query execution plan, resulting in much of the performance benefit of stored procedures. Ad Hoc SQL Just open a console window to your DBMS and type in a SQL statement. In the past, these were the "worst" performers (on average) since the DBMS had no way of pre-optimizing the queries as in the parameterized/stored proc method. Still a disadvantage? Not necessarily. Most DBMS have the ability to "abstract" ad hoc SQL into parameterized versions -- thus more or less negating the difference between the two. Some do this implicitly or must be enabled with a command setting (SQL server: http://msdn.microsoft.com/en-us/library/ms175037.aspx , Oracle: http://www.praetoriate.com/oracle_tips_cursor_sharing.htm ). Lessons learned? Moore's law continues to march on and DBMS optimizers, with every release, get more sophisticated. Sure, you can place every single silly teeny SQL statement inside a stored proc, but just know that the programmers working on optimizers are very smart and are continually looking for ways to improve performance. Eventually (if it's not here already) ad hoc SQL performance will become indistinguishable (on average!) from stored procedure performance, so any sort of massive stored procedure use ** solely for "performance reasons"** sure sounds like premature optimization to me. Anyway, I think if you avoid the edge cases and have fairly vanilla SQL, you won't notice a difference between ad hoc and stored procedures.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/59880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5619/" ] }
59,893
I'm looking for a technique or tool which we can use to obfuscate or somehow secure our compiled c# code. The goal is not for user/data security but to hinder reverse engineering of some of the technology in our software. This is not for use on the web, but for a desktop application. So, do you know of any tools available to do this type of thing? (They need not be free) What kind of performance implications do they have if any? Does this have any negative side effects when using a debugger during development? We log stack traces of problems in the field. How would obfuscation affect this?
This is a pretty good list of obfuscators from Visual Studio Marketplace Obfuscators ArmDot Crypto Obfuscator Demeanor for .NET DeployLX CodeVeil Dotfuscator .NET Obfuscator Semantic Designs : C# Source Code Obfuscator Smartassembly Spices.Net Xenocode Postbuild 2006 .NET Reactor I have not observed any performance issues when obfuscating my code. If your just sending text basted stack traces you might have a problem translating the method names.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/59893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/454247/" ] }
59,895
How do I get the path of the directory in which a Bash script is located, inside that script? I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so: $ ./application
#!/usr/bin/env bashSCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) is a useful one-liner which will give you the full directory name of the script no matter where it is being called from. It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution: #!/usr/bin/env bashSOURCE=${BASH_SOURCE[0]}while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd ) SOURCE=$(readlink "$SOURCE") [[ $SOURCE != /* ]] && SOURCE=$DIR/$SOURCE # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was locateddoneDIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd ) This last one will work with any combination of aliases, source , bash -c , symlinks, etc. Beware: if you cd to a different directory before running this snippet, the result may be incorrect! Also, watch out for $CDPATH gotchas , and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when calling update_terminal_cwd >&2 on Mac). Adding >/dev/null 2>&1 at the end of your cd command will take care of both possibilities. To understand how it works, try running this more verbose form: #!/usr/bin/env bashSOURCE=${BASH_SOURCE[0]}while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink TARGET=$(readlink "$SOURCE") if [[ $TARGET == /* ]]; then echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'" SOURCE=$TARGET else DIR=$( dirname "$SOURCE" ) echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')" SOURCE=$DIR/$TARGET # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located fidoneecho "SOURCE is '$SOURCE'"RDIR=$( dirname "$SOURCE" )DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )if [ "$DIR" != "$RDIR" ]; then echo "DIR '$RDIR' resolves to '$DIR'"fiecho "DIR is '$DIR'" And it will print something like: SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')SOURCE is './sym2/scriptdir.sh'DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
{ "score": 14, "source": [ "https://Stackoverflow.com/questions/59895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2908/" ] }
59,896
I have a page that uses $(id).show("highlight", {}, 2000); to highlight an element when I start a ajax request, that might fail so that I want to use something like $(id).show("highlight", {color: "#FF0000"}, 2000); in the error handler. The problem is that if the first highlight haven't finished, the second is placed in a queue and wont run until the first is ready. Hence the question: Can I somehow stop the first effect?
From the jQuery docs: http://docs.jquery.com/Effects/stop Stop the currently-running animation on the matched elements. ... When .stop() is called on an element, the currently-running animation (if any) is immediately stopped. If, for instance, an element is being hidden with .slideUp() when .stop() is called, the element will now still be displayed, but will be a fraction of its previous height. Callback functions are not called. If more than one animation method is called on the same element, the later animations are placed in the effects queue for the element. These animations will not begin until the first one completes. When .stop() is called, the next animation in the queue begins immediately. If the clearQueue parameter is provided with a value of true , then the rest of the animations in the queue are removed and never run. If the jumpToEnd argument is provided with a value of true, the current animation stops, but the element is immediately given its target values for each CSS property. In our above .slideUp() example, the element would be immediately hidden. The callback function is then immediately called, if provided...
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6093/" ] }
59,942
I started a project a long time ago and created a Data Access Layer project in my solution but have never developed anything in it. What is the purpose of a data access layer? Are there any good sources that I could learn more about the Data Access Layer?
In two words: Loose Coupling To keep the code you use to pull data from your data store (database, flat files, web services, whatever) separate from business logic and presentation code. This way, if you have to change data stores, you don't end up rewriting the whole thing. These days, various ORM frameworks are kind of blending the DAL with other layers. This typically makes development easier, but changing data stores can be painful. To be fair, changing data stores like that is pretty uncommon.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/59942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299/" ] }
60,000
In C++, can member function pointers be used to point to derived (or even base) class members? EDIT: Perhaps an example will help. Suppose we have a hierarchy of three classes X , Y , Z in order of inheritance. Y therefore has a base class X and a derived class Z . Now we can define a member function pointer p for class Y . This is written as: void (Y::*p)(); (For simplicity, I'll assume we're only interested in functions with the signature void f() ) This pointer p can now be used to point to member functions of class Y . This question (two questions, really) is then: Can p be used to point to a function in the derived class Z ? Can p be used to point to a function in the base class X ?
C++03 std, §4.11 2 Pointer to member conversions : An rvalue of type “pointer to member of B of type cv T,” where B is a class type, can be converted to an rvalue of type “pointer to member of D of type cv T,” where D is a derived class (clause 10) of B. If B is an inaccessible (clause 11), ambiguous (10.2) or virtual (10.1) base class of D, a program that necessitates this conversion is ill-formed. The result of the conversion refers to the same member as the pointer to member before the conversion took place, but it refers to the base class member as if it were a member of the derived class. The result refers to the member in D’s instance of B. Since the result has type “pointer to member of D of type cv T,” it can be dereferenced with a D object. The result is the same as if the pointer to member of B were dereferenced with the B sub-object of D. The null member pointer value is converted to the null member pointer value of the destination type. 52) 52) The rule for conversion of pointers to members (from pointer to member of base to pointer to member of derived) appears inverted compared to the rule for pointers to objects (from pointer to derived to pointer to base) (4.10, clause 10). This inversion is necessary to ensure type safety. Note that a pointer to member is not a pointer to object or a pointer to function and the rules for conversions of such pointers do not apply to pointers to members. In particular, a pointer to member cannot be converted to a void*. In short, you can convert a pointer to a member of an accessible, non-virtual base class to a pointer to a member of a derived class as long as the member isn't ambiguous. class A {public: void foo();};class B : public A {};class C {public: void bar();};class D {public: void baz();};class E : public A, public B, private C, public virtual D {public: typedef void (E::*member)();};class F:public E {public: void bam();};...int main() { E::member mbr; mbr = &A::foo; // invalid: ambiguous; E's A or B's A? mbr = &C::bar; // invalid: C is private mbr = &D::baz; // invalid: D is virtual mbr = &F::bam; // invalid: conversion isn't defined by the standard ... Conversion in the other direction (via static_cast ) is governed by § 5.2.9 9: An rvalue of type "pointer to member of D of type cv1 T" can be converted to an rvalue of type "pointer to member of B of type cv2 T", where B is a base class (clause 10 class.derived ) of D, if a valid standard conversion from "pointer to member of B of type T" to "pointer to member of D of type T" exists ( 4.11 conv.mem ), and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1 . 11) The null member pointer value ( 4.11 conv.mem ) is converted to the null member pointer value of the destination type. If class B contains the original member, or is a base or derived class of the class containing the original member, the resulting pointer to member points to the original member. Otherwise, the result of the cast is undefined. [Note: although class B need not contain the original member, the dynamic type of the object on which the pointer to member is dereferenced must contain the original member; see 5.5 expr.mptr.oper .] 11) Function types (including those used in pointer to member function types) are never cv-qualified; see 8.3.5 dcl.fct . In short, you can convert from a derived D::* to a base B::* if you can convert from a B::* to a D::* , though you can only use the B::* on objects that are of type D or are descended from D.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/60000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1077/" ] }
60,030
In Firefox you can enter the following into the awesome bar and hit enter: javascript:self.resizeTo(1024,768); How do you do the same thing in IE?
javascript:resizeTo(1024,768);vbscript:resizeto(1024,768) Will work in IE7, But consider using something like javascript:moveTo(0,0);resizeTo(1024,768); because IE7 doesn't allow the window to "resize" beyond the screen borders. If you work on a 1024,768 desktop, this is what happens... Firefox: 1024x768 Window, going behind the taskbar. If you drop the moveTo part, the top left corner of the window won't change position.(You still get a 1024x768 window) IE7: As close as possible to the requested size without obscuring the taskbar or allowing any part of the window to lie beyond the screen borders. safari: As close as possible to the requested size without obscuring the taskbar or allowing any part of the window to lie beyond the screen borders, but you can ommit the moveTo part. Safari will move the top left corner of the window for you. Opera: Nothing happens. Chrome: Nothing happens.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1496/" ] }
60,032
How do I get the key of the current element in a foreach loop in C#? For example: PHP foreach ($array as $key => $value){ echo("$value is assigned to key: $key");} What I'm trying to do in C#: int[] values = { 5, 14, 29, 49, 99, 150, 999 };foreach (int val in values){ if(search <= val && !stop) { // Set key to a variable }}
Grauenwolf's way is the most straightforward and performant way of doing this with an array: Either use a for loop or create a temp variable that you increment on each pass. Which would of course look like this: int[] values = { 5, 14, 29, 49, 99, 150, 999 };for (int key = 0; key < values.Length; ++key) if (search <= values[key] && !stop) { // set key to a variable } With .NET 3.5 you can take a more functional approach as well, but it is a little more verbose at the site, and would likely rely on a couple support functions for visiting the elements in an IEnumerable. Overkill if this is all you need it for, but handy if you tend to do a lot of collection processing.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/60032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ] }
60,033
I want to make a copy of an ActiveRecord object, changing a single field in the process (in addition to the id ). What is the simplest way to accomplish this? I realize I could create a new record, and then iterate over each of the fields copying the data field-by-field - but I figured there must be an easier way to do this. Perhaps something like this: new_record = Record.copy(:id)
To get a copy, use the dup (or clone for < rails 3.1+) method: #rails >= 3.1new_record = old_record.dup# rails < 3.1new_record = old_record.clone Then you can change whichever fields you want. ActiveRecord overrides the built-in Object#clone to give you a new (not saved to the DB) record with an unassigned ID. Note that it does not copy associations, so you'll have to do this manually if you need to. Rails 3.1 clone is a shallow copy, use dup instead...
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/60033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3764/" ] }
60,034
I am writing a batch file script using Windows command-line environment and want to change each occurrence of some text in a file (ex. "FOO") with another (ex. "BAR"). What is the simplest way to do that? Any built in functions?
A lot of the answers here helped point me in the right direction, however none were suitable for me, so I am posting my solution. I have Windows 7, which comes with PowerShell built-in. Here is the script I used to find/replace all instances of text in a file: powershell -Command "(gc myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt" To explain it: powershell starts up powershell.exe, which is included in Windows 7 -Command "... " is a command line arg for powershell.exe containing the command to run (gc myFile.txt) reads the content of myFile.txt ( gc is short for the Get-Content command) -replace 'foo', 'bar' simply runs the replace command to replace foo with bar | Out-File myFile.txt pipes the output to the file myFile.txt -encoding ASCII prevents transcribing the output file to unicode, as the comments point out Powershell.exe should be part of your PATH statement already, but if not you can add it. The location of it on my machine is C:\WINDOWS\system32\WindowsPowerShell\v1.0 Update Apparently modern windows systems have PowerShell built in allowing you to access this directly using (Get-Content myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/60034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ] }
60,109
What is a good challenge to improve your skills in object oriented programming? The idea behind this poll is to provide an idea of which exercises are useful for learning OOP. The challenge should be as language agnostic as possible, requiring either little or no use of specific libraries, or only the most common of libraries. Try to include only one challenge per answer, so that a vote will correspond to the merits of that challenge alone. Would also be nice if a level of skill required was indicated, and also the rationale behind why it is a useful exercise. Solutions to the challenges could then be posted as answers to a "How to..." question and linked to from here. For example: Challenge - implement a last-in-first-out stack Skill level - beginner Rationale - gives experience of how to reference objects
Building Skills in Object-Oriented Design is a free book that might be of use. The description is as follows: "The intent of this book is to help the beginning designer by giving them a sequence of interesting and moderately complex exercises in OO design. This book can also help managers develop a level of comfort with the process of OO software development. The applications we will build are a step above trivial, and will require some careful thought and design. Further, because the applications are largely recreational in nature, they are interesting and engaging. This book allows the reader to explore the processes and artifacts of OO design before project deadlines make good design seem impossible."
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/60109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4120/" ] }
60,113
Is there a way to access Visual Studio's built-in ASP.NET Development Server over HTTPS?
As of now we can use IIS Express to develop and test in SSL. Here is a complete article explaning how to use IIS Express and Visual Studion 2010 to develop websites in SSL. Next Then you will get this Working with SSL at Development Time is easier with IISExpress Introducing IIS Express
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/60113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247/" ] }
60,121
Silverlight v2.0 is getting closer and closer to RTM but I have yet to hear any stats as to how many browsers are running Silverlight. If I ask Adobe (by googling "Flash install base") they're only too happy to tell me that 97.7% of browsers are running Flash player 9 or better. Not that I believe everything I read, but where are these statistics from Microsoft or some other vendor about Silverlight? I'm going to be making a technology choice soon and a little bit of empirical evidence would be an asset at this point... All you Silverlight developers out there, show me your stats!
Quick Answer: www.riastats.com This site compares the different RIA plugins using graphical charts and graphs. It gets its data from small snippets of javascripts running on sites accross the web (approx 400,000 last time I looked) At the time of this post, Silverlight 2 was sitting at close to 11%. I would not take this as the end-all, be-all in RIA stats, but it's the best site I've found so far.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5642/" ] }
60,137
I'm considering moving a number of small client sites to an unmanaged VPS hosting provider. I haven't decided which one yet, but my understanding is that they'll give me a base OS install (I'd prefer Debian or Ubuntu), an IP address, a root account, SSH, and that's about it. Ideally, I would like to create a complete VM image of my configured setup and just ship those bits to the provider. Has anyone had any experience with this? I've seen Jeff talk about something like this in Coding Horror . But I'm not sure if his experience is typical. I suppose it also depends on the type of VM server used by the host. Also, do such hosts provide reverse-DNS? That's kinda useful for sites that send out e-mails. I know GMail tends to bounce anything originating from a server without it. Finally, I'd probably need multiple IP addresses as at least a couple of the sites have SSL protection which doesn't work with name-based virtual hosts. Has anyone run into trouble with multiple IPs through VPS? I wouldn't think so, but I've heard whisperings to the contrary.
Quick Answer: www.riastats.com This site compares the different RIA plugins using graphical charts and graphs. It gets its data from small snippets of javascripts running on sites accross the web (approx 400,000 last time I looked) At the time of this post, Silverlight 2 was sitting at close to 11%. I would not take this as the end-all, be-all in RIA stats, but it's the best site I've found so far.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/726/" ] }
60,160
Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a "5" after the end of input.
Since Java 1.5, yes : Pattern.quote("$5");
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/60160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2338/" ] }
60,174
If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection , like in the following example: $unsafe_variable = $_POST['user_input']; mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')"); That's because the user can input something like value'); DROP TABLE table;-- , and the query becomes: INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--') What can be done to prevent this from happening?
The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL , so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don't fully understand the details, you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL. You basically have two options to achieve this: Using PDO (for any supported database driver): $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');$stmt->execute([ 'name' => $name ]);foreach ($stmt as $row) { // Do something with $row} Using MySQLi (for MySQL): $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');$stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'$stmt->execute();$result = $stmt->get_result();while ($row = $result->fetch_assoc()) { // Do something with $row} If you're connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option. Correctly setting up the connection PDO Note that when using PDO to access a MySQL database real prepared statements are not used by default . To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is: $dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4', 'user', 'password');$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); In the above example, the error mode isn't strictly necessary, but it is advised to add it . This way PDO will inform you of all MySQL errors by means of throwing the PDOException . What is mandatory , however, is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL). Although you can set the charset in the options of the constructor, it's important to note that 'older' versions of PHP (before 5.3.6) silently ignored the charset parameter in the DSN. Mysqli For mysqli we have to follow the same routine: mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error reporting$dbConnection = new mysqli('127.0.0.1', 'username', 'password', 'test');$dbConnection->set_charset('utf8mb4'); // charset Explanation The SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute , the prepared statement is combined with the parameter values you specify. The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend. Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains 'Sarah'; DELETE FROM employees the result would simply be a search for the string "'Sarah'; DELETE FROM employees" , and you will not end up with an empty table . Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains. Oh, and since you asked about how to do it for an insert, here's an example (using PDO): $preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');$preparedStatement->execute([ 'column' => $unsafeValue ]); Can prepared statements be used for dynamic queries? While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized. For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values. // Value whitelist// $dir can only be 'DESC', otherwise it will be 'ASC'if (empty($dir) || $dir !== 'DESC') { $dir = 'ASC';}
{ "score": 14, "source": [ "https://Stackoverflow.com/questions/60174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428190/" ] }
60,208
I want to write a function in Python that returns different fixed values based on the value of an input index. In other languages I would use a switch or case statement, but Python does not appear to have a switch statement. What are the recommended Python solutions in this scenario?
The original answer below was written in 2008. Since then, Python 3.10 (2021) introduced the match - case statement which provides a first-class implementation of a "switch" for Python. For example: def f(x): match x: case 'a': return 1 case 'b': return 2 case _: return 0 # 0 is the default case if x is not found The match - case statement is considerably more powerful than this simple example. You could use a dictionary: def f(x): return { 'a': 1, 'b': 2, }[x]
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/60208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4907/" ] }