source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
9,122 | I'm trying to use a select statement to get all of the columns from a certain MySQL table except one. Is there a simple way to do this? EDIT: There are 53 columns in this table (NOT MY DESIGN) | Actually there is a way, you need to have permissions of course for doing this ... SET @sql = CONCAT('SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), '<columns_to_omit>,', '') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<table>' AND TABLE_SCHEMA = '<database>'), ' FROM <table>');PREPARE stmt1 FROM @sql;EXECUTE stmt1; Replacing <table>, <database> and <columns_to_omit> | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/9122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44/"
]
} |
9,191 | I'd like to ask a question then follow it up with my own answer, but also see what answers other people have. We have two large files which we'd like to read from two separate threads concurrently. One thread will sequentially read fileA while the other thread will sequentially read fileB. There is no locking or communication between the threads, both are sequentially reading as fast as they can, and both are immediately discarding the data they read. Our experience with this setup on Windows is very poor. The combined throughput of the two threads is in the order of 2-3 MiB/sec. The drive seems to be spending most of its time seeking backwards and forwards between the two files, presumably reading very little after each seek. If we disable one of the threads and temporarily look at the performance of a single thread then we get much better bandwidth (~45 MiB/sec for this machine). So clearly the bad two-thread performance is an artefact of the OS disk scheduler. Is there anything we can do to improve the concurrent thread read performance? Perhaps by using different APIs or by tweaking the OS disk scheduler parameters in some way. Some details: The files are in the order of 2 GiB each on a machine with 2GiB of RAM. For the purpose of this question we consider them not to be cached and perfectly defragmented. We have used defrag tools and rebooted to ensure this is the case. We are using no special APIs to read these files. The behaviour is repeatable across various bog-standard APIs such as Win32's CreateFile, C's fopen, C++'s std::ifstream, Java's FileInputStream, etc. Each thread spins in a loop making calls to the read function. We have varied the number of bytes requested from the API each iteration from values between 1KiB up to 128MiB. Varying this has had no effect, so clearly the amount the OS is physically reading after each disk seek is not dictated by this number. This is exactly what should be expected. The dramatic difference between one-thread and two-thread performance is repeatable across Windows 2000, Windows XP (32-bit and 64-bit), Windows Server 2003, and also with and without hardware RAID5. | The problem seems to be in Windows I/O scheduling policy. According to what I found here there are many ways for an O.S. to schedule disk requests. While Linux and others can choose between different policies, before Vista Windows was locked in a single policy: a FIFO queue, where all requests where splitted in 64 KB blocks. I believe that this policy is the cause for the problem you are experiencing: the scheduler will mix requests from the two threads, causing continuous seek between different areas of the disk. Now, the good news is that according to here and here , Vista introduced a smarter disk scheduler, where you can set the priority of your requests and also allocate a minimum badwidth for your process. The bad news is that I found no way to change disk policy or buffers size in previous versions of Windows. Also, even if raising disk I/O priority of your process will boost the performance against the other processes, you still have the problems of your threads competing against each other. What I can suggest is to modify your software by introducing a self-made disk access policy. For example, you could use a policy like this in your thread B (similar for Thread A): if THREAD A is reading from disk then wait for THREAD A to stop reading or wait for X msRead for X ms (or Y MB)Stop reading and check status of thread A again You could use semaphores for status checking or you could use perfmon counters to get the status of the actual disk queue.The values of X and/or Y could also be auto-tuned by checking the actual trasfer rates and slowly modify them, thus maximizing the throughtput when the application runs on different machines and/or O.S. You could find that cache, memory or RAID levels affect them in a way or the other, but with auto-tuning you will always get the best performance in every scenario. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/9191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755/"
]
} |
9,204 | Is there any IL level debugger in form of a VS plugin or standalone application? Visual studio’s debugger is great, but it allows you to debug on either HLL code level or assembly language, you can’t debug IL.It seems that in some situations it would be useful to have an opportunity to debug at IL level. In particular it might be helpful when debugging a problem in the code that you don't have the source of. It is arguable if it is actually useful to debug IL when you don't have the source, but anyway. | The best way to do this is to use ILDASM to disassemble the managed binary, which will generate the IL instructions. Then recompile that IL source code in debug mode using ILASM, when you fire up the Visual Studio debugger you will be able to step through the raw IL. ildasm foo.exe /OUT=foo.exe.il /SOURCE ilasm foo.exe.il /DEBUG I've written a blog post about this topic at: How to debug Compiler Generated code . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/9204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/578/"
]
} |
9,272 | Anybody have a script or alias to find untracked (really: unadded) files in a Perforce tree? EDIT: I updated the accepted answer on this one since it looks like P4V added support for this in the January 2009 release. | EDIT: Please use p4 status now. There is no need for jumping through hoops anymore. See @ColonelPanic's answer . In the Jan 2009 version of P4V, you can right-click on any folder in your workspace tree and click "reconcile offline work..." This will do a little processing then bring up a split-tree view of files that are not checked out but have differences from the depot version, or not checked in at all. There may even be a few other categories it brings up. You can right-click on files in this view and check them out, add them, or even revert them. It's a very handy tool that's saved my ass a few times. EDIT: ah the question asked about scripts specifically, but I'll leave this answer here just in case. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/9272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1146/"
]
} |
9,279 | I absolutely love the Keep Remote Directory Up-to-date feature in Winscp . Unfortunately, I can't find anything as simple to use in OS X or Linux. I know the same thing can theoretically be accomplished using changedfiles or rsync , but I've always found the tutorials for both tools to be lacking and/or contradictory. I basically just need a tool that works in OSX or Linux and keeps a remote directory in sync (mirrored) with a local directory while I make changes to the local directory. Update Looking through the solutions, I see a couple which solve the general problem of keeping a remote directory in sync with a local directory manually . I know that I can set a cron task to run rsync every minute, and this should be fairly close to real time. This is not the exact solution I was looking for as winscp does this and more: it detects file changes in a directory (while I work on them) and then automatically pushes the changes to the remote server. I know this is not the best solution (no code repository), but it allows me to very quickly test code on a server while I develop it. Does anyone know how to combine rsync with any other commands to get this functionality? | How "real-time" do you want the syncing? I would still lean toward rsync since you know it is going to be fully supported on both platforms (Windows, too, with cygwin) and you can run it via a cron job. I have a super-simple bash file that I run on my system (this does not remove old files): #!/bin/shrsync -avrz --progress --exclude-from .rsync_exclude_remote . remote_login@remote_computer:remote_dir # options# -a archive# -v verbose# -r recursive# -z compress Your best bet is to set it up and try it out. The -n (--dry-run) option is your friend! Keep in mind that rsync (at least in cygwin) does not support unicode file names (as of 16 Aug 2008). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/9279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/302/"
]
} |
9,289 | I would like to filter an array of items by using the map() function. Here is a code snippet: var filteredItems = items.map(function(item){ if( ...some condition... ) { return item; }}); The problem is that filtered out items still uses space in the array and I would like to completely wipe them out. Any idea? EDIT: Thanks, I forgot about filter() , what I wanted is actually a filter() then a map() . EDIT2: Thanks for pointing that map() and filter() are not implemented in all browsers, although my specific code was not intended to run in a browser. | You should use the filter method rather than map unless you want to mutate the items in the array, in addition to filtering. eg. var filteredItems = items.filter(function(item){ return ...some condition...;}); [Edit: Of course you could always do sourceArray.filter(...).map(...) to both filter and mutate] | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/9289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/268/"
]
} |
9,304 | Note: This was posted when I was starting out C#. With 2014 knowledge, I can truly say that auto-properties are among the best things that ever happened to the C# language. I am used to create my properties in C# using a private and a public field: private string title;public string Title{ get { return title; } set { title = value; }} Now, with .NET 3.0, we got auto-properties: public string Title { get; set; } I know this is more a philosophical/subjective questions, but is there any reason to use these auto-properties except from saving five lines of code for each field? My personal gripe is that those properties are hiding stuff from me, and I am not a big fan of black magic. In fact, the hidden private field does not even show up in the debugger, which is OK given the fact that the get/set functions do nothing. But when I want to actually implement some getter/setter logic, I have to use the private/public pair anyway. I see the benefit that I save a lot of code (one vs six lines) without losing the ability to change the getter/setter logic later, but then again I can already do that by simply declaring a public field "Public string Title" without the need of the { get; set; } block, thus even saving more code. So, what am I missing here? Why would anyone actually want to use auto-properties? | We use them all the time in Stack Overflow. You may also be interested in a discussion of Properties vs. Public Variables . IMHO that's really what this is a reaction to, and for that purpose, it's great. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/9304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
]
} |
9,314 | I have a .NET 2.0 windows forms app, which makes heavy use of the ListView control. I've subclassed the ListView class into a templated SortableListView<T> class, so it can be a bit smarter about how it displays things, and sort itself. Unfortunately this seems to break the Visual Studio Forms Designer, in both VS2005 and 2008. The program compiles and runs fine, but when I try view the owning form in the designer, I get these Errors: Could not find type 'MyApp.Controls.SortableListView'. Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built. There is no stack trace or error line information available for this error The variable 'listViewImages' is either undeclared or was never assigned. At MyApp.Main.Designer.cs Line:XYZ Column:1 Call stack:at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.Error(IDesignerSerializationManager manager, String exceptionText, String helpLink)at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement) The line of code in question is where it is actually added to the form, and is this.imagesTab.Controls.Add( this.listViewImages ); listViewImages is declared as private MyApp.Controls.SortableListView<Image> listViewImages; and is instantiated in the InitializeComponent method as follows: this.listViewImages = new MyApp.Controls.SortableListView<Image>(); As mentioned earlier, the program compiles and runs perfectly, and I've tried shifting the SortableListView class out to a seperate assembly so it can be compiled seperately, but this makes no difference. I have no idea where to go from here. Any help would be appreciated! | It happened to me because of x86 / x64 architecture. Since Visual Studio (the development tool itself) has no x64 version, it's not possible to load x64 control into GUI designer. The best approach for this might be tuning GUI under x86, and compile it for x64 when necessary. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/9314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
]
} |
9,321 | How do you create a static class in C++? I should be able to do something like: cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl; Assuming I created the BitParser class. What would the BitParser class definition look like? | If you're looking for a way of applying the "static" keyword to a class, like you can in C# for example, then you won't be able to without using Managed C++. But the looks of your sample, you just need to create a public static method on your BitParser object. Like so: BitParser.h class BitParser{ public: static bool getBitAt(int buffer, int bitIndex); // ...lots of great stuff private: // Disallow creating an instance of this object BitParser() {}}; BitParser.cpp bool BitParser::getBitAt(int buffer, int bitIndex){ bool isBitSet = false; // .. determine if bit is set return isBitSet;} You can use this code to call the method in the same way as your example code. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/9321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
]
} |
9,355 | I can display and select a single file in windows explorer like this: explorer.exe /select, "c:\path\to\file.txt" However, I can't work out how to select more than one file. None of the permutations of select I've tried work. Note: I looked at these pages for docs, neither helped. https://support.microsoft.com/kb/314853 http://web.archive.org/web/20100716112458/http://www.infocellar.com:80/Win98/explorer-switches.htm | This should be possible with the shell function SHOpenFolderAndSelectItems EDIT Here is some sample code showing how to use the function in C/C++, without error checking: //Directory to openITEMIDLIST *dir = ILCreateFromPath(_T("C:\\"));//Items in directory to selectITEMIDLIST *item1 = ILCreateFromPath(_T("C:\\Program Files\\"));ITEMIDLIST *item2 = ILCreateFromPath(_T("C:\\Windows\\"));const ITEMIDLIST* selection[] = {item1,item2};UINT count = sizeof(selection) / sizeof(ITEMIDLIST);//Perform selectionSHOpenFolderAndSelectItems(dir, count, selection, 0);//Free resourcesILFree(dir);ILFree(item1);ILFree(item2); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/9355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
]
} |
9,376 | Do you use ILMerge? Do you use ILMerge to merge multiple assemblies to ease deployment of dll's? Have you found problems with deployment/versioning in production after ILMerging assemblies together? I'm looking for some advice in regards to using ILMerge to reduce deployment friction, if that is even possible. | I use ILMerge for almost all of my different applications. I have it integrated right into the release build process so what I end up with is one exe per application with no extra dll's. You can't ILMerge any C++ assemblies that have native code.You also can't ILMerge any assemblies that contain XAML for WPF (at least I haven't had any success with that). It complains at runtime that the resources cannot be located. I did write a wrapper executable for ILMerge where I pass in the startup exe name for the project I want to merge, and an output exe name, and then it reflects the dependent assemblies and calls ILMerge with the appropriate command line parameters. It is much easier now when I add new assemblies to the project, I don't have to remember to update the build script. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/9376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1083/"
]
} |
9,410 | I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C? | Declaration A prototype for a function which takes a function parameter looks like the following: void func ( void (*f)(int) ); This states that the parameter f will be a pointer to a function which has a void return type and which takes a single int parameter. The following function ( print ) is an example of a function which could be passed to func as a parameter because it is the proper type: void print ( int x ) { printf("%d\n", x);} Function Call When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this: func(print); would call func , passing the print function to it. Function Body As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly: for ( int ctr = 0 ; ctr < 5 ; ctr++ ) { print(ctr);} Since func 's parameter declaration says that f is the name for a pointer to the desired function, we recall first that if f is a pointer then *f is the thing that f points to (i.e. the function print in this case). As a result, just replace every occurrence of print in the loop above with *f : void func ( void (*f)(int) ) { for ( int ctr = 0 ; ctr < 5 ; ctr++ ) { (*f)(ctr); }} Source | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/9410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
]
} |
9,433 | For some reason I never see this done. Is there a reason why not? For instance I like _blah for private variables, and at least in Windows Forms controls are by default private member variables, but I can't remember ever seeing them named that way. In the case that I am creating/storing control objects in local variables within a member function, it is especially useful to have some visual distinction. | This might be counter-intuitive for some, but we use the dreaded Hungarian notation for UI elements. The logic is simple: for any given data object you may have two or more controls associated with it. For example, you have a control that indicates a birth date on a text box, you will have: the text box a label indicating that the text box is for birth dates a calendar control that will allow you to select a date For that, I would have lblBirthDate for the label, txtBirthDate for the text box, and calBirthDate for the calendar control. I am interested in hearing how others do this, however. :) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/9433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
]
} |
9,434 | In my ASP.NET User Control I'm adding some JavaScript to the window.onload event: if (!Page.ClientScript.IsStartupScriptRegistered(this.GetType(), onloadScriptName)) Page.ClientScript.RegisterStartupScript(this.GetType(), onloadScriptName, "window.onload = function() {myFunction();};", true); My problem is, if there is already something in the onload event, than this overwrites it. How would I go about allowing two user controls to each execute JavaScript in the onload event? Edit: Thanks for the info on third party libraries. I'll keep them in mind. | Most of the "solutions" suggested are Microsoft-specific, or require bloated libraries. Here's one good way. This works with W3C-compliant browsers and with Microsoft IE. if (window.addEventListener) // W3C standard{ window.addEventListener('load', myFunction, false); // NB **not** 'onload'} else if (window.attachEvent) // Microsoft{ window.attachEvent('onload', myFunction);} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/9434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233/"
]
} |
9,589 | I'm looking for a tool which can generate a Makefile for a C/C++ project for different compilers ( GCC , Microsoft Visual C++ , C++Builder , etc.) and different platforms (Windows, Linux, and Mac). | Other suggestions you may want to consider: Scons is a cross-platform, cross-compiler build library, uses Python scripting for the build systems. Used in a variety of large projects, and performs very well. If you're using Qt , QMake is a nice build system too. CMake is also pretty sweet. Finally, if all else fails... | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/9589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007/"
]
} |
9,591 | Well, i've got a nice WPF book its called Sams Windows Presentation Foundation Unleashed.I really like to read and learn with it. Are there any other WPF books you could recommend? | I've found the following books very useful: Windows Presentation Foundation Unleashed - Adam Nathan You mention you already have this book, however I wanted to give my opinion on it. It is a great book for the newcomer - it is printed in full color which is a great help for visualizing both xaml and concepts for WPF. Essential Windows Presentation Foundation - Chris Anderson This is also another great book for the newcomer. While it is not printed in color, it does give a great insight into how WPF works. Pro WPF in C# 2008 - Matthew Macdonald This is a great reference book - one that sits on my desk and is constantly referred too. However, I didn't feel is was as newbie friendly as the other two books above. This is the most recently released book (at the time of this posting), and has been updated for VS2008. This is useful, as there are some changes with the versions of WPF. I believe there is a VB.NET version available. Programming WPF - Chris Sells & Ian Griffiths Another great book - I wish this was available when I was first learning the framework. Application = Code + Markup - Charles Petzold This was the very first WPF I purchased. It is not very newbie friendly, and I wouldn't recommend it for a first-time-wpf'er. The fact that Xaml is not introduced until page 457 makes learning the technology for the real world very difficult. That said, this book is invaluable if you really want to understand how things work at a very deep level (which is also important to get the most of the framework. The only book I would totally avoid is: Professional WPF Programming - Chris Andrade et al. While the content was Ok in this book, I just found the other books to be much clearer and delve to a much deeper level. Hope this helps! WPF has a steep learning curve, but once you "get it", UI programming can actually become "fun"! | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/9591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1094/"
]
} |
9,601 | I'm having a weird issue with Visual Studio 2008. Every time I fire it up, the solution explorer is about an inch wide. It's like it can't remember it's layout settings. Every un-docked window is in the position I place it. But if I dock a window, it's position is saved, but it's size will be reset to very-narrow (around an inch) when I load. I've never come across this before and it's pretty annoying. Any ideas? The things I've tried: Saving, then reloading settings via Import/Export. Resetting all environment settings via Import/Export. Window -> Reset Window layout. Comination of rebooting after changing the above. Installed SP1. No improvement none of which changed the behaviour of docked windows. (Also, definitely no other instances running..) I do run two monitors, but I've had this setup on three different workstations and this is the first time I've come across it. | I had the same problem. It turned out that if the VS window was non-maximized, it was reallysmall. So after making the non-maximized wider, the problem disappeared. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/9601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/376/"
]
} |
9,632 | Apparantly when users right-click in our WPF application, and they use the Windows Classic theme, the default ContextMenu of the TextBox (which contains Copy, Cut and Paste) has a black background. I know this works well: <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <TextBox ContextMenu="{x:Null}"/></Page> But this doesn't work: <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"><Page.Resources> <Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}"> <Setter Property="ContextMenu" Value="{x:Null}"/></Style></Page.Resources> <TextBox/></Page> Does anyone know how to style or disable the default ContextMenu for all TextBoxes in WPF? | To style ContextMenu's for all TextBoxes, I would do something like the following: First, in the resources section, add a ContextMenu which you plan to use as your standard ContextMenu in a textbox. e.g. <ContextMenu x:Key="TextBoxContextMenu" Background="White"> <MenuItem Command="ApplicationCommands.Copy" /> <MenuItem Command="ApplicationCommands.Cut" /> <MenuItem Command="ApplicationCommands.Paste" /></ContextMenu> Secondly, create a style for your TextBoxes, which uses the context menu resource: <Style TargetType="{x:Type TextBox}"> <Setter Property="ContextMenu" Value="{StaticResource TextBoxContextMenu}" /></Style> Finally, use your text box as normal: <TextBox /> If instead you want to apply this context menu to only some of your textboxes, do not create the style above, and add the following to your TextBox markup: <TextBox ContextMenu="{StaticResource TextBoxContextMenu}" /> Hope this helps! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/9632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/900/"
]
} |
9,666 | I've been raised to believe that if multiple threads can access a variable, then all reads from and writes to that variable must be protected by synchronization code, such as a "lock" statement, because the processor might switch to another thread halfway through a write. However, I was looking through System.Web.Security.Membership using Reflector and found code like this: public static class Membership{ private static bool s_Initialized = false; private static object s_lock = new object(); private static MembershipProvider s_Provider; public static MembershipProvider Provider { get { Initialize(); return s_Provider; } } private static void Initialize() { if (s_Initialized) return; lock(s_lock) { if (s_Initialized) return; // Perform initialization... s_Initialized = true; } }} Why is the s_Initialized field read outside of the lock? Couldn't another thread be trying to write to it at the same time? Are reads and writes of variables atomic? | For the definitive answer go to the spec. :) Partition I, Section 12.6.6 of the CLI spec states: "A conforming CLI shall guarantee that read and write access to properly aligned memory locations no larger than the native word size is atomic when all the write accesses to a location are the same size." So that confirms that s_Initialized will never be unstable, and that read and writes to primitve types smaller than 32 bits are atomic. In particular, double and long ( Int64 and UInt64 ) are not guaranteed to be atomic on a 32-bit platform. You can use the methods on the Interlocked class to protect these. Additionally, while reads and writes are atomic, there is a race condition with addition, subtraction, and incrementing and decrementing primitive types, since they must be read, operated on, and rewritten. The interlocked class allows you to protect these using the CompareExchange and Increment methods. Interlocking creates a memory barrier to prevent the processor from reordering reads and writes. The lock creates the only required barrier in this example. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/9666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016/"
]
} |
9,667 | Given a handle of type HWND is it possible to confirm that the handle represents a real window? | There is a function IsWindow which does exactly what you asked for. BOOL isRealHandle = IsWindow(unknwodnHandle); Look at this link for more information. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/9667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/887/"
]
} |
9,673 | I have been working with a string[] array in C# that gets returned from a function call. I could possibly cast to a Generic collection, but I was wondering if there was a better way to do it, possibly by using a temp array. What is the best way to remove duplicates from a C# array? | You could possibly use a LINQ query to do this: int[] s = { 1, 2, 3, 3, 4};int[] q = s.Distinct().ToArray(); | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/9673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
]
} |
9,734 | Why does C#.Net allow the declaration of the string object to be case-insensitive? String sHello = "Hello";string sHello = "Hello"; Both the lower-case and upper-case S of the word String are acceptable and this seems to be the only object that allows this. Can anyone explain why? | string is a language keyword while System.String is the type it aliases. Both compile to exactly the same thing, similarly: int is System.Int32 long is System.Int64 float is System.Single double is System.Double char is System.Char byte is System.Byte short is System.Int16 ushort is System.UInt16 uint is System.UInt32 ulong is System.UInt64 I think in most cases this is about code legibility - all the basic system value types have aliases, I think the lower case string might just be for consistency. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/9734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
]
} |
9,877 | I'm currently trying to build a personal website to create a presence on the web for myself. My plan is to include content such as my resume, any projects that I have done on my own and links to open source projects that I have contributed to, and so on. However, I'm not sure which approach would be better from a perspective of "advertising" myself, since that what this site does, especially since I am a software developer. Should I use an out-of-the-box system and extend it as needed, with available modules and custom modules where needed or should I custom build a site and all of its features as I need them? Does a custom site look better in the eyes of a potential employer who might visit my site? | I've toyed with this idea in the past but I don't think it's really a good idea for a number of reasons. Firstly, there are a number of places that can take care of most of this without you needing to do the work or maintenance. Just signing up for a linkedIn account for example will allow you to get most of your needs catered for in this regard. You can create your resume there and bio information etc and make it publicly viewable. The other issue with your "own site" is that if you don't update it often, the information gets stale, and worse yet, people have no reason to go back because "nothing has changed" - and that's not much of an advert for you is it? Now that I've said all that, I'll make another recommendation. Why not start a blog instead?! If you've got decent experience, why not share that. I'd be willing to bet that this will be the best advert for your skills because: It's always updated (if you post often) It's not like you're looking for work doing it - but your (future) employer, or their developers will check it out anyway to get a better insight into your character. Putting something on your resume doesn't mean you can do it. I'm not saying that you'd lie about your skills :-), but there's no argument about your ability when you're writing articles about the stuff, getting comments and feedback, and better yet, learning EVEN MORE about your passions. Best of all - you can run your blog from your chosen domain and also point to your resume that is stored in linkedIn. Just an idea... That's my two pennys worth on that - hope it helps you come to a decision! | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/9877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
]
} |
9,938 | I am trying to find a generic way of accessing a set of containers. I have a standard vector and list in addition to another custom list. The custom list defines an iterator; class Iterator: public std::iterator<std::forward_iterator_tag, T> { // ...}Iterator begin() { return (Iterator(root));}Iterator end() { return (Iterator(NULL));} with the appropriate operators overloaded. Ideally, I would like to do this; class Foo {public: Foo() { std::list<int> x; std::vector<int> y; custom_list<int> z; iter = x.begin(); // OR iter = y.begin(); // OR iter = z.begin(); // ... };private: std::iterator<int> iter;}; But obviously these are all iterators of different types. I can assume all the containers are of the same type however. Is there an elegant way to solve this problem? | Here are some articles you might find of interest Giving STL Iterators a Base Class Type Erasure for C++ Iterators any_iterator Class Reference | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/9938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/263/"
]
} |
9,974 | This is a question I asked on another forum which received some decent answers, but I wanted to see if anyone here has more insight. The problem is that you have one of your pages in a web application timing out when it gets to a stored procedure call, so you use Sql Profiler, or your application trace logs, to find the query and you paste it into management studio to figure our why it's running slow. But you run it from there and it just blazes along, returning in less than a second each time. My particular case was using ASP.NET 2.0 and Sql Server 2005, but I think the problem could apply to any RDBMS system. | This is what I've learned so far from my research. .NET sends in connection settings that are not the same as what you get when you log in to management studio. Here is what you see if you sniff the connection with Sql Profiler: -- network protocol: TCP/IP set quoted_identifier off set arithabort off set numeric_roundabort off set ansi_warnings on set ansi_padding on set ansi_nulls off set concat_null_yields_null on set cursor_close_on_commit off set implicit_transactions off set language us_english set dateformat mdy set datefirst 7 set transaction isolation level read committed I am now pasting those setting in above every query that I run when logged in to sql server, to make sure the settings are the same. For this case, I tried each setting individually, after disconnecting and reconnecting, and found that changing arithabort from off to on reduced the problem query from 90 seconds to 1 second. The most probable explanation is related to parameter sniffing, which is a technique Sql Server uses to pick what it thinks is the most effective query plan. When you change one of the connection settings, the query optimizer might choose a different plan, and in this case, it apparently chose a bad one. But I'm not totally convinced of this. I have tried comparing the actual query plans after changing this setting and I have yet to see the diff show any changes. Is there something else about the arithabort setting that might cause a query to run slowly in some cases? The solution seemed simple: Just put set arithabort on into the top of the stored procedure. But this could lead to the opposite problem: change the query parameters and suddenly it runs faster with 'off' than 'on'. For the time being I am running the procedure 'with recompile' to make sure the plan gets regenerated each time. It's Ok for this particular report, since it takes maybe a second to recompile, and this isn't too noticeable on a report that takes 1-10 seconds to return (it's a monster). But it's not an option for other queries that run much more frequently and need to return as quickly as possible, in just a few milliseconds. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/9974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
]
} |
10,042 | What's the best way to make a linked list in Java? | The obvious solution to developers familiar to Java is to use the LinkedList class already provided in java.util . Say, however, you wanted to make your own implementation for some reason. Here is a quick example of a linked list that inserts a new link at the beginning of the list, deletes from the beginning of the list and loops through the list to print the links contained in it. Enhancements to this implementation include making it a double-linked list , adding methods to insert and delete from the middle or end, and by adding get and sort methods as well. Note : In the example, the Link object doesn't actually contain another Link object - nextLink is actually only a reference to another link. class Link { public int data1; public double data2; public Link nextLink; //Link constructor public Link(int d1, double d2) { data1 = d1; data2 = d2; } //Print Link data public void printLink() { System.out.print("{" + data1 + ", " + data2 + "} "); }}class LinkList { private Link first; //LinkList constructor public LinkList() { first = null; } //Returns true if list is empty public boolean isEmpty() { return first == null; } //Inserts a new Link at the first of the list public void insert(int d1, double d2) { Link link = new Link(d1, d2); link.nextLink = first; first = link; } //Deletes the link at the first of the list public Link delete() { Link temp = first; if(first == null){ return null; //throw new NoSuchElementException(); // this is the better way. } first = first.nextLink; return temp; } //Prints list data public void printList() { Link currentLink = first; System.out.print("List: "); while(currentLink != null) { currentLink.printLink(); currentLink = currentLink.nextLink; } System.out.println(""); }} class LinkListTest { public static void main(String[] args) { LinkList list = new LinkList(); list.insert(1, 1.01); list.insert(2, 2.02); list.insert(3, 3.03); list.insert(4, 4.04); list.insert(5, 5.05); list.printList(); while(!list.isEmpty()) { Link deletedLink = list.delete(); System.out.print("deleted: "); deletedLink.printLink(); System.out.println(""); } list.printList(); }} | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/10042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571/"
]
} |
10,123 | I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs: a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced. How do I decode the exit status indication (which is an integer) to obtain the high and low byte? To be specific, how do I implement the decode function used in the following code snippet: (pid,status) = os.wait()(exitstatus, signum) = decode(status) | This will do what you want: signum = status & 0xffexitstatus = (status & 0xff00) >> 8 | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/10123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
]
} |
10,190 | Many applications have grids that display data from a database table one page at a time. Many of them also let the user pick the number of records per page, sort by any column, and navigate back and forth through the results. What's a good algorithm to implement this pattern without bringing the entire table to the client and then filtering the data on the client. How do you bring just the records you want to display to the user? Does LINQ simplify the solution? | On MS SQL Server 2005 and above, ROW_NUMBER() seems to work: T-SQL: Paging with ROW_NUMBER() DECLARE @PageNum AS INT;DECLARE @PageSize AS INT;SET @PageNum = 2;SET @PageSize = 10;WITH OrdersRN AS( SELECT ROW_NUMBER() OVER(ORDER BY OrderDate, OrderID) AS RowNum ,OrderID ,OrderDate ,CustomerID ,EmployeeID FROM dbo.Orders)SELECT * FROM OrdersRN WHERE RowNum BETWEEN (@PageNum - 1) * @PageSize + 1 AND @PageNum * @PageSize ORDER BY OrderDate ,OrderID; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/10190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373/"
]
} |
10,228 | Is there a way to get the tests inside of a TestCase to run in a certain order? For example, I want to separate the life cycle of an object from creation to use to destruction but I need to make sure that the object is set up first before I run the other tests. | Maybe there is a design problem in your tests. Usually each test must not depend on any other tests, so they can run in any order. Each test needs to instantiate and destroy everything it needs to run, that would be the perfect approach, you should never share objects and states between tests. Can you be more specific about why you need the same object for N tests? | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/10228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/204/"
]
} |
10,230 | Which is more efficient for the compiler and the best practice for checking whether a string is blank? Checking whether the length of the string == 0 Checking whether the string is empty (strVar == "") Also, does the answer depend on language? | Yes, it depends on language, since string storage differs between languages. Pascal-type strings: Length = 0 . C-style strings: [0] == 0 . .NET: .IsNullOrEmpty . Etc. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/10230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/288/"
]
} |
10,274 | When should I not use the ThreadPool in .Net? It looks like the best option is to use a ThreadPool, in which case, why is it not the only option? What are your experiences around this? | The only reason why I wouldn't use the ThreadPool for cheap multithreading is if I need to… interract with the method running (e.g., to kill it) run code on a STA thread (this happened to me) keep the thread alive after my application has died ( ThreadPool threads are background threads) in case I need to change the priority of the Thread. We can not change priority of threads in ThreadPool which is by default Normal. P.S.: The MSDN article "The Managed Thread Pool" contains a section titled, "When Not to Use Thread Pool Threads" , with a very similar but slightly more complete list of possible reasons for not using the thread pool. There are lots of reasons why you would need to skip the ThreadPool , but if you don't know them then the ThreadPool should be good enough for you. Alternatively, look at the new Parallel Extensions Framework , which has some neat stuff in there that may suit your needs without having to use the ThreadPool . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/10274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380/"
]
} |
10,308 | Are you aware of any tool that creates diagrams showing the branch/merge activity in a SVN repository? We've all seen these diagrams in various tutorials. Some good, some not so good. Can they be created automatically (or maybe with a little prodding -- you might have to tell it what if your branching philosophy is dev-test-prod, branch-per-release, etc.) I'm looking at the TortoiseSVN Revision Graph right now, but it has more detail than I want and the wrong layout. Orion, thanks for the response. I guess since branching and merging are more a convention for managing files in a repository than a "built in feature of SVN, it would be pretty tough. I'll stick with the poorly-drawn diagram at the top of the whiteboard in our team's office. | Check this out SvnMapper from Tigris.org | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/10308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/763/"
]
} |
10,314 | Being new to Objective-C (but a long term C/++) programmer I'm looking for advice/recommendations on naming conventions for variables. My personal preference would be to utilize a prefix for instance variables both for clarity within functions and to prevent shadowing of function parameters. However I'm a fan of properties which rules out prefixes (unless you also prefix your property names, which doesn't work too well and looks daft). Similarly I could use the "self.variable" convention, but only if I make EVERYTHING a property. So given the code below what's your preferred naming style for instance/function variables? And if you don't bother, how do you deal with shadowing on function params? @interface GridItem : NSObject{ CGRect _rect; ... }@end-(void) initFromRect:(CGRect)rect{ _rect = rect; ...} Cheers! | Most Cocoa projects use underbar as a non- IBOutlet instance variable prefix, and use no prefix for IBOutlet instance variables. The reason I don't use underbars for IBOutlet instance variables is that when a nib file is loaded, if you have a setter method for a connected outlet, that setter will be called. However this mechanism does not use Key-Value Coding, so an IBOutlet whose name is prefixed with an underbar ( e.g. _myField ) will not be set unless the setter is named exactly like the outlet ( e.g. set_myField: ), which is non-standard and gross. Also, be aware that using properties like self.myProp is not the same as accessing instance variables. You are sending a message when you use a property, just like if you used bracket notation like [self myProp] . All properties do is give you a concise syntax for specifying both the getter and setter in a single line, and allow you to synthesize their implementation; they do not actually short-circuit the message dispatch mechanism. If you want to access an instance variable directly but prefix it with self you need to treat self as a pointer, like self->myProp which really is a C-style field access. Finally, never use Hungarian notation when writing Cocoa code, and shy away from other prefixes like "f" and "m_" — that will mark the code as having been written by someone who doesn't "get it" and will cause it to be viewed by suspicion by other Cocoa developers. In general, follow the advice in the Coding Guidelines for Cocoa document at the Apple Developer Connection , and other developers will be able to pick up and understand your code, and your code will work well with all of the Cocoa features that use runtime introspection. Here's what a window controller class might look like, using my conventions: // EmployeeWindowController.h#import <AppKit/NSWindowController.h>@interface EmployeeWindowController : NSWindowController {@private // model object this window is presenting Employee *_employee; // outlets connected to views in the window IBOutlet NSTextField *nameField; IBOutlet NSTextField *titleField;}- (id)initWithEmployee:(Employee *)employee;@property(readwrite, retain) Employee *employee;@end// EmployeeWindowController.m#import "EmployeeWindowController.h"@implementation EmployeeWindowController@synthesize employee = _employee;- (id)initWithEmployee:(Employee *)employee { if (self = [super initWithWindowNibName:@"Employee"]) { _employee = [employee retain]; } return self;}- (void)dealloc { [_employee release]; [super dealloc];}- (void)windowDidLoad { // populates the window's controls, not necessary if using bindings [nameField setStringValue:self.employee.name]; [titleField setStringValue:self.employee.title];}@end You'll see that I'm using the instance variable that references an Employee directly in my -init and -dealloc method, while I'm using the property in other methods. That's generally a good pattern with properties: Only ever touch the underlying instance variable for a property in initializers, in -dealloc , and in the getter and setter for the property. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/10314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1043/"
]
} |
10,323 | I recently read a nice post on using StringIO in Ruby. What the author doesn't mention, though, is that StringIO is just an "I." There's no "O." You can't do this, for example: s = StringIO.news << 'foo's << 'bar's.to_s# => should be "foo\nbar"# => really is ''` Ruby really needs a StringBuffer just like the one Java has. StringBuffers serve two important purposes. First, they let you test the output half of what Ruby's StringIO does. Second, they are useful for building up long strings from small parts -- something that Joel reminds us over and over again is otherwise very very slow. Is there a good replacement? It's true that Strings in Ruby are mutable, but that doesn't mean we should always rely on that functionality. If stuff is large, the performance and memory requirements of this, for example, is really bad. result = stuff.map(&:to_s).join(' ') The "correct" way to do this in Java is: result = StringBuffer.new("")for(String s : stuff) { result.append(s);} Though my Java is a bit rusty. | I looked at the ruby documentation for StringIO , and it looks like what you want is StringIO#string , not StringIO#to_s Thus, change your code to: s = StringIO.news << 'foo's << 'bar's.string | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/10323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
]
} |
10,324 | In C, what is the most efficient way to convert a string of hex digits into a binary unsigned int or unsigned long ? For example, if I have 0xFFFFFFFE , I want an int with the base10 value 4294967294 . | You want strtol or strtoul . See also the Unix man page | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/10324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
10,349 | I'm sure there is a good (or at least decent) reason for this. What is it? | I think this is a brilliant question - and I think there is need of a better answer. Surely the only reason is that there is something in a framework somewhere that isn't very thread-safe. That "something" is almost every single instance member on every single control in System.Windows.Forms. The MSDN documentation for many controls in System.Windows.Forms, if not all of them, say "Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe." This means that instance members such as TextBox.Text {get; set;} are not reentrant . Making each of those instance members thread safe could introduce a lot of overhead that most applications do not need. Instead the designers of the .Net framework decided, and I think correctly, that the burden of synchronizing access to forms controls from multiple threads should be put on the programmer. [Edit] Although this question only asks "why" here is a link to an article that explains "how": How to: Make Thread-Safe Calls to Windows Forms Controls on MSDN http://msdn.microsoft.com/en-us/library/ms171728.aspx | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/10349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
]
} |
10,412 | I have a project where I would like to generate a report export in MS Word format. The report will include images/graphs, tables, and text. What is the best way to do this? Third party tools? What are your experiences? | The answer is going to depend slightly upon if the application is running on a server or if it is running on the client machine. If you are running on a server then you are going to want to use one of the XML based office generation formats as there are know issues when using Office Automation on a server . However, if you are working on the client machine then you have a choice of either using Office Automation or using the Office Open XML format (see links below), which is supported by Microsoft Office 2000 and up either natively or through service packs. One draw back to this though is that you might not be able to embed some kinds of graphs or images that you wish to show. The best way to go about things will all depend sightly upon how much time you have to invest in development. If you go the route of Office Automation there are quite a few good tutorials out there that can be found via Google and is fairly simple to learn. However, the Open Office XML format is fairly new so you might find the learning curve to be a bit higher. Office Open XML Iinformation Office Open XML - http://en.wikipedia.org/wiki/Office_Open_XML OpenXML Developer - http://openxmldeveloper.org/default.aspx Introducing the Office (2007) Open XML File Formats - http://msdn.microsoft.com/en-us/library/aa338205.aspx | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/10412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/354/"
]
} |
10,456 | The 'click sound' in question is actually a system wide preference, so I only want it to be disabled when my application has focus and then re-enable when the application closes/loses focus. Originally, I wanted to ask this question here on stackoverflow, but I was not yet in the beta. So, after googling for the answer and finding only a little bit of information on it I came up with the following and decided to post it here now that I'm in the beta. using System;using Microsoft.Win32;namespace HowTo{ class WebClickSound { /// <summary> /// Enables or disables the web browser navigating click sound. /// </summary> public static bool Enabled { get { RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current"); string keyValue = (string)key.GetValue(null); return String.IsNullOrEmpty(keyValue) == false && keyValue != "\"\""; } set { string keyValue; if (value) { keyValue = "%SystemRoot%\\Media\\"; if (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor > 0) { // XP keyValue += "Windows XP Start.wav"; } else if (Environment.OSVersion.Version.Major == 6) { // Vista keyValue += "Windows Navigation Start.wav"; } else { // Don't know the file name so I won't be able to re-enable it return; } } else { keyValue = "\"\""; } // Open and set the key that points to the file RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true); key.SetValue(null, keyValue, RegistryValueKind.ExpandString); isEnabled = value; } } }} Then in the main form we use the above code in these 3 events: Activated Deactivated FormClosing private void Form1_Activated(object sender, EventArgs e){ // Disable the sound when the program has focus WebClickSound.Enabled = false;}private void Form1_Deactivate(object sender, EventArgs e){ // Enable the sound when the program is out of focus WebClickSound.Enabled = true;}private void Form1_FormClosing(object sender, FormClosingEventArgs e){ // Enable the sound on app exit WebClickSound.Enabled = true;} The one problem I see currently is if the program crashes they won't have the click sound until they re-launch my application, but they wouldn't know to do that. What do you guys think? Is this a good solution? What improvements can be made? | I've noticed that if you use WebBrowser.Document.Write rather than WebBrowser.DocumentText then the click sound doesn't happen. So instead of this: webBrowser1.DocumentText = "<h1>Hello, world!</h1>"; try this: webBrowser1.Document.OpenNew(true);webBrowser1.Document.Write("<h1>Hello, world!</h1>"); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/10456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1147/"
]
} |
10,458 | Ideally, I'm looking for a templated logical Set class. It would have all of the standard set operations such as Union, Intersection, Etc., and collapse duplicated items. I ended up creating my own set class based on the C# Dictionary<>- just using the Keys. | HashSet<T> is about the closest you'll get, I think. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/10458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
10,475 | Since the keyboard is the interface we use to the computer, I've always thought touch typing should be something I should learn, but I've always been, well, lazy is the word. So, anyone recommend any good touch typing software? It's easy enough to google, but I'ld like to hear recommendations. | Typing of the Dead! It's a good few years old so you may have to hunt around, but it's a lot of fun and as well as the main game there are numerous minigames to practice specific areas you may be weak on. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/10475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/841/"
]
} |
10,486 | What kind of execution rate do you aim for with your unit tests (# test per second)? How long is too long for an individual unit test? I'd be interested in knowing if people have any specific thresholds for determining whether their tests are too slow, or is it just when the friction of a long running test suite gets the better of you? Finally, when you do decide the tests need to run faster, what techniques do you use to speed up your tests? Note: integration tests are obviously a different matter again. We are strictly talking unit tests that need to be run as frequently as possible. Response roundup: Thanks for the great responses so far. Most advice seems to be don't worry about the speed -- concentrate on quality and just selectively run them if they are too slow. Answers with specific numbers have included aiming for <10ms up to 0.5 and 1 second per test, or just keeping the entire suite of commonly run tests under 10 seconds. Not sure whether it's right to mark one as an "accepted answer" when they're all helpful :) | All unit tests should run in under a second (that is all unit tests combined should run in 1 second). Now I'm sure this has practical limits, but I've had a project with a 1000 tests that run this fast on a laptop. You'll really want this speed so your developers don't dread refactoring some core part of the model (i.e., Lemme go get some coffee while I run these tests...10 minutes later he comes back). This requirement also forces you to design your application correctly. It means that your domain model is pure and contains zero references to any type of persistance (File I/O, Database, etc). Unit tests are all about testing those business relatonships. Now that doesn't mean you ignore testing your database or persistence. But these issues are now isolated behind repositories that can be separately tested with integration tests that is located in a separate project. You run your unit tests constantly when writing domain code and then run your integration tests once on check in. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/10486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/906/"
]
} |
10,499 | Sometimes I get Oracle connection problems because I can't figure out which tnsnames.ora file my database client is using. What's the best way to figure this out? ++happy for various platform solutions. | Oracle provides a utility called tnsping : R:\>tnsping someconnectionTNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-2008 10:38:07Copyright (c) 1997 Oracle Corporation. All rights reserved.Used parameter files:C:\Oracle92\network\ADMIN\sqlnet.oraC:\Oracle92\network\ADMIN\tnsnames.oraTNS-03505: Failed to resolve nameR:\>R:\>tnsping entpr01TNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-2008 10:39:22Copyright (c) 1997 Oracle Corporation. All rights reserved.Used parameter files:C:\Oracle92\network\ADMIN\sqlnet.oraC:\Oracle92\network\ADMIN\tnsnames.oraUsed TNSNAMES adapter to resolve the aliasAttempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (COMMUNITY = **) (PROTOCOL = TCP) (Host = ****) (Port = 1521))) (CONNECT_DATA = (SID = ENTPR01)))OK (40 msec)R:\> This should show what file you're using. The utility sits in the Oracle bin directory. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/10499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
]
} |
10,506 | I am having a strange DB2 issue when I run DBUnit tests. My DBUnit tests are highly customized, but I don't think it is the issue. When I run the tests, I get a failure: SQLCODE: -1084, SQLSTATE: 57019 which translates to SQL1084C Shared memory segments cannot be allocated. It sounds like a weird memory issue, though here's the big strange thing. If I ssh to the test database server, then go in to db2 and do "connect to MY_DB", the tests start succeeding! This seems to have no relation to the supposed memory error that is being reported. I have 2 tests, and the first one actually succeeds, the second one is the one that fails. However, it fails in the DBUnit setup code, when it is obtaining the connection to the DB server to load my xml dataset. Any ideas what might be going on? | Oracle provides a utility called tnsping : R:\>tnsping someconnectionTNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-2008 10:38:07Copyright (c) 1997 Oracle Corporation. All rights reserved.Used parameter files:C:\Oracle92\network\ADMIN\sqlnet.oraC:\Oracle92\network\ADMIN\tnsnames.oraTNS-03505: Failed to resolve nameR:\>R:\>tnsping entpr01TNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-2008 10:39:22Copyright (c) 1997 Oracle Corporation. All rights reserved.Used parameter files:C:\Oracle92\network\ADMIN\sqlnet.oraC:\Oracle92\network\ADMIN\tnsnames.oraUsed TNSNAMES adapter to resolve the aliasAttempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (COMMUNITY = **) (PROTOCOL = TCP) (Host = ****) (Port = 1521))) (CONNECT_DATA = (SID = ENTPR01)))OK (40 msec)R:\> This should show what file you're using. The utility sits in the Oracle bin directory. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/10506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
]
} |
10,524 | The Entity Framework does not support the Expression.Invoke operator. You receive the following exception when trying to use it: "The LINQ expression node type 'Invoke' is not supported in LINQ to Entities. Has anyone got a workaround for this missing functionality? I would like to use the PredicateBuilder detailed here in an Entity Framework context. Edit 1 @marxidad - I like your suggestion, however it does baffle me somewhat. Can you give some further advice on your proposed solution? Edit 2 @marxidad - Thanks for the clarification. | PredicateBuilder and LINQKit now support Entity Framework. Sorry, guys, for not doing this earlier! | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/10524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
]
} |
10,564 | I'm trying out Git on Windows . I got to the point of trying "git commit" and I got this error: Terminal is dumb but no VISUAL nor EDITOR defined. Please supply the message using either -m or -F option. So I figured out I need to have an environment variable called EDITOR. No problem. I set it to point to Notepad. That worked, almost. The default commit message opens in Notepad. But Notepad doesn't support bare line feeds. I went out and got Notepad++ , but I can't figure out how to get Notepad++ set up as the %EDITOR% in such a way that it works with Git as expected. I'm not married to Notepad++. At this point I don't mind what editor I use. I just want to be able to type commit messages in an editor rather than the command line (with -m ). Those of you using Git on Windows: What tool do you use to edit your commit messages, and what did you have to do to make it work? | Update September 2015 (6 years later) The last release of git-for-Windows (2.5.3) now includes: By configuring git config core.editor notepad , users can now use notepad.exe as their default editor . Configuring git config format.commitMessageColumns 72 will be picked up by the notepad wrapper and line-wrap the commit message after the user edits it. See commit 69b301b by Johannes Schindelin ( dscho ) . And Git 2.16 (Q1 2018) will show a message to tell the user that it is waiting for the user to finish editing when spawning an editor, in case the editoropens to a hidden window or somewhere obscure and the user getslost. See commit abfb04d (07 Dec 2017), and commit a64f213 (29 Nov 2017) by Lars Schneider ( larsxschneider ) . Helped-by: Junio C Hamano ( gitster ) . (Merged by Junio C Hamano -- gitster -- in commit 0c69a13 , 19 Dec 2017) launch_editor() : indicate that Git waits for user input When a graphical GIT_EDITOR is spawned by a Git command that opens and waits for user input (e.g. " git rebase -i "), then the editor window might be obscured by other windows. The user might be left staring at the original Git terminal window without even realizing that s/he needs to interact with another window before Git can proceed. To this user Git appears hanging. Print a message that Git is waiting for editor input in the original terminal and get rid of it when the editor returns, if the terminal supports erasing the last line Original answer I just tested it with git version 1.6.2.msysgit.0.186.gf7512 and Notepad++5.3.1 I prefer to not have to set an EDITOR variable, so I tried: git config --global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\""# orgit config --global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\" %*" That always gives: C:\prog\git>git config --global --edit"c:\Program Files\Notepad++\notepad++.exe" %*: c:\Program Files\Notepad++\notepad++.exe: command not founderror: There was a problem with the editor '"c:\Program Files\Notepad++\notepad++.exe" %*'. If I define a npp.bat including: "c:\Program Files\Notepad++\notepad++.exe" %* and I type: C:\prog\git>git config --global core.editor C:\prog\git\npp.bat It just works from the DOS session, but not from the git shell . (not that with the core.editor configuration mechanism, a script with " start /WAIT... " in it would not work, but only open a new DOS window) Bennett's answer mentions the possibility to avoid adding a script, but to reference directly the program itself between simple quotes . Note the direction of the slashes! Use / NOT \ to separate folders in the path name! git config --global core.editor \"'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin" Or if you are in a 64 bit system: git config --global core.editor \"'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin" But I prefer using a script (see below): that way I can play with different paths or different options without having to register again a git config . The actual solution (with a script) was to realize that: what you refer to in the config file is actually a shell ( /bin/sh ) script , not a DOS script. So what does work is: C:\prog\git>git config --global core.editor C:/prog/git/npp.bat with C:/prog/git/npp.bat : #!/bin/sh"c:/Program Files/Notepad++/notepad++.exe" -multiInst "$*" or #!/bin/sh"c:/Program Files/Notepad++/notepad++.exe" -multiInst -notabbar -nosession -noPlugin "$*" With that setting, I can do ' git config --global --edit ' from DOS or Git Shell, or I can do ' git rebase -i ... ' from DOS or Git Shell. Bot commands will trigger a new instance of notepad++ (hence the -multiInst ' option), and wait for that instance to be closed before going on. Note that I use only '/', not \ '. And I installed msysgit using option 2. (Add the git\bin directory to the PATH environment variable, but without overriding some built-in windows tools) The fact that the notepad++ wrapper is called .bat is not important. It would be better to name it 'npp.sh' and to put it in the [git]\cmd directory though (or in any directory referenced by your PATH environment variable). See also: How do I view ‘git diff’ output with visual diff program? for the general theory How do I setup DiffMerge with msysgit / gitk? for another example of external tool (DiffMerge, and WinMerge) lightfire228 adds in the comments : For anyone having an issue where N++ just opens a blank file, and git doesn't take your commit message, see " Aborting commit due to empty message ": change your .bat or .sh file to say: "<path-to-n++" .git/COMMIT_EDITMSG -<arguments>. That will tell notepad++ to open the temp commit file, rather than a blank new one. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/10564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/437/"
]
} |
10,580 | What is the difference between early and late binding? | The short answer is that early (or static) binding refers to compile time binding and late (or dynamic) binding refers to runtime binding (for example when you use reflection). | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/10580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
]
} |
10,616 | I'm an ASP.NET developer who has used Microsoft SQL Server for all my database needs (both at work and for personal projects). I am considering trying out the LAMP stack for some of my personal projects. What are some of the main differences between MySQL and SQL Server ? Is using stored procedures a common practice in MySQL ? Any advice or resources you'd recommend to help me with the switch? To those who have experience with both, are there any missing features from MySQL ? | One thing you have to watch out for is the fairly severe differences in the way SQL Server and MySQL implement the SQL syntax. Here's a nice Comparison of Different SQL Implementations . For example, take a look at the top-n section. In MySQL: SELECT ageFROM personORDER BY age ASCLIMIT 1 OFFSET 2 In SQL Server (T-SQL): SELECT TOP 3 WITH TIES *FROM personORDER BY age ASC | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/10616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/285/"
]
} |
10,634 | I currently use nant, ccnet (cruise control), svn, mbunit. I use msbuild to do my sln build just because it was simpler to shell out. Are there any merits to switching my whole build script to MSBuild? I need to be able to run tests, watir style tests, xcopy deploy. Is this easier? Update: Any compelling features that would cause me to shift from nant to msbuild? | I like MSBuild. One reason is that .csproj files are msbuild files, and building in VS is just like building at the command line. Another reason is the good support from TeamCity which is the CI server I've been using. If you start using MSBuild, and you want to do more custom things in your build process, get the MSBuild Community Tasks . They give you a bunch of nice extra tasks. I haven't used NAnt for several years now, and I haven't regretted it. Also, as Ruben mentions, there are the SDC Tasks tasks on CodePlex. For even more fun, there is the MSBuild Extension Pack on CodePlex , which includes a twitter task. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/10634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220/"
]
} |
10,635 | I wrote a simple batch file as a PowerShell script, and I am getting errors when they run. It's in a scripts directory in my path. This is the error I get: Cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about-signing". I looked in the help, but it's less than helpful. | It could be PowerShell's default security level, which (IIRC) will only run signed scripts. Try typing this: set-executionpolicy remotesigned That will tell PowerShell to allow local (that is, on a local drive) unsigned scripts to run. Then try executing your script again. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/10635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220/"
]
} |
10,644 | I need a C# profiler. Although I'm not averse to paying for one, something which is free or at least with a trial version would be ideal since it takes time to raise a purchase order. Any recommendations? | You can try the following: nprof (free but kinda old) ProfileSharp (open source) .Net Memory Profiler (really good for memory leaks, there's a trial version) Edit: Nprof has been replaced with SlimTune and works with .Net 4.0 applications | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/10644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147/"
]
} |
10,658 | I'm looking for a good method of generating an iCalendar file (*.ics) in c# (asp.net). I've found a couple resources, but one thing that has been lacking is their support for quoted-printable fields - fields that have carriage returns and line feeds. For example, if the description field isn't encoded properly, only the first line will display and possibly corrupting the rest of the information in the *.ics file. I'm looking for existing classes that can generate *.ics files and/or a class that can generate quoted-printable fields. | I use DDay.Ical , its good stuff.Has the ability to open up an ical file and get its data in a nice object model. It says beta, but it works great for us. Edit Nov 2016 This library has been deprecated, but was picked up and re-released as iCal.NET by another dev. Notes about the release: rianjs.net/2016/07/dday-ical-is-now-ical-net Source on GitHub: github.com/rianjs/ical.net | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/10658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/519/"
]
} |
10,680 | Is there any difference between int on_exit(void (*function)(int , void *), void *arg); and int atexit(void (*function)(void)); other than the fact that the function used by on_exit gets the exit status? That is, if I don't care about the exit status, is there any reason to use one or the other? Edit: Many of the answers warned against on_exit because it's non-standard. If I'm developing an app that is for internal corporate use and guaranteed to run on specific configurations, should I worry about this? | According to this link I found, it seems there are a few differences. on_exit will let you pass in an argument that is passed in to the on_exit function when it is called... which might let you set up some pointers to do some cleanup work on when it is time to exit. Furthermore, it appears that on_exit was a SunOS specific function that may not be compatible on all platforms... so you may want to stick with atexit, despite it being more restrictive. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/10680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084/"
]
} |
10,752 | I know the so-called textbook definition of unit tests and integration tests. What I am curious about is when it is time to write unit tests... I will write them to cover as many sets of classes as possible. For example, if I have a Word class, I will write some unit tests for the Word class. Then, I begin writing my Sentence class, and when it needs to interact with the Word class, I will often write my unit tests such that they test both Sentence and Word ... at least in the places where they interact. Have these tests essentially become integration tests because they now test the integration of these 2 classes, or is it just a unit test that spans 2 classes? In general, because of this uncertain line, I will rarely actually write integration tests... or is my using the finished product to see if all the pieces work properly the actual integration tests, even though they are manual and rarely repeated beyond the scope of each individual feature? Am I misunderstanding integration tests, or is there really just very little difference between integration and unit tests? | The key difference, to me, is that integration tests reveal if a feature is working or is broken, since they stress the code in a scenario close to reality. They invoke one or more software methods or features and test if they act as expected. On the opposite, a Unit test testing a single method relies on the (often wrong) assumption that the rest of the software is correctly working, because it explicitly mocks every dependency. Hence, when a unit test for a method implementing some feature is green, it does not mean the feature is working. Say you have a method somewhere like this: public SomeResults DoSomething(someInput) { var someResult = [Do your job with someInput]; Log.TrackTheFactYouDidYourJob(); return someResults;} DoSomething is very important to your customer: it's a feature, the only thing that matters. That's why you usually write a Cucumber specification asserting it: you wish to verify and communicate the feature is working or not. Feature: To be able to do something In order to do something As someone I want the system to do this thingScenario: A sample one Given this situation When I do something Then what I get is what I was expecting for No doubt: if the test passes, you can assert you are delivering a working feature. This is what you can call Business Value . If you want to write a unit test for DoSomething you should pretend (using some mocks) that the rest of the classes and methods are working (that is: that, all dependencies the method is using are correctly working) and assert your method is working. In practice, you do something like: public SomeResults DoSomething(someInput) { var someResult = [Do your job with someInput]; FakeAlwaysWorkingLog.TrackTheFactYouDidYourJob(); // Using a mock Log return someResults;} You can do this with Dependency Injection, or some Factory Method or any Mock Framework or just extending the class under test. Suppose there's a bug in Log.DoSomething() .Fortunately, the Gherkin spec will find it and your end-to-end tests will fail. The feature won't work, because Log is broken, not because [Do your job with someInput] is not doing its job. And, by the way, [Do your job with someInput] is the sole responsibility for that method. Also, suppose Log is used in 100 other features, in 100 other methods of 100 other classes. Yep, 100 features will fail. But, fortunately, 100 end-to-end tests are failing as well and revealing the problem. And, yes: they are telling the truth . It's very useful information: I know I have a broken product. It's also very confusing information: it tells me nothing about where the problem is. It communicates me the symptom, not the root cause. Yet, DoSomething 's unit test is green, because it's using a fake Log , built to never break. And, yes: it's clearly lying . It's communicating a broken feature is working. How can it be useful? (If DoSomething() 's unit test fails, be sure: [Do your job with someInput] has some bugs.) Suppose this is a system with a broken class: A single bug will break several features, and several integration tests will fail. On the other hand, the same bug will break just one unit test. Now, compare the two scenarios. The same bug will break just one unit test. All your features using the broken Log are red All your unit tests are green, only the unit test for Log is red Actually, unit tests for all modules using a broken feature are green because, by using mocks, they removed dependencies. In other words, they run in an ideal, completely fictional world. And this is the only way to isolate bugs and seek them. Unit testing means mocking. If you aren't mocking, you aren't unit testing. The difference Integration tests tell what 's not working. But they are of no use in guessing where the problem could be. Unit tests are the sole tests that tell you where exactly the bug is. To draw this information, they must run the method in a mocked environment, where all other dependencies are supposed to correctly work. That's why I think that your sentence "Or is it just a unit test that spans 2 classes" is somehow displaced. A unit test should never span 2 classes. This reply is basically a summary of what I wrote here: Unit tests lie, that's why I love them . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/10752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
]
} |
10,793 | I'm dynamically loading user controls adding them to the Controls collection of the web form. I'd like to hide user controls if they cause a unhandled exception while rendering. So, I tried hooking to the Error event of each UserControl but it seems that this event never fires for the UserControls as it does for Page class. Did some googling around and it doesn't seem promising. Any ideas here? | mmilic, following on from your response to my previous idea .. No additional logic required! That's the point, your doing nothing to the classes in question, just wrapping them in some instantiation bubble-wrap! :) OK, I was going to just bullet point but I wanted to see this work for myself, so I cobbled together some very rough code but the concept is there and it seems to work. APOLOGIES FOR THE LONG POST The SafeLoader This will basically be the "bubble" I mentioned.. It will get the controls HTML, catching any errors that occur during Rendering. public class SafeLoader{ public static string LoadControl(Control ctl) { // In terms of what we could do here, its down // to you, I will just return some basic HTML saying // I screwed up. try { // Get the Controls HTML (which may throw) // And store it in our own writer away from the // actual Live page. StringWriter writer = new StringWriter(); HtmlTextWriter htmlWriter = new HtmlTextWriter(writer); ctl.RenderControl(htmlWriter); return writer.GetStringBuilder().ToString(); } catch (Exception) { string ctlType = ctl.GetType().Name; return "<span style=\"color: red; font-weight:bold; font-size: smaller;\">" + "Rob + Controls = FAIL (" + ctlType + " rendering failed) Sad face :(</span>"; } }} And Some Controls.. Ok I just mocked together two controls here, one will throw the other will render junk. Point here, I don't give a crap. These will be replaced with your custom controls.. BadControl public class BadControl : WebControl{ protected override void Render(HtmlTextWriter writer) { throw new ApplicationException("Rob can't program controls"); }} GoodControl public class GoodControl : WebControl{ protected override void Render(HtmlTextWriter writer) { writer.Write("<b>Holy crap this control works</b>"); }} The Page OK, so lets look at the "test" page.. Here I simply instantiate the controls, grab their html and output it, I will follow with thoughts on designer support etc.. Page Code-Behind protected void Page_Load(object sender, EventArgs e) { // Create some controls (BadControl will throw) string goodHtml = SafeLoader.LoadControl(new BadControl()); Response.Write(goodHtml); string badHtml = SafeLoader.LoadControl(new GoodControl()); Response.Write(badHtml); } Thoughts OK, I know what you are thinking, "these controls are instantiated programatically, what about designer support? I spent freaking hours getting these controls nice for the designer, now you're messing with my mojo". OK, so I havent really tested this yet (probably will do in a min!) but the idea here is to override the CreateChildControls method for the page, and take the instance of each control added on the form and run it through the SafeLoader. If the code passes, you can add it to the Controls collection as normal, if not, then you can create erroneous literals or something, up to you my friend. Finally.. Again, sorry for the long post, but I wanted to get the code here so we can discuss this :)I hope this helps demonstrate my idea :) Update Tested by chucking a control in on the designer and overriding the CreateChildControls method with this, works fine, may need some clean up to make things better looking, but I'll leave that to you ;) protected override void CreateChildControls(){ // Pass each control through the Loader to check // its not lame foreach (Control ctl in Controls) { string s = SafeLoader.LoadControl(ctl); // If its bad, smack it downnnn! if (s == string.Empty) { ctl.Visible = false; // Prevent Rendering string ctlType = ctl.GetType().Name; Response.Write("<b>Problem Occurred Rendering " + ctlType + " '" + ctl.ID + "'.</b>"); } }} Enjoy! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/10793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269/"
]
} |
10,798 | When creating a new ASP.NET project in Visual Studio should I chose create: website or project? I understand that web application project was the way to do it back in the day with VS 2003 but is it still applicable today? What are some of the caveats using one over the other? | There's a pretty good comparison chart on MSDN . Website projects are simple, in that all files added to the project folders are automatically compiled and included, which was supposedly added to make it more palatable to classic ASP and PHP developers. Once benefit is that it includes build providers, which allow for certain actions to be associated with a filetype - that's how the first release of SubSonic would rebuild the data access layer when you added a .abp file to the site. Web Application Projects are a lot more flexible, though. For instance, all class libraries in a Website Project need to be in the App_Code folder, which is frustrating in a complex application. There are a lot of scenarios which just don't work for a Website Project. You can convert from one to another, although if you're unsure I'd recommend just starting with a Web Application. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/10798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/831/"
]
} |
10,808 | Ok, so I've been refactoring my code in my little Rails app in an effort to remove duplication, and in general make my life easier (as I like an easy life). Part of this refactoring, has been to move code that's common to two of my models to a module that I can include where I need it. So far, so good. Looks like it's going to work out, but I've just hit a problem that I'm not sure how to get around. The module (which I've called sendable), is just going to be the code that handles faxing, e-mailing, or printing a PDF of the document. So, for example, I have a purchase order, and I have Internal Sales Orders (imaginatively abbreviated to ISO). The problem I've struck, is that I want some variables initialised (initialized for people who don't spell correctly :P ) after the object is loaded, so I've been using the after_initialize hook. No problem... until I start adding some more mixins. The problem I have, is that I can have an after_initialize in any one of my mixins, so I need to include a super call at the start to make sure the other mixin after_initialize calls get called. Which is great, until I end up calling super and I get an error because there is no super to call. Here's a little example, in case I haven't been confusing enough: class Iso < ActiveRecord::Base include Shared::TracksSerialNumberExtension include Shared::OrderLines extend Shared::Filtered include Sendable::Model validates_presence_of :customer validates_associated :lines owned_by :customer order_lines :despatched # Mixin tracks_serial_numbers :items # Mixin sendable :customer # Mixin attr_accessor :address def initialize( params = nil ) super self.created_at ||= Time.now.to_date endend So, if each one of the mixins have an after_initialize call, with a super call, how can I stop that last super call from raising the error? How can I test that the super method exists before I call it? | You can use this: super if defined?(super) Here is an example: class Aendclass B < A def t super if defined?(super) puts "Hi from B" endendB.new.t | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/10808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/841/"
]
} |
10,810 | I'm doing a authorization check from a WinForms application with the help of the AzMan authorization provider from Enterprise Library and am receiving the the following error: Unable to update the password. The value provided as the current password is incorrect. (Exception from HRESULT: 0x8007052B) (Microsoft.Practices.EnterpriseLibrary.Security.AzMan) Unable to update the password. The value provided as the current password is incorrect. (Exception from HRESULT: 0x8007052B) (Microsoft.Interop.Security.AzRoles) The AzMan store is hosted in ADAM on another computer in the same domain. Other computers and users do not have this problem. The user making the call has read access to both ADAM and the AzMan store. The computer running the WinForms app and the computer running ADAM are both on Windows XP SP2. I've had access problems with AzMan before that I've resolved, but this is a new one... What am I missing? | You can use this: super if defined?(super) Here is an example: class Aendclass B < A def t super if defined?(super) puts "Hi from B" endendB.new.t | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/10810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/966/"
]
} |
10,819 | For certain types of sql queries, an auxiliary table of numbers can be very useful. It may be created as a table with as many rows as you need for a particular task or as a user defined function that returns the number of rows required in each query. What is the optimal way to create such a function? | Heh... sorry I'm so late responding to an old post. And, yeah, I had to respond because the most popular answer (at the time, the Recursive CTE answer with the link to 14 different methods) on this thread is, ummm... performance challenged at best. First, the article with the 14 different solutions is fine for seeing the different methods of creating a Numbers/Tally table on the fly but as pointed out in the article and in the cited thread, there's a very important quote... "suggestions regarding efficiency and performance are often subjective. Regardless of how a query is being used, the physical implementation determines the efficiency of a query. Therefore, rather than relying on biased guidelines, it is imperative that you test the query and determine which one performs better." Ironically, the article itself contains many subjective statements and "biased guidelines" such as "a recursive CTE can generate a number listing pretty efficiently " and "This is an efficient method of using WHILE loop from a newsgroup posting by Itzik Ben-Gen" (which I'm sure he posted just for comparison purposes). C'mon folks... Just mentioning Itzik's good name may lead some poor slob into actually using that horrible method. The author should practice what (s)he preaches and should do a little performance testing before making such ridiculously incorrect statements especially in the face of any scalablility. With the thought of actually doing some testing before making any subjective claims about what any code does or what someone "likes", here's some code you can do your own testing with. Setup profiler for the SPID you're running the test from and check it out for yourself... just do a "Search'n'Replace" of the number 1000000 for your "favorite" number and see... --===== Test for 1000000 rows ==================================GO--===== Traditional RECURSIVE CTE method WITH Tally (N) AS ( SELECT 1 UNION ALL SELECT 1 + N FROM Tally WHERE N < 1000000 ) SELECT N INTO #Tally1 FROM Tally OPTION (MAXRECURSION 0);GO--===== Traditional WHILE LOOP method CREATE TABLE #Tally2 (N INT); SET NOCOUNT ON;DECLARE @Index INT; SET @Index = 1; WHILE @Index <= 1000000 BEGIN INSERT #Tally2 (N) VALUES (@Index); SET @Index = @Index + 1; END;GO--===== Traditional CROSS JOIN table method SELECT TOP (1000000) ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS N INTO #Tally3 FROM Master.sys.All_Columns ac1 CROSS JOIN Master.sys.ALL_Columns ac2;GO--===== Itzik's CROSS JOINED CTE method WITH E00(N) AS (SELECT 1 UNION ALL SELECT 1), E02(N) AS (SELECT 1 FROM E00 a, E00 b), E04(N) AS (SELECT 1 FROM E02 a, E02 b), E08(N) AS (SELECT 1 FROM E04 a, E04 b), E16(N) AS (SELECT 1 FROM E08 a, E08 b), E32(N) AS (SELECT 1 FROM E16 a, E16 b), cteTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY N) FROM E32) SELECT N INTO #Tally4 FROM cteTally WHERE N <= 1000000;GO--===== Housekeeping DROP TABLE #Tally1, #Tally2, #Tally3, #Tally4;GO While we're at it, here's the numbers I get from SQL Profiler for the values of 100, 1000, 10000, 100000, and 1000000... SPID TextData Dur(ms) CPU Reads Writes---- ---------------------------------------- ------- ----- ------- ------ 51 --===== Test for 100 rows ============== 8 0 0 0 51 --===== Traditional RECURSIVE CTE method 16 0 868 0 51 --===== Traditional WHILE LOOP method CR 73 16 175 2 51 --===== Traditional CROSS JOIN table met 11 0 80 0 51 --===== Itzik's CROSS JOINED CTE method 6 0 63 0 51 --===== Housekeeping DROP TABLE #Tally 35 31 401 0 51 --===== Test for 1000 rows ============= 0 0 0 0 51 --===== Traditional RECURSIVE CTE method 47 47 8074 0 51 --===== Traditional WHILE LOOP method CR 80 78 1085 0 51 --===== Traditional CROSS JOIN table met 5 0 98 0 51 --===== Itzik's CROSS JOINED CTE method 2 0 83 0 51 --===== Housekeeping DROP TABLE #Tally 6 15 426 0 51 --===== Test for 10000 rows ============ 0 0 0 0 51 --===== Traditional RECURSIVE CTE method 434 344 80230 10 51 --===== Traditional WHILE LOOP method CR 671 563 10240 9 51 --===== Traditional CROSS JOIN table met 25 31 302 15 51 --===== Itzik's CROSS JOINED CTE method 24 0 192 15 51 --===== Housekeeping DROP TABLE #Tally 7 15 531 0 51 --===== Test for 100000 rows =========== 0 0 0 0 51 --===== Traditional RECURSIVE CTE method 4143 3813 800260 154 51 --===== Traditional WHILE LOOP method CR 5820 5547 101380 161 51 --===== Traditional CROSS JOIN table met 160 140 479 211 51 --===== Itzik's CROSS JOINED CTE method 153 141 276 204 51 --===== Housekeeping DROP TABLE #Tally 10 15 761 0 51 --===== Test for 1000000 rows ========== 0 0 0 0 51 --===== Traditional RECURSIVE CTE method 41349 37437 8001048 1601 51 --===== Traditional WHILE LOOP method CR 59138 56141 1012785 1682 51 --===== Traditional CROSS JOIN table met 1224 1219 2429 2101 51 --===== Itzik's CROSS JOINED CTE method 1448 1328 1217 2095 51 --===== Housekeeping DROP TABLE #Tally 8 0 415 0 As you can see, the Recursive CTE method is the second worst only to the While Loop for Duration and CPU and has 8 times the memory pressure in the form of logical reads than the While Loop . It's RBAR on steroids and should be avoided, at all cost, for any single row calculations just as a While Loop should be avoided. There are places where recursion is quite valuable but this ISN'T one of them . As a side bar, Mr. Denny is absolutely spot on... a correctly sized permanent Numbers or Tally table is the way to go for most things. What does correctly sized mean? Well, most people use a Tally table to generate dates or to do splits on VARCHAR(8000). If you create an 11,000 row Tally table with the correct clustered index on "N", you'll have enough rows to create more than 30 years worth of dates (I work with mortgages a fair bit so 30 years is a key number for me) and certainly enough to handle a VARCHAR(8000) split. Why is "right sizing" so important? If the Tally table is used a lot, it easily fits in cache which makes it blazingly fast without much pressure on memory at all. Last but not least, every one knows that if you create a permanent Tally table, it doesn't much matter which method you use to build it because 1) it's only going to be made once and 2) if it's something like an 11,000 row table, all of the methods are going to run "good enough". So why all the indigination on my part about which method to use??? The answer is that some poor guy/gal who doesn't know any better and just needs to get his or her job done might see something like the Recursive CTE method and decide to use it for something much larger and much more frequently used than building a permanent Tally table and I'm trying to protect those people, the servers their code runs on, and the company that owns the data on those servers . Yeah... it's that big a deal. It should be for everyone else, as well. Teach the right way to do things instead of "good enough". Do some testing before posting or using something from a post or book... the life you save may, in fact, be your own especially if you think a recursive CTE is the way to go for something like this. ;-) Thanks for listening... | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/10819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/224/"
]
} |
10,822 | What would be a very fast way to determine if your connectionstring lets you connect to a database? Normally a connection attempt keeps the user waiting a long time before notifying the attempt was futile anyway. | You haven't mentioned what database you are connecting to, however. In SQL Server 2005 , from .NET, you can specify a connection timeout in your connection string like so: server=<server>;database=<database>;uid=<user>;password=<password>;Connect Timeout=3 This will try to connect to the server and if it doesn't do so in three seconds, it will throw a timeout error. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/10822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1271/"
]
} |
10,825 | In SQL Server I have a DATETIME column which includes a time element. Example: '14 AUG 2008 14:23:019' What is the best method to only select the records for a particular day, ignoring the time part? Example: (Not safe, as it does not match the time part and returns no rows) DECLARE @p_date DATETIMESET @p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )SELECT *FROM table1WHERE column_datetime = @p_date Note: Given this site is also about jotting down notes and techniques you pick up and then forget, I'm going to post my own answer to this question as DATETIME stuff in MSSQL is probably the topic I lookup most in SQLBOL. Update Clarified example to be more specific. Edit Sorry, But I've had to down-mod WRONG answers (answers that return wrong results). @Jorrit: WHERE (date>'20080813' AND date<'20080815') will return the 13th and the 14th. @wearejimbo: Close, but no cigar! badge awarded to you. You missed out records written at 14/08/2008 23:59:001 to 23:59:999 (i.e. Less than 1 second before midnight.) | Technique 1: DECLARE @p_date DATETIME SET @p_date = CONVERT( DATETIME, '14 AUG 2008', 106 ) SELECT * FROM table1 WHERE column_datetime >= @p_date AND column_datetime < DATEADD(d, 1, @p_date) The advantage of this is that it will use any index on 'column_datetime' if it exists. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/10825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/993/"
]
} |
10,848 | Does anybody know if it's possible, and how, to programmatically send a SMS from the iPhone , with the official SDK / Cocoa Touch? | Restrictions If you could send an SMS within a program on the iPhone, you'll be able to write games that spam people in the background. I'm sure you really want to have spams from your friends, "Try out this new game! It roxxers my boxxers, and yours will be too! roxxersboxxers.com!!!! If you sign up now you'll get 3,200 RB points!!" Apple has restrictions for automated (or even partially automated) SMS and dialing operations. (Imagine if the game instead dialed 911 at a particular time of day) Your best bet is to set up an intermediate server on the internet that uses an online SMS sending service and send the SMS via that route if you need complete automation. (ie, your program on the iPhone sends a UDP packet to your server, which sends the real SMS) iOS 4 Update iOS 4, however, now provides a viewController you can import into your application. You prepopulate the SMS fields, then the user can initiate the SMS send within the controller. Unlike using the "SMS:..." url format, this allows your application to stay open, and allows you to populate both the to and the body fields. You can even specify multiple recipients. This prevents applications from sending automated SMS without the user explicitly aware of it. You still cannot send fully automated SMS from the iPhone itself, it requires some user interaction. But this at least allows you to populate everything, and avoids closing the application. The MFMessageComposeViewController class is well documented, and tutorials show how easy it is to implement. iOS 5 Update iOS 5 includes messaging for iPod touch and iPad devices, so while I've not yet tested this myself, it may be that all iOS devices will be able to send SMS via MFMessageComposeViewController. If this is the case, then Apple is running an SMS server that sends messages on behalf of devices that don't have a cellular modem. iOS 6 Update No changes to this class. iOS 7 Update You can now check to see if the message medium you are using will accept a subject or attachments, and what kind of attachments it will accept. You can edit the subject and add attachments to the message, where the medium allows it. iOS 8 Update No changes to this class. iOS 9 Update No changes to this class. iOS 10 Update No changes to this class. iOS 11 Update No significant changes to this class Limitations to this class Keep in mind that this won't work on phones without iOS 4, and it won't work on the iPod touch or the iPad, except, perhaps, under iOS 5. You must either detect the device and iOS limitations prior to using this controller, or risk restricting your app to recently upgraded 3G, 3GS, and 4 iPhones. However, an intermediate server that sends SMS will allow any and all of these iOS devices to send SMS as long as they have internet access, so it may still be a better solution for many applications. Alternately, use both, and only fall back to an online SMS service when the device doesn't support it. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/10848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
10,855 | I'm trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example: var results = from myRow in myDataTablewhere results.Field("RowNo") == 1select results; This is not allowed. How do I get something like this working? I'm amazed that LINQ queries are not allowed on DataTables! | You can't query against the DataTable 's Rows collection, since DataRowCollection doesn't implement IEnumerable<T> . You need to use the AsEnumerable() extension for DataTable . Like so: var results = from myRow in myDataTable.AsEnumerable()where myRow.Field<int>("RowNo") == 1select myRow; And as @Keith says, you'll need to add a reference to System.Data.DataSetExtensions AsEnumerable() returns IEnumerable<DataRow> . If you need to convert IEnumerable<DataRow> to a DataTable , use the CopyToDataTable() extension. Below is query with Lambda Expression, var result = myDataTable .AsEnumerable() .Where(myRow => myRow.Field<int>("RowNo") == 1); | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/10855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445/"
]
} |
10,877 | How can I left-align the numbers in an ordered list? 1. an item// skip some items for brevity 9. another item10. notice the 1 is under the 9, and the item contents also line up Change the character after the number in an ordered list? 1) an item Also is there a CSS solution to change from numbers to alphabetic/roman lists instead of using the type attribute on the ol element. I am mostly interested in answers that work on Firefox 3. | This is the solution I have working in Firefox 3, Opera and Google Chrome. The list still displays in IE7 (but without the close bracket and left align numbers): ol { counter-reset: item; margin-left: 0; padding-left: 0;}li { display: block; margin-bottom: .5em; margin-left: 2em;}li::before { display: inline-block; content: counter(item) ") "; counter-increment: item; width: 2em; margin-left: -2em;} <ol> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> <li>Five</li> <li>Six</li> <li>Seven</li> <li>Eight</li> <li>Nine<br>Items</li> <li>Ten<br>Items</li></ol> EDIT: Included multiple line fix by strager Also is there a CSS solution to change from numbers to alphabetic/roman lists instead of using the type attribute on the ol element. Refer to list-style-type CSS property. Or when using counters the second argument accepts a list-style-type value. For example the following will use upper roman: li::before { content: counter(item, upper-roman) ") "; counter-increment: item;/* ... */ | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/10877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486/"
]
} |
10,880 | I'm looking for a good article on using emacs as C/C++ IDE. Something like Steve Yegge's "Effective emacs" . | No specific article, really, but I've found EmacsWiki to be full of useful information. Consider checking out these entries: CPlusPlus as a starting point for many C++-related articles, and CppTemplate to define a template that can give you a good skeleton when you start new files | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/10880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007/"
]
} |
10,905 | You should be able to create a generic form: public partial class MyGenericForm<T> : Form where T : class{ /* form code */ public List<T> TypedList { get; set; }} Is valid C#, and compiles. However the designer won't work and the form will throw a runtime exception if you have any images stating that it cannot find the resource. I think this is because the windows forms designer assumes that the resources will be stored under the simple type's name. | Yes you can! Here's a blog post I made a while ago with the trick: Designing Generic Forms Edit: Looks like you're already doing it this way. This method works fine so I wouldn't consider it too hacky. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/10905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
]
} |
10,919 | Usually when I'm creating indexes on tables, I generally guess what the Fill Factor should be based on an educated guess of how the table will be used (many reads or many writes). Is there a more scientific way to determine a more accurate Fill Factor value? | You could try running a big list of realistic operations and looking at IO queues for the different actions. There are a lot of variables that govern it, such as the size of each row and the number of writes vs reads. Basically: high fill factor = quicker read, low = quicker write. However it's not quite that simple, as almost all writes will be to a subset of rows that need to be looked up first. For instance: set a fill factor to 10% and each single-row update will take 10 times as long to find the row it's changing, even though a page split would then be very unlikely. Generally you see fill factors 70% (very high write) to 95% (very high read). It's a bit of an art form. I find that a good way of thinking of fill factors is as pages in an address book - the more tightly you pack the addresses the harder it is to change them, but the slimmer the book. I think I explained it better on my blog . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/10919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
]
} |
10,985 | Does anyone know how I can, in platform-independent C++ code prevent an object from being created on the heap? That is, for a class "Foo", I want to prevent users from doing this: Foo *ptr = new Foo; and only allow them to do this: Foo myfooObject; Does anyone have any ideas? Cheers, | Nick's answer is a good starting point, but incomplete, as you actually need to overload: private: void* operator new(size_t); // standard new void* operator new(size_t, void*); // placement new void* operator new[](size_t); // array new void* operator new[](size_t, void*); // placement array new (Good coding practice would suggest you should also overload the delete and delete[] operators -- I would, but since they're not going to get called it isn't really necessary.) Pauldoo is also correct that this doesn't survive aggregating on Foo, although it does survive inheriting from Foo. You could do some template meta-programming magic to HELP prevent this, but it would not be immune to "evil users" and thus is probably not worth the complication. Documentation of how it should be used, and code review to ensure it is used properly, are the only ~100% way. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/10985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1304/"
]
} |
10,990 | Sorry for the basic question - I'm a .NET developer and don't have much experience with LAMP setups. I have a PHP site that will allow uploads to a specific folder. I have been told that this folder needs to be owned by the webserver user for the upload process to work, so I created the folder and then set permissions as such: chown apache:apache -R uploads/chmod 755 -R uploads/ The only problem now is that the FTP user can not modify the uploaded files at all. Is there a permission setting that will allow me to still upload files and then modify them later as a user other than the webserver user? | You can create a new group with both the apache user and FTP user as members and then make the permission on the upload folder 775. This should give both the apache and FTP users the ability to write to the files in the folder but keep everyone else from modifying them. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/10990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1153/"
]
} |
11,043 | What are the pros and cons of using table aliases in SQL? I personally try to avoid them, as I think they make the code less readable (especially when reading through large where/and statements), but I'd be interested in hearing any counter-points to this. When is it generally a good idea to use table aliases, and do you have any preferred formats? | Table aliases are a necessary evil when dealing with highly normalized schemas. For example, and I'm not the architect on this DB so bear with me, it can take 7 joins in order to get a clean and complete record back which includes a person's name, address, phone number and company affiliation. Rather than the somewhat standard single character aliases, I tend to favor short word aliases so the above example's SQL ends up looking like: select person.FirstName ,person.LastName ,addr.StreetAddress ,addr.City ,addr.State ,addr.Zip ,phone.PhoneNumber ,company.CompanyNamefrom tblPeople personleft outer join tblAffiliations affl on affl.personID = person.personIDleft outer join tblCompany company on company.companyID = affl.companyID ... etc | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/11043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/637/"
]
} |
11,045 | How can I get a user-defined function to re-evaluate itself based on changed data in the spreadsheet? I tried F9 and Shift + F9 . The only thing that seems to work is editing the cell with the function call and then pressing Enter. | You should use Application.Volatile in the top of your function: Function doubleMe(d) Application.Volatile doubleMe = d * 2End Function It will then reevaluate whenever the workbook changes (if your calculation is set to automatic). | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/11045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/767/"
]
} |
11,060 | This is a difficult and open-ended question I know, but I thought I'd throw it to the floor and see if anyone had any interesting suggestions. I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to expose this as WebServices. When I developed this code I did it using TDD, but I've found my tests to be brittle as hell. Because each test essentially wanted to verify that for a given bit of input code (which happens to be a C++ header) I'd get a given bit of outputted code I wrote a small engine that reads test definitions from XML input files and generates test cases from these expectations. The problem is I dread going in to modify the code at all. That and the fact that the unit tests themselves are a: complex, and b: brittle. So I'm trying to think of alternative approaches to this problem, and it strikes me I'm perhaps tackling it the wrong way. Maybe I need to focus more on the outcome, IE: does the code I generate actually run and do what I want it to, rather than, does the code look the way I want it to. Has anyone got any experiences of something similar to this they would care to share? | I started writing up a summary of my experience with my own code generator, then went back and re-read your question and found you had already touched upon the same issues yourself, focus on the execution results instead of the code layout/look. Problem is, this is hard to test, the generated code might not be suited to actually run in the environment of the unit test system, and how do you encode the expected results? I've found that you need to break down the code generator into smaller pieces and unit test those. Unit testing a full code generator is more like integration testing than unit testing if you ask me. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/11060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/912/"
]
} |
11,085 | In Perl, an object is just a reference to any of the basic Perl data types that has been blessed into a particular class. When you use the ref() function on an unblessed reference, you are told what data type the reference points to. However, when you call ref() on a blessed reference, you are returned the name of the package that reference has been blessed into. I want to know the actual underlying type of the blessed reference. How can I determine this? | Scalar::Util::reftype() is the cleanest solution. The Scalar::Util module was added to the Perl core in version 5.7 but is available for older versions (5.004 or later) from CPAN. You can also probe with UNIVERSAL::isa() : $x->isa('HASH') # if $x is known to be an objectUNIVERSAL::isa($x, 'HASH') # if $x might not be an object or reference Obviously, you'd also have to check for ARRAY and SCALAR types. The UNIVERSAL module (which serves as the base class for all objects) has been part of the core since Perl 5.003. Another way -- easy but a little dirty -- is to stringify the reference. Assuming that the class hasn't overloaded stringification you'll get back something resembling Class=HASH(0x1234ABCD) , which you can parse to extract the underlying data type: my $type = ($object =~ /=(.+)\(0x[0-9a-f]+\)$/i); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/11085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/166/"
]
} |
11,088 | In Java, there is no such thing as an unsigned byte. Working with some low level code, occasionally you need to work with bytes that have unsigned values greater than 128, which causes Java to interpret them as a negative number due to the MSB being used for sign. What's a good way to work around this? (Saying don't use Java is not an option) | It is actually possible to get rid of the if statement and the addition if you do it like this. byte[] foobar = ..;int value = (foobar[10] & 0xff); This way Java doesn't interpret the byte as a negative number and flip the sign bit on the integer also. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/11088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1309/"
]
} |
11,194 | We're working on a Log Viewer. The use will have the option to filter by user, severity, etc. In the Sql days I'd add to the query string, but I want to do it with Linq. How can I conditionally add where-clauses? | if you want to only filter if certain criteria is passed, do something like this var logs = from log in context.Logs select log;if (filterBySeverity) logs = logs.Where(p => p.Severity == severity);if (filterByUser) logs = logs.Where(p => p.User == user); Doing so this way will allow your Expression tree to be exactly what you want. That way the SQL created will be exactly what you need and nothing less. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/11194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1204/"
]
} |
11,219 | I'd like to start moving our application business layers into a collection of REST web services. However, most of our Intranet has been built using Classic ASP and most of the developers where I work keep programming in Classic ASP. Ideally, then, for them to benefit from the advantages of a unique set of web APIs, it would have to be called from Classic ASP pages. I haven't the slightest idea how to do that. | You could use a combination of JQuery with JSON calls to consume REST services from the client or if you need to interact with the REST services from the ASP layer you can use MSXML2.ServerXMLHTTP like: Set HttpReq = Server.CreateObject("MSXML2.ServerXMLHTTP")HttpReq.open "GET", "Rest_URI", FalseHttpReq.send | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/11219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/160/"
]
} |
11,291 | I'm slowly learning Objective-C and Cocoa, and the only way I see so far to capture key events in Text Views is to use delegation, but I'm having trouble finding useful documentation and examples on how to implement such a solution. Can anyone point me in the right direction or supply some first-hand help? | Generally, the way you implement it is simply to add the required function to your view's controller, and set its delegate. For example, if you want code to run when the view loads, you just delegate your view to the controller, and implement the awakeFromNib function. So, to detect a key press in a text view, make sure your controller is the text view's delegate, and then implement this: - (void)keyUp:(NSEvent *)theEvent Note that this is an inherited NSResponder method, not a NSTextView method. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/11291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344/"
]
} |
11,305 | I work in VBA, and want to parse a string eg <PointN xsi:type='typens:PointN' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <X>24.365</X> <Y>78.63</Y></PointN> and get the X & Y values into two separate integer variables. I'm a newbie when it comes to XML, since I'm stuck in VB6 and VBA, because of the field I work in. How do I do this? | This is a bit of a complicated question, but it seems like the most direct route would be to load the XML document or XML string via MSXML2.DOMDocument which will then allow you to access the XML nodes. You can find more on MSXML2.DOMDocument at the following sites: Manipulating XML files with Excel VBA & Xpath MSXML - http://msdn.microsoft.com/en-us/library/ms763742(VS.85).aspx An Overview of MSXML 4.0 | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/11305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/895/"
]
} |
11,311 | Is it possible to format certain text in a WinForm Label instead of breaking the text into multiple labels? Please disregard the HTML tags within the label's text; it's only used to get my point out. For example: Dim myLabel As New LabelmyLabel.Text = "This is <b>bold</b> text. This is <i>italicized</i> text." Which would produce the text in the label as: This is bold text. This is italicized text. | That's not possible with a WinForms label as it is. The label has to have exactly one font, with exactly one size and one face. You have a couple of options: Use separate labels Create a new Control-derived class that does its own drawing via GDI+ and use that instead of Label; this is probably your best option, as it gives you complete control over how to instruct the control to format its text Use a third-party label control that will let you insert HTML snippets (there are a bunch - check CodeProject); this would be someone else's implementation of #2. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/11311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/299/"
]
} |
11,318 | Imagine you want to animate some object on a WinForm. You setup a timer to update the state or model, and override the paint event of the Form. But from there, what's the best way to continually repaint the Form for the animation? Invalidate the Form as soon as you are done drawing? Setup a second timer and invalidate the form on a regular interval? Perhaps there is a common pattern for this thing? Are there any useful .NET classes to help out? Each time I need to do this I discover a new method with a new drawback. What are the experiences and recommendations from the SO community? | I've created a library that might help with this. It's called Transitions, and can be found here: https://github.com/UweKeim/dot-net-transitions . Available on nuget as the dot-net-transitions package It uses timers running on a background thread to animate the objects. The library is open-source, so if it is any use to you, you can look at the code to see what it's doing. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/11318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/322/"
]
} |
11,405 | The following code doesn't compile with gcc, but does with Visual Studio: template <typename T> class A {public: T foo;};template <typename T> class B: public A <T> {public: void bar() { cout << foo << endl; }}; I get the error: test.cpp: In member function ‘void B::bar()’: test.cpp:11: error: ‘foo’ was not declared in this scope But it should be! If I change bar to void bar() { cout << this->foo << endl; } then it does compile, but I don't think I have to do this. Is there something in the official specs of C++ that GCC is following here, or is it just a quirk? | This changed in gcc-3.4 . The C++ parser got much more strict in that release -- per the spec but still kinda annoying for people with legacy or multi-platform code bases. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/11405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/112/"
]
} |
11,439 | I have created a custom dialog for Visual Studio Setup Project using the steps described here Now I have a combobox in one of my dialogs. I want to populate the combobox with a list of all SQL Server instances running on the local network. It's trivial to get the server list ... but I'm completely lost on how to make them display in the combobox. I would appreciate your help and some code might also be nice as I'm beginner :). | I've always found the custom dialogs in visual studio setup projects to be woefully limited and barely functional. By contrast, I normally create custom actions that display winforms gui's for any remotely difficult tasks during setup. Works really well and you can do just about anything you want by creating a custom action and passing a few parameters across. In the dayjob we built a collection of common custom actions for tasks like application config and database creation / script execution to get around custom dialog limitations. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/11439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360/"
]
} |
11,491 | What is the best way people have found to do String to Lower case / Upper case in C++? The issue is complicated by the fact that C++ isn't an English only programming language. Is there a good multilingual method? | #include <algorithm>std::string data = "Abc";std::transform(data.begin(), data.end(), data.begin(), ::toupper); http://notfaq.wordpress.com/2007/08/04/cc-convert-string-to-upperlower-case/ Also, CodeProject article for common string methods: http://www.codeproject.com/KB/stl/STL_string_util.aspx | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/11491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366/"
]
} |
11,500 | I have an Ajax.Net enabled ASP.Net 2.0 web site. Hosting for both the site and the database are out of my control as is the database's schema. In testing on hardware I do control the site performs well however on the client's hardware, there are noticeable delays when reloading or changing pages. What I would like to do is make my application as compact and speedy as possible when I deliver it. One idea is to set expiration dates for all of the site's static resources so they aren't recalled on page loads. By resources I mean images, linked style sheets and JavaScript source files. Is there an easy way to do this? What other ways are there to optimize a .Net web site? UPDATE: I've run YSlow on the site and the areas where I am getting hit the hardest are in the number of JavaScript and Style Sheets being loaded (23 JS files and 5 style sheets). All but one (the main style sheet) has been inserted by Ajax.net and Asp. Why so many? | Script Combining in .net 3.5 SP1 Best Practices for fast websites HTTP Compression (gzip) Compress JS / CSS (different than http compression, minify javascript) YUI Compressor .NET YUI Compressor My best advice is to check out the YUI content . They have some great articles that talk about things like CSS sprites and have some nice javascript libraries to help reduce the number of requests the browser is making. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/11500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/149/"
]
} |
11,514 | I switched to the dvorak keyboard layout about a year ago. I now use dvorak full-time at work and at home. Recently, I went on vacation to Peru and found myself in quite a conundrum. Internet cafes were qwerty-only (and Spanish qwerty, at that). I was stuck with a hunt-and-peck routine that grew old fairly quickly. That said, is it possible to be "fluent" in both qwerty and dvorak at the same time? If not, are there any good solutions to the situation I found myself in? | Web For your situation of being at a public computer that you cannot switch the keyboard layout on, you can go to this website: http://www.dvzine.org/type/DVconverter.html Use this to translate your typing and then use copy paste. I found this very useful when I was out of the country and had to write a bunch of emails at public computers. USB Drive Put this Dvorak Utility on your USB drive. Run this app and it will put a icon in the system tray on windows. This icon will switch the computer between the two keyboard layouts and it works. (If you have tried switching back and forth from dvorak to qwerty you will know what I mean. Windows does the worst job of this one bit of functionality.) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/11514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1318/"
]
} |
11,532 | How can I find any unused functions in a PHP project? Are there features or APIs built into PHP that will allow me to analyse my codebase - for example Reflection , token_get_all() ? Are these APIs feature rich enough for me not to have to rely on a third party tool to perform this type of analysis? | Thanks Greg and Dave for the feedback. Wasn't quite what I was looking for, but I decided to put a bit of time into researching it and came up with this quick and dirty solution: <?php $functions = array(); $path = "/path/to/my/php/project"; define_dir($path, $functions); reference_dir($path, $functions); echo "<table>" . "<tr>" . "<th>Name</th>" . "<th>Defined</th>" . "<th>Referenced</th>" . "</tr>"; foreach ($functions as $name => $value) { echo "<tr>" . "<td>" . htmlentities($name) . "</td>" . "<td>" . (isset($value[0]) ? count($value[0]) : "-") . "</td>" . "<td>" . (isset($value[1]) ? count($value[1]) : "-") . "</td>" . "</tr>"; } echo "</table>"; function define_dir($path, &$functions) { if ($dir = opendir($path)) { while (($file = readdir($dir)) !== false) { if (substr($file, 0, 1) == ".") continue; if (is_dir($path . "/" . $file)) { define_dir($path . "/" . $file, $functions); } else { if (substr($file, - 4, 4) != ".php") continue; define_file($path . "/" . $file, $functions); } } } } function define_file($path, &$functions) { $tokens = token_get_all(file_get_contents($path)); for ($i = 0; $i < count($tokens); $i++) { $token = $tokens[$i]; if (is_array($token)) { if ($token[0] != T_FUNCTION) continue; $i++; $token = $tokens[$i]; if ($token[0] != T_WHITESPACE) die("T_WHITESPACE"); $i++; $token = $tokens[$i]; if ($token[0] != T_STRING) die("T_STRING"); $functions[$token[1]][0][] = array($path, $token[2]); } } } function reference_dir($path, &$functions) { if ($dir = opendir($path)) { while (($file = readdir($dir)) !== false) { if (substr($file, 0, 1) == ".") continue; if (is_dir($path . "/" . $file)) { reference_dir($path . "/" . $file, $functions); } else { if (substr($file, - 4, 4) != ".php") continue; reference_file($path . "/" . $file, $functions); } } } } function reference_file($path, &$functions) { $tokens = token_get_all(file_get_contents($path)); for ($i = 0; $i < count($tokens); $i++) { $token = $tokens[$i]; if (is_array($token)) { if ($token[0] != T_STRING) continue; if ($tokens[$i + 1] != "(") continue; $functions[$token[1]][1][] = array($path, $token[2]); } } }?> I'll probably spend some more time on it so I can quickly find the files and line numbers of the function definitions and references; this information is being gathered, just not displayed. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/11532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1142/"
]
} |
11,561 | I've used Apache CXF to expose about ten java classes as web services. I've generated clients using CXF, Axis, and .NET. In Axis and CXF a "Service" or "Locator" is generated. From this service you can get a "Port".The "Port" is used to make individual calls to the methods exposed by the web service. In .NET the "Service" directly exposes the calls to the web service. Can someone explain the difference between a port, a service, a locator, and an endpoint when it comes to web services? Axis: PatientServiceImplServiceLocator locator = new PatientServiceImplServiceLocator();PatientService service = locator.getPatientServiceImplPort(); CXF: PatientServiceImplService locator = new PatientServiceImplService();PatientService service = locator.getPatientServiceImplPort(); .net: PatientServiceImplService service = new PatientServiceImplService(); | I found the information based on Kevin Kenny's answer, but I figured I'd post it here for others. A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format bindings. This allows the reuse of abstract definitions: messages, which are abstract descriptions of the data being exchanged, and port types which are abstract collections of operations. The concrete protocol and data format specifications for a particular port type constitutes a reusable binding. A port is defined by associating a network address with a reusable binding, and a collection of ports define a service. Hence, a WSDL document uses the following elements in the definition of network services: Types – a container for data type definitions using some type system (such as XSD). Message – an abstract, typed definition of the data being communicated. Operation – an abstract description of an action supported by the service. Port Type –an abstract set of operations supported by one or more endpoints. Binding – a concrete protocol and data format specification for a particular port type. Port – a single endpoint defined as a combination of a binding and a network address. Service – a collection of related endpoints. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/11561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
]
} |
11,562 | std::swap() is used by many std containers (such as std::list and std::vector ) during sorting and even assignment. But the std implementation of swap() is very generalized and rather inefficient for custom types. Thus efficiency can be gained by overloading std::swap() with a custom type specific implementation. But how can you implement it so it will be used by the std containers? | The right way to overload std::swap 's implemention (aka specializing it), is to write it in the same namespace as what you're swapping, so that it can be found via argument-dependent lookup (ADL) . One particularly easy thing to do is: class X{ // ... friend void swap(X& a, X& b) { using std::swap; // bring in swap for built-in types swap(a.base1, b.base1); swap(a.base2, b.base2); // ... swap(a.member1, b.member1); swap(a.member2, b.member2); // ... }}; | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/11562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366/"
]
} |
11,585 | For my blog I am wanting to use the Output Cache to save a cached version of a perticular post for around 10 minutes, and thats fine... <%@OutputCache Duration="600" VaryByParam="*" %> However, if someone posts a comment, I want to clear the cache so that the page is refreshed and the comment can be seen. How do I do this in ASP.Net C#? | I've found the answer I was looking for: HttpResponse.RemoveOutputCacheItem("/caching/CacheForever.aspx"); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/11585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
]
} |
11,586 | What's the penetration of design patterns in the real world? Do you use them in your day to day job - discussing how and where to apply them with your coworkers - or do they remain more of an academic concept? Do they actually provide actual value to your job? Or are they just something that people talk about to sound smart? Note: For the purpose of this question ignore 'simple' design patterns like Singleton . I'm talking about designing your code so you can take advantage of Model View Controller , etc. | Any large program that is well written will use design patterns, even if they aren't named or recognized as such. That's what design patterns are, designs that repeatedly and naturally occur. If you're interfacing with an ugly API, you'll likely find yourself implementing a Facade to clean it up. If you've got messaging between components that you need to decouple, you may find yourself using Observer . If you've got several interchangeable algorithms, you might end up using Strategy . It's worth knowing the design patterns because you're more likely to recognize them and then converge on a clean solution more quickly. However, even if you don't know them at all, you'll end up creating them eventually (if you are a decent programmer). And of course, if you are using a modern language, you'll probably be forced to use them for some things, because they're baked into the standard libraries. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/11586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/322/"
]
} |
11,620 | I want to rename a database, but keep getting the error that 'couldn't get exclusive lock' on the database, which implies there is some connection(s) still active. How can I kill all the connections to the database so that I can rename it? | The reason that the approach that Adam suggested won't work is that during the time that you are looping over the active connections new one can be established, and you'll miss those. You could instead use the following approach which does not have this drawback: -- set your current connection to use master otherwise you might get an erroruse masterALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE --do you stuff here ALTER DATABASE YourDatabase SET MULTI_USER | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/11620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341/"
]
} |
11,632 | Certainly there's the difference in general syntax, but what other critical distinctions exist? There are some differences, right? | The linked comparisons are very thorough, but as far as the main differences I would note the following: C# has anonymous methods VB has these now, too C# has the yield keyword (iterator blocks) VB11 added this VB supports implicit late binding (C# has explicit late binding now via the dynamic keyword) VB supports XML literals VB is case insensitive More out-of-the-box code snippets for VB More out-of-the-box refactoring tools for C# Visual Studio 2015 now provides the same refactoring tools for both VB and C#. In general the things MS focuses on for each vary, because the two languages are targeted at very different audiences. This blog post has a good summary of the target audiences. It is probably a good idea to determine which audience you are in, because it will determine what kind of tools you'll get from Microsoft. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/11632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
]
} |
11,635 | What is the best way of doing case-insensitive string comparison in C++ without transforming a string to all uppercase or all lowercase? Please indicate whether the methods are Unicode-friendly and how portable they are. | Boost includes a handy algorithm for this: #include <boost/algorithm/string.hpp>// Or, for fewer header dependencies://#include <boost/algorithm/string/predicate.hpp>std::string str1 = "hello, world!";std::string str2 = "HELLO, WORLD!";if (boost::iequals(str1, str2)){ // Strings are identical} | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/11635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366/"
]
} |
11,680 | Does anybody recommend a design pattern for taking a binary data file, parsing parts of it into objects and storing the resultant data into a database? I think a similar pattern could be used for taking an XML or tab-delimited file and parse it into their representative objects. A common data structure would include: (Header) (DataElement1) (DataElement1SubData1) (DataElement1SubData2)(DataElement2) (DataElement2SubData1) (DataElement2SubData2) (EOF) I think a good design would include a way to change out the parsing definition based on the file type or some defined metadata included in the header. So a Factory Pattern would be part of the overall design for the Parser part. | Just write your file parser, using whatever techniques come to mind Write lots of unit tests for it to make sure all your edge cases are covered Once you've done this, you will actually have a reasonable idea of the problem/solution. Right now you just have theories floating around in your head, most of which will turn out to be misguided. Step 3: Refactor mercilessly. Your aim should be to delete about half of your code You'll find that your code at the end will either resemble an existing design pattern, or you'll have created a new one. You'll then be qualified to answer this question :-) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/11680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048/"
]
} |
11,699 | I'm getting notifications to back up my encryption key for EFS in Vista, however i haven't enabled bit locker or drive encryption. Anyone know how to find out what files may be encrypted or have an explanation for why it would notify me? | To find out which files on your system have been encrypted with EFS, you can simply run this command: CIPHER.EXE /U /N | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/11699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
]
} |
11,720 | What I would like to do is create a clean virtual machine image as the output of a build of an application. So a new virtual machine would be created (from a template is fine, with the OS installed, and some base software installed) --- a new web site would be created in IIS, and the web app build output copied to a location on the virtual machine hard disk, and IIS configured correctly, the VM would start up and run. I know there are MSBuild tasks to script all the administrative actions in IIS, but how do you script all the actions with Virtual machines? Specifically, creating a new virtual machine from a template, naming it uniquely, starting it, configuring it, etc... Specifically I was wondering if anyone has successfully implemented any VM scripting as part of a build process. Update: I assume with Hyper-V, there is a different set of libraries/APIs to script virtual machines, anyone played around with this? And anyone with real practical experience of doing something like this? | To find out which files on your system have been encrypted with EFS, you can simply run this command: CIPHER.EXE /U /N | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/11720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341/"
]
} |
11,762 | I needed some simple string encryption, so I wrote the following code (with a great deal of "inspiration" from here ): // create and initialize a crypto algorithm private static SymmetricAlgorithm getAlgorithm(string password) { SymmetricAlgorithm algorithm = Rijndael.Create(); Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes( password, new byte[] { 0x53,0x6f,0x64,0x69,0x75,0x6d,0x20, // salty goodness 0x43,0x68,0x6c,0x6f,0x72,0x69,0x64,0x65 } ); algorithm.Padding = PaddingMode.ISO10126; algorithm.Key = rdb.GetBytes(32); algorithm.IV = rdb.GetBytes(16); return algorithm; } /* * encryptString * provides simple encryption of a string, with a given password */ public static string encryptString(string clearText, string password) { SymmetricAlgorithm algorithm = getAlgorithm(password); byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(clearBytes, 0, clearBytes.Length); cs.Close(); return Convert.ToBase64String(ms.ToArray()); } /* * decryptString * provides simple decryption of a string, with a given password */ public static string decryptString(string cipherText, string password) { SymmetricAlgorithm algorithm = getAlgorithm(password); byte[] cipherBytes = Convert.FromBase64String(cipherText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(cipherBytes, 0, cipherBytes.Length); cs.Close(); return System.Text.Encoding.Unicode.GetString(ms.ToArray()); } The code appears to work fine, except that when decrypting data with an incorrect key, I get a CryptographicException - "Padding is invalid and cannot be removed" - on the cs.Close() line in decryptString. example code: string password1 = "password"; string password2 = "letmein"; string startClearText = "The quick brown fox jumps over the lazy dog"; string cipherText = encryptString(startClearText, password1); string endClearText = decryptString(cipherText, password2); // exception thrown My question is, is this to be expected? I would have thought that decrypting with the wrong password would just result in nonsense output, rather than an exception. | Although this have been already answered I think it would be a good idea to explain why it is to be expected. A padding scheme is usually applied because most cryptographic filters are not semantically secure and to prevent some forms of cryptoatacks. For example, usually in RSA the OAEP padding scheme is used which prevents some sorts of attacks (such as a chosen plaintext attack or blinding ). A padding scheme appends some (usually) random garbage to the message m before the message is sent. In the OAEP method, for example, two Oracles are used (this is a simplistic explanation): Given the size of the modulus you padd k1 bits with 0 and k0 bits with a random number. Then by applying some transformation to the message you obtain the padded message wich is encrypted and sent. That provides you with a randomization for the messages and with a way to test if the message is garbage or not. As the padding scheme is reversible, when you decrypt the message whereas you can't say anything about the integrity of the message itself you can, in fact, make some assertion about the padding and thus you can know if the message has been correctly decrypted or you're doing something wrong (i.e someone has tampered with the message or you're using the wrong key) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/11762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369/"
]
} |
11,767 | How can I present a control to the user that allows him/her to select a directory? There doesn't seem to be any native .net controls which do this? | The FolderBrowserDialog class is the best option. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/11767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
]
} |
11,809 | The only thing I've found has been; .hang { text-indent: -3em; margin-left: 3em;} The only way for this to work is putting text in a paragraph, which causes those horribly unsightly extra lines. I'd much rather just have them in a <span class="hang"></span> type of thing. I'm also looking for a way to further indent than just a single-level of hanging. Using paragraphs to stack the indentions doesn't work. | <span> is an inline element. The term hanging indent is meaningless unless you're talking about a paragraph (which generally means a block element). You can, of course, change the margins on <p> or <div> or any other block element to get rid of extra vertical space between paragraphs. You may want something like display: run-in , where the tag will become either block or inline depending on context... sadly, this is not yet universally supported by browsers . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/11809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/362/"
]
} |
11,820 | This question and answer shows how to send a file as a byte array through an XML web service. How much overhead is generated by using this method for file transfer? I assume the data looks something like this: <?xml version="1.0" encoding="UTF-8" ?><bytes> <byte>16</byte> <byte>28</byte> <byte>127</byte> ...</bytes> If this format is correct, the bytes must first be converted to UTF-8 characters. Each of these characters allocates 8 bytes. Are the bytes stored in base 10, hex, or binary characters? How much larger does the file appear as it is being sent due to the XML data and character encoding? Is compression built into web services? | Typically a byte array is sent as a base64 encoded string, not as individual bytes in tags. http://en.wikipedia.org/wiki/Base64 The base64 encoded version is about 137% of the size of the original content. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/11820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
]
} |
11,831 | Singletons are a hotly debated design pattern, so I am interested in what the Stack Overflow community thought about them. Please provide reasons for your opinions, not just "Singletons are for lazy programmers!" Here is a fairly good article on the issue, although it is against the use of Singletons: scientificninja.com: performant-singletons . Does anyone have any other good articles on them? Maybe in support of Singletons? | In defense of singletons: They are not as bad as globals because globals have no standard-enforced initialization order, and you could easily see nondeterministic bugs due to naive or unexpected dependency orders. Singletons (assuming they're allocated on the heap) are created after all globals, and in a very predictable place in the code. They're very useful for resource-lazy / -caching systems such as an interface to a slow I/O device. If you intelligently build a singleton interface to a slow device, and no one ever calls it, you won't waste any time. If another piece of code calls it from multiple places, your singleton can optimize caching for both simultaneously, and avoid any double look-ups. You can also easily avoid any deadlock condition on the singleton-controlled resource. Against singletons: In C++, there's no nice way to auto-clean-up after singletons. There are work-arounds, and slightly hacky ways to do it, but there's just no simple, universal way to make sure your singleton's destructor is always called. This isn't so terrible memory-wise -- just think of it as more global variables, for this purpose. But it can be bad if your singleton allocates other resources (e.g. locks some files) and doesn't release them. My own opinion: I use singletons, but avoid them if there's a reasonable alternative. This has worked well for me so far, and I have found them to be testable, although slightly more work to test. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/11831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.