Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm writing an application and I'm trying to tie simple AJAX functionality in. It works well in Mozilla Firefox, but there's an interesting bug in Internet Explorer: Each of the links can only be clicked once. The browser must be completely restarted, simply reloading the page won't work. I've written a [very simple ex...
This happens because Internet Explorer ignores the no-cache directive, and caches the results of ajax calls. Then, if the next request is identical, it will just serve up the cached version. There's an easy workaround, and that is to just append random string on the end of your query. ``` xmlHttp.open("GET","blurb.ph...
It looks like IE is caching the response. If you either change your calls to POST methods, or send the appropriate headers to tell IE not to cache the response, it should work. The headers I send to be sure it doesn't cache are: ``` Pragma: no-cache Cache-Control: no-cache Expires: Fri, 30 Oct 1998 14:19:41 GMT ``` ...
Internet Explorer 7 Ajax links only load once
[ "", "javascript", "ajax", "internet-explorer", "" ]
I just migrated to Windows Ultimate 64 SP1, because my system's hard drive crashed. I installed Visual Studio 2005 SP1 and all the patches that Microsoft has recommended. I finally got my source code from my SCM, but now debugging does not stop on any of my breakpoints I have set. This is just a plain Winforms app, not...
This is listed as a [known issue for VS2005 on Vista (Via MSDN):](http://msdn.microsoft.com/en-us/vstudio/aa964140.aspx#question20a) > **Title**: Just-In-Time (JIT) Debugging of > an elevated process will fail > > **Description**: Elevated processes cannot > be JIT Debugged by VS 2005. This > includes system processes...
Couple of questions. When your code fires up, does the breakpoint become an empty circle with a tooltip that indicates that the breakpoint won't be hit? Or does it become a full circle with a tooltip that indicates the process it's attached to? You can try manually attaching the debugger to see if you get any tractio...
VS2005 SP1 breakpoints in Vista Ultimate 64 not working
[ "", "c#", "visual-studio-2005", "vista64", "" ]
Consider the following two ways of writing a loop in Java to see if a list contains a given value: ### Style 1 ``` boolean found = false; for(int i = 0; i < list.length && !found; i++) { if(list[i] == testVal) found = true; } ``` ### Style 2 ``` boolean found = false; for(int i = 0; i < list.length && !foun...
Well, just write a micro benchmark: ``` import java.util.*; public class Test { private static int[] list = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9} ; private static int testVal = 6; public static boolean version1() { boolean found = false; for(int i = 0; i < list.length && !found; i++) ...
Comment about nitpicks corner: If you're *really* concerned with absolute performance, putting a break in and removing the "&& !found" will give you theoretically better performance on #1. Two less binary ops to worry about every iteration. If you wanted to get really anal about optimization without using breaks then...
Will reassigning a variable in every iteration of a loop affect performance?
[ "", "java", "optimization", "" ]
What is the fastest list implementation (in java) in a scenario where the list will be created one element at a time then at a later point be read one element at a time? The reads will be done with an iterator and then the list will then be destroyed. I know that the Big O notation for get is O(1) and add is O(1) for...
It depends largely on whether you know the maximum size of each list up front. If you do, use `ArrayList`; it will certainly be faster. Otherwise, you'll probably have to profile. While access to the `ArrayList` is O(1), creating it is not as simple, because of dynamic resizing. Another point to consider is that the...
**First Thoughts:** * Refactor your code to not need the list. * Simplify the data down to a scalar data type, then use: **int[]** * Or even just use an array of whatever object you have: **Object[]** - John Gardner * Initialize the list to the full size: **new ArrayList(123);** Of course, as everyone else is mention...
Which list<Object> implementation will be the fastest for one pass write, read, then destroy?
[ "", "java", "list", "collections", "big-o", "" ]
Has anyone used [Pear: Spreadsheet\_Excel\_Writer](http://pear.php.net/package/Spreadsheet_Excel_Writer/)? The [Formatting Tutorial](http://pear.php.net/manual/en/package.fileformats.spreadsheet-excel-writer.intro-format.php) lists a script similar to what I'm working with: (trimmed down) ``` <?php require_once 'Spre...
Here is some sample code: ``` <?php require_once 'Spreadsheet/Excel/Writer.php'; $workbook = new Spreadsheet_Excel_Writer('test.xls'); $worksheet =& $workbook->addWorksheet('My first worksheet'); if (PEAR::isError($worksheet)) { die($worksheet->getMessage()); } $workbook->close(); ?> ``` I think for starters, giv...
It is not very clear, but I think that the send command only creates the headers with the correct content type and file name. You have to send the data afterwards, with something lik ``` $tmpDocument = '/path/to/tmp/file.xls'; $workbook = new Spreadsheet_Excel_Writer($tmpDocument); ``` /\* Code to generate the XLS fi...
PHP PEAR Spreadsheet_Excel_Writer sending an empty file
[ "", "php", "export-to-excel", "pear", "" ]
Are there any plugins/tools available to go through the classpath of an eclipse project (or workspace) and highlight any unused jars?
[ClassPathHelper](http://classpathhelper.sourceforge.net/) is a good start. It automatically identifies orphan jars and much more. The only limitation is with dependencies that are not defined in classes, e.g. in dependency injection framework configuration files. You also have other options/complements, such as: *...
**UCDetector** does not help for this : It does not work on JARs. And for **classpathHelper**, I wan't able to find out an easy way just to list the orphan JARs (BTW, if someone has a tutorial for this, i am interested). So, if you are also using Maven as I do, I find out [this great Maven plugin](http://maven.apache....
Finding unused jars used in an eclipse project
[ "", "java", "eclipse", "jar", "" ]
Anyone have a good resource or provide a sample of a natural order sort in C# for an `FileInfo` array? I am implementing the `IComparer` interface in my sorts.
The easiest thing to do is just P/Invoke the built-in function in Windows, and use it as the comparison function in your `IComparer`: ``` [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)] private static extern int StrCmpLogicalW(string psz1, string psz2); ``` Michael Kaplan has some [examples of how this function...
Just thought I'd add to this (with the most concise solution I could find): ``` public static IOrderedEnumerable<T> OrderByAlphaNumeric<T>(this IEnumerable<T> source, Func<T, string> selector) { int max = source .SelectMany(i => Regex.Matches(selector(i), @"\d+").Cast<Match>().Select(m => (int?)m.Value.Len...
Natural Sort Order in C#
[ "", "c#", "sorting", "file", "natural-sort", "" ]
Does anyone know of a graphing library for simple transformation of a point from one coordinate system to another coordinate system which is rotated by a angle and some point transformation and just for 2d? And any graphing tool for plotting and verifying the same visually?
double[3][3]
The [Angtigrain Geometry](http://www.antigrain.com/) library contains code that can do this, and you can also go farther and use it for drawing as well, but you don't have to. You should look at the agg::trans\_affine class in the agg\_trans\_affine.h file. Dave
C++ library for rotating a point over a given axis?
[ "", "c++", "geometry", "graph", "point", "" ]
Would it be possible to write a class that is virtually indistinguishable from an actual PHP array by implementing all the necessary SPL interfaces? Are they missing anything that would be critical? I'd like to build a more advanced Array object, but I want to make sure I wouldn't break an existing app that uses array...
The only problems i can think of are the gettype() and the is\_array() functions. Check your code for ``` gettype($FakeArray) == 'array' is_array($FakeArray) ``` Because although you can use the object just like an array, it will still be identified as an object.
In addition to the points made above, you would not be able to make user-space array type hints work with instances of your class. For example: ``` <?php function f(array $a) { /*...*/ } $ao = new ArrayObject(); f($ao); //error ?> ``` Output: ``` Catchable fatal error: Argument 1 passed to f() must be an array, obj...
PHP's SPL: Do its interfaces involving arrays cover all array properties?
[ "", "php", "arrays", "spl", "" ]
I have a private const int defined in a C# class. I want compilation to fail with an error if the value of this int mod 3 != 0. How can I accomplish this?
Timothy Khouri almost got it. It should be this: ``` int compilerError = 1 / (MY_CONST % 3 == 0 ? 1 : 0); ```
Although there is an [*#error*](http://msdn.microsoft.com/en-us/library/x5hedts0.aspx) pre-processor directive for generating compile-time errors, there is no way for it to be based on the existence of a const value. It only works with compiler symbols, like "DEBUG", for which a value can't be assigned.
Force C# compiler error based on const value
[ "", "c#", "compiler-construction", "" ]
I'm wondering if it is possible to add methods in main program to an existing class defined in header file. For example: There is `class CFun` defined in file `CFun.hpp`, but in our `party.cpp` we want to add a method `void hello() {cout << "hello" << endl;};`without editing `CFun.hpp` Obviously (unfortunately) constr...
No, but you could add a method that takes a reference/pointer to a CFun class - you just won't have access to private data: ``` void Hello(CFun &fun) { cout << "hello" << endl; } ``` This is probably the best you'll be able to do. As pointed out by litb - this function has to be in the same namespace as CFun. For...
You can redefine the class like this: ``` #define CFun CLessFun #include "CFun.hpp" #undef CFun class CFun : CLessFun { public: void hello() {cout << "hello" << endl;}; }; ``` Put this in a new header file `CMoreFun.hpp` and include that instead of `CFun.hpp`
c++ adding method to class defined in header file
[ "", "c++", "file", "class", "header", "methods", "" ]
A [similar question discusses `__construct`](https://stackoverflow.com/questions/217618/construct-vs-sameasclassname-for-constructor-in-php), but I left it in my title for people searching who find this one. Apparently, \_\_get and \_\_set take a parameter that is the variable being gotten or set. However, you have to...
[This page](http://uk.php.net/manual/en/language.oop5.overloading.php) will probably be useful. (Note that what you say is incorrect - `__set()` takes as a parameter both the name of the variable and the value. `__get()` just takes the name of the variable). `__get()` and `__set()` are useful in library functions wher...
\_\_get(), \_\_set(), and \_\_call() are what PHP calls "magic methods" which is a moniker I think that is a bit silly - I think "hook" is a bit more apt. Anyway, I digress... The purpose of these is to provide execution cases for when datamembers (properties, or methods) that *are not* defined on the object are acces...
When do/should I use __construct(), __get(), __set(), and __call() in PHP?
[ "", "php", "magic-function", "" ]
I'm using a the TreeView control and it scrolls automatically to left-align TreeViewItem when one of them is clicked. I've gone looking at my Styles and ControlTemplates, but I haven't found anything. Is there a default ControlTemplate that causes this? I want to disable it.
The items scroll because the ScrollViewer calls BringIntoView() on them. So one way to avoid scrolling is to suppress the handling of the RequestBringIntoView event. You can try that out quickly by subclassing TreeView and instantiating this control instead: ``` public class NoScrollTreeView : TreeView { public cl...
after spending some hours on this problem i found a solution that works for me. brians solution to prevent the RequestBringIntoView event on a TreeViewItem from bubbling was the first step. unfortunately this also stops a treeviewitem to be shown if you change the selected item programmatically by ``` yourtreeview.Se...
WPF ControlTemplate for scrolling TreeView Control
[ "", "c#", "wpf", "" ]
I'm looking for a library that has functionality similar to Perl's [WWW::Mechanize](http://search.cpan.org/dist/WWW-Mechanize/lib/WWW/Mechanize.pm#SYNOPSIS), but for PHP. Basically, it should allow me to submit HTTP GET and POST requests with a simple syntax, and then parse the resulting page and return in a simple for...
SimpleTest's [ScriptableBrowser](http://simpletest.sourceforge.net/en/browser_documentation.html) can be used independendly from the testing framework. I've used it for numerous automation-jobs.
I feel compelled to answer this, even though its an old post... I've been working with PHP curl a lot and it is not as good anywhere near comparable to something like WWW:Mechanize, which I am switching to (I think I am going to go with the Ruby language implementation).. Curl is outdated as it requires too much "grunt...
Is there a PHP equivalent of Perl's WWW::Mechanize?
[ "", "php", "automation", "screen-scraping", "mechanize", "www-mechanize", "" ]
Is it possible in .NET to ascertain whether my application is closing due to Windows being given a shutdown command (as opposed to any old application closing) in order to either write out some temporary cache files or even block the shutdown long enough to prompt for user input? Whilst my current scope involves a Win...
[SystemEvents.SessionEnding](http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.sessionending.aspx) looks like a good starting point for you. That article talks about the event sequence involved when a logout/shutdown is occurring.
In general, you will want to handle the [`WM_QUERYENDSESSION`](http://msdn.microsoft.com/en-us/library/aa376890(VS.85).aspx) Windows message. This will give your application a chance to do cleanup, or to block the shutdown if it's really necessary.
Ascertaining a shutdown is closing my application
[ "", "c#", ".net", "shutdown", "" ]
I want to do a select in MySql that combines several columns... something like this pseudocode: ``` SELECT payment1_paid AND payment2_paid AS paid_in_full FROM denormalized_payments WHERE payment1_type = 'check'; ``` **Edit**: payment1\_paid and payment2\_paid are booleans. I can't use any other language for this ...
Ok, for logical and you can do ``` Select (payment1_paid && payment2_paid) as paid_in_full from denormalized_payments where payment1_type = 'check'; ``` As seen [here](http://dev.mysql.com/doc/refman/5.0/en/logical-operators.html#operator_and).
Just do ``` Select CONCAT(payment1_paid, payment2_paid) as paid_in_full from denormalized_payments where payment1_type = 'check'; ``` You can concat any number of field you want.
How can I do boolean logic on two columns in MySQL?
[ "", "sql", "mysql", "select", "boolean", "" ]
I have a strange issue: I am using SPContext.Current.Web in a .aspx page, but at the end, I get a "Trying to use an SPWeb object that has been closed or disposed and is no longer valid." error message. From what I see, SPContext.Current.Web is Disposed by someone, **but I have no idea where**. I just wonder: With Visu...
Check if this helps: 1. Add a new breakpoint using **Debug > New Breakpoint > Break at Function... (Ctrl+B)**. 2. Enter **Microsoft.SharePoint.SPWeb.Dispose** in the Function edit box. 3. Dismiss the dialog box that says that Intellisense could not find the specified location. 4. Run under the debugger. 5. When the br...
In your custom code make sure you didn't get a reference to the actual SPWeb object of the Context object and dispose of it. For example, the following is very bad. ``` using (SPWeb myWeb = SPContext.Current.Web) { // do something } ``` This will cause the SPContext's object to be disposed and may not cause an iss...
Where is my Object being disposed?
[ "", "c#", ".net", "sharepoint", "" ]
I have headers in `<h1>` through `<h6>` tags. Is there a way that I can use JavaScript to generate a table of contents for the contents that serves as anchor tags as well? I would like the output to be something like: ``` <ol> <li>Header 1</li> <li>Header 1</li> <li>Header 2</li> <li>Heade...
I couldn't resist putting together a quick implementation. Add the following script anywhere on your page: ``` window.onload = function () { var toc = ""; var level = 0; document.getElementById("contents").innerHTML = document.getElementById("contents").innerHTML.replace( /<h([\d])>([...
Here's a great script to do this: <https://github.com/matthewkastor/html-table-of-contents/wiki> To use it: 1. Add this tag: ``` <script src="./node_modules/html-table-of-contents/src/html-table-of-contents.js" type="text/javascript"> ``` 2. Call the function, such as in your body's onload attribute: `...
Is there a JavaScript solution to generating a "table of contents" for a page?
[ "", "javascript", "tableofcontents", "html-heading", "" ]
I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). * Google shows many hits for explanations on how to do this. * Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different. I need to know how to enable, tab/...
Use Python's `readline` bindings. For example, ``` import readline def completer(text, state): options = [i for i in commands if i.startswith(text)] if state < len(options): return options[state] else: return None readline.parse_and_bind("tab: complete") readline.set_completer(completer) ...
Follow the [cmd documentation](http://docs.python.org/library/cmd.html#cmd.Cmd.cmdloop) and you'll be fine ``` import cmd addresses = [ 'here@blubb.com', 'foo@bar.com', 'whatever@wherever.org', ] class MyCmd(cmd.Cmd): def do_send(self, line): pass def complete_send(self, text, line, star...
How to make a python, command-line program autocomplete arbitrary things NOT interpreter
[ "", "python", "linux", "unix", "command-line", "autocomplete", "" ]
I'm building an open source project that uses python and c++ in Windows. I came to the following error message: ``` ImportError: No module named win32con ``` The same happened in a "prebuilt" code that it's working ( except in my computer :P ) I think this is kind of "popular" module in python because I've saw seve...
This module contains constants related to Win32 programming. It is not part of the Python 2.6 release, but should be part of the download of the pywin32 project. **Edit:** I imagine that the executable is an installation program, though the last time I downloaded pywin32 it was just a zip file.
``` pip install pypiwin32 ``` [Glyph](https://glyph.twistedmatrix.com) had packed packed it until somebody sends patch to build wheels as part of `pywin32` build process to close <https://sourceforge.net/p/pywin32/bugs/680/>
What's win32con module in python? Where can I find it?
[ "", "python", "module", "" ]
I am creating a small web page using PHP that will be accessed as an IFRAME from a couple of sites. I'm wanting to restrict access to this site to work ONLY within the "approved" sites, and not other sites or accessed directly. Does anyone have any suggestions? Is this even possible? The PHP site will be Apache, and th...
Thanks for all the great ideas! I think the solution I'm going to go with is a session cookie set by the approved "iframing" site. Someone really determined will still be able to get the content, but I think I can prevent most of the abuse by coming up with a decent "secret" algorithm based on some sort of shared secre...
Thinking about this... I'm not convinced this is completely secure, but here's a shot while I think about it more - The only way you could do this, is if you control the sites it would be embedded in. If you control them, you could pass the time, encrypted, from the frameset to the frame: > ``` > <iframe src="http:/...
Restricting IFRAME access in PHP
[ "", "php", "security", "iframe", "" ]
I have a class with a nullable int? datatype set to serialize as an xml element. Is there any way to set it up so the xml serializer will not serialize the element if the value is null? I've tried to add the `[System.Xml.Serialization.XmlElement(IsNullable=false)]` attribute, but I get a runtime serialization exceptio...
XmlSerializer supports the `ShouldSerialize{Foo}()` pattern, so you can add a method: ``` public bool ShouldSerializeID() {return ID.HasValue;} ``` There is also the `{Foo}Specified` pattern - not sure if XmlSerializer supports that one.
I'm using this micro-pattern to implement Nullable serialization: ``` [XmlIgnore] public double? SomeValue { get; set; } [XmlAttribute("SomeValue")] // or [XmlElement("SomeValue")] [EditorBrowsable(EditorBrowsableState.Never)] public double XmlSomeValue { get { return SomeValue.Value; } set { SomeValue= value; } } ...
How to serialize a nullable int without "xsi:nil" being added to the resulting XML?
[ "", "c#", ".net", "xml", "serialization", "" ]
I just came onto a project with a pretty huge code base. I'm mostly dealing with C++ and a lot of the code they write uses double negation for their boolean logic. ``` if (!!variable && (!!api.lookup("some-string"))) { do_some_stuff(); } ``` I know these guys are intelligent programmers, it's obvious they a...
It's a trick to convert to bool.
It's actually a very useful idiom in some contexts. Take these macros (example from the Linux kernel). For GCC, they're implemented as follows: ``` #define likely(cond) (__builtin_expect(!!(cond), 1)) #define unlikely(cond) (__builtin_expect(!!(cond), 0)) ``` Why do they have to do this? GCC's `__builtin_expect` tr...
Double Negation in C++
[ "", "c++", "boolean", "" ]
Suppose I have the following two strings containing regular expressions. How do I coalesce them? More specifically, I want to have the two expressions as alternatives. ``` $a = '# /[a-z] #i'; $b = '/ Moo /x'; $c = preg_magic_coalesce('|', $a, $b); // Desired result should be equivalent to: // '/ \/[a-zA-Z] |Moo/' ``` ...
I see that porneL actually [described](https://stackoverflow.com/questions/244959/coalescing-regular-expressions-in-php#245326) a bunch of this, but this handles most of the problem. It cancels modifiers set in previous sub-expressions (which the other answer missed) and sets modifiers as specified in each sub-expressi...
## EDIT **I’ve rewritten the code!** It now contains the changes that are listed as follows. Additionally, I've done extensive tests (which I won’t post here because they’re too many) to look for errors. So far, I haven’t found any. * The function is now split into two parts: There’s a separate function `preg_split` ...
Coalescing regular expressions in PHP
[ "", "php", "regex", "abstract-syntax-tree", "" ]
Windbg fans claim that it is quite powerful and I tend to agree. But when it comes to debugging STL containers, I am always stuck. If the variable is on the stack, the `!stl` extension sometimes figures it out, but when a container with a complex type (e.g. `std::vector<TemplateField, std::allocator<TemplateField> >`) ...
You might also want to give this [debugger extension](http://www.nynaeve.net/?p=7) a try. It is a library called SDbgExt, developed by [Skywing](http://www.nynaeve.net).
I often find debugger support for STL data types inadequate. For this reason I'm increasingly using [logging frameworks and logging statements](http://www.spinellis.gr/blog/20060501/). I used to think that these are for people who can't use a debugger, but I now realize that they offer real value. They allow you to emb...
Debugging C++ STL containers in Windbg
[ "", "c++", "stl", "windbg", "" ]
In .NET, Windows Forms have an event that fires before the Form is loaded (Form.Load), but there is no corresponding event that is fired AFTER the form has loaded. I would like to execute some logic after the form has loaded. Can anyone advise on a solution?
You could use the "Shown" event: [MSDN - Form.Shown](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.shown.aspx) "The Shown event is only raised the first time a form is displayed; subsequently minimizing, maximizing, restoring, hiding, showing, or invalidating and repainting will not raise this even...
I sometimes use (in Load) ``` this.BeginInvoke((MethodInvoker) delegate { // some code }); ``` or ``` this.BeginInvoke((MethodInvoker) this.SomeMethod); ``` (change "this" to your form variable if you are handling the event on an instance other than "this"). This pushes the invoke onto the windows-forms loop, so...
How do I execute code AFTER a form has loaded?
[ "", "c#", ".net", "winforms", "events", "" ]
I have a `GridView` control in an Asp.net application, that has a `<asp:buttonField>` of `type="image"` and `CommandName="Delete"`. Is there any way to execute a piece of javascript before reaching the `OnRowDelete` event? I want just a simple confirm before deleting the row. Thanks! **EDIT**: Please Note that `<as...
I would use a TemplateField instead, and populate the ItemTemplate with a regular asp:Button or asp:ImageButton, depending one what is needed. You can then execute the same logic that the RowCommand event was going to do when it intercepted the Delete command. On either of those buttons I would then use the OnClientCl...
I found that the most elegant way to do this is to use jQuery to wire the onClick event: ``` <script type="text/javascript"> $(".deleteLink").click(function() { return confirm('Are you sure you wish to delete this record?'); }); </script> ... <asp:ButtonField ButtonType="Link" Text="Delete" Comman...
Javascript before asp:ButtonField click
[ "", "asp.net", "javascript", "gridview", "" ]
I have a JSP page that will display the exact content of another web page on a different server. My understanding was that c:import from the JSTL should be able to include content from files that are not part of the current web application. I added c:import url="page on my server in a different application" and it wor...
I had a similar error once. It turned out to be that the machine that I was running the app on had some problems connecting to the internet through the firewall. Once I deployed the app to a machine that was always connected it worked fine.
An exact code and how "it fails" would be a great help. All mind-readers are currently on vacation. Meanwhile, take a look at <http://www.ibm.com/developerworks/java/library/j-jsp06173.html> ``` <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> ... <c:import url="http://www.truenorthguitars.com/Clients/...
Importing the content of another web resource using JSTL
[ "", "java", "jsp", "import", "jstl", "" ]
I tried searching around, but I couldn't find anything that would help me out. I'm trying to do this in SQL: ``` declare @locationType varchar(50); declare @locationID int; SELECT column1, column2 FROM viewWhatever WHERE CASE @locationType WHEN 'location' THEN account_location = @locationID WHEN 'area' THEN ...
``` declare @locationType varchar(50); declare @locationID int; SELECT column1, column2 FROM viewWhatever WHERE @locationID = CASE @locationType WHEN 'location' THEN account_location WHEN 'area' THEN xxx_location_area WHEN 'division' THEN xxx_location_division END ```
without a case statement... ``` SELECT column1, column2 FROM viewWhatever WHERE (@locationType = 'location' AND account_location = @locationID) OR (@locationType = 'area' AND xxx_location_area = @locationID) OR (@locationType = 'division' AND xxx_location_division = @locationID) ```
SQL Switch/Case in 'where' clause
[ "", "sql", "switch-statement", "case", "" ]
This question will expand on: [Best way to open a socket in Python](https://stackoverflow.com/questions/68774/best-way-to-open-a-socket-in-python) When opening a socket how can I test to see if it has been established, and that it did not timeout, or generally fail. Edit: I tried this: ``` try: s.connect((...
It seems that you catch not the exception you wanna catch out there :) if the `s` is a `socket.socket()` object, then the right way to call `.connect` would be: ``` import socket s = socket.socket() address = '127.0.0.1' port = 80 # port number is a number, not string try: s.connect((address, port)) # origi...
You can use the function [connect\_ex](http://docs.python.org/2/library/socket.html#socket.socket.connect_ex). It doesn't throw an exception. Instead of that, returns a C style integer value (referred to as [errno](http://linux.die.net/man/3/errno) in C): ``` s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) resu...
Testing socket connection in Python
[ "", "python", "sockets", "" ]
We have the following simple Stored Procedure that runs as an overnight SQL server agent job. Usually it runs in 20 minutes, but recently the MatchEvent and MatchResult tables have grown to over 9 million rows each. This has resulted in the store procedure taking over 2 hours to run, with all 8GB of memory on our SQL b...
There's probably a lot of stuff going on here, and it's not all your query. First, I agree with the other posters. Try to rewrite this without a temp table if at all possible. But assuming that you need a temp table here, you have a BIG problem in that you have no PK defined on it. It's vastly going to expand the amo...
First, indexes are a MUST here see Dave M's answer. Another approach that I will sometime use when deleting very large data sets, is creating a shadow table with all the data, recreating indexes and then using sp\_rename to switch it in. You have to be careful with transactions here, but depending on the amount of dat...
SQL stored procedure temporary table memory problem
[ "", "sql", "sql-server", "stored-procedures", "" ]
I was wondering if there was an alternative to `itoa()` for converting an integer to a string because when I run it in visual Studio I get warnings, and when I try to build my program under Linux, I get a compilation error.
In C++11 you can use [`std::to_string`](http://en.cppreference.com/w/cpp/string/basic_string/to_string): ``` #include <string> std::string s = std::to_string(5); ``` If you're working with prior to C++11, you could use C++ streams: ``` #include <sstream> int i = 5; std::string s; std::stringstream out; out << i; s...
[boost::lexical\_cast](http://www.boost.org/doc/libs/1_36_0/libs/conversion/lexical_cast.htm) works pretty well. ``` #include <boost/lexical_cast.hpp> int main(int argc, char** argv) { std::string foo = boost::lexical_cast<std::string>(argc); } ```
Alternative to itoa() for converting integer to string C++?
[ "", "c++", "integer", "stdstring", "itoa", "" ]
I have the following problem using template instantiation [\*]. file **foo.h** ``` class Foo { public: template <typename F> void func(F f) private: int member_; }; ``` file **foo.cc** ``` template <typename F> Foo::func(F f) { f(member_); } ``` file **caller.cc** ``` Foo::func(boost::bind(&Bar:...
The answer to this is compiler dependent. Some versions of the Sun C++ compiler would handle this automatically by building a cache of template function implementations that would be shared across separate translation units. If you're using Visual C++, and any other compiler that can't do this, you may as well put the...
Splitting it into files Like you want: Not that I recommend this. Just showing that it is possible. plop.h ``` #include <iostream> class Foo { public: Foo(): member_(15){} // Note No definition of this in a header file. // It is defined in plop.cpp and a single instantiation forced // Without actu...
C++ template instantiation of function template parameters
[ "", "c++", "templates", "boost", "function", "linker", "" ]
I've just had to write a string reverse function in C# 2.0 (i.e. LINQ not available) and came up with this: ``` public string Reverse(string text) { char[] cArray = text.ToCharArray(); string reverse = String.Empty; for (int i = cArray.Length - 1; i > -1; i--) { reverse += cArray[i]; } ...
``` public static string Reverse( string s ) { char[] charArray = s.ToCharArray(); Array.Reverse(charArray); return new string(charArray); } ```
Here a solution that properly reverses the string `"Les Mise\u0301rables"` as `"selbare\u0301siM seL"`. This should render just like `selbarésiM seL`, not `selbaŕesiM seL` (note the position of the accent), as would the result of most implementations based on code units (`Array.Reverse`, etc) or even code points (reve...
Best way to reverse a string
[ "", "c#", ".net", "performance", "algorithm", "unicode", "" ]
I'm developing an application that manages network interfaces on behalf of the user and it calls out to several external programs (such as ifconfig) that requires root to make changes. (Specifically, changing the IP address of a local interface, etc.) During development, I have been running the IDE as root (ugh) and th...
Your idea about the daemon has much merit, despite the complexity it introduces. As long as the actions don't require some user interface interaction *as root*, a daemon allows you to control what operations are allowed and disallowed. However, you can use SUDO to create a controlled compromise between ROOT and normal...
What you want is a "Group" You create a group, specify that the account wanting to do the action belongs to the group, then you specify that the resource you want access to is a member of that group. Sometimes group management can be kind of irritating, but it should allow you to do anything you want, and it's the us...
Is there something between a normal user account and root?
[ "", "python", "linux", "root", "" ]
``` const static int foo = 42; ``` I saw this in some code here on StackOverflow and I couldn't figure out what it does. Then I saw some confused answers on other forums. My best guess is that it's used in C to hide the constant `foo` from other modules. Is this correct? If so, why would anyone use it in a C++ context...
It has uses in both C and C++. As you guessed, the `static` part limits its scope to that [compilation unit](https://stackoverflow.com/questions/1106149/what-is-a-translation-unit-in-c). It also provides for static initialization. `const` just tells the compiler to not let anybody modify it. This variable is either pu...
A lot of people gave the basic answer but nobody pointed out that in C++ `const` defaults to `static` at `namespace` level (and some gave wrong information). See the C++98 standard section 3.5.3. First some background: *Translation unit:* A source file after the pre-processor (recursively) included all its include fi...
What does 'const static' mean in C and C++?
[ "", "c++", "c", "" ]
What is the best way to check if a given url points to a valid file (i.e. not return a 404/301/etc.)? I've got a script that will load certain .js files on a page, but I need a way to verify each URL it receives points to a valid file. I'm still poking around the PHP manual to see which file functions (if any) will ac...
The file\_get\_contents is a bit overshooting the purpose as it is enough to have the HTTP header to make the decision, so you'll need to use curl to do so: ``` <?php // create a new cURL resource $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); cur...
one such way would be to request the url and get a response with a status code of 200 back, aside from that, there's really no good way because the server has the option of handling the request however it likes (including giving you other status codes for files that exist, but you don't have access to for a number of r...
Equivalent is_file() function for URLs?
[ "", "php", "" ]
I'd like my program to read the cache line size of the CPU it's running on in C++. I know that this can't be done portably, so I will need a solution for Linux and another for Windows (Solutions for other systems could be useful to others, so post them if you know them). For Linux I could read the content of /proc/cp...
On Win32, [`GetLogicalProcessorInformation`](http://msdn.microsoft.com/en-us/library/ms683194.aspx) will give you back a [`SYSTEM_LOGICAL_PROCESSOR_INFORMATION`](http://msdn.microsoft.com/en-us/library/ms686694.aspx) which contains a [`CACHE_DESCRIPTOR`](http://msdn.microsoft.com/en-us/library/ms681979.aspx), which has...
On Linux try the [proccpuinfo library](https://savannah.nongnu.org/projects/proccpuinfo/), an architecture independent C API for reading /proc/cpuinfo
How to programmatically get the CPU cache line size in C++?
[ "", "c++", "linux", "windows", "cpu", "cpu-cache", "" ]
I'm developing a simple Qt 4 app and making my own dialog. I subclassed `QDialog`, inserted the `Q_OBJECT` macro in the class declaration block, and... I get > [Linker error] undefined reference to `vtable for MyDialog' and there is no > moc\_MyDialog.cpp generated by the moc compiler. I am using Qt 4.1.3 on Windows ...
The undefined reference to "vtable for MyDialog" is caused because there is no moc file. Most c++ compilers create the vtable definition in the object file containing the first virtual function. When subclassing a qt object and using the Q\_OBJECT macro, this will be in the moc\*.cpp file. Therefore, this error means t...
If you have your header file included, follow the steps: 1. Right click on the project where you have added this. 2. Hit 'Run qmake'. This will will clear up the old references and build with th Q\_OBJECT macro. QT doesn't do it on rebuild.
Qt and no moc_*.cpp file
[ "", "c++", "qt", "qt4", "" ]
What I would like to achive is: * I go to admin site, apply some filters to the list of objects * I click and object edit, edit, edit, hit 'Save' * Site takes me to the list of objects... unfiltered. I'd like to have the filter from step 1 remembered and applied. Is there an easy way to do it?
Unfortunately there's no easy way to do this. The filtering does not seem to be saved in any session variable. Clicking back twice is the normal method, but it can be unweildy and annoying if you've just changed an object so that it should no longer be shown using your filter. If it's just a one-off, click back twice...
Click 2 times "Back"?
Keeping filters in Django Admin
[ "", "python", "django", "django-admin", "" ]
I'm looking for a container that keeps all its items in order. I looked at SortedList, but that requires a separate key, and does not allow duplicate keys. I could also just use an unsorted container and explicitly sort it after each insert. Usage: * Occasional insert * Frequent traversal in order * Ideally not worki...
You might want to take a look at the [Wintellect Power Collections](https://github.com/timdetering/Wintellect.PowerCollections). It is available on CodePlex and contains quite a few collections that are very helpful. The OrderedBag collection in the project is exactly what you are looking for. It essentially uses a [re...
Just to make [EBarr's comment](https://stackoverflow.com/questions/196512/is-there-a-sorted-collection-type-in-net/198699#comment10376249_196549) as answer, there is [`SortedSet<T>`](http://msdn.microsoft.com/en-us/library/dd412070%28v=vs.100%29.aspx) since .NET 4.0. Of course it is a set, which means you cannot have d...
Is there a sorted collection type in .NET?
[ "", "c#", ".net", "sorting", "containers", "" ]
Problem with dynamic controls Hello all, I'm wanting to create some dynamic controls, and have them persist their viewstate across page loads. Easy enough, right? All I have to do is re-create the controls upon each page load, using the same IDs. HOWEVER, here's the catch - in my PreRender event, I'm wanting to clear...
ViewState-backed properties are only persisted to ViewState if the control is currently tracking ViewState. This is by design to keep ViewState as small as possible: it should only contain data that is truly dynamic. The upshot of this is that: ViewState propeties set during the Init event are *not* backed to ViewStat...
As others have statement you'll need to ensure that you are creating via the Init method. To learn more about the ASP.NET page life cycle check out this article: <http://msdn.microsoft.com/en-us/library/ms178472.aspx>
Problem with dynamic controls in .NET
[ "", "c#", "asp.net", "dynamic", "controls", "viewstate", "" ]
What's the best/most efficient way to extract text set between parenthesis? Say I wanted to get the string "text" from the string "ignore everything except this (text)" in the most efficient manner possible. So far, the best I've come up with is this: ``` $fullString = "ignore everything except this (text)"; $start =...
i'd just do a regex and get it over with. unless you are doing enough iterations that it becomes a huge performance issue, it's just easier to code (and understand when you look back on it) ``` $text = 'ignore everything except this (text)'; preg_match('#\((.*?)\)#', $text, $match); print $match[1]; ```
So, actually, the code you posted doesn't work: `substr()'s` parameters are $string, $start and **$length**, and `strpos()'s` parameters are `$haystack`, `$needle`. Slightly modified: ``` $str = "ignore everything except this (text)"; $start = strpos($str, '('); $end = strpos($str, ')', $start + 1); $length = $end...
PHP: Best way to extract text within parenthesis?
[ "", "php", "parsing", "string", "" ]
I've programmed C and C++ for a long time and so far I've never used exceptions and try / catch. What are the benefits of using that instead of just having functions return error codes?
Possibly an obvious point - a developer can ignore (or not be aware of) your return status and go on blissfully unaware that something failed. An exception needs to be acknowledged in some way - it can't be silently ignored without actively putting something in place to do so.
The advantage of exceptions are two fold: * **They can't be ignored.** You must deal with them at some level, or they will terminate your program. With error code, you must explicitly check for them, or they are lost. * **They can be ignored.** If an error can't be dealt with at one level, it will automatically bubble...
In C++ what are the benefits of using exceptions and try / catch instead of just returning an error code?
[ "", "c++", "exception", "try-catch", "" ]
Does anyone know of a sample distributed application (.NET or J2EE) using RMI or Web Services?
**Here's a simple solution:** [BEA Weblogic](http://www.bea.com/framework.jsp?CNT=index.htm&FP=/content/products/weblogic/server) has a sample web application called **MedRec** that I've been using for a while. This sample comes with a .NET client built in called **CSharpClient** that connects to MedRec via Web Servic...
As often, Sun has an excellent tutorial on RMI: <http://java.sun.com/docs/books/tutorial/rmi/index.html>
RMI or Web Services sample application
[ "", "java", ".net", "web-services", "" ]
I was hoping to implement a simple XMPP server in Java. What I need is a library which can parse and understand xmpp requests from a client. I have looked at Smack (mentioned below) and JSO. Smack appears to be client only so while it might help parsing packets it doesn't know how to respond to clients. Is JSO maintai...
<http://xmpp.org/xmpp-software/libraries/> has a list of software libraries for XMPP. Here is an *outdated* snapshot of it: ### ActionScript * [as3xmpp](http://code.google.com/p/as3xmpp/) ### C * [iksemel](http://code.google.com/p/iksemel/) * [libstrophe](http://www.onlinegamegroup.com/projects/libstrophe) * [Loudm...
I went through the same search. I first tried Smack and then realized it's targeted at c2s (client to server) and didn't have what I need. I looked at Tinder but didn't like the licensing model (also when I looked it was much more raw). I finally looked at Whack and realized it was what I needed - but it's missing a lo...
Good XMPP Java Libraries for server side?
[ "", "java", "xmpp", "" ]
I am after a regular expression that validates a percentage from 0 100 and allows two decimal places. Does anyone know how to do this or know of good web site that has example of common regular expressions used for client side validation in javascript? @Tom - Thanks for the questions. Ideally there would be no leadin...
Rather than using regular expressions for this, I would simply convert the user's entered number to a floating point value, and then check for the range you want (0 to 100). Trying to do numeric range validation with regular expressions is almost always the wrong tool for the job. ``` var x = parseFloat(str); if (isNa...
I propose this one: ``` (^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$) ``` It matches 100, 100.0 and 100.00 using this part ``` ^100(\.0{1,2})?$ ``` and numbers like 0, 15, 99, 3.1, 21.67 using ``` ^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$ ``` Note what leading zeros are prohibited, but trailing zeros are allow...
Javascript percentage validation
[ "", "javascript", "regex", "" ]
My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. [t-shirt](http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg) So, I have a couple of guesses as to what it means, but I was just wondering if ther...
I emailed the Website Optimizer Team, and they said "There's no secret code, unless you find one. :)"
I think Google are just trying to drive their point home - here are a bunch of different representations of the same page, test them, see which is best. Which block do you like best?
Possible Google Riddle?
[ "", "python", "" ]
What is the best way to access an ASP.NET HiddenField control that is embedded in an ASP.NET PlaceHolder control through JavaScript? The Visible attribute is set to false in the initial page load and can changed via an AJAX callback. Here is my current source code: ``` <script language="javascript" type="text/javascr...
My understanding is if you set controls.Visible = false during initial page load, it doesn't get rendered in the client response. My suggestion to solve your problem is 1. Don't use placeholder, judging from the scenario, you don't really need a placeholder, unless you need to dynamically add controls on the server si...
If the Visibility is set to false server-side, the placeholder won't be rendered and you won't be able to access anything inside it from JavaScript. Your code should work when the placeholder is visible="true" Get rid of the placeholder, leave the hidden field empty at first, after the search populate it.
Access an asp:hiddenfield control in JavaScript
[ "", "asp.net", "javascript", "" ]
First of all there is a [partial question](https://stackoverflow.com/questions/59880/are-stored-procedures-more-efficient-in-general-than-inline-statements-on-moder) regarding this, but it is not exactly what I'm asking, so, bear with me and go for it. My question is, after looking at what [SubSonic](http://subsonicpr...
It doesn't need to be one or the other. If it's a simple query, use the SubSonic query tool. If it's more complex, use a stored procedure and load up a collection or create a dataset from the results. See here: [What are the pros and cons to keeping SQL in Stored Procs versus Code](https://stackoverflow.com/questions/...
See answers [here](https://stackoverflow.com/questions/15142/what-are-the-pros-and-cons-to-keeping-sql-in-stored-procs-versus-code) and [here](https://stackoverflow.com/questions/59880/are-stored-procedures-more-efficient-in-general-than-inline-statements-on-moder). I use sprocs whenever I can, except when red tape mea...
Stored procedures or inline queries?
[ "", "sql", "stored-procedures", "subsonic", "" ]
I'm writing a query for an application that needs to list all the products with the number of times they have been purchased. I came up with this and it works, but I am not too sure how optimized it is. My SQL is really rusty due to my heavy usage of ORM's, But in this case a query is a much more elegant solution. Ca...
I'm not sure about the "(SELECT \*" ... business. This executes (always a good start) and I think is equivalent to what was posted. ``` SELECT products.id, products.long_name AS name, count(oi.order_id) AS sold FROM products LEFT OUTER JOIN orderitems AS oi INNER JOIN orders ...
Here a solution for those of us who are nesting impaired. (I get so confused when I start nesting joins) ``` SELECT products.id, products.long_name AS name, count(oi.order_id) AS sold FROM orders INNER JOIN orderitems AS oi ON oi.order_id = orders.id AND orders.paid = 1 RIGHT JOIN products ON oi.p...
Does this query look optimized?
[ "", "mysql", "sql", "optimization", "" ]
What is the best way to copy a list? I know the following ways, which one is better? Or is there another way? ``` lst = ['one', 2, 3] lst1 = list(lst) lst2 = lst[:] import copy lst3 = copy.copy(lst) ```
If you want a shallow copy (elements aren't copied) use: ``` lst2=lst1[:] ``` If you want to make a deep copy then use the copy module: ``` import copy lst2=copy.deepcopy(lst1) ```
I often use: ``` lst2 = lst1 * 1 ``` If lst1 it contains other containers (like other lists) you should use deepcopy from the copy lib as shown by Mark. --- UPDATE: Explaining deepcopy ``` >>> a = range(5) >>> b = a*1 >>> a,b ([0, 1, 2, 3, 4], [0, 1, 2, 3, 4]) >>> a[2] = 55 >>> a,b ([0, 1, 55, 3, 4], [0, 1, 2, 3,...
What is the best way to copy a list?
[ "", "python", "" ]
Is there a simple out of the box way to impersonate a user in .NET? So far I've been using [this class from code project](http://www.codeproject.com/KB/cs/zetaimpersonator.aspx) for all my impersonation requirements. Is there a better way to do it by using .NET Framework? I have a user credential set, (username, pas...
Here is some good overview of .NET impersonation concepts. * [Michiel van Otegem: WindowsImpersonationContext made easy](https://web.archive.org/web/20150613031724/http://michiel.vanotegem.nl/2006/07/windowsimpersonationcontext-made-easy/) * [WindowsIdentity.Impersonate Method (check out the code samples)](http://msdn...
"Impersonation" in the .NET space generally means running code under a specific user account. It is a somewhat separate concept than getting access to that user account via a username and password, although these two ideas pair together frequently. ## Impersonation The APIs for impersonation are provided in .NET via ...
How do you do Impersonation in .NET?
[ "", "c#", ".net", "impersonation", "" ]
Is there a simple way to prevent browser from downloading and displaying images, best would be via some magic style tag or javasctipe. The thing is, I'd like to tweak the company's website a bit to be more usable via mobile devices. The company is a gaming one, there's like 5MBs of images on it's main page (and those ...
You can use htaccess to redirect image requests made from mobile browser users. I haven't tested this but it should work: ``` RewriteCond %{HTTP_USER_AGENT} (nokia¦symbian¦iphone¦blackberry) [NC] RewriteCond %{REQUEST_URI} !^/images/$ RewriteRule (.*) /blank.jpg [L] ``` This code redirects all requests made to files...
I would not rely on javascript or any other client side method with mobile browsers. Most mobile browsers just don't support javascript well enough. Some server side "branching" is probably the way to go. And don't forget to disable the css background images while you're at it.
A way to prevent a mobile browser from downloading and displaying images
[ "", "javascript", "http-headers", "mobile-website", "" ]
Every time I need to do something *N* times inside an algorithm using C# I write this code ``` for (int i = 0; i < N; i++) { ... } ``` Studying Ruby I have learned about method *times()* which can be used with the same semantics like this ``` N.times do ... end ``` Code fragment in C# looks more complex and...
A slightly briefer version of [cvk's answer](https://stackoverflow.com/questions/177538/any-chances-to-imitate-times-ruby-method-in-c#177551): ``` public static class Extensions { public static void Times(this int count, Action action) { for (int i=0; i < count; i++) { action(); ...
It is indeed possible with C# 3.0: ``` public interface ILoopIterator { void Do(Action action); void Do(Action<int> action); } private class LoopIterator : ILoopIterator { private readonly int _start, _end; public LoopIterator(int count) { _start = 0; _end = count - 1; } ...
Any chances to imitate times() Ruby method in C#?
[ "", "c#", "ruby", "language-features", "cycle", "" ]
I'm writing a WinForms app which has two modes: console or GUI. Three projects within the same solution, one for the console app, one for the UI forms and the third to hold the logic that the two interfaces will both connect too. The Console app runs absolutely smoothly. A model which holds the user-selections, it has...
Since you are doing UI binding via event subscription, [you might find this helpful](http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/214e55884b16f4d9/f12a3c5980567f06#f12a3c5980567f06); it is an example I wrote a while ago that shows how to subclass `BindingList<T>` so tha...
You've answered your own quesion:- > I get an error saying that the DataGridView was being accessed from a thread other than the thread it was created on. WinForms insists that all actions performed on forms and controls are done in the context of the thread the form was created in. The reason for this is complex, bu...
Strange cross-threading UI errors
[ "", "c#", "string", "literals", "multithreading", "" ]
Specifically, I have a model that has a field like this ``` pub_date = models.DateField("date published") ``` I want to be able to easily grab the object with the most recent `pub_date`. What is the easiest/best way to do this? Would something like the following do what I want? ``` Edition.objects.order_by('pub_dat...
``` obj = Edition.objects.latest('pub_date') ``` You can also simplify things by putting [`get_latest_by`](http://docs.djangoproject.com/en/dev/ref/models/options/#get-latest-by) in the model's Meta, then you'll be able to do ``` obj = Edition.objects.latest() ``` See [the docs](http://docs.djangoproject.com/en/dev/...
Harley's answer is the way to go for the case where you want the latest according to some ordering criteria for particular Models, as you do, but the general solution is to reverse the ordering and retrieve the first item: ``` Edition.objects.order_by('-pub_date')[0] ```
In django, how do I sort a model on a field and then get the last item?
[ "", "sql", "django", "sorting", "django-models", "" ]
This is something that's been bothering me a while and there just has to be a solution to this. Every time I call ShellExecute to open an external file (be it a document, executable or a URL) this causes a very long lockup in my program before ShellExecute spawns the new process and returns. Does anyone know how to sol...
Are you multithreaded? I've seen issues with opening files with ShellExecute. Not executables, but files associated an application - usually MS Office. Applications that used DDE to open their files did some of broadcast of a message to all threads in all (well, I don't know if it was *all*...) programs. Since I wasn'...
I don't know what is causing it, but Mark Russinovich (of sysinternal's fame) has a really great blog where he explains how to debug these kinds of things. A good one to look at for you would be [The Case of the Delayed Windows Vista File Open Dialogs](http://blogs.technet.com/markrussinovich/archive/2006/11/27/532465....
Getting rid of the evil delay caused by ShellExecute
[ "", "c++", "winapi", "shellexecute", "" ]
I have Eclipse 3.3.2 with PDT doing PHP development. All projects that I create, even SVN projects have code completion. Now I just opened another SVN project and it has no code completion or PHP templates (CTRL-space does nothing in that project). However, I can open the other projects and code completion all work in ...
Maybe Eclipse doesn't understand the project has a "PHP nature". Try comparing the .project file on both projects to look for differences. It should contain something like: ``` <natures> <nature>org.eclipse.php.core.PHPNature</nature> </natures> ``` The .project file will be in your workspace under the project di...
Look out for the file .buildpath in your project... put this line between the tag: `<buildpathentry kind="con" path="org.eclipse.php.core.LANGUAGE"/>` Save it and restart eclipse. Now everything should be OK... This worked for me. :)
Why does Eclipse code completion not work on some projects?
[ "", "php", "eclipse", "eclipse-pdt", "eclipse-3.3", "" ]
Lucene is an excellent search engine, but the .NET version is behind the official Java release (latest stable .NET release is 2.0, but the latest Java Lucene version is 2.4, which has more features). How do you get around this?
One way I found, which was surprised could work: Create a .NET DLL from a Java .jar file! Using [IKVM](http://www.ikvm.net/) you can [download Lucene](http://www.apache.org/dyn/closer.cgi/lucene/java/), get the .jar file, and run: ``` ikvmc -target:library <path-to-lucene.jar> ``` which generates a .NET dll like this...
Download the source and build it. I did this just last weekend and it was easy. No problem at all. The source is at version 2.3.1. I'm subscribed to the mailing list and judging from it, Lucene.Net is being developed actively.
How do you run Lucene on .net?
[ "", "java", ".net", "search", "indexing", "lucene", "" ]
I was just wondering, since the **sealed** keyword's existence indicates that it's the class author's decision as to whether other classes are allowed to inherit from it, why aren't classes sealed by default, with some keyword to mark them explicitly as extensible? I know it's somewhat different, but access modifiers ...
**In my opinion** there should be no default syntax, that way you always write explicitly what you want. This forces the coder to understand/think more. If you want a class to be inheritable then you write ``` public extensible class MyClass ``` otherwise ``` public sealed class MyClass ``` BTW I think the same sh...
I'd say it was just a mistake. I know many people (including myself) who believe that classes should indeed be sealed by default. There are at least a couple of people in the C# design team in that camp. The pendulum has swung somewhat away from inheritance since C# was first designed. (It has its place, of course, but...
Why aren't classes sealed by default?
[ "", "c#", "inheritance", "sealed", "" ]
The code at the end produces a compile error: ``` NotApplicable.java:7: run() in cannot be applied to (int) run(42); ^ 1 error ``` The question is why? Why does javac think I am calling run(), and does not find run(int bar)? It correctly called foo(int bar). Why do I have to use NotAp...
The explanation for the behavior of your code sample is that `this` is defined to be the class that you are currently "most" inside of. In this case, you are "most" inside the anonymous inner class that subclasses runnable and there is no method which matches `run(int)`. To broaden your search you specify which `this` ...
As far as I recall the rules for selecting a method to run between nested classes are approximately the same as the rules for selecting a method in an inheritance tree. That means that what we are getting here is not overloading, it's hiding. The difference between these is crucial to understanding methods in inheritan...
Why can't I call a method outside of an anonymous class of the same name
[ "", "java", "methods", "javac", "anonymous-class", "" ]
Hopefully I can do the problem justice, because it was too difficult to summarise it in the title! (suggestions are welcome in the comments) Right, so here's my table: ``` Tasks task_id (number) job_id (number) to_do_by_date (date) task_name (varchar / text) status (number) co...
Obviously you will have to fix this up a bit but I hope you get the idea. ``` SELECT task_id, job_id, to_do_by_date, task_name, status, completed_date FROM Tasks WHERE job_id IN ( SELECT job_id FROM Tasks WHERE status <> 'Done' GROUP BY job_id) OR job_id IN ( ...
I agree with Justin -- I don't get why 2 is returned. Here's a query using analytic functions to return the right rows according to the logic description. ``` select * from ( select t.*, min(status) over (partition by job_id) min_status_over_job, max(status) over (partition by job_id) max_status_over_jo...
SQL Query Help - task ordering, grouping and status + date conditions problem
[ "", "sql", "oracle", "" ]
There's a lot of advice out there that you shouldn't expose your fields publically, and instead use trivial properties. I see it over & over. I understand the arguments, but [I don't think it's good advice in most cases](https://stackoverflow.com/questions/174198/c35-automatic-properties-why-not-access-the-field-direc...
It may be hard to make code work in an uncertain future, but that's no excuse to be lazy. Coding a property over a field is convention and it's pragmatic. Call it defensive programming. Other people will also complain that there's a speed issue, but the JIT'er is smart enough to make it just about as fast as exposing ...
I used to think the same thing, Jay. Why use a property if it's only there to provide *direct* access to a private member? If you can describe it as an autoproperty, having a property at all rather than a field seemed kind of silly. Even if you ever need to change the implementation, you could always just refactor into...
Have trivial properties ever saved your bacon?
[ "", "c#", ".net", "" ]
I have a simple website I'm testing. It's running on localhost and I can access it in my web browser. The index page is simply the word "running". `urllib.urlopen` will successfully read the page but `urllib2.urlopen` will not. Here's a script which demonstrates the problem (this is the actual script and not a simplifi...
Sounds like you have proxy settings defined that urllib2 is picking up on. When it tries to proxy "127.0.0.01/", the proxy gives up and returns a 504 error. From [Obscure python urllib2 proxy gotcha](http://kember.net/articles/obscure-python-urllib2-proxy-gotcha): ``` proxy_support = urllib2.ProxyHandler({}) opener =...
Does calling urlib2.open first followed by urllib.open have the same results? Just wondering if the first call to open is causing the http server to get busy causing the timeout?
urllib.urlopen works but urllib2.urlopen doesn't
[ "", "python", "urllib2", "urllib", "" ]
I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word". My limited regex experience just stalled out on me - can someone think of a decent regex to d...
You could try: ``` >>> re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWord") 'Word Word Word' ```
If there are consecutive capitals, then Gregs result could not be what you look for, since the \w consumes the caracter in front of the captial letter to be replaced. ``` >>> re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWWWWWWWord") 'Word Word WW WW WW Word' ``` A look-behind would solve this: ``` >>> re.sub(r"(?<=\w)(...
A pythonic way to insert a space before capital letters
[ "", "python", "regex", "text-files", "" ]
I currently use Notepad++ for most of my development. I have been checking out other, more full-featured options and would like to switch (I'm in particular a fan of Aptana so far) but there is one thing about Notepad++ that I really like and I haven't been able to get so far. My current workflow is something like thi...
I think you're doing things a bit strange. You already have all your information in an SVN repository, so why not take advantage of that? You keep a working copy on your computer for development and testing. Save and commit your changes to SVN. On your server, do an SVN `export` (or `checkout`, with appropriate serve...
Not too sure but I found [PhpEd](http://www.nusphere.com/) better than Zend for this kind of stuff - especially easy save to FTP.
PHP IDE--Want to sync local storage with FTP
[ "", "php", "ide", "tortoisesvn", "notepad++", "aptana", "" ]
I want to do something like this: ``` List<Animal> animals = new ArrayList<Animal>(); for( Class c: list_of_all_classes_available_to_my_app() ) if (c is Animal) animals.add( new c() ); ``` So, I want to look at all of the classes in my application's universe, and when I find one that descends from Animal, I...
I use [org.reflections](https://github.com/ronmamo/reflections): ``` Reflections reflections = new Reflections("com.mycompany"); Set<Class<? extends MyInterface>> classes = reflections.getSubTypesOf(MyInterface.class); ``` Another example: ``` public static void main(String[] args) throws IllegalAccessException,...
The Java way to do what you want is to use the [ServiceLoader](http://java.sun.com/javase/6/docs/api/java/util/ServiceLoader.html) mechanism. Also many people roll their own by having a file in a well known classpath location (i.e. /META-INF/services/myplugin.properties) and then using [ClassLoader.getResources()](htt...
At runtime, find all classes in a Java application that extend a base class
[ "", "java", "reflection", "inheritance", "" ]
What are good reasons to prohibit inheritance in Java, for example by using final classes or classes using a single, private parameterless constructor? What are good reasons of making a method final?
Your best reference here is Item 19 of Joshua Bloch's excellent book "Effective Java", called "Design and document for inheritance or else prohibit it". (It's item 17 in the second edition and item 15 in the first edition.) You should really read it, but I'll summarize. The interaction of inherited classes with their ...
You might want to make a method final so that overriding classes can't change behavior that is counted on in other methods. Methods called in constructors are often declared final so you don't get any unpleasant surprises when creating objects.
Good reasons to prohibit inheritance in Java?
[ "", "java", "inheritance", "final", "" ]
What is the differences and similarities between Domain Specific Languages (DSL) and Domain Driven Design (DDD)?
Domain Driven Design (DDD) is a way of thinking and communicating about the problems and its solutions. Domain Specific Language (DSL) is a way of writing code. They're similar because they both start with the word "domain". That's it, I guess. :-)
Domain-Driven Design emphasizes the role of the problem domain as you create the fundamental vocabulary, concepts, and object model for the system being designed. A Domain-Specific Language is a notation for specifying or implementing specific parts of the system, oriented to the needs of the practitioner in that doma...
Domain Specific Languages (DSL) and Domain Driven Design (DDD)
[ "", "c#", ".net", "domain-driven-design", "dsl", "" ]
I had a little discussion with a friend about the usage of collections in return/input values of a method. He told me that we have to use - the most derived type for return values. - the least derived type for input parameters. So, it means that, for example, a method has to get a ReadOnlyCollection as parameter, and ...
Regarding input parameters, it's generally more flexible to use the least specific type. For example, if all your method is going to do is enumerate the items in a collection passed as an argument, it's more flexible to accept IEnumerable<T>. For example, consider a method "ProcessCustomers" that accepts a parameter t...
I tend to agree with not returning or using List or Dictionary as parameters in API's because it really limits the developer targeting the API. Instead returning or passing IEnumerable<> works really well. Of coarse, all of this depends on the application. Just my opinion.
What are the code convention for parameters/return values (collections)
[ "", "c#", "" ]
How can I programmatically lock/unlock, or otherwise prevent/enable editing, a source file on Linux using C++. I want to be able to lock source file so that if I open it in an editor it will not allow me to save back to the same source file. I am thinking of maybe changing the permissions to read-only (and change it ...
Try man fchmod: ``` NAME chmod, fchmod - change permissions of a file SYNOPSIS #include <sys/types.h> #include <sys/stat.h> int chmod(const char *path, mode_t mode); int fchmod(int fildes, mode_t mode); ```
Why aren't you using a source code management tool like CVS or Subversion? CVS does nice locking (so does Subversion). More importantly, you have the history of changes. Better still (with CVS anyway) you have to make the step of doing a "checkout" to make the file writeable.
Lock / Prevent edit of source files on Linux using C++
[ "", "c++", "linux", "file-locking", "" ]
I know that I can insert multiple rows using a single statement, if I use the syntax in [this answer](https://stackoverflow.com/questions/39576/best-way-to-do-multi-row-insert-in-oracle#39602). However, one of the values I am inserting is taken from a sequence, i.e. ``` insert into TABLE_NAME (COL1,COL2) select MY_SE...
This works: ``` insert into TABLE_NAME (COL1,COL2) select my_seq.nextval, a from (SELECT 'SOME VALUE' as a FROM DUAL UNION ALL SELECT 'ANOTHER VALUE' FROM DUAL) ```
It does not work because sequence does not work in following scenarios: * In a WHERE clause * In a GROUP BY or ORDER BY clause * In a DISTINCT clause * Along with a UNION or INTERSECT or MINUS * In a sub-query Source: <http://www.orafaq.com/wiki/ORA-02287> However this does work: ``` insert into table_name ...
How can I insert multiple rows into oracle with a sequence value?
[ "", "sql", "oracle", "" ]
Is it possible to prevent the browser from following redirects when sending XMLHttpRequest-s (i.e. to get the redirect status code back and handle it myself)?
Not according to [the W3C standard for the XMLHttpRequest object](http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#infrastructure-for-the-send%28%29-method) (emphasis added): > If the response is an HTTP redirect: > > > If the origin of the URL conveyed by the Location header is same origin > > with the XMLHttpReq...
The new [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) supports different modes of redirect handling: `follow`, `error`, and `manual`, but I can't find a way to view the new URL or the status code when the redirection has been canceled. You just can stop the redirection itself, and then it look...
Prevent redirection of XMLHttpRequest
[ "", "javascript", "ajax", "xmlhttprequest", "" ]
I was making the following call: ``` result = RegOpenKeyEx(key, s, 0, KEY_READ, &key); ``` (C++, Visual Studio 5, Vista 64bit). It is failing with error code 2 ("File not found") even though "`regedit`" shows that the key exists. This code has always worked on 32bit XP. Why is it "file not found" when it clearly is ...
I discovered that I could solve my problem using the flag: `KEY_WOW64_64KEY` , as in: ``` result = RegOpenKeyEx(key, s, 0, KEY_READ|KEY_WOW64_64KEY, &key); ``` For a full explanation: [32-bit and 64-bit Application Data in the Registry](http://msdn.microsoft.com/en-us/library/ms724072(VS.85).aspx)
On a Windows 64-bit system the Registry is actually divided into two parts. One section is used by 64-bit processes, and one part by 32-bit processes. For example, if a 32-bit application programatically writes to what it believes is HKLM\SOFTWARE\Company\Application, it's actually redirected by the WoW64-layer to HKL...
Why is RegOpenKeyEx() returning error code 2 on Vista 64bit?
[ "", "c++", "winapi", "windows-vista", "registry", "wow64", "" ]
In our data access layer at work we have this standard implementation where the class is accessed through a singleton public property which looks something like this: ``` public static CustomerController Instance { get { lock(singletonLock) { ...
EDIT: Oh whoops I didn't catch the "Data Access Layers" part. But I have an example of that too: If your multithreaded app funnels all of its' database calls through a singleton class, only one thread will ever access the database at once, avoiding race conditions. If you have a logging mechanism in a multi-threaded a...
You may wish to do this also, its double checked locking, it will speed up access to your singleton ``` public static CustomerController Instance { get { if( _instance == null ) { lock(singletonLock) ...
Singleton Data Access Layers
[ "", "c#", "design-patterns", "singleton", "" ]
As far as I know there's no way to hint the c# compiler to inline a particular function and I guess it's like that by design. I also think that not letting the programmer to specify what to inline and what not is generally a good idea, as it would imply that you think you're smarter than the JIT compiler (my respects ...
The situation has changed a little with the advent of .Net 4.5. You can now decorate a method with the attribute [`[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]`](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions%28v=vs.110%29.aspx) which will cause it to be inline...
Short answer: no Long answer: <http://blogs.msdn.com/ericgu/archive/2004/01/29/64644.aspx> Criteria for inlining: <http://blogs.msdn.com/davidnotario/archive/2004/11/01/250398.aspx> and <http://blogs.msdn.com/ericgu/archive/2004/01/29/64717.aspx> Note that in the last two links about criteria for inlining, the one a...
Is there a way to enforce function inlining in c#?
[ "", "c#", "optimization", "call", "overhead", "inlining", "" ]
I've been reading Skype4Java (java api for skype) and noticed they use jni to access the skype client. intuitively I'd assume that there already is a standard library in java that has an OS-sensitive jni implementation to access other processes. I set up to look for one, but couldn't find it. Is there such a library?...
I think that maybe you need to define what 'access' means to you. IF you are talking about plain old inter-process communication, then sockets or JNI are really your best bet. Garth's comment about using memory mapped files is interesting - I've used MMFs and virtual files for IPC between C applications many times, bu...
From Java 1.4 onwards you can use memory mapped files to exchange arbitrary information with another process. See java.nio.MappedByteBuffer for details.
is there a "best practice" to access another process in the OS through java?
[ "", "java", "operating-system", "native", "" ]
This seems to be a common problem but I cannot find a solution. I type in my username and password which are in a login control I have created. I then press enter once I've typed in my password and the page just refreshes. It triggers the page load event but not the button on click event. If I press the submit button...
using your forms default button is correct, but you need to supply it the correct id as it will be rendered to HTML. so you do as Jon said above: ``` <form runat="server" DefaultButton="SubmitButton"> ``` But ensure you use the Button name that will be rendered. You can achieve this my making the Button public in yo...
If you're using ASP.NET 2.0 or higher, you can set a default button attribute for your page's Form: ``` <form runat="server" DefaultButton="SubmitButton"> ```
Submitting a form on a user control by pressing enter on a text field does not work
[ "", "c#", "asp.net", "user-controls", "" ]
Greetings! I've created a custom button class to render the following: ``` <span class="btnOrange"> <input type="submit" id="ctl00_MainContent_m_GoBack" value="Back" name="ctl00$MainContent$m_GoBack"/> </span> ``` However, it renders like this instead (note the extraneous "class" attribute in the INPUT tag): ``...
You can do this: ``` private string _heldCssClass = null; public override void RenderBeginTag(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass); writer.RenderBeginTag("span"); _heldCssClass = this.CssClass; this.CssClass = String.Empty; base.RenderBeginTag(wri...
How about removing the `class` attribute from the `writer` object after rendering the `span` begin tag? I don't know ASP though so I could be wrong.
Removing CSS Class Attribute From Tag in a Custom Server Control
[ "", "c#", "asp.net", "custom-server-controls", "" ]
I have a program that monitors debug messages and I have tried using a TextBox and appended the messages to it but it doesn't scale very well and slows way down when the number of messages gets large. I then tried a ListBox but the scrolling was snapping to the top when appending new messages. It also doesn't allow for...
RichTextBox has an AppendText method that is fast. And it can handle large text well. I believe it is the best for what you need.
I do this in my C# window programs (WInforms or WPF) using a Win32 console window. I have a small class that wraps some basic Win32 APIs, thin I create a console when the program begins. This is just an example: in 'real life' you'd use a setting or some other thing to only enable the console when you needed it. ``` u...
How do I add a console like element to a c# winforms program
[ "", "c#", ".net", "winforms", "" ]
I have a program that needs to run as a normal user most of the time, but once in a while I need to stop and start a service. How do I go about making a program that runs as a normal user most of the time but elevates into administrator mode for some function?
You can't elevate a process once its running but you could either :- ## Restart the process as elevated ``` private void elevateCurrentProcess() { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.UseShellExecute = true; startInfo.WorkingDirectory = Environment.CurrentDirectory; st...
As far as I know, you need to start a seperate process that runs as the administrator. You can't elevate a process once it's already been started. See [this question](https://stackoverflow.com/questions/78696/vista-uac-access-elevation-and-net).
Running as admin sometimes
[ "", "c#", "windows-vista", "uac", "" ]
Is there any alternative for WPF (windows presentation foundation) in python? <http://msdn.microsoft.com/en-us/library/aa970268.aspx#Programming_with_WPF>
Here is a list of [Python GUI Toolkits](http://wiki.python.org/moin/GuiProgramming). Also, you can [use IronPython to work with WPF directly](http://stevegilham.blogspot.com/2007/07/hello-wpf-in-ironpython.html).
You might want to look at [pygtk](http://www.pygtk.org/) and [glade](http://glade.gnome.org/). [Here](http://www.learningpython.com/2006/05/07/creating-a-gui-using-pygtk-and-glade/) is a tutorial. There is a long [list of alternatives](http://wiki.python.org/moin/GuiProgramming) on the [Python Wiki](http://wiki.python...
WPF Alternative for python
[ "", "python", "user-interface", "" ]
How do I dictate the destination folder of a clickOnce application?
This is not possible with ClickOnce. ClickOnce applications are always installed in the `Apps` subdirectory of local application data.
As a further to the above, this is a security feature. Allowing websites to install software to arbitrary locations on someone's harddrive somewhat automatically is a bad idea.
How do I dictate the destination folder of a clickOnce application?
[ "", "c#", "deployment", "installation", "clickonce", "" ]
Can anyone recommend some useful performance analysis tools for PHP scripts? Anything that could help me find problematic or unusually slow blocks of code, details about execution time, etc. would be really helpful. I know there are tools out there, but I'm wondering what people recommend as being the most useful and w...
Try [webgrind](http://code.google.com/p/webgrind/ "webgrind"). It gives you the profiling of CacheGrinder in an easy to read, browser based format. I'm on a Mac and it has made profiling a breeze.
XDebug's [profiler](http://www.xdebug.org/docs/profiler) is good. But then I'm a KDE user... I think you could install the KCacheGrind in other window managers though.
Can you recommend Performance Analysis tools for PHP?
[ "", "php", "performance", "testing", "" ]
Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list ...
``` def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string else: for i in xrange(len(string)): for perm in getPermutations(string[:i] + string[i+1:], prefix+string[i]): yield perm ``` Or without an accumulator: ``` def getPermutations(str...
This avoids the `len(string)`-deep recursion, and is in general a nice way to handle generators-inside-generators: ``` from types import GeneratorType def flatten(*stack): stack = list(stack) while stack: try: x = stack[0].next() except StopIteration: stack.pop(0) conti...
Python: using a recursive algorithm as a generator
[ "", "python", "recursion", "generator", "" ]
Is it possible to subscribe to a Windows event that fires when Windows is going into or coming out of Sleep or Hibernate state? I need my application to be made aware when the computer is going to sleep to do some cleanup and avoid timing issues when it comes out of sleep.
[`Microsoft.Win32.SystemEvents.PowerModeChanged`](http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.powermodechanged.aspx) event will give you this information. This event is available in all variants of the .NET framework released by Microsoft so far.
In .NET, use the [PowerModeChanged](http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.powermodechanged.aspx) event. In Win32, use the [WM\_POWERBROADCAST](http://msdn.microsoft.com/en-us/library/aa373247(VS.85).aspx) message.
How can I know when Windows is going into/out of sleep or Hibernate mode?
[ "", "c#", "windows", "sleep-mode", "hibernate-mode", "" ]
I need to index a varchar field on my table in MS SQL Server 2005, but it's not clear to me how to do so. If I try to add a non-clustered index on the field, it says "Column 'xxxx' in table 'mytable' is of a type that is invalid for use as a key column in an index" My table has an auto-increment int ID that is set as ...
Is your `varchar(max)`? I think those aren't allowed to be used in an index. Otherwise, post your `CREATE TABLE` statement, normally there is no problem adding a `varchar` to an index.
I assume yours is a VARCHAR(MAX) column which, as the error says, is an invalida data type for an index. Suggestion: create a calculated column that is the hash value of the VARCHAR(MAX) column (e.g. using the HashBytes function) then create an index on the calculated column only. Then, in the search condition (e.g. WH...
Index varchar on MS SQL Server 2005
[ "", "sql", "sql-server-2005", "" ]
I need to recover form an error case where a file gets left in a locked state. How can I in c# tell this file to reset it's locks? I need to add to this the file is opened by a 3rd party dll and I don't actually have access to the file handle.
You could perhaps start a command line process like net or psfile with something along the lines of: `System.Diagnostics.Process.Start("psfile c:\myfile.txt -c");` You can get psfile [here](http://technet.microsoft.com/en-us/sysinternals/bb897552.aspx). You could also use `net file ID /close` but that would requir...
Locking a file is the responsibility of the Operating System (on behalf of the program that opens it). If a file is left in a locked state, its really up to the OS to unlock. This typically happens automatically when the process that opened the file exits. There is, however, a really cool utility that I came across th...
Removing file locks
[ "", "c#", "file-io", "locking", "" ]
I have a MySQL database table with a couple thousand rows. The table is setup like so: `id | text` The `id` column is an auto-incrementing integer, and the `text` column is a 200-character varchar. Say I have the following rows: `3 | I think I'll have duck tonight` `4 | Maybe the chicken will be alright` `5 | I h...
MySQL already does this for you. First make sure your table is a MyISAM table Define a FULLTEXT index on your column On a shell command line navigate to the folder where your MySQL data is stored, then type: ``` myisam_ftdump -c yourtablename 1 >wordfreq.dump ``` You can then process wordfreq.dump to eliminate the...
Extract to flat file and then use your favorite quick language, perl, python, ruby, etc to process the flat file. If you don't have one these languages as part of your skillset, this is a perfect little task to start using one, and it won't take you long. Some database tasks are just so much easier to do OUTSIDE of t...
How can I create an ordered list of the most common substrings inside of my MySQL varchar column?
[ "", "sql", "mysql", "statistics", "" ]
How do I properly convert two columns from SQL (2008) using Linq into a `Dictionary` (for caching)? I currently loop through the `IQueryable` b/c I can't get the `ToDictionary` method to work. Any ideas? This works: ``` var query = from p in db.Table select p; Dictionary<string, string> dic = new Diction...
``` var dictionary = db .Table .Select(p => new { p.Key, p.Value }) .AsEnumerable() .ToDictionary(kvp => kvp.Key, kvp => kvp.Value) ; ```
You are only defining the key, but you need to include the value also: ``` var dic = (from p in db.Table select new {p.Key, p.Value }) .ToDictionary(p => p.Key, p=> p.Value); ```
Linq-to-SQL ToDictionary()
[ "", "c#", "linq", "linq-to-sql", "" ]
Is there any way to determine if an object is a generic list? I'm not going to know the type of the list, I just know it's a list. How can I determine that?
This will return "True" ``` List<int> myList = new List<int>(); Console.Write(myList.GetType().IsGenericType && myList is IEnumerable); ``` Do you care to know if it's exactly a "List"... or are you ok with it being IEnumerable, and Generic?
The following method will return the item type of a generic collection type. If the type does not implement ICollection<> then null is returned. ``` static Type GetGenericCollectionItemType(Type type) { if (type.IsGenericType) { var args = type.GetGenericArguments(); if (args.Length == 1 && ...
If object is Generic List
[ "", "c#", ".net", "vb.net", "list", "generics", "" ]
I've declared Javascript arrays in such a way that I could then access them by a key, but it was a long time ago, and I've forgotten how I did it. Basically, I have two fields I want to store, a unique key, and its value. I know there is a way to do it.. something like: ``` var jsArray = new {key: 'test test', value:...
You can do it in different ways: ``` var a = {'a':0, 'b':1, 'c':2}; var b = new Array(); b['a'] = 0; b['b'] = 1; b['c'] = 2; var c = new Object(); c.a = 0; c.b = 1; c.c = 2; ```
``` var myFancyDictionary = { key: 'value', anotherKey: 'anotherValue', youGet: 'the idea' } ```
JavaScript fake dictionaries
[ "", "javascript", "arrays", "dictionary", "associative-array", "" ]
After I read a bunch of LINQ related stuff, I suddenly realized that no articles introduce how to write asynchronous LINQ query. Suppose we use LINQ to SQL, below statement is clear. However, if the SQL database responds slowly, then the thread using this block of code would be hindered. ``` var result = from item in...
While LINQ doesn't really have this per se, the framework itself does... You can easily roll your own asynchronous query executor in 30 lines or so... In fact, I just threw this together for you :) **EDIT: Through writing this, I've discovered why they didn't implement it. It cannot handle anonymous types since they a...
TheSoftwareJedi's and [ulrikb](http://ulrikb.wordpress.com/2010/04/14/executing-a-linq-query-asynchronously/)'s(aka user316318) solutions are good for any LINQ type, but (as pointed by [Chris Moschini](https://stackoverflow.com/users/176877/chris-moschini)) do NOT delegating to underlying asynchronous calls that levera...
How to write Asynchronous LINQ query?
[ "", "c#", "linq", "linq-to-sql", "asynchronous", "" ]
I am looking to parse a URL to obtain a collection of the querystring parameters in Java. To be clear, I need to parse a given URL(or string value of a URL object), not the URL from a servlet request. It looks as if the `javax.servlet.http.HttpUtils.parseQueryString` method would be the obvious choice, but it has been...
Well, as you mention that the URL does not come from a servlet request, the right answer is, as usual, **it depends**. The problem with query part of an url is that there is no clear specification about how to handle parameters duplication. For example, consider an url like this one: ``` http://www.example.com?param...
I think the idea is to use the HttpServletRequest instead. There is the getParameterMap(), getParameterNames() and getParameterValues() methods to start. There is also the getParameter(String paramname) method to get the value of a specific method. These make no distinction between querystring parameters and form par...
Alternative to deprecated javax.servlet.http.HttpUtils.parseQueryString?
[ "", "java", "url", "parsing", "query-string", "" ]
Is it good practice to have a class constructor that uses default parameters, or should I use separate overloaded constructors? For example: ``` // Use this... class foo { private: std::string name_; unsigned int age_; public: foo(const std::string& name = "", const unsigned int age = 0) : name_(...
Definitely a matter of style. I prefer constructors with default parameters, so long as the parameters make sense. Classes in the standard use them as well, which speaks in their favor. One thing to watch out for is if you have defaults for all but one parameter, your class can be implicitly converted from that parame...
I'd go with the default arguments, especially since C++ doesn't let you chain constructors (so you end up having to duplicate the initialiser list, and possibly more, for each overload). That said, there are some gotchas with default arguments, including the fact that constants may be inlined (and thereby become part ...
Default parameters with C++ constructors
[ "", "c++", "constructor", "coding-style", "overloading", "" ]
I use Visual Studio's "Code Snippet" feature pretty heavily while editing c# code. I always wished I could use them while typing out my aspx markup. Is there a way to enable code snippet use in an aspx file editor window? Are there any third party tools that perform this? If you're familiar with code snippet definit...
Perhaps you might think of trying [Coderush](http://devexpress.com/coderush) which has a lot more to offer than the basic snippets found in VS. It's template facility can operate in vb, cs, aspx, html, xml and sql files.
That would be brilliant! I'd recommend the [world's simplest code generato](http://secretgeek.net/wscg.htm)r, or CodeSmith, or maybe [T4](http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx) (although I haven't tried it yet). Doesn't quite do what you'd like, b...
How can I use Visual Studio's "Code Snippet" feature while editing a .aspx file?
[ "", "c#", "asp.net", "visual-studio", "" ]
I am just looking at the using statement, I have always known what it does but until now not tried using it, I have come up with the below code: ``` using (SqlCommand cmd = new SqlCommand(reportDataSource, new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))) { cmd.CommandType ...
This code should be as follows to ensure timely closing of the connection. Closing just the command doesn't close the connection: ``` using (SqlConnection con = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString)) using (SqlCommand cmd = new SqlCommand(reportDataSource, con)) { ...
When doing IO work I code to *expect* an exception. ``` SqlConnection conn = null; SqlCommand cmd = null; try { conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString) cmd = new SqlCommand(reportDataSource, conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("...
C# using statement catch error
[ "", "c#", "using", "using-statement", "" ]
I want your suggestion on the following pseudo-code. Please suggest how could I improve it, whether or not I could use some design patterns. ``` // i'm receiving a string containing : id operation arguments data = read(socket); tokens = tokenize(data," "); // tokenize the string based on spaces if(tokens[0] == "A"...
Have a class for each ID which implements a common interface. Basically the [Strategy pattern](http://en.wikipedia.org/wiki/Strategy_pattern) IIRC. So you'd call (pseudo)code like: `StrategyFactory.GetStrategy(tokens[0]).parse(tokens[1..n])`
First write down the syntax of what you support, then write the code to support it. Using BNF notation is great for that. And using the Spirit library for the code-part is quite straightforward. ``` Command := ACommand | BCommand ACommand := 'A' AOperation AOperation := 'some_operation' | 'some_other_operation' BCo...
How could I improve this C++ code
[ "", "c++", "design-patterns", "refactoring", "" ]
I've always struggled with how to best include classes into my php code. Pathing is usually an issue but a few minutes ago i found [this question](https://stackoverflow.com/questions/4369/how-to-include-php-files-that-require-an-absolute-path) which dramatically helps that. Now I'm reading about \_\_autoload and thinki...
\_\_autoload is great, but the cost of stating all the files in a recursive search function is expensive. You might want to look at building a tree of files to use for autoloading. In my framework, I consistently name files for their classes and use a map that is cached for the data. Check out <http://trac.framewerk.o...
A common pattern (Pear, Zend Framework as examples...) is to make the classname reflect the path, so Db\_Adapter\_Mysql will be in at /Db/Adapter/Mysql.php, from somewhere that's added to the include-path.
Would performance suffer using autoload in php and searching for the class file?
[ "", "php", "performance", "" ]