Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a friend who is need of a web page. He does interior construction, and would like to have a gallery of his work. I'll probably go for a php host, and was thinking about the best way to implement the image gallery for him. I came up with: * Use flickr to host the images. They can be tagged, added to sets, and I ...
It sounds like a difficult way to do things - have you considered [Gallery](http://gallery.menalto.com/) (No points on creativity for the name!). Unless you're really wanting to save on bandwidth, I think you'd get much better results from installing some pre-built gallery.
The perfect solution for this kind of thing is [Picasa](http://www.picasa.com) (from Google ofcourse) You get: * 1gb of free storage space on a Google Picasaweb account that already has a web interface with embeddable slideshows and stuff * A compete image browse and upoad program for the client side (namely Picasa) ...
Quickest way to implement a searchable, browsable image gallery - flickr integration?
[ "", "php", "flickr", "image-gallery", "" ]
I need to determine the highest .NET framework version installed on a desktop machine from C\C++ code. Looks like I can iterate the folders under `%systemroot%\Microsoft.NET\Framework`, but that seems kind of error prone. Is there a better way? Perhaps a registry key I can inspect? Thanks.
Use the [Windows Registry](http://en.wikipedia.org/wiki/Windows_Registry) location `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP`.
Registry keys for the .NET Framework start like this: ``` HKEY_LOCAL_MACHINE\Software\Microsoft\NET Framework Setup\NDP\ ``` Depending on the version, the rest of the key will be different (check [this page](http://www.walkernews.net/2007/07/30/how-to-verify-dot-net-framework-version/)). You can look up how to acces...
Determine highest .NET Framework version
[ "", ".net", "c++", "c", "version-detection", "" ]
I want to draw DirectX content so that it appears to be floating over top of the desktop and any other applications that are running. I also need to be able to make the directx content semi-transparent, so other things show through. Is there a way of doing this? I am using Managed DX with C#.
I found a solution which works on Vista, starting from the link provided by OregonGhost. This is the basic process, in C# syntax. This code is in a class inheriting from Form. It doesn't seem to work if in a UserControl: ``` //this will allow you to import the necessary functions from the .dll using System.Runtime.Int...
You can either use DirectComposition, LayeredWindows, DesktopWindowManager or WPF. All methods come with their advantages and disadvantages: -DirectComposition is the most efficient one, but needs Windows 8 and is limited to 60Hz. -LayeredWindows are tricky to get working with D3D via Direct2D-interop using DXGI. -W...
How do I draw transparent DirectX content in a transparent window?
[ "", "c#", "windows", "directx", "transparent", "direct3d", "" ]
How can I write from Java to the Windows Event Log?
**EDIT (2023)**: See JNA <https://stackoverflow.com/a/3815771/3937> ### Old answer Log4J is a Java-based logging utility. The class `NTEventLogAppender` can be used to "append to the NT event log system". See the documentation here: <http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/nt/NTEventLogAppender....
You can use [JNA](https://github.com/twall/jna/) to write to the Event Log directly without the need of any native DLLs. See Advapi32 and Advapi32Util classes for various event log methods (ships since JNA 3.2.8). If you're using Log4j, consider [Log4jna](https://github.com/dblock/log4jna) instead of NTEventLogAppende...
How to write from Java to the Windows Event Log?
[ "", "java", "windows", "logging", "event-log", "" ]
I have a fairly large codebase that depends on MooTools v1.11 and am about to convert to version 1.2. Since this is a pretty major overhaul, I've toyed with the idea of converting to jQuery. Anyone have advice on whether to update to jQuery or just stick with MooTools? I mostly use MooTools for Ajax, drag and drop, a...
If you're upgrading *anyway*, then it may be worth looking into. jQuery seems to be well on its way to becoming the One True Javascript library (given that MS and others have decided to embrace it), so if this is code you intend to work on for a while, then it's probably a good idea to switch at some point (if only be...
If it's not broken. Don't fix it. jQuery might have X or Y but if everything is dependent on MooTools, you might have a lot of work ahead of you to convert from MooTools. Keep MooTools if you used it extensively through out your site. However, if you only have 2-3 pages with minor effects... the change might be worth...
Should I convert from MooTools to jQuery?
[ "", "javascript", "jquery", "mootools", "" ]
Is there any way to format a string by name rather than position in C#? In python, I can do something like this example (shamelessly stolen from [here](http://docs.python.org/lib/typesseq-strings.html)): ``` >>> print '%(language)s has %(#)03d quote types.' % \ {'language': "Python", "#": 2} Python has 002 quot...
There is no built-in method for handling this. [Here's one method](http://mo.notono.us/2008/07/c-stringinject-format-strings-by-key.html) ``` string myString = "{foo} is {bar} and {yadi} is {yada}".Inject(o); ``` [Here's another](http://james.newtonking.com/archive/2008/03/29/formatwith-2-0-string-formatting-with-na...
I have an implementation I just posted to my blog here: <http://haacked.com/archive/2009/01/04/fun-with-named-formats-string-parsing-and-edge-cases.aspx> It addresses some issues that these other implementations have with brace escaping. The post has details. It does the DataBinder.Eval thing too, but is still very fa...
Named string formatting in C#
[ "", "c#", ".net-3.5", "string-formatting", "" ]
The output we get when printing C++ sources from Eclipse is rather ugly. Is there are way/a plugin to pretty print C++ source code like e.g. with a2ps (which is probably using yet another filter for C source code)?
I also use `enscript` for this. Here's an alias I often use: ``` alias cpp2ps='enscript --color --pretty-print=cpp --language=PostScript' ``` and I use it like this: ``` cpp2ps -P main.ps main.cpp ``` There are several other great options in `enscript` including rotating, 2-column output, line numbers, headers/foot...
See this [DDJ](http://www.ddj.com/cpp/197002115?pgno=4) article which uses *enscript* as the pretty print engine.
Eclipse C++ pretty printing?
[ "", "c++", "eclipse", "printing", "eclipse-cdt", "" ]
Okay, we know that the following two lines are equivalent - 1. `(0 == i)` 2. `(i == 0)` Also, the first method was encouraged in the past because that would have allowed the compiler to give an error message if you accidentally used '=' instead of '=='. My question is - in today's generation of pretty slick IDE's an...
I prefer the second one, (i == 0), because it feel much more natural when reading it. You ask people, "Are you 21 or older?", not, "Is 21 less than or equal to your age?"
It doesn't matter in C# if you put the variable first or last, because assignments don't evaluate to a bool (or something castable to bool) so the compiler catches any errors like "if (i = 0) EntireCompanyData.Delete()" So, in the C# world at least, its a matter of style rather than desperation. And putting the variab...
How to check for equals? (0 == i) or (i == 0)
[ "", "c++", "c", "coding-style", "" ]
Well, after a long time writing .net programs in C# I started to feel angry and frustrated about all that syntactic trash that comes with statically typed languages. Now I want to change to dynamically typed languages, that takes advantage of CLI. So I searched a bit around and I didn't like of what I saw. I first look...
I'd still use [**Boo**](http://boo.codehaus.org/). I'm not sure why you believe Boo has been halted. Development sometimes seems slow, but there are multiple people currently working on bug fixes as demonstrated by [**this list of recently fixed issues (bugs)**](http://jira.codehaus.org/sr/jira.issueviews:searchrequest...
In terms of practical usability **[IronPython](http://www.codeplex.com/IronPython)** is going to be your best bet right now. Why are people suggesting Boo? It's a statically typed language, which is not what this question is asking for. Yes, I know it has optional duck typing, but really if Boo-related information is ...
Good dynamic programming language for .net recommendation
[ "", "c#", ".net", "ironpython", "boo", "" ]
ReSharper Code cleanup feature (with "[reorder members](http://www.jetbrains.com/resharper/features/code_formatting.html#Reordering_Type_Members_C#_only)" and "[reformat code](http://www.jetbrains.com/resharper/features/code_formatting.html#Code_Style_Configuration_and_Sharing)" enabled) is really great. You define a l...
Yes, it will definitely cause problems. In addition to creating conflicts that have to be manually resolved, when you check in a file that has been reformatted, the VCS will note almost every line as having been changed. This will make it hard for you or a teammate to look back at the history and see what changed when....
I'm waiting for an IDE or an editor that always saves source code using some baseline formatting rules, but allows each individual developer to display and edit the code in their own preferred format. That way I can put my open curly brace at the beginning of the next line and not at the end of the current line where a...
ReSharper Code Cleanup/Reformat Code feature vs Versioning Control Systems
[ "", "c#", "version-control", "resharper", "" ]
I'm trying to create a character generation wizard for a game. In one class I calculate the attributes of the character. In a different class, I'm displaying to the user which specialties are available based on the attributes of the character. However, I can't remember how to pass variables between different classes. ...
You may have "Class" and "Instance" confused. It's not clear from your example, so I'll presume that you're using a lot of class definitions and don't have appropriate object instances of those classes. Classes don't really have usable attribute values. A class is just a common set of definitions for a collection of o...
Each page of a Wizard -- by itself -- shouldn't actually be the container for the information you're gathering. Read up on the [Model-View-Control](http://en.wikipedia.org/wiki/Model-view-controller) design pattern. Your pages have the View and Control parts of the design. They aren't the data model, however. You'll ...
Python-passing variable between classes
[ "", "python", "oop", "variables", "wxpython", "" ]
im trying to locate the position of the minimum value in a vector, using STL find algorithm (and the min\_element algorithm), but instead of returning the postion, its just giving me the value. E.g, if the minimum value is it, is position will be returned as 8 etc. What am I doing wrong here? ``` int value = *min_elem...
`min_element` already gives you the iterator, no need to invoke `find` (additionally, it's inefficient because it's twice the work). Use `distance` or the `-` operator: ``` cout << "min value at " << min_element(v2.begin(), v2.end()) - v2.begin(); ```
Both algorithms you're using return iterators. If you dereference an iterator, you get the object which is "pointed" by this iterator, which is why you print the *value* and not the *position* when doing > ``` > cout << "min value at position " << *find(v2.begin(), v2.end(), value); > ``` An iterator can be seen as a...
Position in Vector using STL
[ "", "c++", "stl", "" ]
I have the following in my Global.asax.cs ``` routes.MapRoute( "Arrival", "{partnerID}", new { controller = "Search", action = "Index", partnerID="1000" } ); routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); ``` My SearchContro...
IIS 5.1 interprets your url such that its looking for a folder named 1000 under the folder named Test. Why is that so? > This happens because IIS 6 only > invokes ASP.NET when it sees a > “filename extension” in the URL that’s > mapped to aspnet\_isapi.dll (which is a > C/C++ ISAPI filter responsible for > invoking AS...
If you are doing this on Windows XP, then you're using IIS 5.1. You need to get ASP.Net to handle your request. You need to either add an extension to your routes ({controller}.mvc/{action}/{id}) and map that extension to ASP.Net or map all requests to ASP.Net. The <http://localhost/Test> works because it goes to Defau...
ASP.NET MVC in a virtual directory
[ "", "c#", "asp.net-mvc", "model-view-controller", "iis-5", "" ]
A friend of mine has embedded a google earth plugin into a C# user control. All works fine but when you close the window we recieve and "Unspecified Error" with the option to continue running the scripts or not. From our tracking it down it appears this is being cause by a script that google is dropping onto the page. ...
Here is an example, by me, of c#/Google Earth API integration that covers the problem you are having (see the comments) <http://fraserchapman.blogspot.com/2008/08/google-earth-plug-in-and-c.html> Also, here is another of my projects that uses COM Google Earth Plugin Type Library (plugin\_ax.dll) converted into the equ...
We have now tried this in both IE and FF. Works fine. Any ideas why the error only comes up on close? can we somehow disable it? here is our code. ``` <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <html> <head> <script src="http://www.google.com/jsapi?key=ABQIAAAAzghEPRV_D0MDzTELJ4nkXBT2AlV...
C# Google Earth Error
[ "", "c#", "controls", "google-earth-plugin", "" ]
Suppose that two tables exist: `users` and `groups`. **How does one provide "simple search" in which a user enters text and results contain both users and groups whose names contain the text?** The result of the search must distinguish between the two types.
The trick is to combine a `UNION` with a literal string to determine the type of 'object' returned. In most (?) cases, UNION ALL will be more efficient, and should be used unless duplicates are required in the sub-queries. The following pattern should suffice: ``` SELECT "group" type, name FROM groups WHERE name...
If you use "UNION ALL" then the db doesn't try to remove duplicates - you won't have duplicates between the two queries anyway (since the first column is different), so UNION ALL will be faster. (I assume that you don't have duplicates inside each query that you want to remove)
How do I perform a simple one-statement SQL search across tables?
[ "", "sql", "search", "" ]
Does anyone have experience with [**LLVM**](http://llvm.org/), [**llvm-gcc**](http://dragonegg.llvm.org/), or [**Clang**](http://clang.llvm.org/)? The whole idea behind llvm seems very intriguing to me and I'm interested in seeing how it performs. I just don't want to dump a whole lot of time into trying the tools out...
I've had an initial play around with LLVM and working through [this tutorial](http://llvm.org/docs/tutorial/LangImpl1.html) left me very very excited about it's potential; the idea that I can use it to build a JIT into an app with relative ease has me stoked. I haven't gone deep enough to be able to offer any kind of ...
I can't say enough good things about LLVM. It is so easy to work with compared to other compiler projects I have looked at. I am not a compiler guy, but when I get frustrated with some limitation of LLVM or clang it is usually pretty easy to dive in and change it. We (Nate Begeman, myself, and a few others) wrote the ...
What are the greatest benefits of LLVM?
[ "", "c++", "c", "llvm", "clang", "" ]
**I do not currently have this issue**, but you never know, and thought experiments are always fun. **Ignoring the obvious problems that you would have to have with your architecture to even be attempting this**, let's assume that you had some horribly-written code of someone else's design, and you needed to do a bunc...
It's pretty obvious that you'd write the code in VB.NET, which actually does have [On Error Resume Next](http://msdn.microsoft.com/en-us/library/5hsw66as.aspx), and export it in a DLL to C#. Anything else is just being a glutton for punishment.
``` public delegate void VoidDelegate(); public static class Utils { public static void Try(VoidDelegate v) { try { v(); } catch {} } } Utils.Try( () => WidgetMaker.SetAlignment(57) ); Utils.Try( () => contactForm["Title"] = txtTitle.Text ); Utils.Try( () => Casserole.Season(true, false) ); Util...
Try-catch every line of code without individual try-catch blocks
[ "", "c#", "try-catch", "expression-trees", "" ]
Many languages have standard repositories where people donate useful libraries that they want others to have access to. For instance Perl has CPAN, PHP has PEAR, Ruby has RubyGems, and so on. What is the best option for JavaScript? I ask because a few months ago I ported [Statistics::Distributions](http://search.cpan....
AFAIK, there is no central JavaScript repository, but you might have success promoting it on [Snipplr](http://snipplr.com/) or as a project on [Google Code](http://code.google.com/).
[JSAN (JavaScript Archive Network)](http://openjsan.org) sounds like the kind of thing you're looking for, but I've never personally used anything from it apart from Test.Builder. As long as your JavaScript can be dropped in to people's projects without polluting the global namespace or doing things which are liable t...
What JavaScript Repository should I use?
[ "", "javascript", "open-source", "" ]
How do I locate resources on the classpath in java? Specifically stuff that ends in .hbm.xml. My goal is to get a List of all resources on the classpath that end with ".hbm.xml".
You have to get a [classloader](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#getContextClassLoader()), and test whether it's a URLClassLoader. If so, downcast and [get its URLs](http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLClassLoader.html#getURLs()). From there, open each as a JarFile and look ...
Method `findClasses` from our `ClassLoaderUtil` might be a good starting point to adapt to your needs. ``` public class ClassLoaderUtil { /** * Recursive method used to find all classes in a given path (directory or zip file url). Directories * are searched recursively. (zip files are * Adapted fr...
How do I locate resources on the classpath in java? Specifically stuff that ends in .hbm.xml
[ "", "java", "" ]
Is there any easy way to retrieve table creation DDL from Microsoft Access (2007) or do I have to code it myself using VBA to read the table structure? I have about 30 tables that we are porting to Oracle and it would make life easier if we could create the tables from the Access definitions.
Thanks for the other suggestions. While I was waiting I wrote some VBA code to do it. It's not perfect, but did the job for me. ``` Option Compare Database Public Function TableCreateDDL(TableDef As TableDef) As String Dim fldDef As Field Dim FieldIndex As Integer Dim fldName As String, fld...
I've done this: There's a tool for "upsizing" from Access to SQL Server. Do that, then use the excellent SQL Server tools to generate the script. <http://support.microsoft.com/kb/237980>
Table Creation DDL from Microsoft Access
[ "", "sql", "ms-access", "" ]
I know Googling I can find an appropriate answer, but I prefer listening to your personal (and maybe technical) opinions. **What is the main reason of the difference between Java and C# in throwing exceptions?** In Java the signature of a method that throws an exception has to use the "throws" keyword, while in C# ...
Because the response to checked exceptions is almost always: ``` try { // exception throwing code } catch(Exception e) { // either log.error("Error fooing bar",e); // OR throw new RuntimeException(e); } ``` If you actually know that there is something you can do if a particular exception is thrown, then...
In the article [The Trouble with Checked Exceptions](http://www.artima.com/intv/handcuffs.html) and in Anders Hejlsberg's (designer of the C# language) own voice, there are three main reasons for C# not supporting checked exceptions as they are found and verified in Java: * **Neutral on Checked Exceptions** > “C# i...
Why are Exceptions not Checked in .NET?
[ "", "java", ".net", "exception", "" ]
I have a class in system-C with some data members as such: ``` long double x[8]; ``` I'm initializing it in the construction like this: ``` for (i = 0; i < 8; ++i) { x[i] = 0; } ``` But the first time I use it in my code I have garbage there. Because of the way the system is built I can't connect a debugger ea...
You could try starting a second thread which spins, looking for changes in the variable: ``` #include <pthread.h> void *ThreadProc(void *arg) { volatile long double *x = (volatile long double *)arg; while(1) { for(int i = 0; i < 8; i++) { if(x[i] != 0) { __asm__ __volatile__ ("int 3"...
Just use [printk/syslog](http://linux.die.net/man/2/syslog). It's old-fashioned, but super duper easy.
Can I set a data breakpoint in runtime in System C (or in Plain Vanilla C++)?
[ "", "c++", "linux", "debugging", "" ]
We've got a scenario that requires us to parse lots of e-mail (plain text), each e-mail 'type' is the result of a script being run against various platforms. Some are tab delimited, some are space delimited, some we simply don't know yet. We'll need to support more 'formats' in the future too. Do we go for a solution...
The three solutions you stated each cover very different needs. **Manual parsing** (simple text search) is the most flexible and the most adaptable, however, it very quickly becomes a real pain in the ass as the parsing required is more complicated. **Regex** are a middle ground, and probably your best bet here. They...
Regex. Regex can solve almost everything except for world peace. Well maybe world peace too.
What's the best way of parsing strings?
[ "", "c#", "email", "parsing", "projects-and-solutions", "" ]
There is a way to keep the scroll on bottom for a multi line textbox? Something like in the vb6 ``` txtfoo.selstart=len(txtfoo.text) ``` I'm trying with txtfoo.selectionstart=txtfoo.text.length without success. Regards.
Ok, I found that the solution was to use ``` txtfoo.AppendText ``` instead of ``` txtfoo.text+="something" ```
The other solution is to use: ``` txtfoo.Text += "something"; txtfoo.SelectionStart = txtfoo.Text.Length; txtfoo.ScrollToCaret(); ```
Scroll of a texbox always on bottom
[ "", "c#", "winforms", "" ]
I have an RFID reader connected to an Arduino board. I'd like to connect to it over its serial interface, and whenever the RFID reader omits a signal ( when it has read an (RF)ID ), I'd like to retrieve it in my C++ program. I already have the code for simply printing the RFID to serial from the Arduino. What I don't...
I found the Boost::Asio library, which reads from serial interfaces asynchronously. [Boost::Asio Documentation](http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio.html)
On unix you use the select() call to wait for an input. The select() call acts like a sleep - using no CPU until the kernel receives the hardware interrupt and triggers the select(). <http://tldp.org/HOWTO/Serial-Programming-HOWTO/index.html>
How to communicate with an Arduino over its serial interface in C++ on Linux?
[ "", "c++", "linux", "serial-port", "arduino", "rfid", "" ]
In my tests I need to test what happens when an OracleException is thrown (due to a stored procedure failure). I am trying to setup Rhino Mocks to ``` Expect.Call(....).Throw(new OracleException()); ``` For whatever reason however, OracleException seems to be sealed with no public constructor. What can I do to test t...
It seems that Oracle changed their constructors in later versions, therefore the solution above will not work. If you only want to set the error code, the following will do the trick for 2.111.7.20: ``` ConstructorInfo ci = typeof(OracleException) .GetConstructor( BindingFlags.NonPublic | ...
Here is how you do it: ``` ConstructorInfo ci = typeof(OracleException).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] {typeof(string), typeof(int)}, null); var c = (OracleException)ci.Invoke(new object[] { "some message", 123 }); ``` Thanks to all that helped, you have been u...
How can I mock/fake/stub sealed OracleException with no public constructor?
[ "", "c#", ".net", "oracle", "mocking", "oracleclient", "" ]
Are C++ enums signed or unsigned? And by extension is it safe to validate an input by checking that it is <= your max value, and leave out >= your min value (assuming you started at 0 and incremented by 1)?
You shouldn't rely on any specific representation. Read the following [link](http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.19). Also, the standard says that it is implementation-defined which integral type is used as the underlying type for an enum, except that it shall not be larger than int, unless some va...
Let's go to the source. Here's what the C++03 standard (ISO/IEC 14882:2003) document says in 7.2-5 (Enumeration declarations): > The underlying type of an enumeration > is an integral type that can represent > all the enumerator values defined in > the enumeration. It is > implementation-defined which integral > type ...
Are C++ enums signed or unsigned?
[ "", "c++", "enums", "" ]
One thing I am concerned with is that I discovered two ways of registering delegates to events. 1. OnStuff += this.Handle; 2. OnStuff += new StuffEventHandler(this.Handle); The first one is clean, and it makes sense doing "OnStuff -= this.Handle;" to unregister from the event... But with the latter case, should I do ...
You don't need to worry about keeping a reference to the originally registered delegate, and you will not start a "nasty memory pool". When you call "OnStuff -= new StuffEventHandler(this.Handle);" the removal code does *not* compare the delegate you are removing by reference: it checks for equality by comparing refer...
Number one is just shorthand that will generate the same MSIL as the 2nd one, at compile type it'll look at this.Handle and infer the delegate to instantiate. But you should never unsubscribe by using new. So there is no difference between the 2, just some syntactic sugar to make our code cleaner.
Is it safe to add delegates to events with keyword new?
[ "", "c#", ".net", "events", "delegates", "" ]
I am developping a (relatively small) website in ASP.Net 2.0. I am also using nAnt to perform some easy tweaking on my project before delivering executables. In its current state, the website is "precompiled" using > `aspnet_compiler.exe -nologo -v ${Appname} -u ${target}` I have noticed that after the IIS pool is re...
Make sure that: 1. You are using a Web Application project rather than a Web Site project, this will result in a precompiled binary for your code behind 2. You have turned off debug code generation in the web.config file - I guess if this is different to when you used aspnet\_compiler the code may be recompiled If yo...
For ultimate reponsiveness, don't allow your app to be shutdown. The first method is to make sure that it's incredibly popular so that there's always someone using it. Alternatively, fetching a tiny keep-alive page from somewhere else as a scheduled activity can be used to keep your site 'hot'.
Precompilation and startup times on ASP.Net
[ "", "c#", "asp.net", "compilation", "startup", "aspnet-compiler", "" ]
I wrote a sample program at <http://codepad.org/ko8vVCDF> that uses a template function. How do I retrict the template function to only use numbers? (int, double etc.) ``` #include <vector> #include <iostream> using namespace std; template <typename T> T sum(vector<T>& a) { T result = 0; int size = a.si...
The only way to restrict a template is to make it so that it uses something from the types that you want, that other types don't have. So, you construct with an int, use + and +=, call a copy constructor, etc. Any type that has all of these will work with your function -- so, if I create a new type that has these fea...
This is possible by using [SFINAE](https://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error), and made easier by using helpers from either Boost or C++11 Boost: ``` #include <vector> #include <boost/utility/enable_if.hpp> #include <boost/type_traits/is_arithmetic.hpp> template<typename T> typename boo...
Restrict Template Function
[ "", "c++", "templates", "" ]
Been running into this problem lately... When debugging an app in VS.Net 2005, breakpoints are not connected. Error indicates that the compiled code is not the same as the running version and therefore there's a mismatch that causes the breakpoint to be disconnected. Cleaned solution of all bin file and re-compile doe...
Maybe this suggestion might help: 1. While debugging in Visual Studio, click on Debug > Windows > Modules. The IDE will dock a Modules window, showing all the modules that have been loaded for your project. 2. Look for your project's DLL, and check the Symbol Status for it. 3. If it says Symbols Loaded, then you're go...
<http://dpotter.net/Technical/2009/05/upgrading-to-ie8-breaks-debugging-with-visual-studio-2005/>
Breakpoint not hooked up when debugging in VS.Net 2005
[ "", "c#", "debugging", "visual-studio-2005", "breakpoints", "" ]
I'm trying to pass in a Base64 string into a C#.Net web application via the QueryString. When the string arrives the "+" (plus) sign is being replaced by a space. It appears that the automatic URLDecode process is doing this. I have no control over what is being passed via the QueryString. Is there any way to handle th...
You could manually replace the value (`argument.Replace(' ', '+')`) or consult the `HttpRequest.ServerVariables["QUERY_STRING"]` (even better the HttpRequest.Url.Query) and parse it yourself. You should however try to solve the problem where the URL is given; a plus sign needs to get encoded as "%2B" in the URL becaus...
The suggested solution: ``` Request.QueryString["VLTrap"].Replace(" ", "+"); ``` Should work just fine. As for your concern: > I had though of this but my concern with it, and I should have mentioned this to start, is that I don't know what other characters might be malformed in addition to the plus sign. This is e...
QueryString malformed after URLDecode
[ "", "c#", "asp.net", "url", "" ]
In SQL Server 2005, are there any disadvantages to making all character fields nvarchar(MAX) rather than specifying a length explicitly, e.g. nvarchar(255)? (Apart from the obvious one that you aren't able to limit the field length at the database level)
Same question was asked on MSDN Forums: * [Varchar(max) vs Varchar(255)](https://social.msdn.microsoft.com/Forums/sqlserver/en-US/4d9c6504-496e-45ba-a7a3-ed5bed731fcc/varcharmax-vs-varchar255) From the original post (much more information there): > When you store data to a VARCHAR(N) column, the values are physicall...
Based on the link provided in the accepted answer it appears that: 1. 100 characters stored in an `nvarchar(MAX)` field will be stored no different to 100 characters in an `nvarchar(100)` field - the data will be stored inline and you will not have the overhead of reading and writing data 'out of row'. So no worries t...
Are there any disadvantages to always using nvarchar(MAX)?
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I've seen a few different ways to iterate over a dictionary in C#. Is there a standard way?
``` foreach(KeyValuePair<string, string> entry in myDictionary) { // do something with entry.Value or entry.Key } ```
If you are trying to use a generic Dictionary in C# like you would use an associative array in another language: ``` foreach(var item in myDictionary) { foo(item.Key); bar(item.Value); } ``` Or, if you only need to iterate over the collection of keys, use ``` foreach(var item in myDictionary.Keys) { foo(item);...
How to iterate over a dictionary?
[ "", "c#", "dictionary", "loops", "" ]
Why does the code below return true only for a = 1? ``` main(){ int a = 10; if (true == a) cout<<"Why am I not getting executed"; } ```
When a Bool true is converted to an int, it's always converted to 1. Your code is thus, equivalent to: ``` main(){ int a = 10; if (1 == a) cout<<"y i am not getting executed"; } ``` This is part of the [C++ standard](http://www.bond.id.au/~gnb/wp/cd2/conv.html), so it's something you would expect to ha...
The reason your print statement is not getting executed is because your boolean is getting implicitly converted to a number instead of the other way around. I.e. your if statement is equivalent to this: if (1 == a) You could get around this by first explicitly converting it to a boolean: ``` main(){ int a = 10; if ((...
Why does the code below return true only for a = 1?
[ "", "c++", "conditional-statements", "" ]
I need to scramble the names and logins of all the users in a UAT database we have. (because of the data protection act) However, there is a catch. The testers still need to be able to login using the hashed login names so if a user login is "Jesse.J.James" then the hash should be something like Ypois.X.Qasdf i.e....
You do not need to hash the data. You should just randomize it so it has no relation to the original data. For example, update all the login names, and replace each letter with another random letter.
Testers should NOT be logging in as legitimate users. That would clearly violate the non-repudiation requirement of whatever data protection act you're working under. The system should not allow anyone to log in using the hashed value. That defeats the whole purpose of hashing! I'm sorry I am not answering your speci...
hashing sensitive data
[ "", "c#", "encryption", "hash", "" ]
I have a set of callback classes that I use for handling callbacks with variable numbers of parameters. Right now I have about 6 different instances of it to handle differing numbers of arguments. Is there a way to make one instance than can handle a variable number of arguments?? Ultimately I would love to have each p...
Not yet in the language itself but C++0x will have support for [variadic templates](http://en.wikipedia.org/wiki/C%2B%2B0x#Variadic_templates).
C++0x variatdic templates is your best bet, but it will also be a while before you can use them. If you need sequences of types today, take a look at MPL's [vector](http://www.boost.org/doc/libs/1_36_0/libs/mpl/doc/refmanual/vector.html) of types, as well as other type sequence types. It's part of the [Boost](http://b...
Is there a way to handle a variable number of parameters in a template class?
[ "", "c++", "parameters", "templates", "arguments", "" ]
I just set up my new homepage at <http://ritter.vg>. I'm using jQuery, but very minimally. It loads all the pages using AJAX - I have it set up to allow bookmarking by detecting the hash in the URL. ``` //general functions function getUrl(u) { return u + '.html'; } function loadURL(u) { $.get(getU...
Use the [jQuery hashchange event](https://github.com/cowboy/jquery-hashchange) plugin instead. Regarding your full ajax navigation, try to have [SEO friendly ajax](http://www.chazzuka.com/blog/?p=90). Otherwise your pages shown nothing in browsers with JavaScript limitations.
The answers here are all quite old. In the HTML5 world, you should the use [`onpopstate`](https://developer.mozilla.org/en-US/docs/DOM/window.onpopstate) event. ``` window.onpopstate = function(event) { alert("location: " + document.location + ", state: " + JSON.stringify(event.state)); }; ``` Or: ``` window.ad...
Detecting Back Button/Hash Change in URL
[ "", "javascript", "ajax", "navigation", "fragment-identifier", "hashchange", "" ]
Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves. My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound li...
Don't try and obfuscate or encrypt the code - it will never work. I would suggest selling the Django application "as a service" - either host it for them, or sell them the code *and support*. Write up a contract that forbids them from redistributing it. That said, if you were determined to obfuscate the code in some ...
You could package the whole thing up as an Amazon Machine Instance (AMI), and then have them run your app on [Amazon EC2](http://aws.amazon.com/ec2/). The nice thing about this solution is that Amazon will [take care of billing for you](http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/index.html?paidamis-...
How would I package and sell a Django app?
[ "", "python", "django", "piracy-prevention", "" ]
I'm a big fan of Capistrano but I need to develop an automated deployment script for a Java-only shop. I've looked at Ant and Maven and they don't seem to be well geared towards remote administration the way Capistrano is - they seem much more focused on simply building and packaging applications. Is there a better too...
I don't think there is a Capistrano-like application for Java Web Applications, but that shouldn't really keep you from using it (or alternatives like Fabric) to deploy your applications. As you've already said, Ant is more a replacement for GNU Make while Maven is primary a buildout/dependency-management application. ...
I think that controltier (see: <http://controltier.org>) is what you are looking for. Though controltier doesn't need to be exclusively used for Java deploys. See this excerpt from the docs (see: [control tier documentation](http://doc36.controltier.org/wiki/ControlTier#Is_ControlTier_the_same_as_Capistrano.2C_Fabric....
Capistrano for Java?
[ "", "java", "deployment", "capistrano", "" ]
I have a C++ template class that gets instantiated with 3 different type parameters. There's a method that the class needs to have for only one of those types and that isn't ever called with the two other types. Will object code for that method be generated thrice (for all types for which the template is instantiated)...
Virtual member functions are instantiated when a class template is instantiated, but non-virtual member functions are instantiated only if they are called. This is covered in [temp.inst] in the C++ standard (In C++11, this is §14.7.1/10. In C++14, it is §14.7.1/11, and in C++17 it is §17.7.1/9. Excerpt from C++17 belo...
I think it depends on the compiler and settings. For example, I believe MSVC6 generated everything, but VS2005 does not. The spec says the compiler should not, but in the real world, it depends on the actual compiler (there are many work-arounds in boost for MSVC6, for example). The linker can remove unreferenced funct...
Is object code generated for unused template class methods?
[ "", "c++", "templates", "footprint", "" ]
In SQL Server you can use the `IsNull()` function to check if a value is null, and if it is, return another value. Now I am wondering if there is anything similar in C#. For example, I want to do something like: ``` myNewValue = IsNull(myValue, new MyValue()); ``` instead of: ``` if (myValue == null) myValue = ne...
It's called the null coalescing (`??`) operator: ``` myNewValue = myValue ?? new MyValue(); ```
Sadly, there's no equivalent to the null coalescing operator that works with DBNull; for that, you need to use the ternary operator: ``` newValue = (oldValue is DBNull) ? null : oldValue; ```
C# equivalent of the IsNull() function in SQL Server
[ "", "c#", ".net", "sql-server", "isnull", "" ]
Is there an efficient way to tell if a DOM element (in an HTML document) is currently visible (appears in the **viewport**)? (The question refers to Firefox.)
**Update:** Time marches on and so have our browsers. **This technique is no longer recommended** and you should use [Dan's solution](https://stackoverflow.com/questions/123999/how-can-i-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433) if you do not need to support version of Internet Explorer ...
Now [most browsers](http://www.quirksmode.org/dom/w3c_cssom.html) support [getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) method, which has become the best practice. Using an old answer is very slow, [not accurate](http://weblogs.asp.net/bleroy/archive/2008/01/29/...
How can I tell if a DOM element is visible in the current viewport?
[ "", "javascript", "html", "firefox", "dom", "browser", "" ]
I'm writing a Java Tree in which tree nodes could have children that take a long time to compute (in this case, it's a file system, where there may be network timeouts that prevent getting a list of files from an attached drive). The problem I'm finding is this: 1. `getChildCount()` is called before the user specific...
There are a few parts to the solution: * Like Lorenzo Boccaccia said, use the [TreeWillExpandListener](http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#data) * **Also**, need to call nodesWereInserted on the tree, so the proper number of nodes will be displayed. [See this code](http://www.jroller.c...
<http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#data> scroll a little down, there is the exact tutorial on how to create lazy loading nodes for the jtree, complete with examples and documentation
Java TreeNode: How to prevent getChildCount from doing expensive operation?
[ "", "java", "swing", "jtree", "" ]
I want to display the TIME field from my mysql table on my website, but rather than showing 21:00:00 etc I want to show 8:00 PM. I need a function/code to do this or even any pointers in the right direction. Will mark the first reply with some code as the correct reply.
Check this out: <http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html> I'd imagine you'd want date\_format(). Example: DATE\_FORMAT($date, "%r")
Show the date & time data in AM/PM format with the following example... ``` SELECT DATE_FORMAT(`t`.`date_field`,'%h:%i %p') AS `date_field` FROM `table_name` AS `t` ``` OR ``` SELECT DATE_FORMAT(`t`.`date_field`,'%r') AS `date_field` FROM `table_name` AS `t` ``` Both are working properly.
Converting mysql TIME from 24 HR to AM/PM format
[ "", "php", "mysql", "datetime", "date", "time", "" ]
I'm used to writing classes like this: ``` public class foo { private string mBar = "bar"; public string Bar { get { return mBar; } set { mBar = value; } } //... other methods, no constructor ... } ``` Converting Bar to an auto-property seems convenient and concise, but how can I retain the initializa...
Update - the answer below was written before C# 6 came along. In C# 6 you can write: ``` public class Foo { public string Bar { get; set; } = "bar"; } ``` You can *also* write read-only automatically-implemented properties, which are only writable in the constructor (but can also be given a default initial value)...
You can do it via the constructor of your class: ``` public class foo { public foo(){ Bar = "bar"; } public string Bar {get;set;} } ``` If you've got another constructor (ie, one that takes paramters) or a bunch of constructors you can always have this (called constructor chaining): ``` public class foo { ...
Initializing C# auto-properties
[ "", "c#", "initialization", "automatic-properties", "" ]
Does any one know of an opensource Java VNC server, that can be run from a web page, so requiring no installation on the server end, possibley applet based.
<http://vncj.com/default.aspx> Once you get it setup you wont know how you lived w/o it. The server and the client are using the same .jar file all in the html page pointing where your listen client is at.
A signed Java applet (or application) can use the Robot class to get screenshots of the current window and use this for remote control. It will never be very efficient, but it can be done.
Java VNC Applet
[ "", "java", "applet", "vnc", "" ]
If I have a script tag like this: ``` <script id = "myscript" src = "http://www.example.com/script.js" type = "text/javascript"> </script> ``` I would like to get the content of the "script.js" file. I'm thinking about something like `document.getElementById("myscript").text` but it doesn't work in this c...
Do you want to get the contents of the file <http://www.example.com/script.js>? If so, you could turn to AJAX methods to fetch its content, assuming it resides on the same server as the page itself.
**tl;dr** script tags are not subject to [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) and [same-origin-policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) and therefore javascript/DOM cannot offer access to the text content of the resource loaded via a `<script>` tag, or ...
How can I get the content of the file specified as the 'src' of a <script> tag?
[ "", "javascript", "" ]
I have a number of code value tables that contain a code and a description with a Long id. I now want to create an entry for an Account Type that references a number of codes, so I have something like this: ``` insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id) ( select account_...
Outter joins don't work "as expected" in that case because you have explicitly told Oracle you only want data if that criteria on that table matches. In that scenario, the outter join is rendered useless. A work-around ``` INSERT INTO account_type_standard (account_type_Standard_id, tax_status_id, recipient_id) V...
A slightly simplified version of Oglester's solution (the sequence doesn't require a select from DUAL: ``` INSERT INTO account_type_standard (account_type_Standard_id, tax_status_id, recipient_id) VALUES( account_type_standard_seq.nextval, (SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?), ...
Oracle Insert via Select from multiple tables where one table may not have a row
[ "", "sql", "oracle", "select", "insert", "" ]
Is there a way through the .net framework to determine if a folder is shared or not? Neither Diretory, DirectoryInfo or FileAttributes seem to have any corresponding field. One thing I forgot to mention was that I want to be checking for network shares. But I'll investigate the WMI stuff.
You can use WMI Win32\_Share. Take a look at: <http://www.gamedev.net/community/forums/topic.asp?topic_id=408923> Shows a sample for querying, creating and deleting shared folders.
You can get a list of all the shared folders using the WMI Win32\_Share and see if the folder you're looking for is between them. Here's a snippet that might help you with this: ``` public static List<string> GetSharedFolders() { List<string> sharedFolders = new List<string>(); // Object to query the WMI Win32_S...
Determining if a folder is shared in .NET
[ "", "c#", ".net", "windows", "" ]
I'm at the beginning/middle of a project that we chose to implement using GWT. Has anyone encountered any major pitfalls in using GWT (and GWT-EXT) that were unable to be overcome? How about from a performance perspective? A couple things that we've seen/heard already include: * Google not being able to index content...
I'll start by saying that I'm a massive GWT fan, but yes there are many pitfalls, but most if not all we were able to overcome: **Problem:** Long compile times, as your project grows so does the amount of time it takes to compile it. I've heard of reports of 20 minute compiles, but mine are on average about 1 minute. ...
We have been working with gwt for almost 2 years. We have learned a lot of lessons. Here is what we think: 1. Dont use third party widget libraries especially gwt-ext. It will kill your debugging, development and runtime performance. If you have questions about how this happens, contact me directly. 2. Use gwt to only...
Biggest GWT Pitfalls?
[ "", "java", "ajax", "gwt", "gwt-ext", "" ]
I want to create basic line, bar, pie and area charts for .NET 3.5 WinForms and I'm interested in finding a free, mature, open-source .NET (preferably C# based) project to help me accomplish that. I would consider a WPF based project, however I'm more comfortable in GDI+ so I'd rather it used System.Drawing and/or GDI ...
[ZedGraph](http://zedgraph.org/). 'Nuff said.
This one's quite nice: [zed graph](http://zedgraph.org)
What's a good f/oss GDI+ (System.Drawing) based graphing and charting component for .NET?
[ "", "c#", ".net", "vb.net", "gdi+", "graph", "" ]
I've got a function that runs a user generated Regex. However, if the user enters a regex that won't run then it stops and falls over. I've tried wrapping the line in a Try/Catch block but alas nothing happens. If it helps, I'm running jQuery but the code below does not have it as I'm guessing that it's a little more ...
Try this the new RegExp is throwing the exception Regex ``` <script type="text/javascript" charset="utf-8"> var grep; try { grep = new RegExp("gr["); } catch(e) { alert(e); } try { ...
The problem is with this line: ``` var grep = new RegExp('gr['); ``` '[' is a special character so it needs to be escaped. Also this line is not wrapped in try...catch, so you still get the error. **Edit**: You could also add an ``` alert(e.message); ``` in the catch clause to see the error message. It's useful fo...
Javascript Try/Catch
[ "", "javascript", "regex", "try-catch", "" ]
Given the following: ``` &row->count ``` Would &(row->count) be evaluated or (&row)->count be evaluated in C++? EDIT: Here's a great [link](http://www.cppreference.com/wiki/operator_precedence) for C++ precedence.
[&(row->count)](http://www.cppreference.com/wiki/operator_precedence)
As far as precedence rules go, I've always liked the one put forth by Steve Oualline in "Practical C": > There are fifteen precedence rules in > C (&& comes before || comes before > ?:). The practical programmer reduces > these to two: > > 1) Multiplication and division come > before addition and subtraction. > > 2) P...
Priority of C++ operators "&" and "->"
[ "", "c++", "operators", "operator-precedence", "" ]
In C++ you can initialize a variable in an if statement, like so: ``` if (CThing* pThing = GetThing()) { } ``` Why would one consider this bad or good style? What are the benefits and disadvantages? Personally i like this style because it limits the scope of the pThing variable, so it can never be used accidentally ...
The important thing is that a declaration in C++ is not an expression. ``` bool a = (CThing* pThing = GetThing()); // not legit!! ``` You can't do both a declaration and boolean logic in an if statement, C++ language spec specifically allows either an expression or a declaration. ``` if(A *a = new A) { // this i...
You can have initialization statements inside `if` and `switch` since **C++17**. Your code would now be: ``` if (CThing* pThing = GetThing(); pThing->IsReallySomeThing()) { // use pThing here } // pThing is out of scope here ```
Pro/con: Initializing a variable in a conditional statement
[ "", "c++", "coding-style", "if-statement", "" ]
Which of these queries is the faster? NOT EXISTS: ``` SELECT ProductID, ProductName FROM Northwind..Products p WHERE NOT EXISTS ( SELECT 1 FROM Northwind..[Order Details] od WHERE p.ProductId = od.ProductId) ``` Or NOT IN: ``` SELECT ProductID, ProductName FROM Northwind..Products p WHERE p.ProductI...
I always default to `NOT EXISTS`. The execution plans may be the same at the moment but if either column is altered in the future to allow `NULL`s the `NOT IN` version will need to do more work (even if no `NULL`s are actually present in the data) and the semantics of `NOT IN` if `NULL`s *are* present are unlikely to ...
Also be aware that NOT IN is not equivalent to NOT EXISTS when it comes to null. This post explains it very well <http://sqlinthewild.co.za/index.php/2010/02/18/not-exists-vs-not-in/> > When the subquery returns even one null, NOT IN will not match any > rows. > > The reason for this can be found by looking at the d...
NOT IN vs NOT EXISTS
[ "", "sql", "sql-server", "notin", "" ]
I need to create a custom volume slider for a WMP object. The current slider is complicated to modify, and use, is there a simple way to generate a slider on an HTML page that can have it's value passed to a javascript function?
[jQuery UI Slider](http://jqueryui.com/demos/slider/) ([API docs](http://docs.jquery.com/UI/Slider))
hey i've just created my own JS slider because I had enough of the heavy Jquery UI one. Interested to hear people's thoughts. Been on it for 5 hours, so really really early stages. [jsfiddle\_slider](http://jsfiddle.net/LucP/BPdKR/2/)
Is there a simple JavaScript slider?
[ "", "javascript", "slider", "controls", "wmp", "" ]
I have a c# application that runs as a windows service controlling socket connections and other things. Also, there is another windows forms application to control and configure this service (systray with start, stop, show form with configuration parameters). I'm using .net remoting to do the IPC and that was fine, bu...
Two separate processes that communicate using your technology of choice. Services with UI is a **bad idea**. Don't go down this road - you'll regret it. I've had very good results having service communication through a simple socket connection - document your service protocol well, keep it as simple as possible, and i...
In practice you should not couple your service with the management UI.
Windows services with windows forms in the same process
[ "", "c#", "windows", "windows-services", "" ]
What's the best way to break from nested loops in Javascript? ``` //Write the links to the page. for (var x = 0; x < Args.length; x++) { for (var Heading in Navigation.Headings) { for (var Item in Navigation.Headings[Heading]) { if (Args[x] == Navigation.Headings[Heading][Item].Name) ...
Just like Perl, ``` loop1: for (var i in set1) { loop2: for (var j in set2) { loop3: for (var k in set3) { break loop2; // breaks out of loop3 and loop2 } } } ``` as defined in EMCA-262 section 12.12. [[MDN Docs]](https://developer.mozilla.org/docs/Web/...
Wrap that up in a function and then just `return`.
What's the best way to break from nested loops in JavaScript?
[ "", "javascript", "loops", "nested-loops", "break", "" ]
I'm having some trouble with plain old JavaScript (no frameworks) in referencing my object in a callback function. ``` function foo(id) { this.dom = document.getElementById(id); this.bar = 5; var self = this; this.dom.addEventListener("click", self.onclick, false); } foo.prototype = { onclick : fu...
*(extracted some explanation that was hidden in comments in other answer)* The problem lies in the following line: ``` this.dom.addEventListener("click", self.onclick, false); ``` Here, you pass a function object to be used as callback. When the event trigger, the function is called but now it has no association wit...
``` this.dom.addEventListener("click", function(event) { self.onclick(event) }, false); ```
JavaScript Callback Scope
[ "", "javascript", "events", "binding", "scope", "callback", "" ]
Is it possible to find the `foreach` index? in a `for` loop as follows: ``` for ($i = 0; $i < 10; ++$i) { echo $i . ' '; } ``` `$i` will give you the index. Do I have to use the `for` loop or is there some way to get the index in the `foreach` loop?
``` foreach($array as $key=>$value) { // do stuff } ``` `$key` is the index of each `$array` element
You can put a hack in your `foreach`, such as a field incremented on each run-through, which is exactly what the `for` loop gives you in a numerically-indexed array. Such a field would be a pseudo-index that needs manual management (increments, etc). A `foreach` will give you your index in the form of your `$key` valu...
How to find the foreach index?
[ "", "php", "loops", "foreach", "" ]
Mixing the use of primitive data types and their respective wrapper classes, in Java, can lead to a lot of bugs. The following example illustrates the issue: ``` int i = 4; ... if (i == 10) doStuff(); ``` Later on you figure that you want the variable *i* to be either defined or undefined, so you change the above i...
Using the boxed types *does* have both performance and memory issues. When doing comparisons (eg `(i == 10)` ), java has to unbox the type before doing the comparison. Even using `i.equals(TEN)` uses a method call, which is costlier and (IMO) uglier than the == syntax. Re memory, the object has to be stored on the he...
Firstly, switching from using a primitive to using an object just to get the ability to set it to null is probably a bad design decision. I often have arguments with my coworkers about whether or not null is a sentinel value, and my opinion is usually that it is not (and thus shouldn't be prohibited like sentinel value...
Should I never use primitive types again?
[ "", "java", "types", "" ]
Can someone provide an explanation of variable scope in JS as it applies to objects, functions and closures?
### Global variables Every variable in Javascript is a named attribute of an object. For example:- ``` var x = 1; ``` x is added to the global object. The global object is provided by the script context and may already have a set of attributes. For example in a browser the global object is window. An equivalent to t...
Variables not declared with var are global in scope. Functions introduce a scope, but note that if blocks and other blocks do not introduce a scope. I could also see much information about this by Googling Javascript scope. That's really what I would recommend. <http://www.digital-web.com/articles/scope_in_javascript/...
OO Javascript : Definitive explanation of variable scope
[ "", "javascript", "oop", "" ]
I'm using the document.form.submit() function for a rather large input form (hundreds of fields, it's an inventory application). I'm calling this after the user has been idle for a certain amount of time and I would like to save any data they've typed. When I try this the page reloads (the action is #) but any new text...
I guess I put the answer here. What I found was that doing this: setTimeout('frm.submit();', 2000); caused the page to reload but didn't submit the form. When I did this: frm.submit(); The form was submitted and the data was passed. I don't know why the first way didn't work, but I don't need to know that:)
Might the server be voiding out the input values. Say if your page on the server looks like this: ``` <form action="/page.cgi"> ... <input name="Fieldx" value=""/> </form> ``` I think it'll void out the field. Or this the server action might be setting it indirectly. In JSF, something like this. ``` <input name=...
How to submit form with data before logging someone out?
[ "", "javascript", "forms", "submit", "" ]
I was writing some Unit tests last week for a piece of code that generated some SQL statements. I was trying to figure out a regex to match `SELECT`, `INSERT` and `UPDATE` syntax so I could verify that my methods were generating valid SQL, and after 3-4 hours of searching and messing around with various regex editors ...
Regular expressions can match languages only a finite state automaton can parse, which is very limited, whereas SQL is a syntax. **It can be demonstrated you can't validate SQL with a regex.** So, you can stop trying.
SQL is a [type-2 grammar](http://en.wikipedia.org/wiki/Chomsky_hierarchy), it is too powerful to be described by regular expressions. It's the same as if you decided to generate C# code and then validate it without invoking a compiler. Database engine in general is too complex to be easily stubbed. That said, you may ...
Regular expression to match common SQL syntax?
[ "", "sql", "regex", "unit-testing", "" ]
I'm in the process of writing a Java 2D game. I'm using the built-in Java 2D drawing libraries, drawing on a Graphics2D I acquire from a BufferStrategy from a Canvas in a JFrame (which is sometimes full-screened). The BufferStrategy is double-buffered. Repainting is done actively, via a timer. I'm having some performan...
I'm having the same issues as you are I think. Check out my post here: [Java2D Performance Issues](https://stackoverflow.com/questions/196890/java2d-performance-issues) It shows the reason for the performance degradation and how to fix it. It's not guaranteed to work well on all platforms though. You'll see why in th...
A synthesis of the answers to this post, the answers to [Consty's](https://stackoverflow.com/questions/196890/java2d-performance-issues), and my own research: What works: * Use `GraphicsConfiguration.createCompatibleImage` to create images compatible with what you're drawing on. This is absolutely essential! * Use do...
Java 2D Drawing Optimal Performance
[ "", "java", "performance", "graphics", "java-2d", "" ]
I need to get the actual local network IP address of the computer (e.g. 192.168.0.220) from my program using C# and .NET 3.5. I can't just use 127.0.0.1 in this case. How can I accomplish this?
In [*How to get IP addresses in .NET with a host name*](http://www.devcity.net/Articles/62/1/gethostbyname.aspx "Article by John Spano, Published 1 Dec 2002") by John Spano, it says to add the `System.Net` namespace, and use the following code: > ``` > //To get the local IP address > string sHostName = Dns.GetHostNam...
If you are looking for the sort of information that the command line utility, ipconfig, can provide, you should probably be using the System.Net.NetworkInformation namespace. This sample code will enumerate all of the network interfaces and dump the addresses known for each adapter. ``` using System; using System.Net...
How do I get the Local Network IP address of a computer programmatically?
[ "", "c#", ".net", ".net-3.5", "ip-address", "" ]
In languages like Java and C#, strings are immutable and it can be computationally expensive to build a string one character at a time. In said languages, there are library classes to reduce this cost such as C# `System.Text.StringBuilder` and Java `java.lang.StringBuilder`. Does php (4 or 5; I'm interested in both) s...
No, there is no type of stringbuilder class in PHP, since strings are mutable. That being said, there are different ways of building a string, depending on what you're doing. echo, for example, will accept comma-separated tokens for output. ``` // This... echo 'one', 'two'; // Is the same as this echo 'one'; echo '...
I was curious about this, so I ran a test. I used the following code: ``` <?php ini_set('memory_limit', '1024M'); define ('CORE_PATH', '/Users/foo'); define ('DS', DIRECTORY_SEPARATOR); $numtests = 1000000; function test1($numtests) { $CORE_PATH = '/Users/foo'; $DS = DIRECTORY_SEPARATOR; $a = array(); ...
php String Concatenation, Performance
[ "", "php", "string", "concatenation", "" ]
I have a search form with a query builder. The builder is activated by a button. Something like this ``` <h:form id="search_form"> <h:outputLabel for="expression" value="Expression"/> <h:inputText id="expression" required="true" value="#{searcher.expression}"/> <button onclick="openBuilder(); return false;">Open...
A button in an HTML form is assumed to be used to submit the form. Change button to input type="button" and that should fix it. Alternatively, add type="button" to the button element.
as first, give an ID to Search button. Then,on textbox, you could intercept client event **onkeydown**, with a (javascript) function like this: ``` function KeyDownHandler(event) { // process only the Enter key if (event.keyCode == 13) { // cancel the default submit ...
Seam/JSF form submit firing button onclick event
[ "", "java", "html", "firefox", "jsf", "seam", "" ]
I have a .net 2.0 ascx control with a start time and end time textboxes. The data is as follows: txtStart.Text = 09/19/2008 07:00:00 txtEnd.Text = 09/19/2008 05:00:00 I would like to calculate the total time (hours and minutes) in JavaScript then display it in a textbox on the page.
Once your textbox date formats are known in advance, you can use [Matt Kruse's Date functions](http://www.mattkruse.com/javascript/date/) in Javascript to convert the two to a timestamp, subtract and then write to the resulting text box. Equally the [JQuery Date Input](http://jonathanleighton.com/projects/date-input#d...
``` function stringToDate(string) { var matches; if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2}) (\d{2,2}):(\d{2,2}):(\d{2,2})$/)) { return new Date(matches[1], matches[2] - 1, matches[3], matches[4], matches[5], matches[6]); } else { return null; }; } function getTimeS...
Calculate timespan in JavaScript
[ "", "asp.net", "javascript", "" ]
The following method does not work because the inner block declares a variable of the same name as one in the outer block. Apparently variables belong to the method or class in which they are declared, not to the block in which they are declared, so I therefore can't write a short little temporary block for debugging t...
I believe the rationale is that most of the time, that isn't intentional, it is a programming or logic flaw. in an example as trivial as yours, its obvious, but in a large block of code, accidentally redeclaring a variable may not be obvious. ETA: it might also be related to exception handling in java. i thought part...
Well, strictly speaking, Java *does* have block-scoped variable declarations; so this is an error: ``` void methodName() { for (int j = 0; j < 10; j++) { int i = j * 2; } System.out.println(i); // error } ``` Because 'i' doesn't exist outside the for block. The problem is that Java doesn't allow you to cre...
Why does Java not have block-scoped variable declarations?
[ "", "java", "syntax", "language-design", "" ]
I have a c# object with a property called Gender which is declared as a char. ``` private char _Gender; public char Gender { get{ return _Gender; } set{ _Gender = value; } } ``` What string is returned/created when I call MyObject.Gender.ToString()? I ask because I am calling a webservice (which accepts a s...
The default value of char is unicode 0, so I'd expect "\u0000" to be returned.
Fields are always initialized to their default value; 0/false/null - this this is the 0 character, \0. If you want an empty string, use strings directly - i.e. "". You could use a conditional operator: ``` string s = c == 0 ? "" : c.ToString(); ``` Alternatively, nullable types might help - i.e. ``` char? c; // a ...
What is returned when I call ToString() on an uninitialized char object property?
[ "", "c#", "" ]
I heard that you could right-shift a number by .5 instead of using Math.floor(). I decided to check its limits to make sure that it was a suitable replacement, so I checked the following values and got the following results in Google Chrome: ``` 2.5 >> .5 == 2; 2.9999 >> .5 == 2; 2.999999999999999 >> .5 == 2; // 15 9...
Actually, you're simply ending up doing a floor() on the first operand, without any floating point operations going on. Since the left shift and right shift bitwise operations only make sense with integer operands, the JavaScript engine is converting the two operands to integers first: ``` 2.999999 >> 0.5 ``` Becomes...
This is possibly the single worst idea I have ever seen. Its only possible purpose for existing is for winning an obfusticated code contest. There's no significance to the long numbers you posted -- they're an artifact of the underlying floating-point implementation, filtered through god-knows how many intermediate lay...
2.9999999999999999 >> .5?
[ "", "javascript", "bit-manipulation", "precision", "" ]
I have a marker interface defined as ``` public interface IExtender<T> { } ``` I have a class that implements IExtender ``` public class UserExtender : IExtender<User> ``` At runtime I recieve the UserExtender type as a parameter to my evaluating method ``` public Type Evaluate(Type type) // type == typeof(UserExt...
I went this way based on some of the tidbits provided. It could be made more robust to handle multiple generic arguments on the interface.... but I didn't need it to ;) ``` private static Type SafeGetSingleGenericParameter(Type type, Type interfaceType) { if (!interfaceType.IsGenericType || interfaceType.GetGeneri...
I read your question completely differently than the other answers. If the evaluate signature can be changed to: ``` public Type Evaluate<T>(IExtender<T> it) { return typeof(T); } ``` This doesn't require the calling code to change, but does require the parameter to be of type `IExtender<T>`, however you can eas...
How do I determine the value of a generic parameter on my class instance
[ "", "c#", "generics", "reflection", "" ]
Is there anyway to declare an object of a class before the class is created in C++? I ask because I am trying to use two classes, the first needs to have an instance of the second class within it, but the second class also contains an instance of the first class. I realize that you may think I might get into an infinit...
You can't do something like this: ``` class A { B b; }; class B { A a; }; ``` The most obvious problem is the compiler doesn't know how to large it needs to make class A, because the size of B depends on the size of A! You can, however, do this: ``` class B; // this is a "forward declaration" class A { ...
You can't declare an instance of an undefined class but you can declare a **pointer** to one: ``` class A; // Declare that we have a class A without defining it yet. class B { public: A *itemA; }; class A { public: B *itemB; }; ```
Declare an object even before that class is created
[ "", "c++", "class", "object", "instantiation", "" ]
Is it possible to specify a Java `classpath` that includes a JAR file contained within another JAR file?
If you're trying to create a single jar that contains your application and its required libraries, there are two ways (that I know of) to do that. The first is [One-Jar](http://one-jar.sourceforge.net/), which uses a special classloader to allow the nesting of jars. The second is [UberJar](http://classworlds.codehaus.o...
You do NOT want to use those "explode JAR contents" solutions. They definitely make it harder to see stuff (since everything is exploded at the same level). Furthermore, there could be naming conflicts (should not happen if people use proper packages, but you cannot always control this). The feature that you want is o...
Classpath including JAR within a JAR
[ "", "java", "classpath", "" ]
What are some of the new features that can be used in .NET 2.0 that are specific to C# 3.0/3.5 after upgrading to Visual Studio 2008? Also, what are some of the features that aren't available? **Available** * Lambdas * Extension methods (by declaring an empty System.Runtime.CompilerServices.ExtensionAttribute) * Auto...
You can use any new C# 3.0 feature that is handled by the compiler by emitting 2.0-compatible IL and doesn't reference any of the new 3.5 assemblies: * Lambdas (used as `Func<..>`, not `Expression<Func<..>>` ) * Extension methods (by declaring an empty `System.Runtime.CompilerServices.ExtensionAttribute`) * Automatic ...
Pretty much everything! Daniel Moth covers this [here](http://www.danielmoth.com/Blog/2007/05/using-c-30-from-net-20.html) and [here](http://www.danielmoth.com/Blog/2007/05/using-extension-methods-in-fx-20.html). That only leaves runtime support: LINQ-to-Objects is provided by [LINQBridge](http://www.albahari.com/nutsh...
C# .NET 3.0/3.5 features in 2.0 using Visual Studio 2008
[ "", "c#", ".net", "visual-studio", "" ]
What is the best way to make a `<div>` fade away after a given amount of time (without using some of the JavaScript libraries available). I'm looking for a very lightweight solution not requiring a huge JavaScript library to be sent to the browser.
Not sure why you'd be so against using something like jQuery, which would make accomplishing this effect all but trivial, but essentially, you need to wrap a series of changes to the -moz-opacity, opacity, and filter:alpha CSS rules in a setTimeout(). Or, use jQuery, and wrap a fadeOut() call in setTimeout. Your choic...
Here's some javascript that does it. I found it on a javascript tutorial web site somewhere (which I was unable to find again) and modified it. ``` var TimeToFade = 200.0; function fade(eid) { var element = document.getElementById(eid); if(element == null) return; if(element.FadeState == null) { ...
Make a div fade away nicely after a given amount of time
[ "", "javascript", "css", "html", "fade", "" ]
I've been using Xcode for the usual C/C++/ObjC development. I'm wondering what are practical considerations, opinions of Xcode, Eclipse or NetBeans usage on a Mac for Java development? Please don't include my current usage of Xcode in your analysis.
I like [NetBeans](http://netbeans.org/) on OS X for Java. It seems like I spend more time configuring eclipse to get a decent java programming environment. With NetBeans the setup time is less and I can get down to programming quicker...
You missed the Rolls Royce of all IDEs. [IntelliJ Idea](http://www.jetbrains.com/idea/). If you can afford to buy a personal license, go for it. Edit: There’s a free Community Edition which is a superb way to get started with Java, Scala or Kotlin.
Java Development on a Mac - Xcode, Eclipse, or Netbeans
[ "", "java", "eclipse", "xcode", "macos", "netbeans", "" ]
Are there any more generic tools that can "compile" or basically merge multiple PHP files into a single file based on includes and autoloading classes? I'm thinking of something similar to Doctrine's compiling functionality or the compiling that many of the major JS frameworks do for "production" sites to lighten the f...
Out of curiosity, why do you want to do this? If it's for performance, don't bother. Just use regular includes instead of auto-loading, and it will have much of the same effect. For performance you're better off looking at one of the run-time caching solutions.
I am not a php programmer, but I have seen something called "phar" file. Its like jar for php. maybe u shud look into that A quick google search reveals <http://pear.php.net/pepr/pepr-proposal-show.php?id=88> <http://www.pixelated-dreams.com/archives/78-PHAR-PHPs-Answer-to-.jar.html>
PHP Script Compression/"Compilation" Tools
[ "", "php", "optimization", "compilation", "merge", "" ]
I'm looking for something that will monitor Windows directories for size and file count over time. I'm talking about a handful of servers and a few thousand folders (millions of files). Requirements: * Notification on X increase in size over Y time * Notification on X increase in file count over Y time * Historical g...
You might want to take a look at [PolyMon](http://www.codeplex.com/polymon), which is an open source systems monitoring solution. It allows you to write custom monitors in any .NET language, and allows you to create custom PowerShell monitors. It stores data on a SQL Server back end and provides graphing. For your pur...
There are several solutions out there, including some free ones. Some that I have worked with include: [Nagios](http://www.nagios.org/) and [Big Brother](http://bb4.com/) A quick google search can probably find more.
Monitoring Windows directory size
[ "", "java", "ruby", "perl", "powershell", "groovy", "" ]
I thought I'd offer this softball to whomever would like to hit it out of the park. What are generics, what are the advantages of generics, why, where, how should I use them? Please keep it fairly basic. Thanks.
* Allows you to write code/use library methods which are type-safe, i.e. a List<string> is guaranteed to be a list of strings. * As a result of generics being used the compiler can perform compile-time checks on code for type safety, i.e. are you trying to put an int into that list of strings? Using an ArrayList would ...
I really hate to repeat myself. I hate typing the same thing more often than I have to. I don't like restating things multiple times with slight differences. Instead of creating: ``` class MyObjectList { MyObject get(int index) {...} } class MyOtherObjectList { MyOtherObject get(int index) {...} } class Anoth...
What is cool about generics, why use them?
[ "", "c#", "generics", "types", "" ]
We have an "engine" that loads dlls dynamically (whatever is located in a certain directory) and calls Workflow classes from them by way of reflection. We now have some new Workflows that require access to a database, so I figured that I would put a config file in the dll directory. But for some reason my Workflows j...
If your code sample for reading the AppSettings is in your DLL, then it will attempt to read the config file for the application and not the config file for the DLL. This is because you're using Reflection to execute the code.
Funny, where I'm at we're doing something very similar and the config file loads just fine. In our case I think each new config file's name matches that of it's associated assembly. So MyLibrary.dll would have a file named MyLibrary.dll.config with information for that file assembly. Also, the example I have handy is u...
App.config for dll
[ "", "c#", "dll", "app-config", "" ]
Is it possible to unsubscribe an anonymous method from an event? If I subscribe to an event like this: ``` void MyMethod() { Console.WriteLine("I did it!"); } MyEvent += MyMethod; ``` I can un-subscribe like this: ``` MyEvent -= MyMethod; ``` But if I subscribe using an anonymous method: ``` MyEvent += deleg...
``` Action myDelegate = delegate(){Console.WriteLine("I did it!");}; MyEvent += myDelegate; // .... later MyEvent -= myDelegate; ``` Just keep a reference to the delegate around.
One technique is to declare a variable to hold the anonymous method which would then be available inside the anonymous method itself. This worked for me because the desired behavior was to unsubscribe after the event was handled. Example: ``` MyEventHandler foo = null; foo = delegate(object s, MyEventArgs ev) { ...
Unsubscribe anonymous method in C#
[ "", "c#", "delegates", "anonymous-methods", "" ]
I'm looking for a XPath library to query over XML documents in FF, IE, Opera and Safari... and couldn't find one. Have you seen any?
Google has just released Wicked Good XPath - A rewrite of Cybozu Lab's famous JavaScript-XPath. Link: <https://github.com/google/wicked-good-xpath> The rewritten version is 40% smaller and about 30% faster than the original implementation.
[**Google's AJAXSLT**](http://code.google.com/p/ajaxslt/) open source project fits well the stated requirements. As their own description goes to say: "AJAXSLT is an implementation of XSLT in **JavaScript**. Because XSLT uses XPath, **it is also an implementation of XPath that can be used independently of XSLT**. Thi...
Cross-browser XPath implementation in JavaScript
[ "", "javascript", "xml", "xpath", "" ]
I am trying to use the `Directory.GetFiles()` method to retrieve a list of files of multiple types, such as `mp3`'s and `jpg`'s. I have tried both of the following with no luck: ``` Directory.GetFiles("C:\\path", "*.mp3|*.jpg", SearchOption.AllDirectories); Directory.GetFiles("C:\\path", "*.mp3;*.jpg", SearchOption.Al...
For .NET 4.0 and later, ``` var files = Directory.EnumerateFiles("C:\\path", "*.*", SearchOption.AllDirectories) .Where(s => s.EndsWith(".mp3") || s.EndsWith(".jpg")); ``` For earlier versions of .NET, ``` var files = Directory.GetFiles("C:\\path", "*.*", SearchOption.AllDirectories) .Where(s...
How about this: ``` private static string[] GetFiles(string sourceFolder, string filters, System.IO.SearchOption searchOption) { return filters.Split('|').SelectMany(filter => System.IO.Directory.GetFiles(sourceFolder, filter, searchOption)).ToArray(); } ``` I found it here (in the comments): <http://msdn.microsof...
Can you call Directory.GetFiles() with multiple filters?
[ "", "c#", "filesystems", ".net", "" ]
Let's say I have a java program that makes an HTTP request on a server using HTTP 1.1 and doesn't close the connection. I make one request, and read all data returned from the input stream I have bound to the socket. However, upon making a second request, I get no response from the server (or there's a problem with the...
According to your code, the only time you'll even reach the statements dealing with sending the second request is when the server closes the output stream (your input stream) after receiving/responding to the first request. The reason for that is that your code that is supposed to read only the first response ``` whi...
Writing a simple http/1.1 client respecting the RFC is not such a difficult task. To solve the problem of the blocking i/o access where reading a socket in java, you must use java.nio classes. SocketChannels give the possibility to perform a non-blocking i/o access. This is necessary to send HTTP request on a persiste...
HTTP 1.1 Persistent Connections using Sockets in Java
[ "", "java", "http", "sockets", "" ]
I'm making a simple scheduler with C# in .Net. All it does is execute a simple select statement on a table in a SQL Server DB once per minute (this does not need to scale or anything... the db does not have a high load). Here is my proposed implementation: ``` static void Main(string[] args) { while (true) { ...
While it is technically legal you are probably better of using a timer. They are not much more code to set up and you can let the runtime take care of spawning new threads. If you ever needed to use this again in another program it would also create a performance bottleneck where a timer would not. The timer will add ...
Close. 1. This will run every (1 minute + time to call proc). Maybe that's OK, maybe it isn't. If it isn't OK you need to subtract the amount of time it took to ran. 2. You should have a try-catch block around it. You don't want it to die entirely just because of a temporary database or network issue.
Is this an acceptable way to make a simple "scheduler" in C#?
[ "", "c#", "sql-server", "scheduling", "" ]
Is there a Generics Friendly way of using Collection.EMPTY\_LIST in my Java Program. I know I could just declare one myself, but I'm just curious to know if there's a way in the JDK to do this. Something like `users = Collections<User>.EMPTY_LIST;`
By doing the following: ``` List<User> users = Collections.emptyList(); ``` The type of the returned list from `Collections.emptyList();` will be *inferred* as a `String` due to the left-hand-side of the assignment. However, if you prefer to not have this inference, you can define it explicitly by doing the following...
``` List<User> users = Collections.emptyList(); ```
Can I use Collections.EMPTY_LIST wihout an UncheckedException?
[ "", "generics", "java", "" ]
I'm encountering some peculiarities with LINQ to SQL. With a relatively simple query, I want to select some fields, but have the date fields formatted as strings, which I first achieved like this: ``` var list = dataContext.MyLists.Single(x => x.ID == myId); var items = from i in list.MyItems ...
I'd do the SQL part without doing the formatting, then do the formatting on the client side: ``` var items = list.MyItems.Select(item => new { item.ID, item.Sector, item.Description, item.CompleteDate, item.DueDate }) .AsEnumerable() // Don't do th...
In the first query, you have already got the data back from the database by the time the second line runs (var items = ...). This means that the 2nd line runs at the client, where ToShortDateString can run quite happily. In the second query, because the select runs directly on an IQueryable collection (dataContext.MyL...
LINQ to SQL Peculiarities
[ "", "c#", "linq", "linq-to-sql", "" ]
I'm currently working on the `Tips.js` from `mootools` library and my code breaks on the line that has those `el.$tmp`, and console says it's undefined Can anybody help me?
in 1.11 (haven't checked in 1.2+) $tmp is a reference to the element itself, created and used internally by the garbage collector: ``` var Garbage = { elements: [], collect: function(el){ if (!el.$tmp){ Garbage.elements.push(el); el.$tmp = {'opacity': 1}; } ret...
I'd suggest taking your question and posting it, along with a link to the page to either/or/and: <http://mooforum.net> <http://groups.google.com/group/mootools-users/topics> That's the community that swarms with it. Now as for answering it here - I'd need a lot more information (code example?)
mootools or javascript : what does $tmp stand for or what does it pertain too
[ "", "javascript", "mootools", "" ]
I have a helper class pulling a string from an XML file. That string is a file path (so it has backslashes in it). I need to use that string as it is... How can I use it like I would with the literal command? Instead of this: ``` string filePath = @"C:\somepath\file.txt"; ``` I want to do this: ``` string filePath ...
I don't think you have to worry about it if you already have the value. The @ operator is for when you're specifying the string (like in your first code snippet). What are you attempting to do with the path string that isn't working?
I'm not sure if I understand. In your example: if `helper.getFilePath()` returns `"c:\somepath\file.txt"`, there will be no problem, since the `@` is only needed if you are explicitely specifying a string with "". When Functions *talk to each other*, you will always get the literal path. If the XML contains `c:\somepa...
Using the literal '@' with a string variable
[ "", "c#", "string", "" ]
I want to make sure people can't type the name of a PHP script in the URL and run it. What's the best way of doing this? I could set a variable in the file that will be including this file, and then check that variable in the file being included, but is there an easier way?
You could check the URI and see if that file is being called with ` ``` $_SERVER['SCRIPT_FILENAME'] ``` or you could move the file outside the public folder, this is a better solution.
In a few of the open source applications I've poked around in, including Joomla and PHPBB, they declare a constant in the main includes file, and then verify that constant exists in each of the includes: ``` // index.php require_once 'includes.php'; // includes.php define('IN_MY_PROJECT', true); include 'myInc.php'; ...
What's the best way to only allow a PHP file to be included?
[ "", "php", "" ]
Given: ``` interface I { } class B: I { } class C: I { } class A { public void Method(B arg) { } public void Method(C arg) { } public void Method(I arg) { // THIS is the method I want to simplify. if (I is B) { this.Method(arg as B); } ...
What you want is [double dispatch](http://en.wikipedia.org/wiki/Double_dispatch), and [visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern) in particular.
I would put the method inside the interface and then let polymorphism decide which method to call ``` interface I { void Method(); } class B : I { public void Method() { /* previously A.Method(B) */} } class C : I { public void Method() { /* previously A.Method(C) */ } } class A { public void Method(I o...
conditional logic based on type
[ "", "c#", ".net", "polymorphism", "" ]
How do I fix that error once and for all? I just want to be able to do unions in MySQL. (I'm looking for a shortcut, like an option to make MySQL ignore that issue or take it's best guess, not looking to change collations on 100s of tables ... at least not today)
Not sure about mySQL but in MSSQL you can change the collation in the query so for example if you have 2 tables with different collation and you want to join them or as in you situation crate UNION you can do ``` select column1 from tableWithProperCollation union all select column1 COLLATE SQL_Latin1_General_CP1_CI_AS...
Thanks Kristof. In this case it was being caused by selecting a literal in the first select, and not from any different table collations. Ironically I got it working by following this [old blog post](http://www.answermysearches.com/mysql-fixing-illegal-mix-of-collations-message/352/) I made for that issue.
MySQL - Illegal mix of collations (utf8_general_ci,COERCIBLE) and (latin1_swedish_ci,IMPLICIT) for operation 'UNION'
[ "", "sql", "mysql", "unicode", "union", "collation", "" ]
Is there any way to determine a removable drive speed in Windows without actually reading in a file. And if I do have to read in a file, how much needs to be read to get a semi accurate speed (e.g. determine whether a device is USB2 or USB1)? **EDIT**: Just to clarify, USB2 and USB1 were an example. These could be Com...
[WMI - Physical Disks Properties](http://www.computerperformance.co.uk/vbscript/wmi_disks_physical.htm) is an article I found which would at least help you figure out what you have connected. I foresee things heading toward tables equating particular manufacturers and models to speeds, which is not as simple a solution...
You may have better results querying the operating system for information about the hardware rather than trying to reverse engineer it from data transfer timing information. For example, identical transfer speeds don't necessarily mean the same technology is being used by two devices, although other factors such as se...
Any way to determine speed of a removable drive in windows?
[ "", "c++", "windows", "removable-storage", "" ]
Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there i...
One issue is that there is a race condition in your above code, since there is a gap between testing for existance, and creating the file. There may be security implications to this (think about someone maliciously inserting a symlink to a sensitive file which they wouldn't be able to overwrite, but your program runnin...
Yes, this is a good strategy for readable but unique filenames. **One important change**: You should replace `os.path.isfile` with `os.path.lexists`! As it is written right now, if there is a directory named /foo/bar.baz, your program will try to overwrite that with the new file (which won't work)... since `isfile` on...
Is this the best way to get unique version of filename w/ Python?
[ "", "python", "filenames", "" ]
In an aspx C#.NET page (I am running framework v3.5), I need to know where the user came from since they cannot view pages without logging in. If I have page `A` (the page the user wants to view) redirect to page `B` (the login page), the Request.UrlReferrer object is null. Background: If a user isn't logged in, I red...
If you use the standard Membership provider, and set the Authorization for the directory/page, the code will automatically set a query parameter of ReturnUrl and redirect after a successfull login. If you don't want to use the Membership provider pattern, I would suggest manually doing the query string parameter thing...
UrlReferrer is based off the [HTTP\_REFERER](http://en.wikipedia.org/wiki/Referer) header that a browser *should* send. But, as with all things left up to the client, it's variable. I know some "security" suites (like Norton's Internet Security) will strip that header, in the belief that it aids tracking user behavior...
Request.UrlReferrer null?
[ "", "c#", ".net", "visual-studio", "visual-studio-2008", "" ]
I'm not sure if this is something I should do in T-SQL or not, and I'm pretty sure using the word 'iterate' was wrong in this context, since you should never iterate anything in sql. It should be a set based operation, correct? Anyway, here's the scenario: I have a stored proc that returns many uniqueidentifiers (sing...
This may not be the most efficient, but I would create a temp table to hold the results of the stored proc and then use that in a join against the target table. For example: ``` CREATE TABLE #t (uniqueid int) INSERT INTO #t EXEC p_YourStoredProc UPDATE TargetTable SET a.FlagColumn = 1 FROM TargetTable a JOIN #t b ...
You could also change your stored proc to a user-defined function that returns a table with your uniqueidentifiers. You can joing directly to the UDF and treat it like a table which avoids having to create the extra temp table explicitly. Also, you can pass parameters into the function as you're calling it, making this...
How can one iterate over stored procedure results from within another stored procedure....without cursors?
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
Currently I have this (edited after reading advice): ``` struct Pair<T, K> : IEqualityComparer<Pair<T, K>> { readonly private T _first; readonly private K _second; public Pair(T first, K second) { _first = first; _second = second; } public T First { get { return _first; } } ...
It looks like you need IEquatable instead: ``` internal struct Pair<T, K> : IEquatable<Pair<T, K>> { private readonly T _first; private readonly K _second; public Pair(T first, K second) { _first = first; _second = second; } public T First { get { return _first; } } public K Second {...
Your IEqualityComparer implementation should be a different class (and definately not a struct as you want to reuse the reference). Also, your hashcode should never be cached, as the default GetHashcode implementation for a struct (which you do not override) will take that member into account.
How do I implement IEqualityComparer on an immutable generic Pair struct?
[ "", "c#", "generics", "struct", "" ]