source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
187,915
How do I detect if a process is already running under the Windows Task Manager? I'd like to get the memory and cpu usage as well.
Simple example... bool processIsRunning(string process){ return (System.Diagnostics.Process.GetProcessesByName(process).Length != 0);} Oops... forgot the mem usage, etc... bool processIsRunning(string process){System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(process);foreach (System.Diagnostics.Process proc in processes){ Console.WriteLine("Current physical memory : " + proc.WorkingSet64.ToString()); Console.WriteLine("Total processor time : " + proc.TotalProcessorTime.ToString()); Console.WriteLine("Virtual memory size : " + proc.VirtualMemorySize64.ToString());}return (processes.Length != 0);} (I'll leave the mechanics of getting the data out of the method to you - it's 17:15 here, and I'm ready to go home. :)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/187915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1316/" ] }
187,936
We don't currently have our SQL Server objects in any form of source control. We recently installed TFS 2008 and I'd like to get our SQL server code added. I think I could script all of the database and create script files for each object, but I'm hoping there is a way to point to a database in SSMS and create a project that can be added to TFS or something similar. Basically, I'm look for the simplest way to get from point A to point B. I've installed the TFS MSSCCI Provider and I see TFS in the source control provider options in SSMS. The SQL Server instance is SS2005.
If you have a visual studio Team Developer license you can download the Database edition. It has a project type that can bring your tables, sprocs, triggers, etc under source control and check it into TFS. update: Redgate has a product called SQL Source Control . Which ties back into several source control systems like TFS, SVN, etc.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/187936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162/" ] }
187,983
I have a requirement to hide a process in Task Manager. It is for Intranet scenario. So, everything is legitimate. :) Please feel free to share any code you have (preferably in C#) or any other techniques or any issues in going with this route. Update1 : Most of the users have admin privileges in order to run some legacy apps. So, one of the suggestion was to hide it in task manager. If there are other approaches to prevent users from killing the process, that would be great. Update2 : Removing the reference to rootkit. Somehow made this post look negative.
There is no supported way to accomplish this. The process list can be read at any privilege level. If you were hoping to hide a process from even Administrators, then this is doubly unsupported. To get this to work, you would need to write a kernel mode rootkit to intercept calls to NtQuerySystemInformation so that the SystemProcessInformation info class fails to list your hidden process. Intercepting system calls is very difficult to do safely, and the 64 bit Windows kernels go out of their way to prevent this from being possible: trying to modify the syscall table results in an instant blue screen. It's going to be very difficult on those platforms Here is an example of a rootkit that tries to do something similar (and has several serious problems).
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/187983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4337/" ] }
187,990
I'm not a C++ developer, but I've always been interested in compilers, and I'm interested in tinkering with some of the GCC stuff (particularly LLVM). On Windows, GCC requires a POSIX-emulation layer (cygwin or MinGW) to run correctly. Why is that? I use lots of other software, written in C++ and cross-compiled for different platforms (Subversion, Firefox, Apache, MySQL), and none of them require cygwin or MinGW. My understanding about C++ best-practice programming is that you can write reasonably platform-neutral code and deal with all the differences during the compilation process. So what's the deal with GCC? Why can't it run natively on Windows? EDIT: Okay, the two replies so far say, basically, "GCC uses the posix layer because it uses the posix headers". But that doesn't really answer the question. Let's say I already have a set of headers for my favorite standard library. Why would I still need the posix headers? Does GCC require cygwin/mingw to actually RUN ? Or does it only need the emulation layer for headers and libraries? If so, why can't I just give it a "lib" directory with the required resources? EDIT AGAIN: Okay, I'll try again to clarify the question... I also write code in the D Programming Language . The official compiler is named "dmd" and there are official compiler binaries for both Windows and linux. The Windows version doesn't require any kind of POSIX emulation. And the Linux version doesn't require any kind of Win32 emulation. If the compiler has assumptions about its environment, it hides those assumptions pretty well. Of course, I have to tell the compiler where to find the standard library and where to find libraries to statically or dynamically link against. GCC, by contrast, insists on pretending it's operating within a posix environment, and it asks ME to humor those assumptions by setting up an emulation layer. But what, exactly, within GCC relies on that layer? Is it just looking for stdlib headers, and it assumes it'll find those headers within "/usr/lib"? If that's the case, shouldn't I just be able to tell it to look in "C:/gcc/lib" to find those header files? Or does GCC itself rely on the POSIX libraries to access the file system (and to do other low-level stuff)? If that's the case, then I wonder why they don't just statically link with their favorite windows POSIX libraries. Why require the user to set up the dependencies, when they could build those dependencies right into the application?
Actually, the question premise is wrong: MinGW GCC does NOT require Cygwin. You will see you don't need Cygwin at all. It runs natively on Windows (32-bit, at least). Both the toolchain and the produced binaries are independent of Cygwin. The MinGW compilers available in Cygwin are different: they are built on the Cygwin platform, to generate code which does not depend on the Cygwin runtime. The compilers themselves do depend on Cygwin in that case. But that's because you installed them from Cygwin.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/187990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22979/" ] }
187,998
Is there any way in SQL Server to get the results starting at a given offset? For example, in another type of SQL database, it's possible to do: SELECT * FROM MyTable OFFSET 50 LIMIT 25 to get results 51-75. This construct does not appear to exist in SQL Server. How can I accomplish this without loading all the rows I don't care about? Thanks!
I would avoid using SELECT * . Specify columns you actually want even though it may be all of them. SQL Server 2005+ SELECT col1, col2 FROM ( SELECT col1, col2, ROW_NUMBER() OVER (ORDER BY ID) AS RowNum FROM MyTable) AS MyDerivedTableWHERE MyDerivedTable.RowNum BETWEEN @startRow AND @endRow SQL Server 2000 Efficiently Paging Through Large Result Sets in SQL Server 2000 A More Efficient Method for Paging Through Large Result Sets
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/187998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/420/" ] }
187,999
One small function of a large program examines assemblies in a folder and replaces out-of-date assemblies with the latest versions. To accomplish this, it needs to read the version numbers of the existing assembly files without actually loading those assemblies into the executing process.
I found the following in this article . using System.Reflection;using System.IO;...// Get current and updated assembliesAssemblyName currentAssemblyName = AssemblyName.GetAssemblyName(currentAssemblyPath);AssemblyName updatedAssemblyName = AssemblyName.GetAssemblyName(updatedAssemblyPath);// Compare both versionsif (updatedAssemblyName.Version.CompareTo(currentAssemblyName.Version) <= 0){ // There's nothing to update return;}// Update older versionFile.Copy(updatedAssemblyPath, currentAssemblyPath, true);
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/187999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26553/" ] }
188,007
I'm using my code-behind page to create a save button programmatically: Button btnSave = new Button(); btnSave.ID = "btnSave"; btnSave.Text = "Save"; However I think this must create an html button or perhaps needs something else as I cannot seem to set the OnClick attribute in the following line, I can specify OnClientClick but this isn't the one I want to set.
Button btnSave = new Button(); btnSave.ID = "btnSave"; btnSave.Text = "Save"; btnSave.Click += new System.EventHandler(btnSave_Click);protected void btnSave_Click(object sender, EventArgs e){ //do something when button clicked. }
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26126/" ] }
188,118
I've tried this, but it doesn't work: col * format a20000 Do I really have to list every column specifically? That is a huge pain in the arse.
Never mind, figured it out: set wrap offset linesize 3000 -- (or to a sufficiently large value to hold your results page) Which I found by: show all And looking for some option that seemed relevant.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8913/" ] }
188,120
So .NET 3.0/3.5 provides us with lots of new ways to query, sort, and manipulate data, thanks to all the neat functions supplied with LINQ. Sometimes, I need to compare user-defined types that don't have a built-in comparison operator. In many cases, the comparison is really simple -- something like foo1.key ?= foo2.key. Rather than creating a new IEqualityComparer for the type, can I simply specify the comparison inline using anonymous delegates/lambda functions? Something like: var f1 = ..., f2 = ...;var f3 = f1.Except( f2, new IEqualityComparer( (Foo a, Foo b) => a.key.CompareTo(b.key) ) ); I'm pretty sure the above doesn't actually work. I just don't want to have to make something as "heavy" as a whole class just to tell the program how to compare apples to apples.
My MiscUtil library contains a ProjectionComparer to build an IComparer<T> from a projection delegate. It would be the work of 10 minutes to make a ProjectionEqualityComparer to do the same thing. EDIT: Here's the code for ProjectionEqualityComparer: using System;using System.Collections.Generic;/// <summary>/// Non-generic class to produce instances of the generic class,/// optionally using type inference./// </summary>public static class ProjectionEqualityComparer{ /// <summary> /// Creates an instance of ProjectionEqualityComparer using the specified projection. /// </summary> /// <typeparam name="TSource">Type parameter for the elements to be compared</typeparam> /// <typeparam name="TKey">Type parameter for the keys to be compared, /// after being projected from the elements</typeparam> /// <param name="projection">Projection to use when determining the key of an element</param> /// <returns>A comparer which will compare elements by projecting /// each element to its key, and comparing keys</returns> public static ProjectionEqualityComparer<TSource, TKey> Create<TSource, TKey>(Func<TSource, TKey> projection) { return new ProjectionEqualityComparer<TSource, TKey>(projection); } /// <summary> /// Creates an instance of ProjectionEqualityComparer using the specified projection. /// The ignored parameter is solely present to aid type inference. /// </summary> /// <typeparam name="TSource">Type parameter for the elements to be compared</typeparam> /// <typeparam name="TKey">Type parameter for the keys to be compared, /// after being projected from the elements</typeparam> /// <param name="ignored">Value is ignored - type may be used by type inference</param> /// <param name="projection">Projection to use when determining the key of an element</param> /// <returns>A comparer which will compare elements by projecting /// each element to its key, and comparing keys</returns> public static ProjectionEqualityComparer<TSource, TKey> Create<TSource, TKey> (TSource ignored, Func<TSource, TKey> projection) { return new ProjectionEqualityComparer<TSource, TKey>(projection); }}/// <summary>/// Class generic in the source only to produce instances of the /// doubly generic class, optionally using type inference./// </summary>public static class ProjectionEqualityComparer<TSource>{ /// <summary> /// Creates an instance of ProjectionEqualityComparer using the specified projection. /// </summary> /// <typeparam name="TKey">Type parameter for the keys to be compared, /// after being projected from the elements</typeparam> /// <param name="projection">Projection to use when determining the key of an element</param> /// <returns>A comparer which will compare elements by projecting each element to its key, /// and comparing keys</returns> public static ProjectionEqualityComparer<TSource, TKey> Create<TKey>(Func<TSource, TKey> projection) { return new ProjectionEqualityComparer<TSource, TKey>(projection); }}/// <summary>/// Comparer which projects each element of the comparison to a key, and then compares/// those keys using the specified (or default) comparer for the key type./// </summary>/// <typeparam name="TSource">Type of elements which this comparer /// will be asked to compare</typeparam>/// <typeparam name="TKey">Type of the key projected/// from the element</typeparam>public class ProjectionEqualityComparer<TSource, TKey> : IEqualityComparer<TSource>{ readonly Func<TSource, TKey> projection; readonly IEqualityComparer<TKey> comparer; /// <summary> /// Creates a new instance using the specified projection, which must not be null. /// The default comparer for the projected type is used. /// </summary> /// <param name="projection">Projection to use during comparisons</param> public ProjectionEqualityComparer(Func<TSource, TKey> projection) : this(projection, null) { } /// <summary> /// Creates a new instance using the specified projection, which must not be null. /// </summary> /// <param name="projection">Projection to use during comparisons</param> /// <param name="comparer">The comparer to use on the keys. May be null, in /// which case the default comparer will be used.</param> public ProjectionEqualityComparer(Func<TSource, TKey> projection, IEqualityComparer<TKey> comparer) { if (projection == null) { throw new ArgumentNullException("projection"); } this.comparer = comparer ?? EqualityComparer<TKey>.Default; this.projection = projection; } /// <summary> /// Compares the two specified values for equality by applying the projection /// to each value and then using the equality comparer on the resulting keys. Null /// references are never passed to the projection. /// </summary> public bool Equals(TSource x, TSource y) { if (x == null && y == null) { return true; } if (x == null || y == null) { return false; } return comparer.Equals(projection(x), projection(y)); } /// <summary> /// Produces a hash code for the given value by projecting it and /// then asking the equality comparer to find the hash code of /// the resulting key. /// </summary> public int GetHashCode(TSource obj) { if (obj == null) { throw new ArgumentNullException("obj"); } return comparer.GetHashCode(projection(obj)); }} And here's a sample use: var f3 = f1.Except(f2, ProjectionEqualityComparer<Foo>.Create(a => a.key));
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/188120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26286/" ] }
188,138
I've seen a number of references to gzipping a javascript to save download time. But I also see a number of warnings that certain browsers do not support this. I have two different methods at my disposal: use mod_deflate to make Apache compress JS/CSS files in a given directory through htaccess use ob_start('gzhandler') to compress a file and return it to the browser with the correct headers. The problems with method 1 are that not all browsers support mod_deflate, and I have no clue how to write the .htaccess file to be smart enough to adjust for this. The problem with method 2 is that there is no definitive answer about how to tell if a browser supports a gzipped script, or stylesheet, and that if it does what mime-type must be given as the content type in the header. I need some advice. First, which method is more universally accepted by browsers? Second, how do I decay using either method to provide the uncompressed backup script? Third, would <script src="js/lib.js.gz" type="text/javascript"></script> work by itself? (It obviously wouldn't decay.) For the record, I'm using PHP5 with mod_deflate and full gzip creation capabilities, and my doctype is xhtml strict. Also, the javascript itself is compressed with YUI. Edit: I just went back and looked, but I have only Apache 1.3; I thought I had 2, so sorry for mentioning mod_deflate when I probably don't have it.
mod_deflate and php's gzhandler both are based on zlib, so in that sense there is little difference to a browser how the content is being compressed. in response to your first concern, you can set module specific .htaccess info like this: <IfModule mod_deflate.c> # stuff</IfModule> in response to your second concern, you can detect for browser support in PHP: if (strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') ) { ob_start('ob_gzhandler'); header("Content-Encoding: gzip");// etc...} here's some untested .htaccess that should be able to handle negotiation of compressed vs uncompressed .js files: ( source ) <FilesMatch "\\.js.gz$"> ForceType text/javascript Header set Content-Encoding: gzip</FilesMatch><FilesMatch "\\.js$"> RewriteEngine On RewriteCond %{HTTP_USER_AGENT} !".*Safari.*" RewriteCond %{HTTP:Accept-Encoding} gzip RewriteCond %{REQUEST_FILENAME}.gz -f RewriteRule (.*)\.js$ $1\.js.gz [L] ForceType text/javascript</FilesMatch>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24950/" ] }
188,141
I'm using C# on Framework 3.5. I'm looking to quickly sort a Generic List<T> . For the sake of this example, let's say I have a List of a Person type with a property of lastname. How would I sort this List using a lambda expression? List<Person> people = PopulateList();people.OrderBy(???? => ?????)
If you mean an in-place sort (i.e. the list is updated): people.Sort((x, y) => string.Compare(x.LastName, y.LastName)); If you mean a new list: var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/188141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7215/" ] }
188,162
Just wondering what little scripts/programs people here have written that helps one with his or her everyday life (aka not work related). Anything goes, groundbreaking or not. For me right now, it's a small python script to calculate running pace given distance and time elapsed.
My o key fell off on my laptop; so I wrote a program that replaces two 0 keystrokes within 200 MS of each other as an o , two 0 keystrokes within 700 MS of each other as a 0 and ignore the rest; so I could use my laptop before I get around to replacing the keyboard. Wow; I didn't know this would be so popular :p As for how - Microsoft exposes a nice little API feature called Hooks . Using that hook; I was able to write a "filter" that did what I needed it to do (hint: if you return 1 with your callback windows will not process the keystroke). The reason I know about this actually is not because I was writing a keylogger - but because I wrote a program smiler to Synergy a while ago. And yes. I did write another program that swapped alpha-numeric keys with a random alpha-numeric key and yes; it was really funny :D
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/188162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25664/" ] }
188,166
I am using Team Foundation Server (TFS) for Visual Studio 2005. Whenever i wish to compare two file's versions TFS displays a window with the differences. The problem is that it is always split vertically. In fact, almost every time, i would prefer to have it split horizontally. I've already looked at TFS options and googled but i found nothing. I'm appalled to think that such option is not available! Is there any way to configure TFS to split it horizontally?
I've found the built in differencing tool in TFS woefully lacking so I set up WinMerge ( http://www.winmerge.org/ ) in my environment in Tools -> Options -> Source COntrol -> Visual Studio Team Foundation. A nice blog post exists below: http://www.vitalygorn.com/blog/post/2007/12/Better-DiffMerge-tool-for-TFS.aspx
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/188166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20335/" ] }
188,176
I am looking for a simple but "good enough" Named Entity Recognition library (and dictionary) for java, I am looking to process emails and documents and extract some "basic information" like:Names, places, Address and Dates I've been looking around, and most seems to be on the heavy side and full NLP kind of projects. Any recommendations ?
You might want to have a look at one of my earlier answers to a similar problem. Other than that, most lighter NER systems depend a lot on the domain used. You will find a whole lot of tools and papers about biomedical NER systems, for example. In addition to my previous post (which already contains my main recommendation if you want to do NER), here are some more tools you might want to look into: The Stanford CER-NER The Postech Biomedical NER System if you are interested in this particular domain OpenCalais seems to be a commercial system. There are UIMA wrappers for OpenCalais but they seem dated. There is also a dictionary based Context-Mapper annotator for UIMA that may help you out. Be aware that UIMA implies significant overhead in learning curve ;-) OpenNLP also have an NER tool. Balie does NER, too, among other things. ABNER does NER, but again its focused on the biomedical domain. The JULIE Lab Tools from the university of Jena, Germany also do NER. They have standalone versions and UIMA analysis engines. One additional remark: you won't get away without tokenization on the input. Tokenization of natural language is slightly non-trivial, that's why I suggest you use a toolbox that does both for you.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23238/" ] }
188,241
If I want to have a case-insensitive string-keyed dictionary, which version of StringComparer should I use given these constraints: The keys in the dictionary come from either C# code or config files written in english locale only (either US, or UK) The software is internationalized and will run in different locales I normally use StringComparer.InvariantCultureIgnoreCase but wasn't sure if that is the correct case. Here is example code: Dictionary< string, object> stuff = new Dictionary< string, object>(StringComparer.InvariantCultureIgnoreCase);
There are three kinds of comparers: Culture-aware Culture invariant Ordinal Each comparer has a case-sensitive as well as a case-insensitive version. An ordinal comparer uses ordinal values of characters. This is the fastest comparer, it should be used for internal purposes. A culture-aware comparer considers aspects that are specific to the culture of the current thread. It knows the "Turkish i", "Spanish LL", etc. problems. It should be used for UI strings. The culture invariant comparer is actually not defined and can produce unpredictable results, and thus should never be used at all. References New Recommendations for Using Strings in Microsoft .NET 2.0
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16501/" ] }
188,266
What is the series of steps needed to securely verify a ssl certificate? My (very limited) understanding is that when you visit an https site, the server sends a certificate to the client (the browser) and the browser gets the certificate's issuer information from that certificate, then uses that to contact the issuerer, and somehow compares certificates for validity. How exactly is this done? What about the process makes it immune to man-in-the-middle attacks? What prevents some random person from setting up their own verification service to use in man-in-the-middle attacks, so everything "looks" secure?
Here is a very simplified explanation: Your web browser downloads the web server's certificate, which contains the public key of the web server. This certificate is signed with the private key of a trusted certificate authority. Your web browser comes installed with the public keys of all of the major certificate authorities. It uses this public key to verify that the web server's certificate was indeed signed by the trusted certificate authority. The certificate contains the domain name and/or ip address of the web server. Your web browser confirms with the certificate authority that the address listed in the certificate is the one to which it has an open connection. Your web browser generates a shared symmetric key which will be used to encrypt the HTTP traffic on this connection; this is much more efficient than using public/private key encryption for everything. Your browser encrypts the symmetric key with the public key of the web server then sends it back, thus ensuring that only the web server can decrypt it, since only the web server has its private key. Note that the certificate authority (CA) is essential to preventing man-in-the-middle attacks. However, even an unsigned certificate will prevent someone from passively listening in on your encrypted traffic, since they have no way to gain access to your shared symmetric key.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/188266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3446/" ] }
188,281
In Delphi 2009 I'm finding that any time I use TThread.CurrentThread in an application, I'll get an error message like the following when the application closes: Exception EAccessViolation in module ntdll.dll at 0003DBBA.Access violation at address 7799DBBA in module 'ntdll.dll'. Write ofaddress 00000014. Unless it's just my machine, you can replicate this in a few seconds: create a new Delphi Forms Application, add a button to the form, and use something like the following for the button's event handler: procedure TForm1.Button1Click(Sender: TObject);begin TThread.CurrentThread;end; On both my Vista machine and my XP machine I'm finding that, if I don't click the button everything's fine, but if I do click the button I get the above error message when I close the application. So... I'm wondering if this is a bug, but at the same time I think it's rather likely that I'm simply not understanding something very basic about how you're supposed to work with TThreads in Delphi. I am a bit of a Delphi newbie I'm afraid. Is there something obviously wrong with using TThread.CurrentThread like that? If not, and you have Delphi 2009, do you get the same problem if you implement my simple sample project? Update: As François noted below, this actually is a bug in Delphi 2009 at the moment - you can vote for it here . Update: This bug was fixed in Delphi 2010.
Unfortunately it seems like a bug linked to the call order of the finalization section in the Classes unit: DoneThreadSynchronization clears the ThreadLock structure, then FreeExternalThreads wants to destroy the Thread object you just created when calling CurrentThread , and that requires the ThreadLock to be already initialized in the call to EnterCriticalSection(ThreadLock) in TThread.RemoveQueuedEvents ... UPDATE : There is now a workaround patch in the QC report .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11961/" ] }
188,299
I have the following struct in C++: #define MAXCHARS 15typedef struct { char data[MAXCHARS]; int prob[MAXCHARS];} LPRData; And a function that I'm p/invoking into to get an array of 3 of these structures: void GetData(LPRData *data); In C++ I would just do something like this: LPRData *Results;Results = (LPRData *)malloc(MAXRESULTS*sizeof(LPRData));GetData( Results ); And it would work just fine, but in C# I can't seem to get it to work.I've created a C# struct like this: public struct LPRData{ /// char[15] [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)] public string data; /// int[15] [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 15)] public int[] prob;} And if I initialize an array of 3 of those (and all their sub-arrays) and pass it into this: GetData(LPRData[] data); It returns with success, but the data in the LPRData array has not changed. I've even tried to create a raw byte array the size of 3 LPRData's and pass that into a function prototype like this: GetData(byte[] data); But in that case I will get the "data" string from the very first LPRData structure, but nothing after it, including the "prob" array from the same LPRData. Any ideas of how to properly handle this?
I would try adding some attributes to your struct decloration [StructLayout(LayoutKind.Sequential, Size=TotalBytesInStruct),Serializable]public struct LPRData{/// char[15][MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)]public string data;/// int[15][MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 15)]public int[] prob;} *Note TotalBytesInStruct is not intended to represent a variable JaredPar is also correct that using the IntPtr class could be helpful, but it has been quite awhile since I have used PInvoke so I'm rusty.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/188299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ] }
188,306
Right now, my SVN repository is on my laptop's HDD (although I use a code hosting service for more "critical" personal projects) and I just copy the directory over on a weekly basis (which will eventually be scripted or perhaps I'll make an app for the hell of it). Am I at risk for corrupting my SVN repository? So far, I haven't had any problems with the original or the copy, but that doesn't mean that I'm not at risk in the future.
Consider using hot copy : svnadmin hotcopy — Make a hot copy of a repository... This subcommand makes a full “hot” backup of your repository, including all hooks, configuration files, and, of course, database files. If you pass the --clean-logs switch, svnadmin will perform a hotcopy of your repository, and then remove unused Berkeley DB logs from the original repository. You can run this command at any time and make a safe copy of the repository, regardless of whether other processes are using the repository...
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ] }
188,311
In a nutshell, the hashCode contract, according to Java's object.hashCode(): The hash code shouldn't change unless something affecting equals() changes equals() implies hash codes are == Let's assume interest primarily in immutable data objects - their information never changes after they're constructed, so #1 is assumed to hold. That leaves #2: the problem is simply one of confirming that equals implies hash code ==. Obviously, we can't test every conceivable data object unless that set is trivially small. So, what is the best way to write a unit test that is likely to catch the common cases? Since the instances of this class are immutable, there are limited ways to construct such an object; this unit test should cover all of them if possible. Off the top of my head, the entry points are the constructors, deserialization, and constructors of subclasses (which should be reducible to the constructor call problem). [I'm going to try to answer my own question via research. Input from other StackOverflowers is a welcome safety mechanism to this process.] [This could be applicable to other OO languages, so I'm adding that tag.]
EqualsVerifier is a relatively new open source project and it does a very good job at testing the equals contract. It doesn't have the issues the EqualsTester from GSBase has. I would definitely recommend it.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/188311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18160/" ] }
188,349
I need to knock out a quick animation in C#/Windows Forms for a Halloween display. Just some 2D shapes moving about on a solid background. Since this is just a quick one-off project I really don't want to install and learn an entire new set of tools for this. (DirectX dev kits, Silverlight, Flash, etc..) I also have to install this on multiple computers so anything beyond the basic .Net framework (2.0) would be a pain in the arse. For tools I've got VS2k8, 25 years of development experience, a wheelbarrow, holocaust cloak, and about 2 days to knock this out. I haven't done animation since using assembler on my Atari 130XE (hooray for page flipping and player/missile graphics!) Advice? Here's some of the things I'd like to know: I can draw on any empty widget (like a panel) by fiddling with it's OnPaint handler, right? That's how I'd draw a custom widget. Is there a better technique than this? Is there a page-flipping technique for this kind of thing in Windows Forms? I'm not looking for a high frame rate, just as little flicker/drawing as necessary. Thanks. Post Mortem Edit ... "a couple of coding days later" Well, the project is done. The links below came in handy although a couple of them were 404. (I wish SO would allow more than one reply to be marked "correct"). The biggest problem I had to overcome was flickering, and a persistent bug when I tried to draw on the form directly. Using the OnPaint event for the Form: bad idea. I never got that to work; lots of mysterious errors (stack overflows, or ArgumentNullExceptions). I wound up using a panel sized to fill the form and that worked fine. Using the OnPaint method is slow anyway. Somewhere online I read that building the PaintEventArgs was slow, and they weren't kidding. Lots of flickering went away when I abandoned this. Skip the OnPaint/Invalidate() and just paint it yourself. Setting all of the "double buffering" options on the form still left some flicker that had to be fixed. (And I found conflicting docs that said "set them on the control" and "set them on the form". Well controls don't have a .SetStyle() method.) I haven't tested without them, so they might be doing something ( this is the form): this.SetStyle(ControlStyles.UserPaint, true); this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); So the workhorse of the code wound up looking like ( pf is the panel control): void PaintPlayField() { Bitmap bufl = new Bitmap(pf.Width, pf.Height); using (Graphics g = Graphics.FromImage(bufl)) { g.FillRectangle(Brushes.Black, new Rectangle(0, 0, pf.Width, pf.Height)); DrawItems(g); DrawMoreItems(g); pf.CreateGraphics().DrawImageUnscaled(bufl, 0, 0); } } And I just called PaintPlayField from the inside of my Timer loop. No flicker at all.
Set off a timer at your desired frame rate. At each timer firing twiddle the internal representation of the shapes on the screen (your model) per the animation motion you want to achieve, then call Invalidate(true) . Inside the OnPaint just draw the model on the screen. Oh yeah, and you probably want to turn Double Buffering on (this is like automatic page flipping).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8173/" ] }
188,414
I have used the XML Parser before, and even though it worked OK, I wasn't happy with it in general, it felt like I was using workarounds for things that should be basic functionality. I recently saw SimpleXML but I haven't tried it yet. Is it any simpler? What advantages and disadvantages do both have? Any other parsers you've used?
I would have to say SimpleXML takes the cake because it is firstly an extension, written in C, and is very fast. But second, the parsed document takes the form of a PHP object. So you can "query" like $root->myElement .
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/188414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25910/" ] }
188,425
I have been trying to work my way through Project Euler, and have noticed a handful of problems ask for you to determine a prime number as part of it. I know I can just divide x by 2, 3, 4, 5, ..., square root of X and if I get to the square root, I can (safely) assume that the number is prime. Unfortunately this solution seems quite klunky. I've looked into better algorithms on how to determine if a number is prime, but get confused fast. Is there a simple algorithm that can determine if X is prime, and not confuse a mere mortal programmer? Thanks much!
The first algorithm is quite good and used a lot on Project Euler. If you know the maximum number that you want you can also research Eratosthenes's sieve. If you maintain the list of primes you can also refine the first algo to divide only with primes until the square root of the number. With these two algoritms (dividing and the sieve) you should be able to solve the problems. Edit : fixed name as noted in comments
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/188425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2156/" ] }
188,444
Is it possible to read and write Word (2003 and 2007) files in Python without using a COM object? I know that I can: f = open('c:\file.doc', "w")f.write(text)f.close() but Word will read it as an HTML file not a native .doc file.
See python-docx , its official documentation is available here . This has worked very well for me. Note that this does not work for .doc files, only .docx files.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ] }
188,449
In a C++ project, compilation dependencies can make a software project difficult to maintain. What are some of the best practices for limiting dependencies, both within a module and across modules?
Forward Declarations Abstract Interfaces The Pimpl Idiom
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1674/" ] }
188,452
Is it possible to read and write Word (2003 and 2007) files in PHP without using a COM object?I know that I can: $file = fopen('c:\file.doc', 'w+');fwrite($file, $text);fclose(); but Word will read it as an HTML file not a native .doc file.
Reading binary Word documents would involve creating a parser according to the published file format specifications for the DOC format. I think this is no real feasible solution. You could use the Microsoft Office XML formats for reading and writing Word files - this is compatible with the 2003 and 2007 version of Word. For reading you have to ensure that the Word documents are saved in the correct format (it's called Word 2003 XML-Document in Word 2007). For writing you just have to follow the openly available XML schema. I've never used this format for writing out Office documents from PHP, but I'm using it for reading in an Excel worksheet (naturally saved as XML-Spreadsheet 2003) and displaying its data on a web page. As the files are plainly XML data it's no problem to navigate within and figure out how to extract the data you need. The other option - a Word 2007 only option (if the OpenXML file formats are not installed in your Word 2003) - would be to ressort to OpenXML . As databyss pointed out here the DOCX file format is just a ZIP archive with XML files included. There are a lot of resources on MSDN regarding the OpenXML file format, so you should be able to figure out how to read the data you want. Writing will be much more complicated I think - it just depends on how much time you'll invest. Perhaps you can have a look at PHPExcel which is a library able to write to Excel 2007 files and read from Excel 2007 files using the OpenXML standard. You could get an idea of the work involved when trying to read and write OpenXML Word documents.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/188452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ] }
188,461
For as long as I can remember I have avoided using switch statement fall-through. Actually, I can't remember it ever entering my consciousness as a possible way to do things as it was drilled into my head early on that it was nothing more than a bug in the switch statement. However, today I ran across some code that uses it by design, which got me immediately wondering what everyone in the community thinks about switch statement fall-through. Is it something that a programming language should explicitly not allow (like C# does, though it supplies a workaround) or is it a feature of any language that is powerful enough to leave in the programmer's hands? Edit: I wasn't specific enough to what I meant by fall-through. I use this type a lot: switch(m_loadAnimSubCt){ case 0: case 1: // Do something break; case 2: case 3: case 4: // Do something break; } However, I'm concerned about something like this. switch(m_loadAnimSubCt){ case 0: case 1: // Do something, but fall through to the other cases // after doing it. case 2: case 3: case 4: // Do something else. break; } This way whenever the case is 0, 1 it will do everything in the switch statement. I've seen this by design and I just don't know if I agree that switch statements should be used this way. I think the first code example is very useful and safe. The second seems kind of dangerous.
It may depend on what you consider fallthrough. I'm ok with this sort of thing: switch (value){ case 0: result = ZERO_DIGIT; break; case 1: case 3: case 5: case 7: case 9: result = ODD_DIGIT; break; case 2: case 4: case 6: case 8: result = EVEN_DIGIT; break;} But if you have a case label followed by code that falls through to another case label, I'd pretty much always consider that evil. Perhaps moving the common code to a function and calling from both places would be a better idea. And please note that I use the C++ FAQ definition of "evil"
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/188461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16524/" ] }
188,473
I have a C# object with a critical resource that needs to be flushed very specific points in time making it a bad candidate to leave around for the garbage collector to take care of whenever it gets around to it, how should I handle this? Is there something like C++'s delete operator that will let me manually kill the instance of this object when needed?
You are looking for IDisposable . Here is an example class that implements this. class MyDisposableObject : IDisposable{ public MyDisposableObject() { } ~MyDisposableObject() { Dispose(false); } private bool disposed; private void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { // Dispose of your managed resources here. } // Dispose of your unmanaged resources here. this.disposed = true; } } void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); }} To use it, you can do something like this: public void DoingMyThing(){ using (MyDisposableObject obj = new MyDisposableObject()) { // Use obj here. }} The using keyword makes sure that the Dispose() method on IDisposable gets called at the end of its scope.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
188,491
My application connects to an FTP server with a username and password. I can create an encryption routine to encrypt and decrypt the password, but anybody with access to the source code and the encrypted password can decrypt the password. Is there an easy way to prevent every human being from knowing the entire password used by an application? (I think it's okay if multiple people know part of the password.) EDIT: I know FTP is not secure. Ideally, I'd like a technique that would work in any situation where a username and password are required (e.g. a database connection).
No. All an app user has to do is sniff their own network traffic (easy to do with Wireshark or such). You really need a way to give each user a unique token of some sort. Edit - more info: Any system that relies on "secret" login information that is the same for every copy of the application is flawed by design. In order to keep things secure, every install of your app must have a unique secret that it uses to authenticate with the server. How you accomplish that is dependent on how you license/distribute your app. Here is how I would do it. (Perform all communication over an SSL connection). App is launched for the first time - it sees that it has no authentication information saved. App prompts you for a registration code, email address and/or however you want to identify your users. App generates a public/private keypair and submits the public key with your ID info from step 2 to the server. Server remembers your key and uses it to identify your app from now on. Alternate step 3 is: app submits info from step 2 and server sends back a hash signature of the info + salt. Hash signature is now your app's key. The important thing is that there is no "secret" shared between all your users.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681/" ] }
188,503
How do you detect the number of physical processors/cores in .net?
System.Environment.ProcessorCount returns the number of logical processors http://msdn.microsoft.com/en-us/library/system.environment.processorcount.aspx For physical processor count you'd probably need to use WMI - the following metadata is supported in XP/Win2k3 upwards (Functionality enabled in SP's prior to Vista/Win2k8). Win32_ComputerSystem.NumberOfProcessors returns physical count Win32_ComputerSystem.NumberOfLogicalProcessors returns logical (duh!) Be cautious that HyperThreaded CPUs appear identical to multicore'd CPU's yet the performance characteristics are very different. To check for HT-enabled CPUs examine each instance of Win32_Processor and compare these two properties. Win32_Processor.NumberOfLogicalProcessors Win32_Processor.NumberOfCores On multicore systems these are typically the same the value. Also, be aware of systems that may have multiple Processor Groups , which is often seen on computers with a large number of processors. By default .Net will only using the first processor group - which means that by default, threads will utilize only CPUs from the first processor group, and Environment.ProcessorCount will return only the number of CPUs in this group. According to Alastair Maw's answer , this behavior can be changed by altering the app.config as follows: <configuration> <runtime> <Thread_UseAllCpuGroups enabled="true"/> <GCCpuGroup enabled="true"/> <gcServer enabled="true"/> </runtime></configuration>
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/188503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1952/" ] }
188,510
I have a string "1112224444' it is a telephone number. I want to format as 111-222-4444 before I store it in a file. It is on a datarecord and I would prefer to be able to do this without assigning a new variable. I was thinking: String.Format("{0:###-###-####}", i["MyPhone"].ToString() ); but that does not seem to do the trick. ** UPDATE ** Ok. I went with this solution Convert.ToInt64(i["Customer Phone"]).ToString("###-###-#### ####") Now its gets messed up when the extension is less than 4 digits. It will fill in the numbers from the right. so 1112224444 333 becomes11-221-244 3334 Any ideas?
I prefer to use regular expressions: Regex.Replace("1112224444", @"(\d{3})(\d{3})(\d{4})", "$1-$2-$3");
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/188510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ] }
188,532
I want to make sure that a set of functions have the same signature in some C code. Ideally I would be able to define a new type that described the return value and arguments of a function and then declare my set of functions using this new type. Additionally, is there a way to specify default values for the arguments to this function typedef?
/* define a typedef for function_t - functions that return void *//* and take an int and char parameter */typedef void function_t( int param1, char param2);/* declare some functions that use that signature */function_t foo;function_t bar; Now when you define the functions there will be an error if they do not use the same signature as in the typedef. void foo( int x, char c){ /* do some stuff */ return;}/* this will result in a compiler error */int bar( int x, char c){ /* do some stuff */ return 1;} As for your new question (added 20 Oct 08): "Additionally, is there a way to specify default values for the arguments to this function typedef?" No, there's no way to add default parameters to the typedef. Certainly not in C, which doesn't support default parameters at all. Even in C++ you can't do this because the default value of a parameter is not part of the type. In fact, a class that overrides a virtual method from a base class can specify a different value for a default parameter (or even remove the default altogether) - however, this is something that should not be done in general as it will simply cause confusion ( http://www.gotw.ca/gotw/005.htm ). If you're using C++ you might be able to get the behavior you want using one of (or a combination of) the following: abstract base classes overloading template functions macros But it would be difficult to suggest something without knowing more specifics about exactly what you're trying to accomplish. And I think it's likely that the result might well be pretty hacky.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26551/" ] }
188,545
I was looking for a way to remove text from and RTF string and I found the following regex: ({\\)(.+?)(})|(\\)(.+?)(\b) However the resulting string has two right angle brackets "}" Before: {\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 MS Shell Dlg 2;}{\f1\fnil MS Shell Dlg 2;}} {\colortbl ;\red0\green0\blue0;} {\*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\tx720\cf1\f0\fs20 can u send me info for the call pls\f1\par } After: } can u send me info for the call pls } Any thoughts on how to improve the regex? Edit: A more complicated string such as this one does not work: {\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 MS Shell Dlg 2;}} {\colortbl ;\red0\green0\blue0;} {\*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\tx720\cf1\f0\fs20 HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\test\\myapp\\Apps\\\{3423234-283B-43d2-BCE6-A324B84CC70E\}\par }
In RTF, { and } marks a group. Groups can be nested. \ marks beginning of a control word. Control words end with either a space or a non alphabetic character. A control word can have a numeric parameter following, without any delimiter in between. Some control words also take text parameters, separated by ';'. Those control words are usually in their own groups. I think I have managed to make a pattern that takes care of most the cases. \{\*?\\[^{}]+}|[{}]|\\\n?[A-Za-z]+\n?(?:-?\d+)?[ ]? It leaves a few spaces when run on your pattern though. Going trough the RTF specification (some of it), I see that there are a lot of pitfalls for pure regex based strippers. The most obvious one are that some groups should be ignored (headers, footers, etc.), while others should be rendered (formatting). I have written a Python script that should work better than my regex above: def striprtf(text): pattern = re.compile(r"\\([a-z]{1,32})(-?\d{1,10})?[ ]?|\\'([0-9a-f]{2})|\\([^a-z])|([{}])|[\r\n]+|(.)", re.I) # control words which specify a "destionation". destinations = frozenset(( 'aftncn','aftnsep','aftnsepc','annotation','atnauthor','atndate','atnicn','atnid', 'atnparent','atnref','atntime','atrfend','atrfstart','author','background', 'bkmkend','bkmkstart','blipuid','buptim','category','colorschememapping', 'colortbl','comment','company','creatim','datafield','datastore','defchp','defpap', 'do','doccomm','docvar','dptxbxtext','ebcend','ebcstart','factoidname','falt', 'fchars','ffdeftext','ffentrymcr','ffexitmcr','ffformat','ffhelptext','ffl', 'ffname','ffstattext','field','file','filetbl','fldinst','fldrslt','fldtype', 'fname','fontemb','fontfile','fonttbl','footer','footerf','footerl','footerr', 'footnote','formfield','ftncn','ftnsep','ftnsepc','g','generator','gridtbl', 'header','headerf','headerl','headerr','hl','hlfr','hlinkbase','hlloc','hlsrc', 'hsv','htmltag','info','keycode','keywords','latentstyles','lchars','levelnumbers', 'leveltext','lfolevel','linkval','list','listlevel','listname','listoverride', 'listoverridetable','listpicture','liststylename','listtable','listtext', 'lsdlockedexcept','macc','maccPr','mailmerge','maln','malnScr','manager','margPr', 'mbar','mbarPr','mbaseJc','mbegChr','mborderBox','mborderBoxPr','mbox','mboxPr', 'mchr','mcount','mctrlPr','md','mdeg','mdegHide','mden','mdiff','mdPr','me', 'mendChr','meqArr','meqArrPr','mf','mfName','mfPr','mfunc','mfuncPr','mgroupChr', 'mgroupChrPr','mgrow','mhideBot','mhideLeft','mhideRight','mhideTop','mhtmltag', 'mlim','mlimloc','mlimlow','mlimlowPr','mlimupp','mlimuppPr','mm','mmaddfieldname', 'mmath','mmathPict','mmathPr','mmaxdist','mmc','mmcJc','mmconnectstr', 'mmconnectstrdata','mmcPr','mmcs','mmdatasource','mmheadersource','mmmailsubject', 'mmodso','mmodsofilter','mmodsofldmpdata','mmodsomappedname','mmodsoname', 'mmodsorecipdata','mmodsosort','mmodsosrc','mmodsotable','mmodsoudl', 'mmodsoudldata','mmodsouniquetag','mmPr','mmquery','mmr','mnary','mnaryPr', 'mnoBreak','mnum','mobjDist','moMath','moMathPara','moMathParaPr','mopEmu', 'mphant','mphantPr','mplcHide','mpos','mr','mrad','mradPr','mrPr','msepChr', 'mshow','mshp','msPre','msPrePr','msSub','msSubPr','msSubSup','msSubSupPr','msSup', 'msSupPr','mstrikeBLTR','mstrikeH','mstrikeTLBR','mstrikeV','msub','msubHide', 'msup','msupHide','mtransp','mtype','mvertJc','mvfmf','mvfml','mvtof','mvtol', 'mzeroAsc','mzeroDesc','mzeroWid','nesttableprops','nextfile','nonesttables', 'objalias','objclass','objdata','object','objname','objsect','objtime','oldcprops', 'oldpprops','oldsprops','oldtprops','oleclsid','operator','panose','password', 'passwordhash','pgp','pgptbl','picprop','pict','pn','pnseclvl','pntext','pntxta', 'pntxtb','printim','private','propname','protend','protstart','protusertbl','pxe', 'result','revtbl','revtim','rsidtbl','rxe','shp','shpgrp','shpinst', 'shppict','shprslt','shptxt','sn','sp','staticval','stylesheet','subject','sv', 'svb','tc','template','themedata','title','txe','ud','upr','userprops', 'wgrffmtfilter','windowcaption','writereservation','writereservhash','xe','xform', 'xmlattrname','xmlattrvalue','xmlclose','xmlname','xmlnstbl', 'xmlopen', )) # Translation of some special characters. specialchars = { 'par': '\n', 'sect': '\n\n', 'page': '\n\n', 'line': '\n', 'tab': '\t', 'emdash': u'\u2014', 'endash': u'\u2013', 'emspace': u'\u2003', 'enspace': u'\u2002', 'qmspace': u'\u2005', 'bullet': u'\u2022', 'lquote': u'\u2018', 'rquote': u'\u2019', 'ldblquote': u'\201C', 'rdblquote': u'\u201D', } stack = [] ignorable = False # Whether this group (and all inside it) are "ignorable". ucskip = 1 # Number of ASCII characters to skip after a unicode character. curskip = 0 # Number of ASCII characters left to skip out = [] # Output buffer. for match in pattern.finditer(text): word,arg,hex,char,brace,tchar = match.groups() if brace: curskip = 0 if brace == '{': # Push state stack.append((ucskip,ignorable)) elif brace == '}': # Pop state ucskip,ignorable = stack.pop() elif char: # \x (not a letter) curskip = 0 if char == '~': if not ignorable: out.append(u'\xA0') elif char in '{}\\': if not ignorable: out.append(char) elif char == '*': ignorable = True elif word: # \foo curskip = 0 if word in destinations: ignorable = True elif ignorable: pass elif word in specialchars: out.append(specialchars[word]) elif word == 'uc': ucskip = int(arg) elif word == 'u': c = int(arg) if c < 0: c += 0x10000 if c > 127: out.append(unichr(c)) else: out.append(chr(c)) curskip = ucskip elif hex: # \'xx if curskip > 0: curskip -= 1 elif not ignorable: c = int(hex,16) if c > 127: out.append(unichr(c)) else: out.append(chr(c)) elif tchar: if curskip > 0: curskip -= 1 elif not ignorable: out.append(tchar) return ''.join(out) It works by parsing the RTF code, and skipping any groups which has a "destination" specified, and all "ignorable" groups ( {\* ... } ). I also added handling of some special characters. There are lots of features missing to make this a full parser, but should be enough for simple documents. UPDATED: This url have this script updated to run on Python 3.x: https://gist.github.com/gilsondev/7c1d2d753ddb522e7bc22511cfb08676
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/188545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324/" ] }
188,547
Is it possible for Eclipse to read stdin from a file?
Pure Java You can redirect System.in with a single line of code: System.setIn(new FileInputStream(filename)); See System.setIn() . Eclipse config In Eclipse 4.5 or later, the launch configuration dialog can set System.in to read from a file. See the announcement here .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/188547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
188,584
In c#, how can I check to see if a link button has been clicked in the page load method? I need to know if it was clicked before the click event is fired.
if( IsPostBack ) { // get the target of the post-back, will be the name of the control // that issued the post-back string eTarget = Request.Params["__EVENTTARGET"].ToString();}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/188584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13053/" ] }
188,663
I'm curious as to if there are any best practices relating to JQuery when constructing encapsulated code blocks. Generally, when I construct a page I like to encapsulate the functions used within that page inside an object. This allows me some encapsulation when building applications. There's nothing I hate more than seeing a JavaScript file with a bunch of this function doSomethingOnlyRelevantOnThisPage() { // do some stuff} I this makes for messy design, and doesn't really encapsulate functionality nicely. Commonly in many frameworks, there is a standard that is used to perform this encapsulation. In Mootools they favor the Object Literal Notation: var Site = { // properties and methods} In YUI they favor the Self Executing Function notation: (function() { // properties and methods })() The nice thing about the second example is that a closure is created, thus allowing you to define private properties and methods. My question is this: Do any JQuery aficionados have any best practices for creating these cleanly encapsulated structures? What is the rationale behind their use?
Since I've been working with jQuery for a while now, I've decided on a standard pattern that works well for me. It's a combination of the YUI module pattern with a bit of jQuery plugin pattern mixed in. . We ended up using the self executing closure pattern. This is beneficial in a few ways: It keeps code to a minimum It enforces separation of behavior from presentation It provides a closure which prevents naming conflicts This is what it looks like: ;(function($) { var myPrivateFunction = function() { }; var init = function() { myPrivateFunction(); }; $(init);})(jQuery); We realized that assigning the result of the function execution, similar to the YUI module pattern, exposes code that could potentially be called from within presentation code. We want to prevent this, so this pattern fits. Of course we could have written the init method inline, without defining a variable for the function. We agreed that explicitly defining the init function made the code clearer to readers. What happens if we want to share functions between pages/external js files? We simply hook into the existing mechanism that jQuery provides for extending the jQuery object itself - the extend function. If the functions are static, we use $.extend, and if they operate over a wrapped set, we use the $.fn.extend function. Hope this helps someone.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769/" ] }
188,669
I have a page being loaded with jQuery. The initial load includes 100 records with 6 icons per record. Needless to say, it takes a few seconds to load and I want to give the user a "loading" prompt/animation. Any ideas?
http://www.ajaxload.info/ is a great resource for generating animated GIFs for this sort of thing. Once you've got your animation, render it as part of the page; fire the jQuery load mechanism on the animation's onload() event (so you're certain the animation has loaded first), and use a callback at the end of your loading sequence to disable/hide the animated GIF.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26121/" ] }
188,688
I am looking at some code and it has this statement: ~ConnectionManager(){ Dispose(false);} The class implements the IDisposable interface, but I do not know if that is part of that the tilde(~) is used for.
~ is the destructor Destructors are invoked automatically, and cannot be invoked explicitly. Destructors cannot be overloaded. Thus, a class can have, at most, one destructor. Destructors are not inherited. Thus, a class has no destructors other than the one, which may be declared in it. Destructors cannot be used with structs. They are only used with classes.An instance becomes eligible for destruction when it is no longer possible for any code to use the instance. Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction. When an instance is destructed, the destructors in its inheritance chain are called, in order, from most derived to least derived. Finalize In C#, the Finalize method performs the operations that a standard C++ destructor would do. In C#, you don't name it Finalize -- you use the C++ destructor syntax of placing a tilde ( ~ ) symbol before the name of the class. Dispose It is preferable to dispose of objects in a Close() or Dispose() method that can be called explicitly by the user of the class. Finalize (destructor) are called by the GC. The IDisposable interface tells the world that your class holds onto resources that need to be disposed and provides users a way to release them. If you do need to implement a finalizer in your class, your Dispose method should use the GC.SuppressFinalize() method to ensure that finalization of your instance is suppressed. What to use? It is not legal to call a destructor explicitly. Your destructor will be called by the garbage collector. If you do handle precious unmanaged resources (such as file handles) that you want to close and dispose of as quickly as possible, you ought to implement the IDisposable interface.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/188688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1048/" ] }
188,692
I recall reading, on multiple occasions and in multiple locations, that when firing the typical event: protected virtual OnSomethingHappened(){ this.SomethingHappened(this, EventArgs.Empty);} e should be EventArgs.Empty if there are no interesting event args, not null. I've followed the guidance in my code, but I realized that I'm not clear on why that's the preferred technique. Why does the stated contract prefer EventArgs.Empty over null?
I believe the reasoning behind the NOT NULL is that when passed as a parameter, it is not expected for the method to need to potentially handle a null reference exception. If you pass null, and the method tries to do something with e it will get a null reference exception, with EventArgs.Empty it will not.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/188692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6932/" ] }
188,693
Looking for an answer for C# and C++. (in C#, replace 'destructor' with 'finalizer')
Preamble: Herb Sutter has a great article on the subject: http://herbsutter.wordpress.com/2008/07/25/constructor-exceptions-in-c-c-and-java/ C++ : Yes and No While an object destructor won't be called if its constructor throws (the object "never existed"), the destructors of its internal objects could be called. As a summary, every internal parts of the object (i.e. member objects) will have their destructors called in the reverse order of their construction. Every thing built inside the constructor won't have its destructor called unless RAII is used in some way. For example: struct Class{ Class() ; ~Class() ; Thing * m_pThing ; Object m_aObject ; Gizmo * m_pGizmo ; Data m_aData ;}Class::Class(){ this->m_pThing = new Thing() ; this->m_pGizmo = new Gizmo() ;} The order of creation will be: m_aObject will have its constructor called. m_aData will have its constructor called. Class constructor is called Inside Class constructor, m_pThing will have its new and then constructor called. Inside Class constructor, m_pGizmo will have its new and then constructor called. Let's say we are using the following code: Class pClass = new Class() ; Some possible cases: Should m_aData throw at construction, m_aObject will have its destructor called. Then, the memory allocated by "new Class" is deallocated. Should m_pThing throw at new Thing (out of memory), m_aData, and then m_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated. Should m_pThing throw at construction, the memory allocated by "new Thing" will be deallocated. Then m_aData, and then m_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated. Should m_pGizmo throw at construction, the memory allocated by "new Gizmo" will be deallocated. Then m_aData, and then m_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated. Note that m_pThing leaked If you want to offer the Basic Exception Guarantee, you must not leak, even in the constructor. Thus, you'll have to write this this way (using STL, or even Boost): struct Class{ Class() ; ~Class() ; std::auto_ptr<Thing> m_pThing ; Object m_aObject ; std::auto_ptr<Gizmo> m_pGizmo ; Data m_aData ;}Class::Class() : m_pThing(new Thing()) , m_pGizmo(new Gizmo()){} Or even: Class::Class(){ this->m_pThing.reset(new Thing()) ; this->m_pGizmo.reset(new Gizmo()) ;} if you want/need to create those objects inside the constructor. This way, no matter where the constructor throws, nothing will be leaked.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/188693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22820/" ] }
188,719
A friend and I are about to embark on creating a machine that performs some image comparison for sorting. I know about histogram comparison and am generally confident that a small grid of histograms per image precalculated and stored in columns in a database table will generally give us pretty good matches on the first pass because we are matching like things. The second comparison we want to perform is to use a color coherence vector (CCV) of images which passed the histogram match test from our subject image to the candidate images. I know that this sort of comparison is more precise. My friend is confident that he can develop CCV in C# using the C# wrapper to OpenCV . I am pretty sure he can too. However I would like to know: Has anyone already done this in C# and released the source code? Or a C# wrapper? Are we barking up the wrong tree? (Should we just use CCV and forgo histogram comparisons at the database level? Or is CCV too much?)
Preamble: Herb Sutter has a great article on the subject: http://herbsutter.wordpress.com/2008/07/25/constructor-exceptions-in-c-c-and-java/ C++ : Yes and No While an object destructor won't be called if its constructor throws (the object "never existed"), the destructors of its internal objects could be called. As a summary, every internal parts of the object (i.e. member objects) will have their destructors called in the reverse order of their construction. Every thing built inside the constructor won't have its destructor called unless RAII is used in some way. For example: struct Class{ Class() ; ~Class() ; Thing * m_pThing ; Object m_aObject ; Gizmo * m_pGizmo ; Data m_aData ;}Class::Class(){ this->m_pThing = new Thing() ; this->m_pGizmo = new Gizmo() ;} The order of creation will be: m_aObject will have its constructor called. m_aData will have its constructor called. Class constructor is called Inside Class constructor, m_pThing will have its new and then constructor called. Inside Class constructor, m_pGizmo will have its new and then constructor called. Let's say we are using the following code: Class pClass = new Class() ; Some possible cases: Should m_aData throw at construction, m_aObject will have its destructor called. Then, the memory allocated by "new Class" is deallocated. Should m_pThing throw at new Thing (out of memory), m_aData, and then m_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated. Should m_pThing throw at construction, the memory allocated by "new Thing" will be deallocated. Then m_aData, and then m_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated. Should m_pGizmo throw at construction, the memory allocated by "new Gizmo" will be deallocated. Then m_aData, and then m_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated. Note that m_pThing leaked If you want to offer the Basic Exception Guarantee, you must not leak, even in the constructor. Thus, you'll have to write this this way (using STL, or even Boost): struct Class{ Class() ; ~Class() ; std::auto_ptr<Thing> m_pThing ; Object m_aObject ; std::auto_ptr<Gizmo> m_pGizmo ; Data m_aData ;}Class::Class() : m_pThing(new Thing()) , m_pGizmo(new Gizmo()){} Or even: Class::Class(){ this->m_pThing.reset(new Thing()) ; this->m_pGizmo.reset(new Gizmo()) ;} if you want/need to create those objects inside the constructor. This way, no matter where the constructor throws, nothing will be leaked.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/188719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5645/" ] }
188,738
People keep giving me examples with carp instead of warn. Why? What makes carp better than warn?
carp gives you more info as to where the message comes from (context) #!/usr/bin/perluse Carp;foo();bar();baz();sub foo { warn "foo";}sub bar { carp "bar";}sub baz { foo(); bar(); } produces foo at ./foo.pl line 9.bar at ./foo.pl line 13 main::bar() called at ./foo.pl line 6foo at ./foo.pl line 10.bar at ./foo.pl line 14 main::bar() called at ./foo.pl line 19 main::baz() called at ./foo.pl line 7 kinda silly for this small program but comes in handy when you want to know who called the method that's carp'ing.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/188738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ] }
188,839
I use a structure of function pointers to implement an interface for different backends. The signatures are very different, but the return values are almost all void, void * or int. struct my_interface { void (*func_a)(int i); void *(*func_b)(const char *bla); ... int (*func_z)(char foo);}; But it is not required that a backends supports functions for every interface function. So I have two possibilities, first option is to check before every call if the pointer is unequal NULL. I don't like that very much, because of the readability and because I fear the performance impacts (I haven't measured it, however). The other option is to have a dummy function, for the rare cases an interface function doesn't exist. Therefore I'd need a dummy function for every signature, I wonder if it is possible to have only one for the different return values. And cast it to the given signature. #include <stdio.h>int nothing(void) {return 0;}typedef int (*cb_t)(int);int main(void){ cb_t func; int i; func = (cb_t) nothing; i = func(1); printf("%d\n", i); return 0;} I tested this code with gcc and it works. But is it sane? Or can it corrupt the stack or can it cause other problems? EDIT: Thanks to all the answers, I learned now much about calling conventions, after a bit of further reading. And have now a much better understanding of what happens under the hood.
By the C specification, casting a function pointer results in undefined behavior. In fact, for a while, GCC 4.3 prereleases would return NULL whenever you casted a function pointer, perfectly valid by the spec, but they backed out that change before release because it broke lots of programs. Assuming GCC continues doing what it does now, it will work fine with the default x86 calling convention (and most calling conventions on most architectures), but I wouldn't depend on it. Testing the function pointer against NULL at every callsite isn't much more expensive than a function call. If you really want, you may write a macro: #define CALL_MAYBE(func, args...) do {if (func) (func)(## args);} while (0) Or you could have a different dummy function for every signature, but I can understand that you'd like to avoid that. Edit Charles Bailey called me out on this, so I went and looked up the details (instead of relying on my holey memory). The C specification says 766 A pointer to a function of one type may be converted to a pointer to a function of another type and back again; 767 the result shall compare equal to the original pointer. 768 If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined. and GCC 4.2 prereleases (this was settled way before 4.3) was following these rules: the cast of a function pointer did not result in NULL, as I wrote, but attempting to call a function through a incompatible type, i.e. func = (cb_t)nothing;func(1); from your example, would result in an abort . They changed back to the 4.1 behavior (allow but warn), partly because this change broke OpenSSL, but OpenSSL has been fixed in the meantime, and this is undefined behavior which the compiler is free to change at any time. OpenSSL was only casting functions pointers to other function types taking and returning the same number of values of the same exact sizes, and this (assuming you're not dealing with floating-point) happens to be safe across all the platforms and calling conventions I know of. However, anything else is potentially unsafe.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18687/" ] }
188,850
I would like a batch file to launch two separate programs then have the command line window close. Actually, to clarify, I am launching Internet Explorer with two different URLs. So far I have something like this: start "~\iexplore.exe" "url1"start "~\iexplore.exe" "url2" What I get is one instance of Internet Explorer with only the second URL loaded. Seems the second is replacing the second. I seem to remember a syntax where I would load a new command line window and pass the command to execute on load, but can't find the reference. As a second part of the question: what is a good reference URL to keep for the times you need to write a quick batch file? Edit: I have marked an answer, because it does work. I now have two windows open, one for each URL. (thanks!) The funny thing is that without the /d approach using my original syntax I get different results based on whether I have a pre-existing Internet Explorer instance open. If I do I get two new tabs added formy two URLs (sweet!) If not I get only one final tab for the second URL I passed in.
Try this in your batch file: @echo offstart /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.google.comstart /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.yahoo.com
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/188850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10552/" ] }
188,864
So C# now allows you to use default(Foo) to get a recognized "not filled in yet"/empty instance of a class -- I'm not sure if it is exactly the same as new Foo() or not. Many library classes also implement a Foo.Empty property, which returns a similar instance. And of course any reference type can point to null . So really, what's the difference? When is one right or wrong? What's more consistent, or performs better? What tests should I use when checking if an object is conceptually "not ready for prime time"? Not everybody has Foo.IsNullOrEmpty() .
default(Foo) will return null when Foo is a class type, zero where Foo is a value type (such as int), and an instance of Foo with all fields initialized to their respective default() values where Foo is a struct. It was added to the language so that generics could support both value and reference types - more info at MSDN Use default(Foo) when you're testing a T in the context of SomeClass<T> or MyMethod<T> and you don't know whether T will be value type, a class type or a struct. Otherwise, null should mean "unknown", and empty should mean "I know this is empty". Use the Foo.Empty pattern if you genuinely need an empty - but non-null - instance of your class; e.g. String.Empty as an alternative to "" if you need to initialize some variable to the empty string. Use null if you know you're working with reference types (classes), there's no generics involved, and you're explicitly testing for uninitialized references.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26286/" ] }
188,870
Is there a library or acceptable method for sanitizing the input to an html page? In this case I have a form with just a name, phone number, and email address. Code must be C#. For example: "<script src='bobs.js'>John Doe</script>" should become "John Doe"
We are using the HtmlSanitizer .Net library, which: Is open-source (MIT) - GitHub link Is fully customizable, e.g. configure which elements should be removed. see wiki Is actively maintained Doesn't have the problems like Microsoft Anti-XSS library Is unit tested with the OWASP XSS Filter Evasion Cheat Sheet Is special built for this (in contrast to HTML Agility Pack , which is a parser - not a sanitizer) Doesn't use regular expressions ( HTML isn't a regular language! ) Also on NuGet
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/188870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2424/" ] }
188,886
After my form.Form validates the user input values I pass them to a separate (external) process for further processing. This external process can potentially find further errors in the values. Is there a way to inject these errors into the already validated form so they can be displayed via the usual form error display methods (or are there better alternative approaches)? One suggestions was to include the external processing in the form validation, which is not ideal because the external process does a lot more than merely validate.
Form._errors can be treated like a standard dictionary. It's considered good form to use the ErrorList class, and to append errors to the existing list: from django.forms.utils import ErrorListerrors = form._errors.setdefault("myfield", ErrorList())errors.append(u"My error here") And if you want to add non-field errors, use django.forms.forms.NON_FIELD_ERRORS (defaults to "__all__" ) instead of "myfield" .
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/188886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13055/" ] }
188,892
Is there a built-in mechanism in .NET to match patterns other than Regular Expressions? I'd like to match using UNIX style (glob) wildcards (* = any number of any character). I'd like to use this for a end-user facing control. I fear that permitting all RegEx capabilities will be very confusing.
I found the actual code for you: Regex.Escape( wildcardExpression ).Replace( @"\*", ".*" ).Replace( @"\?", "." );
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/188892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1807/" ] }
188,913
Is there a tool, method or setting in the standard VBA Editor to warn about variables that have been Dim 'med, but aren't being used?
MZ-Tools will search through your code and tell you what is not being used. The version for VBA can be found here . The specific feature in MZ-Tools that performs what you asking about is Review Source Code : The Review Source Code feature allows you to review the source code to detect some unused declarations (constants, variables, parameters, procedures, etc.).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13295/" ] }
188,934
As far as I know (not much I'll admit), the currently popular programming paradigms are Object Oriented (Java, C#, Ruby) vs functional (F#). As someone who is mostly familiar with the first paradigm, I have several questions: Can a programmer simply stick with one paradigm all of his/her life? Or in other words, can all problems be reduced to nails for one hammer? If not, which tool is suited for which type of task? For instance: web-based vs desktop, creating beautiful and responsive interfaces, able to crunch data quickly, etc. Have people ever needed to learn a new paradigm? For my past two jobs, my workplaces required Java and C#. Are there workplaces that specifically use non-OO languages? Obviously, there are no "best" languages, but I'm wondering whether it's worth the investment of time and energy to learn a new paradigm. Thanks in advance!
"Or in other words, can all problems be reduced to nails for one hammer?" Yes. Period. Any programming language you are likely to run into will be as complete as all others. There's actually a formal definition of "completeness" for a programming language. "Have people ever needed to learn a new paradigm?" Always. There's actually a trick to following the ups and downs of the "paradigm shifts". Over the last 30 years of my career, I've seen that programming has grown from a relatively simplistic imperative/procedural model to a number of much richer models that include a better balance between process and data. I've noticed the following... Part of the driving force is the artificial intelligence community. Many of these "new models" started as AI knowledge representation schemes. They got traction there, then they trickled into more mainstream applications. The Entity Relationship model was originally for knowledge representation, not business transactions. The Object model, similarly, was for knowledge representation. Then the simulation folks found it. Now the rest of us have it. Here's my conclusion. Software is Knowledge Representation. Your choice of Paradigm or Model or Approach or Style is based on the answer to the following question: "How Can I Best Represent This Problem?" If the problem has objects and relationships, OO. If the problem has algorithms and transformations, maps, filters and reduces, Functional. If the problem is dynamic, changing and flexible, Dynamic. If the problem is static and will scale up rapidly, Static.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6833/" ] }
188,942
I'm writing some cross-platform code between Windows and Mac. If list::end() "returns an iterator that addresses the location succeeding the last element in a list" and can be checked when traversing a list forward, what is the best way to traverse backwards? This code workson the Mac but not on Windows (can't decrement beyond first element): list<DVFGfxObj*>::iterator iter = m_Objs.end();for (iter--; iter!=m_Objs.end(); iter--)// By accident discovered that the iterator is circular ?{} this works on Windows: list<DVFGfxObj*>::iterator iter = m_Objs.end(); do{ iter--; } while (*iter != *m_Objs.begin()); Is there another way to traverse backward that could be implemented in a for loop?
Use reverse_iterator instead of iterator .Use rbegin() & rend() instead of begin() & end() . Another possibility, if you like using the BOOST_FOREACH macro is to use the BOOST_REVERSE_FOREACH macro introduced in Boost 1.36.0.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/188942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8761/" ] }
188,963
I find it odd that in Visual C# 2008 Express edition, when you use the database explorer, your options are: Microsoft Access SQL Server Compact 3.5, and SQL Server Database File. BUT if you use Visual Web Developer 2008 Express, you can connect to a regular SQL Server, Oracle, ODBC, etc. For people developing command-line or other C# apps that need to talk to a SQL Server database, do you really need to build your LINQ/Data Access code with one IDE (Visual Web Developer) and your program in another (Visual C#)? It's not a hard workaround, but it seems weird. If Microsoft wanted to force you to upgrade to Visual Studio to connect to SQL Server, why would they include that feature in one of their free IDEs but not the other? I feel like I might be missing something (like how to do it all in Visual C#).
You should be able to choose the SQL Server Database file option to get the right kind of database (the system.data.SqlClient provider), and then manually correct the connection string to point to your db. I think the reasoning behind those db choices probably goes something like this: If you're using the Express Edition, and you're not using Visual Web Developer, you're probably building a desktop program. If you're building a desktop program, and you're using the express edition, you're probably a hobbyist or uISV-er working at home rather than doing development for a corporation. If you're not developing for a corporation, your app is probably destined for the end-user and your data store is probably going on their local machine. You really shouldn't be deploying server-class databases to end-user desktops. An in-process db like Sql Server Compact or MS Access is much more appropriate. However, this logic doesn't quite hold. Even if each of those 4 points is true 90% of the time, by the time you apply all four of them it only applies to ~65% of your audience, which means up to 35% of the express market might legitimately want to talk to a server-class db, and that's a significant group. And so, the simplified (greedy) version: A real db server (and the hardware to run it) costs real money. If you have access to that, you ought to be able to afford at least the standard edition of visual studio.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26624/" ] }
188,967
I want to do this in code, not with ALT+F1.
You can also do it this way: select columnproperty(object_id('mytable'),'mycolumn','IsIdentity') Returns 1 if it's an identity, 0 if not.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/188967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2484/" ] }
188,968
I would like a constraint on a SQL Server 2000 table column that is sort of a combination of a foreign key and a check constraint. The value of my column must exist in the other table, but I am only concerned with values in the other table where one of its columns equal a specified value. The simplified tables are: import_table:part_number varchar(30)quantity intinventory_master:part_number varchar(30)type char(1) So I want to ensure the part_number exists in inventory_master , but only if the type is 'C'. Is this possible? Thanks.
You can also do it this way: select columnproperty(object_id('mytable'),'mycolumn','IsIdentity') Returns 1 if it's an identity, 0 if not.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/188968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23976/" ] }
188,977
I have a method running in a seperate thread. The thread is created and started from a form in a windows application. If an exception is thrown from inside the thread, what is the best way to pass it back to the main application. Right now, I'm passing a reference to the main form into the thread, then invoking the method from the thread, and causing the method to be called by the main application thread. Is there a best practice way to do this because I'm not comfortable with how I'm doing it now. Example of my form: public class frmMyForm : System.Windows.Forms.Form{ /// <summary> /// Create a thread /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnTest_Click(object sender, EventArgs e) { try { //Create and start the thread ThreadExample pThreadExample = new ThreadExample(this); pThreadExample.Start(); } catch (Exception ex) { MessageBox.Show(ex.Message, Application.ProductName); } } /// <summary> /// Called from inside the thread /// </summary> /// <param name="ex"></param> public void HandleError(Exception ex) { //Invoke a method in the GUI's main thread this.Invoke(new ThreadExample.delThreadSafeTriggerScript(HandleError), new Object[] { ex }); } private void __HandleError(Exception ex) { MessageBox.Show(ex.Message); }} Example of my thread class: public class ThreadExample{ public delegate void delThreadSafeHandleException(System.Exception ex); private Thread thExample_m; frmMyForm pForm_m; private frmMyForm Form { get { return pForm_m; } } public ThreadExample(frmMyForm pForm) { pForm_m = pForm; thExample_m = new Thread(new ThreadStart(Main)); thExample_m.Name = "Example Thread"; } public void Start() { thExample_m.Start(); } private void Main() { try { throw new Exception("Test"); } catch (Exception ex) { Form.HandleException(ex); } }}
So you're using Invoke to marshall back to the UI thread, by the looks of it - which is exactly what you need to do. I'd personally use an Action<Exception> for simplicity's sake, and possibly BeginInvoke instead of Invoke, but basically you're doing the right thing.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/188977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9266/" ] }
189,019
I found an example of implementing the repository pattern in NHibernate on the web, and one of the methods uses this code to get the first result of a query: public IEnumerable<T> FindAll(DetachedCriteria criteria, int firstResult, int numberOfResults, params Order[] orders){ criteria.SetFirstResult(firstResult).SetMaxResults(numberOfResults); return FindAll(criteria, orders);} But VS intellisense isn't picking up this method from DetachedCriteria. Does anyone know if this is possible with DetachedCriteria? I'm using NHibernate version 1.2.1.
So you're using Invoke to marshall back to the UI thread, by the looks of it - which is exactly what you need to do. I'd personally use an Action<Exception> for simplicity's sake, and possibly BeginInvoke instead of Invoke, but basically you're doing the right thing.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ] }
189,031
Is there any way to set the same icon to all my forms without having to change one by one?Something like when you setup GlobalAssemblyInfo for all your projects inside your solution.
One option would be to inherit from a common base-Form that sets the Icon in the constructor (presumably from a resx). Another option might be PostSharp - it seems like it should be possible to do this (set .Icon) via AOP; not trivial, though. Finally, you could use a simple utility method (perhaps an extension method) to do the same. Best of all, with the first option, you could probably risk a Ctrl + H (replace all) from : Form or : System.Windows.Forms.Form to : MyCustomForm .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/189031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4386/" ] }
189,043
Is there any way to change the background color of the Solution Explorer in Visual Studio using a Theme? - or any other way for that matter? I can change it by changing windows-wide color settings, but obviously that affects too much.
Just created VS extension for that in under an hour, search extension manager for "SExColor". Enjoy ;)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/189043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/410357/" ] }
189,055
Typically you will find STL code like this: for (SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(); Iter != m_SomeMemberContainerVar.end(); ++Iter){} But we actually have the recommendation to write it like this: SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin();SomeClass::SomeContainer::iterator IterEnd = m_SomeMemberContainerVar.end();for (; Iter != IterEnd; ++Iter){} If you're worried about scoping, add enclosing braces: { SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(); SomeClass::SomeContainer::iterator IterEnd = m_SomeMemberContainerVar.end(); for (; Iter != IterEnd; ++Iter) { }} This is supposed to give a speed and efficiency gain, especially if you are programming consoles, because the .end() function is not called on each iteration of the loop. I just take the performance improvement for granted, it sounds reasonable but i don't know how much and it certainly depends on the type of container and actual STL implementation in use. But having used this style for a couple months now i actually prefer it over the first anyway. The reason being readability: the for line is neat and tidy. With qualifiers and member variables in real production code it is quite easy to have really long for lines if you use the style in the first example. That's why i intentionally made it to have a horizontal scrollbar in this example, just so you see what i'm talking about. ;) On the other hand, you suddenly introduce the Iter variables to the outer scope of the for loop. But then, at least in the environment i work in, the Iter would have been accessible in the outer scope even in the first example. What is your take on this? Are there any pro's to the first style other than possibly limiting the scope of Iter?
If you wrap your code into lines properly, the inline form would be equally readable. Besides, you should always do the iterEnd = container.end() as an optimization: for (SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(), IterEnd = m_SomeMemberContainerVar.end(); Iter != IterEnd; ++Iter){} Update: fixed the code per paercebal's advice.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15328/" ] }
189,062
When I navigate on a website utilizing MasterPages, does the application know what page I am on? If so, does it store it in an object I can access? The reason I am asking is so I can replace this: //masterpage <div id="nav_main"> <ul><asp:ContentPlaceHolder ID="navigation" runat="server"> </asp:ContentPlaceHolder></ul></div>//content page(s)<asp:Content ContentPlaceHolderID="navigation" ID="theNav" runat="server"> <li><a href="default.aspx">Home</a></li> <li id="current"><a href="faq.aspx">FAQ</a></li> <li><a href="videos.aspx">Videos</a></li> <li><a href="#">Button 4</a></li> <li><a href="#">Button 5</a></li></asp:Content> With a more elegant solution for the navigation, which highlights the link to the page by having the list item's ID set to "current". Currently each page recreates the navigation with its respective link's ID set to current.
I'd concur with Chris: use a control to handle display of this menu and make it aware of what link should be highlighted. Here's a method I use regularly. It may become more complex if you've got multiple pages that would need the same link styled differently, but you get the idea. Dim thisURL As String = Request.Url.Segments(Request.Url.Segments.Count - 1)Select Cast thisUrl Case "MenuItem1.aspx" lnkMenu1.CssClass = "Current" Case "MenuItem2.aspx" lnkMenu2.CssClass = "Current"End Select
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ] }
189,087
If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this. for i in range(len(alist)): for j in range(len(alist[i])): if alist[i][j].isWhatever: blist[i][j].doSomething() Is there a nicer way to do something like this?
I'd start by writing a generator method: def grid_objects(alist, blist): for i in range(len(alist)): for j in range(len(alist[i])): yield(alist[i][j], blist[i][j]) Then whenever you need to iterate over the lists your code looks like this: for (a, b) in grid_objects(alist, blist): if a.is_whatever(): b.do_something()
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25680/" ] }
189,094
How can I get list all the files within a folder recursively in Java?
Not sure how you want to represent the tree? Anyway here's an example which scans the entire subtree using recursion. Files and directories are treated alike. Note that File.listFiles() returns null for non-directories. public static void main(String[] args) { Collection<File> all = new ArrayList<File>(); addTree(new File("."), all); System.out.println(all);}static void addTree(File file, Collection<File> all) { File[] children = file.listFiles(); if (children != null) { for (File child : children) { all.add(child); addTree(child, all); } }} Java 7 offers a couple of improvements. For example, DirectoryStream provides one result at a time - the caller no longer has to wait for all I/O operations to complete before acting. This allows incremental GUI updates, early cancellation, etc. static void addTree(Path directory, Collection<Path> all) throws IOException { try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) { for (Path child : ds) { all.add(child); if (Files.isDirectory(child)) { addTree(child, all); } } }} Note that the dreaded null return value has been replaced by IOException. Java 7 also offers a tree walker : static void addTree(Path directory, final Collection<Path> all) throws IOException { Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { all.add(file); return FileVisitResult.CONTINUE; } });}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/189094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8418/" ] }
189,113
I moved a WordPress installation to a new folder on a Windows/ IIS server. I'm setting up 301 redirects in PHP, but it doesn't seem to be working. My post URLs have the following format: http:://www.example.com/OLD_FOLDER/index.php/post-title/ I can't figure out how to grab the /post-title/ part of the URL. $_SERVER["REQUEST_URI"] - which everyone seems to recommend - is returning an empty string. $_SERVER["PHP_SELF"] is just returning index.php . Why is this, and how can I fix it?
Maybe, because you are under IIS, $_SERVER['PATH_INFO'] is what you want, based on the URLs you used to explain. For Apache, you'd use $_SERVER['REQUEST_URI'] .
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/189113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19487/" ] }
189,118
There are so many little options and settings within Microsoft Visual Studio. Which adjustments do you recommend to others?
Line Numbers Tools > Options Text Editor > All Languages > General Display: Line Numbers
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ] }
189,121
using MVP, what is the normal order of construction and dependency injection. normally you create a presenter for each view and pass the view into the presenter on constructor. But what if you have: A Service that multiple views need to listen to events on. Multiple views all pointing to the same data model cache. can someone display a normal flow of info from a user click to data coming back in a service from a server.
Here is what I do: First, I define theses interfaces: public interface IView<TPresenter>{ TPresenter Presenter { get; set; }}public interface IPresenter<TView, TPresenter> where TView : IView<TPresenter> where TPresenter : IPresenter<TView, TPresenter>{ TView View { get; set; }} Then this abstract presenter class: public abstract class AbstractPresenter<TView, TPresenter> : IPresenter<TView, TPresenter> where TView : IView<TPresenter> where TPresenter : class, IPresenter<TView, TPresenter>{ protected TView view; public TView View { get { return this.view; } set { this.view = value; this.view.Presenter = this as TPresenter; } }} The view is injected via a property, instead of the constructor, to allow the bi-directional affection in the setter. Notice that a safe cast is needed... Then, my concrete presenter is something like : public class MyPresenter : AbstractPresenter<IMyView, MyPresenter>{ //...} Where IMyView implements IView . A concrete view type must exists (e.g. MyView ), but it's the container that resolves it: I register MyPresenter type as itself in the container, with a transient behavior. I register MyView as an IMyView in the container with a transient behavior. I then asks for a MyPresenter to the container. Container instanciate a MyView It instanciates a MyPresenter It inject the view into the presenter through the AbstractPresenter.View property. The setter code completes the bi-directional association The container returns the couple Presenter/View It allows you to inject other dependencies (services, repos) into both your view and your presenter. But in the scenario you described, I recommend you to inject services and caches into the presenter , instead of the view.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ] }
189,156
Running FxCop on my code, I get this warning: Microsoft.Maintainability : 'FooBar.ctor is coupled with 99 different types from 9 different namespaces. Rewrite or refactor the method to decrease its class coupling, or consider moving the method to one of the other types it is tightly coupled with. A class coupling above 40 indicates poor maintainability, a class coupling between 40 and 30 indicates moderate maintainability, and a class coupling below 30 indicates good maintainability. My class is a landing zone for all messages from the server. The server can send us messages of different EventArgs types: public FooBar(){ var messageHandlers = new Dictionary<Type, Action<EventArgs>>(); messageHandlers.Add(typeof(YouHaveBeenLoggedOutEventArgs), HandleSignOut); messageHandlers.Add(typeof(TestConnectionEventArgs), HandleConnectionTest); // ... etc for 90 other types} The "HandleSignOut" and "HandleConnectionTest" methods have little code in them; they usually pass the work off to a function in another class. How can I make this class better with lower coupling?
Have the classes that do the work register for events they're interested in...an event broker pattern. class EventBroker { private Dictionary<Type, Action<EventArgs>> messageHandlers; void Register<T>(Action<EventArgs> subscriber) where T:EventArgs { // may have to combine delegates if more than 1 listener messageHandlers[typeof(T)] = subscriber; } void Send<T>(T e) where T:EventArgs { var d = messageHandlers[typeof(T)]; if (d != null) { d(e); } }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/536/" ] }
189,172
I'm told that the template system in C++ is Turing-complete at compile time. This is mentioned in this post and also on wikipedia . Can you provide a nontrivial example of a computation that exploits this property? Is this fact useful in practice?
Example #include <iostream>template <int N> struct Factorial{ enum { val = Factorial<N-1>::val * N };};template<>struct Factorial<0>{ enum { val = 1 };};int main(){ // Note this value is generated at compile time. // Also note that most compilers have a limit on the depth of the recursion available. std::cout << Factorial<4>::val << "\n";} That was a little fun but not very practical. To answer the second part of the question: Is this fact useful in practice? Short Answer: Sort of. Long Answer: Yes, but only if you are a template daemon. To turn out good programming using template meta-programming that is really useful for others to use (ie a library) is really really tough (though do-able). To Help boost even has MPL aka (Meta Programming Library). But try debugging a compiler error in your template code and you will be in for a long hard ride. But a good practical example of it being used for something useful: Scott Meyers has been working extensions to the C++ language (I use the term loosely) using the templating facilities. You can read about his work here ' Enforcing Code Features '
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/189172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18770/" ] }
189,190
It needs to be graphical. No sed, awk, grep, perl, whatever. I know how to use those and I do use them now, but I need to cherry-pick each replace in 300+ files. I want a tool where I can: type a search string type a replace string select a directory and file extension and it would recursively go into each file in that directory and its sub-directories, open it and scroll to the place where search string is and offer two options: replace (and find next) find next Nothing more. Reg.exp. support is a plus, but not required. SOLVED: Regexxer is exactly what I needed. In case someone needs it on Slackware, here's what you need to download and how to compile it (choosing correct version of each dependency can be a PITA)
I think regexxer is exactly what you're looking for: Regexxer regexxer is a nifty GUI search/replace tool featuring Perl-style regularexpressions. If you need project-wide substitution and you’re tired ofhacking sed command lines together, then you should definitely give it a try. See also the screenshot, looks a lot like what you're describing:
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/189190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14690/" ] }
189,209
For a long time ago, I have thought that, in java, reversing the domain you own for package naming is silly and awkward. Which do you use for package naming in your projects?
Once you understand why the convention exists, it shouldn't feel silly or awkward in the least. This scheme does two important things: All of your code is contained in packages that no one else will collide with. You own your domain name, so it's isolated. If we didn't have this convention, many companies would have a "utilities" package, containing classes like "StringUtil", "MessageUtil" etc. These would quickly collide if you tried to use anyone else's code. The "reverse" nature of it makes class-directory layout very narrow at the top level. If you expand a jar, you'll see "com", "org", "net", etc dirs, then under each of those the organization/company name. (added in 2021) This is even more important nowadays when this type of package naming is used for third-party libraries which are pulled in transitively during builds and could easily conflict if the names were not unique. If everyone adheres to the same convention, there will be no accidental collisions. (added in 2021) The same naming convention can be used for application ids on an app store to ensure uniqueness as well. We usually don't expand jars, but in early java development, this was important because people used expanded dir structures for applets. However, this is nice now as source code dir structures have a very "top-down" feel. You go from the most general (com, org, net...) to less general (company name) to more specific (project/product/lib name).
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/189209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18300/" ] }
189,213
Using the following query and results, I'm looking for the most recent entry where the ChargeId and ChargeType are unique. select chargeId, chargeType, serviceMonth from invoice CHARGEID CHARGETYPE SERVICEMONTH1 101 R 8/1/20082 161 N 2/1/20083 101 R 2/1/20084 101 R 3/1/20085 101 R 4/1/20086 101 R 5/1/20087 101 R 6/1/20088 101 R 7/1/2008 Desired: CHARGEID CHARGETYPE SERVICEMONTH1 101 R 8/1/20082 161 N 2/1/2008
You can use a GROUP BY to group items by type and id. Then you can use the MAX() Aggregate function to get the most recent service month. The below returns a result set with ChargeId, ChargeType, and MostRecentServiceMonth SELECT CHARGEID, CHARGETYPE, MAX(SERVICEMONTH) AS "MostRecentServiceMonth"FROM INVOICEGROUP BY CHARGEID, CHARGETYPE
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/189213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16345/" ] }
189,280
I use NHibernate for my dataacess, and for awhile not I've been using SQLite for local integration tests. I've been using a file, but I thought I would out the :memory: option. When I fire up any of the integration tests, the database seems to be created (NHibernate spits out the table creation sql) but interfacting with the database causes an error. Has anyone every gotten NHibernate working with an in memory database? Is it even possible? The connection string I'm using is this: Data Source=:memory:;Version=3;New=True
A SQLite memory database only exists as long as the connection to it remains open. To use it in unit tests with NHibernate: 1. Open an ISession at the beginning of your test (maybe in a [SetUp] method). 2. Use the connection from that session in your SchemaExport call. 3. Use that same session in your tests. 4. Close the session at the end of your test (maybe in a [TearDown] method).
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/189280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5802/" ] }
189,291
Odd behavior loading emacs on ubuntu, there seems to be some initialization that goes on that is not in the .emacs nor in any of the files emacs reports loading through "emacs --debug-init". I've found some references to font-related resizing but this behavior doesn't seem to be limited to that (e.g reappearing menus and toolbars). Does anyone have any additional information about the emacs initialization process?Does it load /etc/emacs/site-start.d files before or after the .emacs, and are there any other locations it loads by default?
The sequence of the Emacs initialization is the following (at least, for Emacs 22): Load the file debian-startup (.el or .elc) found in load-path (usually, /usr/share/emacs/site-lisp/debian-startup.el or /usr/share/emacs22/site-lisp/debian-startup.elc ) and call the function debian-startup defined in this file. This function loads all files in /etc/emacs/site-start.d/ and /etc/emacs22/site-start.d/ . Load site-start (.el or .elc) found in load-path . Load your init file .emacs , .emacs.el or ~/.emacs.d/init.el . Load a default init file default.el or default.elc . I also suggest you reading the section " Emacs startup strategy " in /usr/share/doc/emacsen-common/debian-emacs-policy.gz for more Ubuntu/Debian specific information. To find the reason of odd behavior you can start emacs with the argument --no-site-file and load these init files one by one until you find a file that causes this behavior.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19479/" ] }
189,293
I have a subroutine that takes a filehandle as an argument. How do I make a filehandle from a file path specified on the command line? I don't want to do any processing of this file myself, I just want to pass it off to this other subroutine, which returns an array of hashes with all the parsed data from the file. Here's what the command line input I'm using looks like: $ ./getfile.pl /path/to/some/file.csv Here's what the beginning of the subroutine I'm calling looks like: sub parse { my $handle = shift; my @data = <$handle>; while (my $line = shift(@data)) { # do stuff }}
Command line arguments are available in the predefined @ARGV array. You can get the file name from there and use open to open a filehandle to it. Assuming that you want read-only access to the file, you would do it this way: my $file = shift @ARGV;open(my $fh, '<', $file) or die "Can't read file '$file' [$!]\n";parse($fh); Note that the or die... checks the call open for success and dies with an error message if it wasn't. The built-in variable $! will contain the (OS dependent) error message on failure that tells you why the call wasn't successful. e.g. "Permission denied."
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6406/" ] }
189,350
Is there a way to find out what gcc flags a particular binary was compiled with?
A quick look at the GCC documentation doesn't turn anything up. The Boost guys are some of the smartest C++ developers out there, and they resort to naming conventions because this is generally not possible any other way (the executable could have been created in any number of languages, by any number of compiler versions, after all). (Added much later): Turns out GCC has this feature in 4.3 if asked for when you compile the code : A new command-line switch -frecord-gcc-switches ... causes the command line that was used to invoke the compiler to be recorded into the object file that is being created. The exact format of this recording is target and binary file format dependent, but it usually takes the form of a note section containing ASCII text.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/189350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2831/" ] }
189,359
I just saw Ayende's post today about PostSharp. I downloaded the code and tried it out, and I thought it was the coolest, most easy to use way to handle AOP that I've seen. In his post, Ayende says that PostSharp accomplishes it's magic via IL Weaving . Now, at some abstract level I can deduce what that means, but I wanted to see if there was a more detailed answer out there. Unfortunately, for the first time in a very long time, Google came up empty for me. And so I thought this would be a great question for StackOverflow (since I've been a subscribe to Jeff's blog for a couple years now and knew this site was doing its thing). So what exactly is IL Weaving and how is it accomplished?
Weaving refers to the process of injecting functionality into an existing program. This can be done conceptually at a number of levels: Source code weaving would inject source code lines before the code is compiled IL weaving (for .NET) adds the code as IL instructions in the assembly ByteCode weaving (for Java) works on the class file, see these comments wrt AspectJ In theory you could go one deeper and weave with an executable compiled to native instructions, but this would add a lot of complexity and I'm not aware of anything that does this.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
189,388
I would like to track metrics that can be used to improve my team’s software development process, improve time estimates, and detect special case variations that need to be addressed during the project execution. Please limit each answer to a single metric, describe how to use it, and vote up the good answers.
(source: osnews.com )
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/189388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25546/" ] }
189,391
I am looking for a way to take a user uploaded image that is currently put in a temporary location ex: /tmp/jkhjkh78 and create a php image from it, autodetecting the format. Is there a more clever way to do this than a bunch of try/catching with imagefromjpeg, imagefrompng, etc?
This is one of the functions of getimagesize . They probably should have called it "getimageinfo", but that's PHP for you.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24694/" ] }
189,422
I need to do a join across two different database servers (IPs 10.0.0.50 and 10.0.0.51). What's the best way?
You need to use sp_linkedserver to create a linked server. sp_addlinkedserver [ @server= ] 'server' [ , [ @srvproduct= ] 'product_name' ] [ , [ @provider= ] 'provider_name' ] [ , [ @datasrc= ] 'data_source' ] [ , [ @location= ] 'location' ] [ , [ @provstr= ] 'provider_string' ] [ , [ @catalog= ] 'catalog' ] More information available on MSDN .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109/" ] }
189,430
How to detect the Internet connection is offline in JavaScript?
You can determine that the connection is lost by making failed XHR requests . The standard approach is to retry the request a few times. If it doesn't go through, alert the user to check the connection, and fail gracefully . Sidenote: To put the entire application in an "offline" state may lead to a lot of error-prone work of handling state.. wireless connections may come and go, etc. So your best bet may be to just fail gracefully, preserve the data, and alert the user.. allowing them to eventually fix the connection problem if there is one, and to continue using your app with a fair amount of forgiveness. Sidenote: You could check a reliable site like google for connectivity, but this may not be entirely useful as just trying to make your own request, because while Google may be available, your own application may not be, and you're still going to have to handle your own connection problem. Trying to send a ping to google would be a good way to confirm that the internet connection itself is down, so if that information is useful to you, then it might be worth the trouble. Sidenote : Sending a Ping could be achieved in the same way that you would make any kind of two-way ajax request, but sending a ping to google, in this case, would pose some challenges. First, we'd have the same cross-domain issues that are typically encountered in making Ajax communications. One option is to set up a server-side proxy, wherein we actually ping google (or whatever site), and return the results of the ping to the app. This is a catch-22 because if the internet connection is actually the problem, we won't be able to get to the server, and if the connection problem is only on our own domain, we won't be able to tell the difference. Other cross-domain techniques could be tried, for example, embedding an iframe in your page which points to google.com, and then polling the iframe for success/failure (examine the contents, etc). Embedding an image may not really tell us anything, because we need a useful response from the communication mechanism in order to draw a good conclusion about what's going on. So again, determining the state of the internet connection as a whole may be more trouble than it's worth. You'll have to weight these options out for your specific app.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/189430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1100/" ] }
189,451
My team is trying to setup an Apache reverse proxy from a customer's site into one of our web applications. http://www.example.com/app1/some-path maps to http://internal1.example.com/some-path Inside our application we use struts and have redirect = true set on certain actions in order to provide certain functionality. The 302 status messages from these re-directs cause the user to break out of the proxy resulting in an error page for the end user. HTTP/1.1 302 Found Location: http://internal.example.com/some-path/redirect Is there any way to setup the reverse proxy in apache so that the redirects work correctly? http://www.example.com/app1/some-path/redirect
There is an article titled Running a Reverse Proxy in Apache that seems to address your problem. It even uses the same example.com and /app1 that you have in your example. Go to the "Configuring the Proxy" section for examples on how to use ProxyPassReverse .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6021/" ] }
189,490
I tried looking for the .emacs file for my Windows installation for Emacs, but I could not find it. Does it have the same filename under Windows as in Unix? Do I have to create it myself? If so, under what specific directory does it go?
Copy and pasted from the Emacs FAQ, http://www.gnu.org/software/emacs/windows/ : Where do I put my init file? On Windows, the .emacs file may be called _emacs for backward compatibility with DOS and FAT filesystems where filenames could not start with a dot. Some users prefer to continue using such a name, because Windows Explorer cannot create a file with a name starting with a dot, even though the filesystem and most other programs can handle it. In Emacs 22 and later, the init file may also be called .emacs.d/init.el . Many of the other files that are created by Lisp packages are now stored in the .emacs.d directory too, so this keeps all your Emacs related files in one place. All the files mentioned above should go in your HOME directory. The HOME directory is determined by following the steps below: If the environment variable HOME is set, use the directory it indicates. If the registry entry HKCU\SOFTWARE\GNU\Emacs\HOME is set, use the directory it indicates. If the registry entry HKLM\SOFTWARE\GNU\Emacs\HOME is set, use the directory it indicates. Not recommended, as it results in users sharing the same HOME directory. If C:\.emacs exists, then use C:/ . This is for backward compatibility, as previous versions defaulted to C:/ if HOME was not set. Use the user's AppData directory, usually a directory called Application Data under the user's profile directory, the location of which varies according to Windows version and whether the computer is part of a domain. Within Emacs, ~ at the beginning of a file name is expanded to your HOME directory, so you can always find your .emacs file with C-x C-f ~/.emacs . There's further information at HOME and Startup Directories on MS-Windows .
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/189490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ] }
189,516
For ActionScript 2, I've used NaturalDocs . However it has pretty poor support for PHP. I've looked so far at doxygen and phpDocumentor , but their output is pretty ugly in my opinion. Does anyone have any experience with automatic documentation generation for PHP? I'd prefer to be able to use javadoc-style tags, they are short to write and easy to remember.
ApiGen http://apigen.org/ ApiGen has support for PHP 5.3 namespaces, packages, linking between documentation, cross referencing to PHP standard classes and general documentation, creation of highlighted source code and experimental support for PHP 5.4 traits. DocBlox http://www.docblox-project.org/ PHP 5.3 compatible API Documentation generator aimed at projects of all sizes and Continuous Integration. able to fully parse and transform Zend Framework 2
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14569/" ] }
189,549
Is it possible to embed a pre-existing DLL into a compiled C# executable (so that you only have one file to distribute)? If it is possible, how would one go about doing it? Normally, I'm cool with just leaving the DLLs outside and having the setup program handle everything, but there have been a couple of people at work who have asked me this and I honestly don't know.
I highly recommend to use Costura.Fody - by far the best and easiest way to embed resources in your assembly. It's available as NuGet package. Install-Package Costura.Fody After adding it to the project, it will automatically embed all references that are copied to the output directory into your main assembly. You might want to clean the embedded files by adding a target to your project: Install-CleanReferencesTarget You'll also be able to specify whether to include the pdb's, exclude certain assemblies, or extracting the assemblies on the fly. As far as I know, also unmanaged assemblies are supported. Update Currently, some people are trying to add support for DNX . Update 2 For the lastest Fody version, you will need to have MSBuild 16 (so Visual Studio 2019). Fody version 4.2.1 will do MSBuild 15. (reference: Fody is only supported on MSBuild 16 and above. Current version: 15 )
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/189549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5133/" ] }
189,552
I'm trying to host a subdomain for my site with a different hosting company and I'm running into issues on how to set it up. Here are the specifics: Domain is registered with GoDaddy. Nameservers are pointing to DiscountASP.net where ASP.NET app has been happily running for couple of years. Would like blog.mydomain.example to point to my account with DreamHost.com to take advantage of their LAMP stack. I have added blog.mydomain.example to DreamHost (after adding mydomain.example ) via their control panel. I thought I would be able to add a subdomain entry on GoDaddy to point to DreamHost, but all they allow is blog.mydomain.example = new URL. In theory I could just take our .biz or .net domain and host it on DreamHost but was hoping I could do it all with a subdomain. So, to summarize I'd like to know if what I want to do is feasible and if so, how do I go about it (given the constraints of GoDaddy, DiscountASP, & DreamHost).
A sub domain is part of the domain, it's like subletting a room of an apartment. A records has to be setup on the DNS for the domain e.g mydomain.example has IP 123.456.789.999 and hosted with Godaddy. Now to get the sub domain anothersite.mydomain.example of which the site is actually on another server then login to Godaddy and add an A record dnsimple anothersite.mydomain.example and point the IP to the other server 98.22.11.11 And that's it.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/189552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3262/" ] }
189,555
I want to download and parse webpage using python, but to access it I need a couple of cookies set. Therefore I need to login over https to the webpage first. The login moment involves sending two POST params (username, password) to /login.php. During the login request I want to retrieve the cookies from the response header and store them so I can use them in the request to download the webpage /data.php. How would I do this in python (preferably 2.6)? If possible I only want to use builtin modules.
import urllib, urllib2, cookielibusername = 'myuser'password = 'mypassword'cj = cookielib.CookieJar()opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))login_data = urllib.urlencode({'username' : username, 'j_password' : password})opener.open('http://www.example.com/login.php', login_data)resp = opener.open('http://www.example.com/hiddenpage.php')print resp.read() resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/189555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26668/" ] }
189,559
Conditions: do not modify the original lists; JDK only, no external libraries. Bonus points for a one-liner or a JDK 1.3 version. Is there a simpler way than: List<String> newList = new ArrayList<String>();newList.addAll(listOne);newList.addAll(listTwo);
In Java 8: List<String> newList = Stream.concat(listOne.stream(), listTwo.stream()) .collect(Collectors.toList()); Java 16+: List<String> newList = Stream.concat(listOne.stream(), listTwo.stream()).toList();
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/189559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17294/" ] }
189,562
There are many ways of doing debugging, using a debugger is one, but the simple one for the humble, lazy, programmer is to just add a bunch of print statements to your code. i.e. def foo(x): print 'Hey wow, we got to foo!', x ... print 'foo is returning:', bar return bar Is there a proper name for this style of debugging?
Yes - it's known as printf() debugging , named after the ubiquitous C function: Used to describe debugging work done by inserting commands that output more or less carefully chosen status information at key points in the program flow, observing that information and deducing what's wrong based on that information. -- printf() debugging@everything2 Native users of other languages no doubt refer to it by the default print / log / or trace command available for their coding platform of choice, but i've heard the "printf()" name used to refere to this technique in many languages other than C. Perhaps this is due to its history: while BASIC and FORTRAN had basic but serviceable PRINT commands, C generally required a bit more work to format various data types: printf() was (and often still is) by far the most convenient means to this end, providing many built-in formatting options. Its cousin, fprintf() , takes another parameter, the stream to write to: this allowed a careful "debugger" to direct diagnostic information to stderr (possibly itself redirected to a log file) while leaving the output of the program uncorrupted. Although often looked down on by users of modern debugging software, printf() debugging continues to prove itself indispensable: the wildly popular FireBug tool for the Firefox web browser (and similar tools now available for other browsers) is built around a console window into which web page scripts can log errors or diagnostic messages containing formatted data.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/189562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14648/" ] }
189,621
I am wondering if someone can put a bit of an authoritative reference summary of when the !important declaration in CSS does not work to override inline styles.
There are many factors involved in determining which styles override one another. The lower a style declaration appears in the cascade , and the more specific it is in targeting the element, the more it will weigh against other styles. This is the CSS2 standard for style inheritance: If the cascade results in a value, use it. Otherwise, if the property is inherited, use the value of the parent element, generally the computed value. Otherwise use the property's initial value. The initial value of each property is indicated in the property's definition. Internally, the browser will calculate the specificity of a rule , according to the standard. The !important declaration will add weight to the rule, but dynamically assigning a style attribute will often take precedence, because it is usually more-highly specified..
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ] }
189,622
I frequently encounter some definitions for Win32API structures (but not limited to it) that have a cbSize member as in the following example. typedef struct _TEST { int cbSize; // other members follow} TEST, *PTEST; And then we use it like this: TEST t = { sizeof(TEST) };... or TEST t;t.cbSize = sizeof(TEST);... My initial guess is that this could potentially be used for versioning. A DLL that receives a pointer for a struct like this can check if the cbSize member has the expected value with which the DLL was compiled. Or to check if proper packing is done for the struct. But I would like to here from you. What is the purpose of the cbSize member in some C++ structures on Win32API?
My initial guess is that this could potentially be used for versioning. That's one reason. I think it's the more usual one. Another is for structures that have variable length data. I don't think that checking for correct packing or bugs in the caller are a particular reasoning behind it, but it would have that effect.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6508/" ] }
189,644
I'm developing an application for an internal customer. One of the requirements is that it be developed in such a way that it could potentially be sold to other organizations. The application is a tracking application for a fund-raising organization that will manage their donations, donors, participants, and events. I already know that I'll need to develop a plugin architecture for authentication (authorization will be handled internally) and to derive demographic data from an external directory. The application will be built on ASP.NET/C#/Linq/SQL Server. At this point I'm not really open to supporting alternative databases, but I'm thinking I could do this in the future via different Linq drivers, if necessary. All of the web applications that I've built to date have been custom implementations so I'd like to know if there are other things that I need to address via plugins and/or configuration items. Any input would be helpful. Thanks.
I want to caution you against trying to make the "do everything" framework. This is a common mistake that a lot of developers make when trying to build their first few mass-market software apps. You have a customer already, and they are likely bankrolling the initial version of the application. You need to deliver as much of what this customer needs as fast as you can or it fails before you even get to thinking about the mass-market. Do yourself a favor and expect that this is the only customer that will EVER use or buy the application. Design your application pretty much the exact same as you would have designed any of your other custom apps in the past. All you need to do in order to scale it out to other customers later is to stick to the stock asp.net features and functionality as much as possible, keep it as simple and lean as possible, and cut as many "advanced" features from version 1.x as you can get away with. 1.x will be your proving ground. Make sure you deliver an application that does what your initial customer needs it to do and that it does it exceedingly well. If you are successful, and 1.x does actually meet most of your initial customer's requirements then you will know you also have an application that will meet most of the needs of any of your customers. Congratulations, you are already most of the way towards having a viable commercial market application! Things to watch out for: Do you really need to support multiple database platforms? Sure, you might have "some" customers that might "prefer" MySql to SQL Server. You will be tempted to try and write some magic DAL that can support Oracle, MySQL, VistaDB, SQL Server, etc. just by changing some config options or making the right selection in an installer. But the fact is that this kind of "platform" neutrality adds massive complexity to your design and imposes severe limitations on what features you take advantage of. Things like the provider design pattern may fool you into thinking that this kind of design isn't so hard... but you would be wrong. Be pragmatic and design your application so that it will be acceptable to 90% of your potential market. With data access in particular it is generally safe to say that 90% or more of the market willing to install and run an ASP.NET application are also capable and willing to use SQLExpress or SQL Server. In most cases You will save much more money and time by designing for just SQL server than you will ever make in additional sales from supporting multiple databases. Try to avoid making "everything" configurable via online admin tools. For example, you will be tempted to have ALL text in the application configurable by admin tools. That's great, but it is also expensive. It takes longer to develop, requires that you increase the scope of your application to include a whole mess of admin tools that you wouldn't have otherwise needed, and it makes the application more complex and difficult to use for the 90% of your customers that don't mind the default text. Carefully consider localization. If you don't think you will have a large international market stick to one language. Localization isn't too hard, but it does complicate every aspect of your code a little... and that adds up to a lot in any application of any size at all. My rule of thumb is to target only the language of my initial market. If the app has interest in other markets then I go back and do localization in version 2.x after I recoup some cash from version 1.0 and prove the application has a viable market in the first place. But if you know you will be in more than one language or culture, support localization from the very beginning. For version 1.0, don't worry too much about drop-in modules or fancy service APIs. If you already had a lot of experience in reusable frameworks you would be able to have this stuff in version 1.0, but if you lack experience in this kind of architectures you will just waste too much time on these features in version 1.x and you will likely still get it wrong and have to re-architect in version 2.x anyway. Make sure the application has REALLY good reporting. For the kind of application you are talking about, this will be what decides if the application even has a market at all. You need pretty reports that are not only sortable/filterable on screen, but are also printable. Put your money and time into this out of the gate.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/189644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12950/" ] }
189,645
Given the following code (that doesn't work): while True: # Snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok.lower() == "y": break 2 # This doesn't work :( if ok.lower() == "n": break # Do more processing with menus and stuff Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?
My first instinct would be to refactor the nested loop into a function and use return to break out.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/189645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ] }
189,725
During recent discussions at work, someone referred to a trampoline function. I have read the description at Wikipedia . It is enough to give a general idea of the functionality, but I would like something a bit more concrete. Do you have a simple snippet of code that would illustrate a trampoline?
There is also the LISP sense of 'trampoline' as described on Wikipedia: Used in some LISP implementations, a trampoline is a loop that iteratively invokes thunk-returning functions. A single trampoline is sufficient to express all control transfers of a program; a program so expressed is trampolined or in "trampolined style"; converting a program to trampolined style is trampolining. Trampolined functions can be used to implement tail recursive function calls in stack-oriented languages Let us say we are using Javascript and want to write the naive Fibonacci function in continuation-passing-style. The reason we would do this is not relevant - to port Scheme to JS for instance, or to play with CPS which we have to use anyway to call server-side functions. So, the first attempt is function fibcps(n, c) { if (n <= 1) { c(n); } else { fibcps(n - 1, function (x) { fibcps(n - 2, function (y) { c(x + y) }) }); }} But, running this with n = 25 in Firefox gives an error 'Too much recursion!'. Now this is exactly the problem (missing tail-call optimization in Javascript) that trampolining solves. Instead of making a (recursive) call to a function, let us return an instruction (thunk) to call that function, to be interpreted in a loop. function fibt(n, c) { function trampoline(x) { while (x && x.func) { x = x.func.apply(null, x.args); } } function fibtramp(n, c) { if (n <= 1) { return {func: c, args: [n]}; } else { return { func: fibtramp, args: [n - 1, function (x) { return { func: fibtramp, args: [n - 2, function (y) { return {func: c, args: [x + y]} }] } } ] } } } trampoline({func: fibtramp, args: [n, c]});}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/189725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ] }
189,726
Have had to write my first "proper" multithreaded coded recently, and realised just how little I knew about how "imperative-style" (ie, concurrency models used by C++/C#/Java, and the like) concurrent programming techniques. What resources are there (both books and online tutorials, etc) in order to learn more about this area of coding-fu? NB: I'm not asking about concurrency models that are arguably better (Erlang's message passing, or Clojure's STM), just paradigms used in imperative languages.
Patterns for Parallel Porgramming is a good general book on concurrent programming techniques. It uses Java threads, OpenMP in C and MPI in C for the examples. Pretty much any decent book on multithreaded programming in any of the languages you mention should cover the general principles. I'm covering this ground in C++ Concurrency in Action , for example.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10569/" ] }
189,751
I've setup a static website on GAE using hints found elsewhere, but can't figure out how to return a 404 error. My app.yaml file looks like - url: (.*)/ static_files: static\1/index.html upload: static/index.html- url: / static_dir: static with all the static html/jpg files stored under the static directory. The above works for files that exist, but returns a null length file if they don't. The answer is probably to write a python script to return a 404 error, but how do you set things up to serve the static files that exist but run the script for files that don't? Here is the log from fetching a non-existent file (nosuch.html) on the development application server: ERROR 2008-11-25 20:08:34,084 dev_appserver.py] Error encountered reading file "/usr/home/ctuffli/www/tufflinet/static/nosuch.html":[Errno 2] No such file or directory: '/usr/home/ctuffli/www/tufflinet/static/nosuch.html'INFO 2008-11-25 20:08:34,088 dev_appserver.py] "GET /nosuch.html HTTP/1.1" 404 -
You need to register a catch-all script handler. Append this at the end of your app.yaml: - url: /.* script: main.py In main.py you will need to put this code: from google.appengine.ext import webappfrom google.appengine.ext.webapp.util import run_wsgi_appclass NotFoundPageHandler(webapp.RequestHandler): def get(self): self.error(404) self.response.out.write('<Your 404 error html page>')application = webapp.WSGIApplication([('/.*', NotFoundPageHandler)], debug=True)def main(): run_wsgi_app(application)if __name__ == "__main__": main() Replace <Your 404 error html page> with something meaningful. Or better use a template, you can read how to do that here . Please let me know if you have problems setting this up.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/189751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26683/" ] }
189,757
Just wondering if a .NET app can be compiled down to native machine code ahead of time? I'm not planning on doing so even if I could; I'm just curious. Thanks
You can use NGen to compile it ahead of time, but this still depends on the .NET framework. Remotesoft's Salamander (a commercial app) can make a framework-less app.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ] }
189,765
I have a query that ran fine on SQL2005 but moving the database to SQL2008 gives me the error from the title. The code that is the problem is a call to CONTAINS, CONTAINSTABLE or FREETEXT with an empty parameter. However I'm trying to only call or join when there is a value like such where (@search_term = '' or (FREETEXT(lst.search_text, @search_term))) or left join containstable (listing_search_text, search_text, @search_term) ftb on l.listing_id = ftb.[key] and len(@search_term) > 0 However I cannot find any workaround for this to work on SQL2008. Any ideas? I know I can do dynamic SQL or have a if statement with two different cases (select with FT join, select without FT join. Any better workaround which doesn't require doing this?
I found the answer to this today when converting my own database from SQL 2005 to SQL 2008. Pass "" for your search term and change the @search_term = '' test to be @search_term = '""' SQL server will ignore the double quotes and not throw an error. For example, the following would actually returns all records in the Users table: declare @SearchTerm nvarchar(250)SET @SearchTerm = '""'select UserId, U.Description, U.UserNamefrom dbo.Users UWHERE ((@SearchTerm = '""') OR CONTAINS( (U.Description, U.UserName), @SearchTerm)) If you are using .Net, you might grab a copy of E. W. Bachtal's FullTextSearch class. His site is very informative: http://ewbi.blogs.com/develops/
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/189765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6084/" ] }
189,770
How would you go about retrieving the @@IDENTITY value for each row when the SQLDataAdapater.Update is executed on a table? eg. Is it possible to modify/intercept the InsertCommand, generated by the SQLCommandBuilder, to say add an output parameter, and then retrieve its value in the da.RowUpdated event???
I found the answer to this today when converting my own database from SQL 2005 to SQL 2008. Pass "" for your search term and change the @search_term = '' test to be @search_term = '""' SQL server will ignore the double quotes and not throw an error. For example, the following would actually returns all records in the Users table: declare @SearchTerm nvarchar(250)SET @SearchTerm = '""'select UserId, U.Description, U.UserNamefrom dbo.Users UWHERE ((@SearchTerm = '""') OR CONTAINS( (U.Description, U.UserName), @SearchTerm)) If you are using .Net, you might grab a copy of E. W. Bachtal's FullTextSearch class. His site is very informative: http://ewbi.blogs.com/develops/
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/189770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1885/" ] }
189,780
I have an odd problem...I'm using a documentation generator which generates a lot of output like docs/foo.php.html. It's XHTML, and thus contains <?xml...> tags at the beginning of file. The problem is, Apache has somehow decided to run it through the PHP interpreter, even though ".php" appears in the middle of the filename, and not at the end. This, in turn, triggers a PHP error, because it sees " <? " as the command to start executing PHP code, and immediately gets confused by the " xml... " which follows it. How do I configure Apache to ONLY execute .php files and not .php.html files? The string "php.html" does not appear explicitly anywhere in my Apache config files. There is a line " AddHandler php5-script .php ", but I don't see how that would also include ".php.html" files.
The problem seems to be in mod_mime . Quote from the Apache mod_mime documentation page: If you would prefer only the last dot-separated part of the filename to be mapped to a particular piece of meta-data, then do not use the Add* directives. For example, if you wish to have the file foo.html.cgi processed as a CGI script, but not the file bar.cgi.html, then instead of using AddHandler cgi-script .cgi, use <FilesMatch \.cgi$> SetHandler cgi-script </FilesMatch> Also, you can google for apache mod_mime "multiple extensions"
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14569/" ] }
189,787
I have never seen a way to do this nicely, i would be interested in seeing how others do it. Currently i format it like this: public Booking createVehicleBooking(Long officeId, Long start, Long end, String origin, String destination, String purpose, String requirements, Integer numberOfPassengers) throws ServiceException {/*..Code..*/}
A large set of parameters like this is often (but not always) an indicator that you could be using an object to represent the parameter set. This is especially true if either: There are several methods with similar large parameter sets, that can be replaced with a single method taking a parameter object. The method is called create... So your above code could become (pardon my C++, I'm a Java developer): class BuildVehicleBooking { Long officeId; Long start; Long end; String origin; String destination; String purpose; String requirements; Integer numberOfPassengers; Booking createVehicleBooking () throws ServiceException { ... }} This is the Builder Pattern . The advantage of this pattern is that you can build up a complex set of parameters in pieces, including multiple variations on how the parameters relate to each other, and even overwriting parameters as new information becomes available, before finally calling the create method at the end. Another potential advantage is that you could add a verifyParameters method that checked their consistence before you go as far as creating the final object. This is applicable in cases where creating the object involves non-reversible steps, such as writing to a file or database. Note that, as with all patterns, this doesn't apply in every case and may not apply in yours. If your code is simple enough then this pattern may be over-engineering it. If the code is getting messy, refactoring into this pattern can be a good way to simplify it.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/189787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24390/" ] }
189,791
Compared to most people on this site I am admittedly a novice. I wanted to get some advice from the pros on how to avoid making stupid errors in your code. Is there anyone else who had the problem when they were first starting out of missing some detail that causes big problems? Are there any habits or behaviors that helped you over come this.
Here's a list of common pitfalls, and/or suggestions to avoid them: Experience, the best way to avoid mistakes is to have already had them happen to you. Review other people's code Have other people review your code Use source control, even if you are the only developer Review all of your changes before doing a commit to source control Consider using a more modern language that makes it harder for you to make mistakes Comment your code extensively Refactor your code early and often Fix bugs before adding features Create extensive test cases, because knowing about your mistakes help you avoid future ones faster. Learn and use design patterns. Avoid code duplication at all costs, try to never copy/paste blocks of code Read about specific common pitfalls in the programming language you're using
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/189791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25012/" ] }