Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
On a question of just performance, how does Python 3 compare to Python 2.x?
3.0 is slower than 2.5 on official benchmarks. From ["What’s New in Python 3.0"](http://docs.python.org/3.0/whatsnew/3.0.html#performance): > The net result of the 3.0 > generalizations is that Python 3.0 > runs the pystone benchmark around 10% > slower than Python 2.5. Most likely > the biggest cause is the removal o...
I'd say any difference will be below trivial. For example, looping over a list will be the exact same. The idea behind Python 3 is to clean up the language syntax itself - remove ambigious stuff like `except Exception1, Exception2`, cleanup the standard modules (no urllib, urllib2, httplib etc). There really isn't mu...
Performance: Python 3.x vs Python 2.x
[ "", "python", "performance", "python-3.x", "python-2.x", "" ]
According to the [feedparser documentation](http://feedparser.org/docs/introduction.html), I can turn an RSS feed into a parsed object like this: ``` import feedparser d = feedparser.parse('http://feedparser.org/docs/examples/atom10.xml') ``` but I can't find anything showing how to go the other way; I'd like to be a...
Appended is a not hugely-elegant, but working solution - it uses feedparser to parse the feed, you can then modify the entries, and it passes the data to PyRSS2Gen. It preserves *most* of the feed info (the important bits anyway, there are somethings that will need extra conversion, the parsed\_feed['feed']['image'] el...
If you're looking to read in an XML feed, modify it and then output it again, there's [a page on the main python wiki indicating that the RSS.py library might support what you're after](http://wiki.python.org/moin/RssLibraries) (it reads most RSS and is able to output RSS 1.0). I've not looked at it in much detail thou...
How do I turn an RSS feed back into RSS?
[ "", "python", "rss", "" ]
I agree, that programming against interfaces is a good practice. In most cases in Java "interface" in this sense means the language construct interface, so that you write an interface and an implementation class and that you use the interface instead of the implementation class most of the time. I wonder if this is a ...
Writing interfaces "just because" strikes me as a waste of time and energy, not to mention a violation of the KISS-principle. I write them when they are actually useful in representing common behavior of related classes, not just as a fancy header file.
Don't over design your system. If you find out that you have several types of Orders and think it's appropriate to declare an interface for Orders than refactor it when the need arises. For domain models, the probability is high that the specific interface will change much over the lifetime of development, so it rarely...
Programming against interfaces: Do you write interfaces for all your domain classes?
[ "", "java", "model", "dns", "interface", "" ]
I'm interested in actual examples of using fixed point combinators (such as the [y-combinator](https://stackoverflow.com/questions/93526/what-is-a-y-combinator) in C++. Have you ever used a fixed point combinator with [egg](http://p-stade.sourceforge.net/boost/libs/egg/doc/html/boost_egg/function_adaptors.html#boost_eg...
Here is the same code converted into `boost::bind` notice the y-combinator and its application site in the main function. I hope this helps. ``` #include <boost/function.hpp> #include <boost/bind.hpp> #include <iostream> // Y-combinator compatible factorial int fact(boost::function<int(int)> f,int v) { if(v == 0) ...
``` #include <functional> #include <iostream> template <typename Lamba, typename Type> auto y (std::function<Type(Lamba, Type)> f) -> std::function<Type(Type)> { return std::bind(f, std::bind(&y<Lamba, Type>, f), std::placeholders::_1); } int main(int argc,char** argv) { std::cout << y < std::function<int(int...
Fixed point combinators in C++
[ "", "c++", "bind", "y-combinator", "" ]
I have a UI widget that needs to be put in an IFRAME both for performance reasons and so we can syndicate it out to affiliate sites easily. The UI for the widget includes tool-tips that display over the top of other page content. See screenshot below or **[go to the site](http://www.bookabach.co.nz/)** to see it in act...
No it's not possible. Ignoring any historical reasons, nowadays it would be considered a security vulnerability -- eg. many sites put untrusted content into iframes (the iframe source being a different origin so cannot modify the parent frame, per the same origin policy). If such untrusted content had a mechanism to p...
I couldn't find a way to make the content of the frame flow out of the frame, but I did find a way to hack around it, by moving the tooltip into the parent document and placing it above (z-index) the iframe. The approach was: 1) find the iframe in the parent document 2) remove the tooltip element from where it is ...
Is there a way to have content from an IFRAME overflow onto the parent frame?
[ "", "javascript", "css", "iframe", "tooltip", "" ]
Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not? I found the functions bisect\_left/right in the [bisect module](http://docs.python.org/library/bisect.html), but they still return a position even if the item is not...
`bisect_left` finds the first position `p` at which an element could be inserted in a given sorted range while maintaining the sorted order. That will be the position of `x` if `x` exists in the range. If `p` is the past-the-end position, `x` wasn't found. Otherwise, we can test to see if `x` is there to see if `x` was...
Why not look at the code for bisect\_left/right and adapt it to suit your purpose. like this: ``` def binary_search(a, x, lo=0, hi=None): if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)//2 midval = a[mid] if midval < x: lo = mid+1 elif midval > x: ...
Binary search (bisection) in Python
[ "", "python", "binary-search", "bisection", "" ]
I have an embedded webserver that has a total of 2 Megs of space on it. Normally you gzip files for the clients benefit, but this would save us space on the server. I read that you can just gzip the js file and save it on the server. I tested that on IIS and I didn't have any luck at all. What exactly do I need to do o...
As others have mentioned mod\_deflate does that for you, but I guess you need to do it manually since it is an embedded environment. First of all you should leave the name of the file foo.js after you gzip it. You should not change anything in your html files. Since the file is still foo.js In the response header of...
Using gzip compression on a webserver usually means compressing the output from it to conserve your bandwidth - not quite what you have in mind. [Look at this description](http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/25d2170b-09c0-45fd-8da4-898cf9a7d568.mspx?mfr=true) or [This example](ht...
How do I set up gzip compression on a web server?
[ "", "javascript", "compression", "gzip", "" ]
I am trying to create a multi dimensional array using this syntax: ``` $x[1] = 'parent'; $x[1][] = 'child'; ``` I get the error: `[] operator not supported for strings` because it is evaluating the `$x[1]` as a string as opposed to returning the array so I can append to it. What is the correct syntax for doing it th...
The parent has to be an array! ``` $x[1] = array(); $x[1][] = 'child'; ```
``` $x = array(); $x[1] = array(); $x[1][] = 'child'; ```
Error: [] operator not supported for strings
[ "", "php", "arrays", "" ]
From the Java 6 [Pattern](http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html) documentation: > Special constructs (non-capturing) > > `(?:`*X*`)`   *X*, as a non-capturing group > > … > > `(?>`*X*`)`   *X*, as an independent, non-capturing group Between `(?:X)` and `(?>X)` what is the difference? What...
It means that the grouping is [atomic](http://www.regular-expressions.info/atomic.html), and it throws away backtracking information for a matched group. So, this expression is possessive; it won't back off even if doing so is the only way for the regex as a whole to succeed. It's "independent" in the sense that it doe...
I think [this tutorial](https://www.regular-expressions.info/atomic.html) explains what exactly "independent, non-capturing group" or "Atomic Grouping" is > The regular expression `a(bc|b)c` (capturing group) matches **abcc** > and **abc**. The regex `a(?>bc|b)c` (atomic group) matches **abcc** > but not **abc**. > > ...
What is a regex "independent non-capturing group"?
[ "", "java", "regex", "" ]
It's been a while since I've programmed a GUI program, so this may end up being super simple, but I can't find the solution anywhere online. Basically my problem is that when I maximize my program, all the things inside of the window (buttons, textboxes, etc.) stay in the same position in the window, which results in ...
You want to check and properly set the Anchor and Dock properties on each control in the Form. The Anchor property on a control tells which sides of the form (top, bottom, left, right) the control is 'anchored' to. When the form is resized, the distance between the control and its anchors will stay the same. This lets ...
Anchor and Dock properties
Stuff in Windows Form Move When Maximized - C#
[ "", "c#", "windows", "user-interface", "" ]
How do I pick a random element from a set? I'm particularly interested in picking a random element from a HashSet or a LinkedHashSet, in Java.
``` int size = myHashSet.size(); int item = new Random().nextInt(size); // In real life, the Random object should be rather more shared than this int i = 0; for(Object obj : myhashSet) { if (i == item) return obj; i++; } ```
A somewhat related Did You Know: There are useful methods in [`java.util.Collections`](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html) for shuffling whole collections: [`Collections.shuffle(List<?>)`](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#shuffle-java.util.List-) an...
Picking a random element from a set
[ "", "java", "algorithm", "random", "set", "" ]
From Wikipedia, the free encyclopedia: **Closure (computer science)** > In computer science, a closure is a > function that is evaluated in an > environment containing one or more > bound variables. When called, the > function can access these variables. > The explicit use of closures is > associated with functional p...
(using an example from jQuery) ``` function SetClassOnHover(className){ $("td").hover( function () { $(this).addClass(className); }, function () { $(this).removeClass(className); } ); } ``` The closure comes into play when the variable className is used inside the scope of each functio...
Searching for "javascript closures" gave plenty of encouraging-looking links. The top three were these two (the third link was a reformatted version of the second): * [Javascript closures](http://www.jibbering.com/faq/faq_notes/closures.html) * [JavaScript closures for dummies](http://web.archive.org/web/2010111301310...
JavaScript - How do I learn about "closures" usage?
[ "", "javascript", "closures", "" ]
I'm a Java developer looking to learn some C#/ASP.NET. One thing I've never liked about .NET from the get-go was that it didn't have support for MVC. But now it does! So I was wondering if anybody knew where to get started learning C# MVC. Also, do you need the non-free version of developer-studio to do this?
Just to add to Will's answer, Scott has a series on ASP.NET MVC development: [ASP.NET MVC Framework Part 1](http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mvc-framework-part-1.aspx) [ASP.NET MVC Framework (Part 2): URL Routing](http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-...
Keep an eye on [Scott Guthrie](http://weblogs.asp.net/Scottgu/)'s and [Phil Haack](http://haacked.com/)'s blogs. They are the primary source of documentation right now. Be wary, as most posts about MVC are about previous versions and don't apply anymore (anything that uses a lambda is right out, unfortunately). Of co...
Where can I get some information on starting C# programming with MVC / ASP.NET?
[ "", "c#", "asp.net-mvc", "" ]
Scenario: I'm currently writing a layer to abstract 3 similar webservices into one useable class. Each webservice exposes a set of objects that share commonality. I have created a set of intermediary objects which exploit the commonality. However in my layer I need to convert between the web service objects and my obj...
Alternative answer: generics. ``` public static T[] CreateProperties<T>(IProperty[] properties) where T : class, new() { //Empty so return null if (properties==null || properties.Length == 0) return null; //Check the type is allowed CheckPropertyTypes("CreateProperties(Type,IProperty[])",t...
Basically, no. There are a few, limited, uses of array covariance, but it is better to simply know which type of array you want. There is a generic Array.ConvertAll that is easy enough (at least, it is easier with C# 3.0): ``` Property[] props = Array.ConvertAll(source, prop => (Property)prop); ``` The C# 2.0 version...
Unable to cast object of type 'System.Object[]' to 'MyObject[]', what gives?
[ "", "c#", ".net", "arrays", "reflection", "casting", "" ]
Is there a way to use .NET reflection to capture the values of all parameters/local variables?
You could get at this information using the [CLR debugging API](http://msdn.microsoft.com/en-us/library/bb384548.aspx) though it won't be a simple couple of lines to extract it.
Reflection is not used to capture information from the stack. It reads the Assembly. You might want to take a look at StackTrace <http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx> Good article here: <http://www.codeproject.com/KB/trace/customtracelistener.aspx>
Capturing method state using Reflection
[ "", "c#", ".net", "reflection", "" ]
I have a combo box on a WinForms app in which an item may be selected, but it is not mandatory. I therefore need an 'Empty' first item to indicate that no value has been set. The combo box is bound to a DataTable being returned from a stored procedure (I offer no apologies for Hungarian notation on my UI controls :p )...
There are two things you can do: 1. Add an empty row to the `DataTable` that is returned from the stored procedure. ``` DataRow emptyRow = hierarchies.NewRow(); emptyRow["guid"] = ""; emptyRow["ObjectLogicalName"] = ""; hierarchies.Rows.Add(emptyRow); ``` Create a DataView and sort it using Obje...
``` cmbHierarchies.SelectedIndex = -1; ```
How to insert 'Empty' field in ComboBox bound to DataTable
[ "", "c#", "combobox", "" ]
I wonder what the best way to make an entire tr clickable would be? The most common (and only?) solution seems to be using JavaScript, by using onclick="javascript:document.location.href('bla.htm');" (not to forget: Setting a proper cursor with onmouseover/onmouseout). While that works, it is a pity that the target U...
Fortunately or unfortunately, most modern browsers do not let you control the status bar anymore (it was possible and popular back in the day) because of fraudulent intentions. Your better bet would be a title attribute or a [javascript tooltip](http://www.google.com/search?q=javascript+tooltip).
If you don't want to use javascript, you can do what Chris Porter suggested by wrapping each td element's content in matching anchor tags. Then set the anchor tags to `display: block` and set the `height` and `line-height` to be the same as the td's height. You should then find that the td's touch seamlessly and the ef...
Making a Table Row clickable
[ "", "javascript", "html", "" ]
Given a week number, e.g. `date -u +%W`, how do you calculate the days in that week starting from Monday? Example rfc-3339 output for week 40: ``` 2008-10-06 2008-10-07 2008-10-08 2008-10-09 2008-10-10 2008-10-11 2008-10-12 ```
**PHP** ``` $week_number = 40; $year = 2008; for($day=1; $day<=7; $day++) { echo date('m/d/Y', strtotime($year."W".$week_number.$day))."\n"; } ``` --- Below post was because I was an idiot who didn't read the question properly, but will get the dates in a week starting from Monday, given the date, not the week n...
If you've got Zend Framework you can use the Zend\_Date class to do this: ``` require_once 'Zend/Date.php'; $date = new Zend_Date(); $date->setYear(2008) ->setWeek(40) ->setWeekDay(1); $weekDates = array(); for ($day = 1; $day <= 7; $day++) { if ($day == 1) { // we're already at day 1 } ...
Calculating days of week given a week number
[ "", "php", "date", "" ]
I've worked with a couple of Visual C++ compilers (VC97, VC2005, VC2008) and I haven't really found a clearcut way of adding external libraries to my builds. I come from a Java background, and in Java libraries are everything! I understand from compiling open-source projects on my Linux box that all the source code fo...
In I think you might be asking the mechanics of how to add a lib to a project/solution in the IDEs... In 2003, 2005 and 2008 it is something similar to: from the solution explorer - right click on the project select properties (typically last one) I usually select all configurations at the top... Linker Input Additi...
Libraries in C++ are also considered helpful, but the way you integrate them is different to Java because the compiler only has to see the *interface* of the library, which is usually declared in header files. In Java, the compiler will have to inspect the actual libraries because Java doesn't have this distinction bet...
How do you add external libraries for compilation in VC++?
[ "", "c++", "visual-studio-2008", "visual-c++", "visual-studio-2005", "" ]
I have done a little Django development, but it has all been in a text editor. I was curious what more advanced development tools others are using in their Django development. I am used to using Visual Studio for development and really like the [IntelliSense](https://en.wikipedia.org/wiki/Intelligent_code_completion#I...
I use Eclipse and a plain vanilla [PyDev](https://en.wikipedia.org/wiki/PyDev). There isn't any specific Django functionality. The best I came up with was setting up a run profile to run the development web server. If you add the web tools project (WTP), you'll get syntax highlighting in your templates, but nothing th...
There is [PyCharm](http://www.jetbrains.com/pycharm/index.html) from JetBrains which supports Django and [Google Apps](http://en.wikipedia.org/wiki/Google_Apps). It looks promising. Note: You need to buy a license for the Professional version if you want Django support. The Community version desn't support Django.
Django development IDE
[ "", "python", "django", "ide", "" ]
I'm writing an winforms app that needs to set internet explorer's proxy settings and then open a new browser window. At the moment, I'm applying the proxy settings by going into the registry: ``` RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", t...
This depends somewhat on your exact needs. If you are writing a C# app and simply want to set the default proxy settings that your app will use, use the class System.Net.GlobalProxySelection (<http://msdn.microsoft.com/en-us/library/system.net.globalproxyselection.aspx>). You can also set the proxy for any particular c...
from: <http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/19517edf-8348-438a-a3da-5fbe7a46b61a> Add these lines at the beginning of your code: using System.Runtime.InteropServices; using Microsoft.Win32; ``` [DllImport("wininet.dll")] public static extern bool InternetSetOption(IntPtr hInternet,...
Programmatically Set Browser Proxy Settings in C#
[ "", "c#", "proxy", "registry", "" ]
I have a stored procedure that returns multiple tables. How can I execute and read both tables? I have something like this: ``` SqlConnection conn = new SqlConnection(CONNECTION_STRING); SqlCommand cmd = new SqlCommand("sp_mult_tables",conn); cmd.CommandType = CommandType.StoredProcedure); IDataReader rdr = cmd.Exec...
Adapted from [MSDN](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter(VS.71).aspx): ``` using (SqlConnection conn = new SqlConnection(connection)) { SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = new SqlCommand(query, conn); adapter.Fill(dataset); retu...
If you want to read the results into a DataSet, you'd be better using a DataAdapter. But with a DataReader, first iterate through the first result set, then call NextResult to advance to the second result set.
How can I read multiple tables into a dataset?
[ "", "c#", "ado.net", "dataset", "" ]
As far as I can understand, when I new up a *Linq to SQL class*, it is the equivalent of new'ing up a *SqlConnection object*. Suppose I have an object with two methods: `Delete()` and `SubmitChanges()`. Would it be wise of me to new up the *Linq to SQL class* in each of the methods, or would a private variable holding...
Having now reviewed the code sample you edited to post, I would definitely refactor your class to take advantage of LINQ-to-SQL's built in functionality. (I won't edit my previous comment because it's a better answer to the general question) Your class's fields appear to be a pretty direct mapping of the columns on t...
Depends on to what you refer by a "LINQ-to-SQL class", and what the code in question looks like. If you're talking about the DataContext object, and your code is a class with a long lifetime or your program itself, I believe it would be best to initialize it in the constructor. It's not really like creating and/or op...
Linq to SQL class lifespan
[ "", "c#", "linq-to-sql", "oop", "c#-3.0", "" ]
Recent versions of PHP have a cache of filenames for knowing the real path of files, and `require_once()` and `include_once()` can take advantage of it. There's a value you can set in your *php.ini* to set the size of the cache, but I have no idea how to tell what the size should be. The default value is 16k, but I se...
You've probably already found this, but for those who come across this question, you can use realpath\_cache\_size() and realpath\_cache\_get() to figure out how much of the realpath cache is being used on your site and tune the settings accordingly.
Though I can't offer anything specific to your situation, my understanding is that 16k is pretty low for most larger PHP applications (particularly ones that use a framework like the [Zend Framework](http://framework.zend.com)). I'd say at least double the cache size if your application uses lots of includes and see wh...
How can I tune the PHP realpath cache?
[ "", "php", "optimization", "require-once", "realpath", "" ]
I'm writing an article about editing pages in order to hand pick what you really want to print. There are many tools (like "Print What you like") but I also found this script. Anyone knows anything about it? I haven't found any kind of documentation or references. ``` javascript:document.body.contentEditable='true'; d...
The contentEditable property is what you want -- It's supported by IE, Safari (and by chrome as a byproduct), and I *think* firefox 3 (alas not FFX2). And hey, it's also part of HTML5 :D Firefox 2 supports designMode, but that is restricted to individual frames, whereas the contentEditable property applies applies to ...
document.designMode is supported in IE 4+ (which started it apparently) and FireFox 1.3+. You turn it on and you can edit the content right in the browser, it's pretty trippy. I've never used it before but it sounds like it would be pretty perfect for hand picking printable information. Edited to say: It also appears ...
Java Script to edit page content on the fly
[ "", "javascript", "html", "editing", "" ]
Is there a Java equivalent to .NET's App.Config? If not is there a standard way to keep you application settings, so that they can be changed after an app has been distributed?
For WebApps, web.xml can be used to store application settings. Other than that, you can use the [Properties](http://java.sun.com/javase/6/docs/api/java/util/Properties.html) class to read and write properties files. You may also want to look at the [Preferences](http://java.sun.com/javase/6/docs/api/java/util/prefs/...
To put @Powerlord's suggestion (+1) of using the `Properties` class into example code: ``` public class SomeClass { public static void main(String[] args){ String dbUrl = ""; String dbLogin = ""; String dbPassword = ""; if (args.length<3) { //If no inputs passed in,...
Java equivalent to app.config?
[ "", "java", "configuration-files", "" ]
Anyone know a simple method to swap the background color of a webpage using JavaScript?
Modify the JavaScript property `document.body.style.background`. For example: ``` function changeBackground(color) { document.body.style.background = color; } window.addEventListener("load",function() { changeBackground('red') }); ``` Note: this does depend a bit on how your page is put together, for example if ...
You don't need AJAX for this, just some plain java script setting the background-color property of the body element, like this: ``` document.body.style.backgroundColor = "#AA0000"; ``` If you want to do it as if it was initiated by the server, you would have to poll the server and then change the color accordingly.
How do I change the background color with JavaScript?
[ "", "javascript", "css", "" ]
I need to find out the time a function takes for computing the performance of the application / function. is their any open source Java APIs for doing the same ?
You're in luck as there are quite a few [open source Java profilers](http://java-source.net/open-source/profilers) available for you.
Take a look at the official [TPTP plugin](http://www.eclipse.org/tptp/) for Eclipse. This pretty much does all you describe and a (frikkin') whole lot more. I can really recommend it.
computing performance
[ "", "java", "performance", "profiling", "" ]
After discovering [Clojure](http://clojure.org) I have spent the last few days immersed in it. What project types lend themselves to Java over Clojure, vice versa, and in combination? What are examples of programs which you would have never attempted before Clojure?
Clojure lends itself well to [concurrent programming](http://clojure.org/concurrent_programming). It provides such wonderful tools for dealing with threading as Software Transactional Memory and mutable references. As a demo for the Western Mass Developer's Group, Rich Hickey made an ant colony simulation in which eac...
If you are going to try concurrent programming, then I think clojure is much better than what you get from Java out of the box. Take a look at this presentation to see why: <http://blip.tv/file/812787> I documented my first 20 days with Clojure on my blog <http://loufranco.com/blog/files/category-20-days-of-clojure....
How can I transition from Java to Clojure?
[ "", "java", "functional-programming", "clojure", "use-case", "" ]
Many times I've seen links like these in HTML pages: ``` <a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a> ``` What's the effect of the `return false` in there? Also, I don't usually see that in buttons. Is this specified anywhere? In some spec in w3.org?
The return value of an event handler determines whether or not the default browser behaviour should take place as well. In the case of clicking on links, this would be following the link, but the difference is most noticeable in form submit handlers, where you can cancel a form submission if the user has made a mistake...
You can see the difference with the following example: ``` <a href="http://www.google.co.uk/" onclick="return (confirm('Follow this link?'))">Google</a> ``` Clicking "Okay" returns true, and the link is followed. Clicking "Cancel" returns false and doesn't follow the link. If javascript is disabled the link is follow...
What's the effect of adding 'return false' to a click event listener?
[ "", "javascript", "html", "" ]
This question is for C# 2.0 Winform. For the moment I use checkboxes to select like this : Monday[x], Thuesday[x]¸... etc. It works fine but **is it a better way to get the day of the week?** (Can have more than one day picked)
Checkboxes are the standard UI component to use when selection of multiple items is allowed. From UI usability guru [Jakob Nielsen's](http://www.useit.com/jakob/) article on [Checkboxes vs. Radio Buttons](http://www.useit.com/alertbox/20040927.html): > "Checkboxes are used when there are lists of options and the user ...
checkbox seems appropriate.
C# Day from Week picker component
[ "", "c#", "winforms", "" ]
The problem is in the title - IE is misbehaving and is saying that there is a script running slowly - FF and Chrome don't have this problem. How can I find the problem . .there's a lot of JS on that page. Checking by hand is not a good ideea **EDIT :** It's a page from a project i'm working on... but I need a tool to...
Get yourself a copy of the IBM Page Profiler: <https://www.ibm.com/developerworks/community/groups/service/html/communityview?communityUuid=61d74777-1701-4014-bfc0-96067ed50156> It's free (always a win). Start it up in the background, give it a few seconds, then refresh the page in IE. Go back to the profiler and it ...
Long running scripts are detected differently by different browsers: * IE will raise the warning once 5 million statements have been executed ([more info on MSDN](http://support.microsoft.com/kb/175500)) * Firefox will warn if the script takes longer than 10 seconds ([more info on MDN](http://support.mozilla.com/en-US...
a script on this page is causing ie to run slowly
[ "", "javascript", "internet-explorer", "" ]
If I have $var defined in Page1.php and in Page2.php I have ``` //Page2.php include('Page1.php'); echo $var; ``` For what reasons will it not print the value of $var to the screen? The files are in the same directory so paths shouldn't be the issue. I've checked the php.ini file and nothing really jumps out at me. A...
If it were a path problem you would see a warning in your error log. You could also change to require instead of include and it would become obvious. ``` echo getcwd(); ``` You can also print your working directory to figure out what's wrong. Is $var created in a function? If so, make sure you have ``` global $var;...
Possible causes: * The current working path isn't always the same as the file's. For example, if Page2.php is being included at a higher level, that higher level will be the path. Either make sure you've loaded Page2.php directly or move Page1.php accordingly. * Make sure `$var` is really what you expect it to be. Ech...
In PHP, for what reasons can I not include a variable from external file?
[ "", "php", "" ]
Take this simple *C# LINQ* query, and imagine that `db.Numbers` is an *SQL* table with one column `Number`: ``` var result = from n in db.Numbers where n.Number < 5 select n.Number; ``` This will run very efficiently in *C#*, because it generates an *SQL* query something like ``` select Number f...
I believe that when IronPython 2.0 is complete, it will have LINQ support (see [this thread](http://groups.google.com/group/ironpy/browse_thread/thread/eb6b9eb2241cc68e) for some example discussion). Right now you should be able to write something like: ``` Queryable.Select(Queryable.Where(someInputSequence, somePredi...
[sqlsoup](http://www.sqlalchemy.org/trac/wiki/SqlSoup) in sqlalchemy gives you the quickest solution in python I think if you want a clear(ish) one liner . Look at the page to see. It should be something like... ``` result = [n.Number for n in db.Numbers.filter(db.Numbers.Number < 5).all()] ```
Can you do LINQ-like queries in a language like Python or Boo?
[ "", "python", "linq", "linq-to-sql", "ironpython", "boo", "" ]
I have 2 classes with a LINQ association between them i.e.: ``` Table1: Table2: ID ID Name Description ForiegnID ``` The association here is between **Table1.ID -> Table2.ForiegnID** I need to be able to change the value of Table2.ForiegnID, however I can't and think it is bec...
Check out the designer.cs file. This is the key's property ``` [Column(Storage="_ParentKey", DbType="Int")] public System.Nullable<int> ParentKey { get { return this._ParentKey; } set { if ((this._ParentKey != value)) { //This code is added by the association ...
``` Table1: Table2: ID ID Name Description ForeignID ``` With this : Table2.ForeignID = 2 you receive an error.......... Example : You can change ForeignID field in Table 2 whit this : ``` Table2 table = dataContext.Table2.single(d => d.ID == Id) table.Table1 = dataC...
How to change the value of associated field
[ "", "c#", "linq", "linq-to-sql", "associations", "" ]
Just wondering why people like case sensitivity in a programming language? I'm not trying to start a flame war just curious thats all. Personally I have never really liked it because I find my productivity goes down when ever I have tried a language that has case sensitivity, mind you I am slowly warming up/getting u...
Consistency. Code is more difficult to read if "foo", "Foo", "fOO", and "fOo" are considered to be identical. SOME PEOPLE WOULD WRITE EVERYTHING IN ALL CAPS, MAKING EVERYTHING LESS READABLE. Case sensitivity makes it easy to use the "same name" in different ways, according to a capitalization convention, e.g., ``` F...
An advantage of VB.NET is that although it is not case-sensitive, the IDE automatically re-formats everything to the "official" case for an identifier you are using - so it's easy to be consistent, easy to read. Disadvantage is that I hate VB-style syntax, and much prefer C-style operators, punctuation and syntax. In...
Why do people like case sensitivity?
[ "", "c#", "case-sensitive", "" ]
Is there a good way to have a `Map<String, ?>` get and put ignoring case?
TreeMap extends Map and supports custom comparators. String provides a default case insensitive comparator. So: ``` final Map<String, ...> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); ``` The comparator does not take locale into account. Read more about it in its JavaDoc.
You could use [CaseInsensitiveMap](http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/map/CaseInsensitiveMap.html) from Apache's Commons Collections.
Is there a good way to have a Map<String, ?> get and put ignoring case?
[ "", "java", "dictionary", "case-insensitive", "" ]
Which is the most correct code? ``` if (HttpContext.Current.Response.Cookies[authCookieName] != null) { HttpContext.Current.Response.Cookies[authCookieName].Value = "New Value"; } ``` or ``` if (HttpContext.Current != null) if (HttpContext.Current.Response != null) if (HttpContext.Current.Response.Co...
If any one of HttpContext, HttpContext.Current, HttpContext.Current.Response, or Http.Current.Response.Cookies is null, you're already in trouble. Let the exception happen and fix your web server.
Both are good. Assuming that you have already checked everything else that need to be checked first. E.g.: ``` private bool CheckSuspendersAndBelt() { try { //ensure that true is true... if (true == true) { //...and that false is false... if (false == false) ...
Which is correct way to check for Null exception?
[ "", "c#", "asp.net", "" ]
It looks like I had a fundamental misunderstanding about C++ :< I like the polymorphic container solution. Thank you SO, for bringing that to my attention :) --- So, we have a need to create a relatively generic container type object. It also happens to encapsulate some business related logic. However, we need to st...
Can you not have a root Container class that contains elements: ``` template <typename T> class Container { public: // You'll likely want to use shared_ptr<T> instead. virtual void push(T *element) = 0; virtual T *pop() = 0; virtual void InvokeSomeMethodOnAllItems() = 0; }; template <typename T> class L...
You can look at using a standard container of [boost::any](http://www.boost.org/doc/libs/1_36_0/doc/html/any.html) if you are storing truly arbitrary data into the container. It sounds more like you would rather have something like a [boost::ptr\_container](http://www.boost.org/doc/libs/1_36_0/libs/ptr_container/doc/p...
C++ alternatives to void* pointers (that isn't templates)
[ "", "c++", "templates", "pointers", "polymorphism", "" ]
At the moment, I'm creating an XML file in Java and displaying it in a JSP page by transforming it with XSL/XSLT. Now I need to take that XML file and display the same information in a PDF. Is there a way I can do this by using some kind of XSL file? I've seen the [iText](http://www.lowagie.com/iText/) Java-PDF librar...
You can use XSL Formatting objects. Here are some good articles on how to do it: * <http://www.xml.com/pub/a/2001/01/17/xsl-fo/index.html> * <http://www.xml.com/pub/a/2001/01/24/xsl-fo/index.html?page=1> * <http://www.javaworld.com/javaworld/jw-04-2006/jw-0410-html.html>
### A - Explanation You should use **Apache FOP** framework to generate **pdf** output. Simply you provide data in **xml** format and render the page with an **xsl-fo** file and specify the parameters like *margin*, *page layout* in this **xsl-fo** file. I'll provide a simple demo, I use **maven** build tool to gathe...
How do you create a PDF from XML in Java?
[ "", "java", "xml", "pdf", "xslt", "itext", "" ]
I’m having an issue where a drop down list in IE 6/7 is behaving as such: ![alt text](https://i488.photobucket.com/albums/rr249/djfloetic/ie7.jpg) You can see that the drop down `width` is not wide enough to display the whole text without expanding the overall drop down list. However in Firefox, there is no issue as...
[This guy](http://www.dougboude.com/blog/1/2008/05/Viewing-Option-Text-in-IE7-thats-Wider-than-the-Select-List.cfm) had the same problem as you and he came up with a solution. It is a bit of a hack and depends on how you have your UI setup, but it is an option. I hope it helps. **edit** The link that I started off lo...
Would something like this be doable in your situation? <http://www.hedgerwow.com/360/dhtml/ui_select_with_fixed_width/demo.php> The width of the dropdown grows/shrinks during a mouseover.
Drop Down List Issue
[ "", "javascript", "internet-explorer", "drop-down-menu", "cross-browser", "html-select", "" ]
How do you save data from ExtJS form? Load data from the business layer into form or grid?
Most likely I found the best solution <http://developmentalmadness.blogspot.com/2008/07/using-extjs-with-wcf.html>
For me, I have used an ASHX page to push straight XML - and then use the ExtJS data reader to read.. then, say using a form etc, I push the form data straight back to another ASHX page to interrogate/post to the DB.. darned if I know the best way - but it suited me, and seems very quick and stable, and most importantly...
What is the best practice to use ExtJS with Asp.net and WCF in .NET 3.5?
[ "", "javascript", "asp.net-ajax", "extjs", "" ]
I'm trying to write some SQL that will delete files of type '.7z' that are older than 7 days. Here's what I've got that's not working: ``` DECLARE @DateString CHAR(8) SET @DateString = CONVERT(CHAR(8), DATEADD(d, -7, GETDATE()), 1) EXECUTE master.dbo.xp_delete_file 0, N'e:\Database Backups',N'7z', ...
Had a similar problem, found various answers. Here's what I found. You can't delete 7z files with xp\_delete\_file. This is an undocumented extended stored procedure that's a holdover from SQL 2000. It checks the first line of the file to be deleted to verify that it is either a SQL backup file or a SQL report file. I...
AFAIK `xp_delete_file` only delete files recognized by SQL Server 2005 (backup files, transaction logs, ...). Perhaps you can try something like this: ``` xp_cmdshell 'del <filename>' ```
SQL Server xp_delete_file not deleting files
[ "", "sql", "sql-server", "maintenance-plan", "" ]
I have a function that is effectively a replacement for print, and I want to call it without parentheses, just like calling print. ``` # Replace print $foo, $bar, "\n"; # with myprint $foo, $bar, "\n"; ``` In Perl, you can create subroutines with parameter templates and it allows exactly this behavior if you define ...
print is not a [variable functions](http://ca.php.net/manual/en/functions.variable-functions.php) > Because this is a language construct > and not a function, it cannot be > called using variable functions And : > Variable functions > > PHP supports the concept of variable > functions. This means that if a > variabl...
Only by editing the PHP codebase and adding a new language construct. -Adam
Can I create a PHP function that I can call without parentheses?
[ "", "php", "function", "" ]
In a C++ Linux app, what is the simplest way to get the functionality that the [Interlocked](http://msdn.microsoft.com/en-us/library/system.threading.interlocked.aspx) functions on Win32 provide? Specifically, a lightweight way to atomically increment or add 32 or 64 bit integers?
Upon further review, [this](http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/Atomic-Builtins.html) looks promising. Yay stack overflow.
Just few notes to clarify the issue which has nothing to do with *Linux*. **RWM** (read-modify-write) operations and those that do not execute in a single-step need the hardware-support to execute *atomically*; among them increments and decrements, fetch\_and\_add, etc. For some architecture (including I386, AMD\_64 ...
Interlocked equivalent on Linux
[ "", "c++", "linux", "multithreading", "atomic", "" ]
I am putting together a Samba-based server as a Primary Domain Controller, and ran into a cute little problem that should have been solved many times over. But a number of searches did not yield a result. I need to be able to remove an existing user from an existing group with a command line script. It appears that the...
Web Link: <http://www.ibm.com/developerworks/linux/library/l-roadmap4/> To add members to the group, use the gpasswd command with the -a switch and the user id you wish to add: gpasswd -a userid mygroup Remove users from a group with the same command, but a -d switch rather than -a: gpasswd -d userid mygroup "man ...
I found [This](http://search.cpan.org/~ssnodgra/Unix-ConfigFile-0.06/GroupFile.pm) for you. It should do what you need. As far as I can tell Perl does not have any built in functions for removing users from a group. It has several for seeing the group id of a user or process.
Perl or Python script to remove user from group
[ "", "python", "perl", "system-administration", "centos", "redhat", "" ]
Here's my issue, I'd like to mock a class that creates a thread at initialization and closes it at destruction. There's no reason for my mock class to actually create and close threads. But, to mock a class, I have inherit from it. When I create a new instance of my mock class, the base classes constructor is called, c...
You instead make an interface that describes the type, and have both the real class and the mock class inherit from that. So if you had: ``` class RAIIClass { public: RAIIClass(Foo* f); ~RAIIClass(); bool DoOperation(); private: ... }; ``` You would make an interface like: ``` class MockableInterface { p...
First of all, it is not necessarily an unreasonable thing that your classes might be well designed for their use, but poorly designed for testing. Not everything is easy to test. Presumably you want to use another function or class which makes use of the class which you want to mock (otherwise the solution is trivial)...
How do you mock classes that use RAII in c++
[ "", "c++", "unit-testing", "mocking", "" ]
Should a method that implements an interface method be annotated with `@Override`? The [javadoc of the `Override` annotation](http://java.sun.com/javase/6/docs/api/java/lang/Override.html) says: > Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotate...
You should use `@Override` whenever possible. It prevents simple mistakes from being made. Example: ``` class C { @Override public boolean equals(SomeClass obj){ // code ... } } ``` This doesn't compile because it doesn't properly override [`public boolean equals(Object obj)`](https://docs.oracle....
I believe that javac behaviour has changed - with 1.5 it prohibited the annotation, with 1.6 it doesn't. The annotation provides an extra compile-time check, so if you're using 1.6 I'd go for it.
Should we @Override an interface's method implementation?
[ "", "java", "oop", "interface", "annotations", "" ]
I'm working profesionally on a php web application which contains contacts, among other data. I was wondering how hard it would be to make this data available to external programs using the LDAP protocol. Are there specific tools out there for this? I couldn't really find anything, but I can't imagine I'm the first to...
The LDAP server protocol is big, and I don't think there is a PHP server in existence. I would suggest running an LDAP server and pushing records to it. I like OpenLDAP, but there are plenty of servers out there, depending on your platform. Even ActiveDirectory is an LDAP server. Typically, LDAP objects have internal...
Rather than trying to get an LDAP server to use your database, I'd recommend storing your data in the LDAP server. You can create custom fields for anything that doesn't fit in the standard LDAP fields.
Implementing LDAP compliance
[ "", "php", "ldap", "" ]
Templates are a pretty healthy business in established programming languages, but are there any good ones that can be processed in JavaScript? By "template" I mean a document that accepts a data object as input, inserts the data into some kind of serialized markup language, and outputs the markup. Well-known examples ...
You might want to check out [Mustache](https://mustache.github.io/) - it's really portable and simple template language with javascript support among other languages.
[John Resig](http://ejohn.org/) has a mini javascript templating engine at [http://ejohn.org/blog/javascript-micro-templating/](https://web.archive.org/web/20160314000941/http://ejohn.org/blog/javascript-micro-templating/)
What good template language is supported in JavaScript?
[ "", "javascript", "templates", "" ]
I'm not exactly sure how to ask this question really, and I'm no where close to finding an answer, so I hope someone can help me. I'm writing a Python app that connects to a remote host and receives back byte data, which I unpack using Python's built-in struct module. My problem is with the strings, as they include mu...
There's no built-in functionality for decoding a string like this, since it is really its own custom codec. You simply need to split up the string on those control characters and decode it accordingly. Here's a (very slow) example of such a function that handles latin1 and shift-JIS: ``` latin1 = "latin-1" japanese =...
Here's a relatively simple example of how do it... ``` # -*- coding: utf-8 -*- import re # Test Data ENCODING_RAW_DATA = ( ('latin_1', 'L', u'Hello'), # Latin 1 ('iso8859_2', 'E', u'dobrý večer'), # Central Europe ('iso8859_9', 'T', u'İyi akşamlar'), # Turkish ('iso8859_13', 'B', u'Į svei...
Dealing with a string containing multiple character encodings
[ "", "python", "string", "unicode", "encoding", "" ]
I have code to create another "row" (div with inputs) on a button click. I am creating new input elements and everything works fine, however, I can't find a way to access these new elements. Example: I have input element (name\_1 below). Then I create another input element (name\_2 below), by using the javascript's `c...
You have to create the element AND add it to the DOM using functions such as appendChild. See [here](http://www.w3schools.com/htmldom/dom_methods.asp) for details. My guess is that you called createElement() but never added it to your DOM hierarchy.
If it's properly added to the dom tree you will be able to query it with document.getElementById. However browser bugs may cause troubles, so use a JavaScript toolkit like jQuery that works around browser bugs.
Accessing created DOM elements
[ "", "javascript", "jquery", "html", "dom", "" ]
The problem is you can't tell the user how many characters are allowed in the field because the escaped value has more characters than the unescaped one. I see a few solutions, but none looks very good: * One whitelist for each field *(too much work and doesn't quite solve the problem)* * One blacklist for each field...
Don't build your application around the database - build the database for the application! Design how you want the interface to work for the user first, work out the longest acceptable field length, and use that. In general, don't escape before storing in the database - store raw data in the database and format it fo...
making some wild assumptions about the context here: * if the field can hold 32 characters, that is 32 unescaped characters * let the user enter 32 characters * escape/unescape is not the user's problem * why is this an issue? + if this is form data-entry it won't matter, and + if you are for some reason escaping ...
HTML Data exceeds field length after being hex-sanitized
[ "", "php", "html", "validation", "" ]
I have found an interesting issue in windows which allows me to cause the Windows clock (but not the hardware clocks) to run fast - as much as 8 seconds every minute. I am doing some background research to work out how Windows calculates and updates it's internal time (not how it syncs with an NTP servers). Any informa...
[This MSDN article](http://msdn.microsoft.com/en-us/library/ms724961(VS.85).aspx) gives a very brief description of how the system time is handled: "When the system first starts, it sets the system time to a value based on the real-time clock of the computer and then regularly updates the time." Another interesting fun...
Regarding how `_ftime()` works: If you have Microsoft Visual C++ installed, you probably have the C runtime source installed as well. `_ftime()` is defined in `%ProgramFiles%\Microsoft Visual Studio <version>\VC\crt\src\ftime.c` and `ftime64.c`.
How does _ftime / Windows internal time work?
[ "", "c++", "windows", "winapi", "time", "" ]
I am developing a WebPart (it will be used in a SharePoint environment, although it does not use the Object Model) that I want to expose AJAX functionality in. Because of the nature of the environment, Adding the Script Manager directly to the page is not an option, and so must be added programmatically. I have attempt...
I was able to get this to work by using the Page's Init event: ``` protected override void OnInit(EventArgs e) { Page.Init += delegate(object sender, EventArgs e_Init) { if (ScriptManager.GetCurrent(Page) == null) { ScriptManager s...
I had the same basic issue the rest of you had. I was creating a custom ascx control and wanted to be able to not worry about whether or not the calling page had the scriptmanager declared. I got around the issues by adding the following to the ascx contorl itself. **to the ascx page -** `<asp:PlaceHolder runat="serv...
Add ScriptManager to Page Programmatically?
[ "", "c#", "sharepoint-2007", "web-parts", "scriptmanager", "" ]
I'm writing some JavaScript code to parse user-entered functions (for spreadsheet-like functionality). Having parsed the formula I *could* convert it into JavaScript and run `eval()` on it to yield the result. However, I've always shied away from using `eval()` if I can avoid it because it's evil (and, rightly or wron...
I'd like to take a moment to address the premise of your question - that eval() is "*evil*". The word "*evil*", as used by programming language people, usually means "dangerous", or more precisely "able to cause lots of harm with a simple-looking command". So, when is it OK to use something dangerous? When you know wha...
`eval()` isn't evil. Or, if it is, it's evil in the same way that reflection, file/network I/O, threading, and IPC are "evil" in other languages. If, *for your purpose*, `eval()` is faster than manual interpretation, or makes your code simpler, or more clear... then you should use it. If neither, then you shouldn't. S...
When is JavaScript's eval() not evil?
[ "", "javascript", "coding-style", "eval", "" ]
I was recommeded a book called: Accelerated C++ Practical Programming by Example by Andrew Koenig and Barbara E. Moo Addison-Wesley, 2000 ISBN 0-201-70353-X The basis of this book is that Object Oriented Programming is highly wasteful memory-wise, and that most source-code should not be written this way, rather that ...
I haven't read the book, but I have trouble believe that they wrote a book whose "basis ...is that Object Oriented Programming is highly wasteful memory-wise" (Full disclosure: Andy & Barbara are friends of mine). Andy would never say the OOP is wasteful of memory. He WOULD say that a particular algorithm or technique...
Wow, no. Modern C++ compilers are excellent. Massive memory usage is more of a symptom of a poor design or large memory data set. The overhead needed for C++ classes is minimal and really not a problem these days. Object oriented programming is a way to write components in such a way that they can logically group act...
Do the concepts in Accelerated C++ Practical Programming by Example still hold up today?
[ "", "c++", "performance", "oop", "procedural-programming", "" ]
How do I format a number in Java? What are the "Best Practices"? Will I need to round a number before I format it? > `32.302342342342343` => `32.30` > > `.7323` => `0.73` etc.
From [this thread](http://bytes.com/forum/thread16212.html), there are different ways to do this: ``` double r = 5.1234; System.out.println(r); // r is 5.1234 int decimalPlaces = 2; BigDecimal bd = new BigDecimal(r); // setScale is immutable bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP); r = bd.doubleVal...
You and `String.format()` will be new best friends! <https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax> ``` String.format("%.2f", (double)value); ```
How do I format a number in Java?
[ "", "java", "number-formatting", "" ]
One of the guys I work with needs a custom control that would work like a multiline ddl since such a thing does not exist as far as we have been able to discover does anyone have any ideas or have created such a thing before we have a couple ideas but they involve to much database usage We prefer that it be FREE!!!
We use a custom modified version of [suckerfish](http://www.google.com/search?q=suckerfish) at work. DB performance isn't an issue for us because we cache the control. The control renders out nested `UL`/`LI`s either for all nodes in the `web.sitemap` or for a certain set of pages pulled from the DB. We then use [jQue...
Have a look at [EasyListBox](http://www.easylistbox.com/home.aspx). I used on a project and while a bit quirky at first, got the job done.
Multiline ddl Custom Control
[ "", "c#", "asp.net", "custom-controls", "" ]
When hiring a front-end developer, what specific skills and practices should you test for? What is a good metric for evaluating their skill in HTML, CSS and Javascript? Obviously, table-less semantic HTML and pure CSS layout are probably the key skills. But what about specific techniques? Should he/she be able to effo...
When I interview people for a position of Client-Side developer I try to figure out: ``` 1) Understanding DOM (what is that, how is it related to HTML etc) 2) Understanding XML/namespaces 3) Understanding JavaScript (object-oriented? what otherwise) 4) Knowing approaches to componentization (XBL, HTC) - plus 5) Unders...
I can suggest you online test, that includes HTML, CSS and JavaScript together. <http://tests4geeks.com/test/html-css-javascript> It has 60 questions (20 for each subject). And you will recieve the report via email, when the candidate finishes the test.
Testing HTML/CSS/Javascript skills when hiring
[ "", "javascript", "html", "css", "frontend", "" ]
How can I detect mouse clicks regardless of the window the mouse is in? Perferabliy in python, but if someone can explain it in any langauge I might be able to figure it out. I found this on microsoft's site: <http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx> But I don't see how I can detect or pick up t...
The only way to detect mouse events outside your program is to install a Windows hook using [SetWindowsHookEx](http://msdn.microsoft.com/en-us/library/ms644990(VS.85).aspx). The [pyHook](http://www.cs.unc.edu/Research/assist/developer.shtml) module encapsulates the nitty-gritty details. Here's a sample that will print ...
I use win32api. It works when clicking on any windows. ``` # Code to check if left or right mouse buttons were pressed import win32api import time state_left = win32api.GetKeyState(0x01) # Left button down = 0 or 1. Button up = -127 or -128 state_right = win32api.GetKeyState(0x02) # Right button down = 0 or 1. Butt...
Detecting Mouse clicks in windows using python
[ "", "python", "windows", "mouse", "" ]
What are differences between declaring a method in a base type "`virtual`" and then overriding it in a child type using the "`override`" keyword as opposed to simply using the "`new`" keyword when declaring the matching method in the child type?
The "new" keyword doesn't override, it signifies a new method that has nothing to do with the base class method. ``` public class Foo { public bool DoSomething() { return false; } } public class Bar : Foo { public new bool DoSomething() { return true; } } public class Test { public static void Main () ...
I always find things like this more easily understood with pictures: Again, taking joseph daigle's code, ``` public class Foo { public /*virtual*/ bool DoSomething() { return false; } } public class Bar : Foo { public /*override or new*/ bool DoSomething() { return true; } } ``` If you then call the code ...
C# - Keyword usage virtual+override vs. new
[ "", "c#", "syntax", "overriding", "method-hiding", "member-hiding", "" ]
Every class that wants to use java.util.logging generally needs to declare a logger like this: ``` public class MyClass { private static Logger _log = Logger.getLogger(MyClass.class.getName()); } ``` How do you avoid this MyClass.class.getName() boilerplate code?
I have a template set up in Eclipse so that I only have to type a portion of the declaration, and then Eclipse will auto-complete the rest for me. ``` ${:import(org.apache.log4j.Logger)} private final static Logger log = Logger.getLogger(${enclosing_type}.class); ${cursor} ``` So, I only have to type `logger`, hit `C...
Have a look at using point cuts in your code I have not looked back since using them with spring. Here is an article on using AspectJ <http://www.developer.com/java/other/article.php/3109831>
How do you reduce Java logging boilerplate code?
[ "", "java", "logging", "" ]
I am in the process of writing a Bluetooth scanner that locates and identifies mobile devices in the local vicinity. Is this something that I can accomplish using C#, or do I need to drop down into the C/C++ APIs? My application is targeting Windows XP and Vista. Pointers are appreciated. Thanks!
One problem with Bluetooth on the PC is that there are several BT stacks in use and you can never quite know which one is available on a given machine. The most common ones are Widcomm (now Broadcom) and Microsoft (appeared in XP, maybe one of the service packs). However, some BT hardware vendors package BlueSoleil and...
There is also Peter Foot's 32feet.net <http://inthehand.com/content/32feet.aspx> I've played around with this back when it was v1.5 and it worked well.
Bluetooth APIs in Windows/.Net?
[ "", "c#", ".net", "windows", "windows-xp", "bluetooth", "" ]
What's the best way to create a non-NULL constraint in MySQL such that fieldA and fieldB can't both be NULL. I don't care if either one is NULL by itself, just as long as the other field has a non-NULL value. And if they both have non-NULL values, then it's even better.
MySQL 5.5 introduced [SIGNAL](http://dev.mysql.com/doc/refman/5.5/en/signal.html), so we don't need the extra column in Bill Karwin's answer any more. Bill pointed out you also need a trigger for update so I've included that too. ``` CREATE TABLE foo ( FieldA INT, FieldB INT ); DELIMITER // CREATE TRIGGER InsertF...
This isn't an answer directly to your question, but some additional information. When dealing with multiple columns and checking if all are null or one is not null, I typically use `COALESCE()` - it's brief, readable and easily maintainable if the list grows: ``` COALESCE(a, b, c, d) IS NULL -- True if all are NULL ...
Either OR non-null constraints in MySQL
[ "", "sql", "mysql", "null", "" ]
I have two web applications running in the same Tomcat Instance. In one of these applications the user will have the ability to upload files such as images and pdf files. I would like the uploaded files to be available to the second application. Is there a best practice for such a scenario? Or just a pointer to a tech...
Cheap, bad answer - have both applications softlink to a shared directory. This has the benefit of being stupid-simple to do but has evil transactional-type issues. Since you say that only one application is changing the data, and the other is read-only you might be able to get away with it, as long as the second app c...
I'd say it depends on how robust you need the file storage to be, and how transactional. The simplest way would be a shared directory that's on the classpath of both apps. A database would be a more robust, but more complex, solution.
Transferring files between web applications running in the same Tomcat Instance
[ "", "java", "tomcat", "" ]
I have an Open Source app and I have it working on Windows, Linux and Macintosh ( it's in C++ and built with gcc ). I've only tested it on a few different flavors of Linux so I don't know if it compiles and runs on all different Linux versions. Is there a place where I can upload my code and have it tested across a bun...
There are a few options but there don't appear to be many (any?) free services like this, which isn't surprising considering the amount of effort and resources it requires. Sourceforge used to operate a compile farm like what you describe but it shut down a year or so ago. You might look into some of the following. If ...
Take a look at the [OpenSuSE build service](http://en.opensuse.org/Build_Service), it includes a fairly wide variety of Linux distros (not just SuSE/OpenSuSE).
Is there build farm for checking open source apps against different OS'es?
[ "", "c++", "build", "operating-system", "" ]
My database contains three tables called `Object_Table`, `Data_Table` and `Link_Table`. The link table just contains two columns, the identity of an object record and an identity of a data record. I want to copy the data from `DATA_TABLE` where it is linked to one given object identity and insert corresponding records...
The following sets up the situation I had, using table variables. ``` DECLARE @Object_Table TABLE ( Id INT NOT NULL PRIMARY KEY ) DECLARE @Link_Table TABLE ( ObjectId INT NOT NULL, DataId INT NOT NULL ) DECLARE @Data_Table TABLE ( Id INT NOT NULL Identity(1,1), Data VARCHAR(50) NOT NULL ) -- cre...
In one *statement*: No. In one *transaction*: Yes ``` BEGIN TRANSACTION DECLARE @DataID int; INSERT INTO DataTable (Column1 ...) VALUES (....); SELECT @DataID = scope_identity(); INSERT INTO LinkTable VALUES (@ObjectID, @DataID); COMMIT ``` The good news is that the above code is also guaranteed to be *a...
SQL Server: Is it possible to insert into two tables at the same time?
[ "", "sql", "sql-server", "insert", "temp-tables", "" ]
I try to add an addons system to my Windows.Net application using Reflection; but it fails when there is addon with dependencie. Addon class have to implement an interface 'IAddon' and to have an empty constructor. Main program load the addon using Reflection: ``` Assembly assembly = Assembly.LoadFile(@"C:\Temp...
If *MyTools.dll* is located in the same directory as *Addon.dll*, all you need to do is call `Assembly.LoadFrom` instead of `Assembly.LoadFile` to make your code work. Otherwise, handling the `AppDomain.AssemblyResolve` event is the way to go.
Assembly.LoadFrom works well until I try to use a webService in my addon, I had had a "*Unable to cast object of type 'X' to type 'X'*" exception. It's ugly, but i will use Assembly.LoadFile with the AppDomain.AssemblyResolve. Thanks guys.
Reflection.Net: how to load dependencies?
[ "", "c#", "reflection", "dependencies", "add-on", "" ]
I work on a Webproject using [jQuery](http://jquery.com/) and CakePHP. I use [jeditable](http://www.appelsiini.net/projects/jeditable) as an inplace edit plugin. For textareas I extend it using the [autogrow plugin](http://www.appelsiini.net/2008/4/autogrow-textarea-for-jeditable). Well, I have two problems with this:...
I didn't see any problems using Autogrow with jeditable in any browsers but here is an implementation of Growfield with jeditable. It works much in the same way that the Autogrow plugin for jeditable does. You create a special input type for jeditable and just apply .growfield() to it. The necessary javascript is below...
**Mika Tuupola**: If you are Interested in my modified jeditable (added two callback events), you can [get it here](http://knightkiller.ch/jquery.jeditable.js). It would be great if you would provide these events in your official version of jeditable! Here is my (simplified) integration code. I use the events for more...
Problems using jeditable and autogrow
[ "", "javascript", "jquery", "ajax", "jeditable", "autogrow", "" ]
I have a two dimensional array that I need to load data into. I know the width of the data (22 values) but I do not know the height (estimated around 4000 records, but variable). I have it declared as follows: ``` float[,] _calibrationSet; .... int calibrationRow = 0; While (recordsToRead) { for (int i = 0; i <...
You can't use an array. Or rather, you would need to pick a size, and if you ended up needing more then you would have to allocate a new, larger, array, copy the data from the old one into the new one, and continue on as before (until you exceed the size of the new one...) Generally, you would go with one of the colle...
You can't create an array in .NET (as opposed to declaring a reference to it, which is what you did in your example) without specifying its dimensions, either explicitly, or implicitly by specifying a set of literal values when you initialize it. (e.g. int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };) You n...
How do you initialize a 2 dimensional array when you do not know the size
[ "", "c#", "array-initialize", "" ]
Is it possible at runtime to programmatically check the name of the Thread that is holding the lock of a given object?
You can only tell whether the current thread holds a normal lock ([`Thread.holdsLock(Object)`](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#holdsLock%28java.lang.Object%29)). You can't get a reference to the thread that has the lock without native code. However, if you're doing anything complicated w...
You can get at the locks held by threads with reflection. This only works with java 1.6. ``` ThreadMXBean bean = ManagementFactory.getThreadMXBean(); ThreadInfo[] ti = bean.getThreadInfo(bean.getAllThreadIds(), true, true); ``` On each of these ThreadInfo objects there are LockInfo objects which you can use the ident...
Programmatically determine which Java thread holds a lock
[ "", "java", "multithreading", "concurrency", "" ]
When I started writing database queries I didn't know the JOIN keyword yet and naturally I just extended what I already knew and wrote queries like this: ``` SELECT a.someRow, b.someRow FROM tableA AS a, tableB AS b WHERE a.ID=b.ID AND b.ID= $someVar ``` Now that I know that this is the same as an INNER JOIN I find...
Filtering joins solely using `WHERE` can be extremely inefficient in some common scenarios. For example: ``` SELECT * FROM people p, companies c WHERE p.companyID = c.id AND p.firstName = 'Daniel' ``` Most databases will execute this query quite literally, first taking the [Cartesian product](http://en.wikipedia...
The more verbose `INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN` are from the ANSI SQL/92 syntax for joining. For me, this verbosity makes the join more clear to the developer/DBA of what the intent is with the join.
Is there something wrong with joins that don't use the JOIN keyword in SQL or MySQL?
[ "", "sql", "mysql", "join", "" ]
I have a web application using JPA and JTA with Spring. I would like to support both JBoss and Tomcat. When running on JBoss, I'd like to use JBoss' own TransactionManager, and when running on Tomcat, I'd like to use JOTM. I have both scenarios working, but I now find that I seem to need two separate Spring configurat...
I think you have missed the point of JNDI. JNDI was pretty much written to solve the problem you have! I think you can take it up a level, so instead of using the "userTransaction" or "transactionManager from JNDI" depending on your situation. Why not add the "JtaTransactionManager" to JNDI. That way you push the conf...
You can use PropertyConfigurerPlaceholder to inject bean references as well as simple values. For example if you call your beans 'jotm' and 'jboss' then you could inject your TM like: ``` <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="systemPropertiesModeName...
Spring JTA TransactionManager config: Supporting both Tomcat and JBoss
[ "", "java", "spring", "jboss", "jta", "jotm", "" ]
I've found a few samples online but I'd like to get feedback from people who use PHP daily as to potential security or performance considerations and their solutions. Note that I am only interested in uploading a single file at a time. Ideally no browser plugin would be required (Flash/Java), although it would be int...
# File Upload Tutorial ## HTML ``` <form enctype="multipart/form-data" action="action.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="1000000" /> <input name="userfile" type="file" /> <input type="submit" value="Go" /> </form> ``` * `action.php` is the name of a PHP file that will process ...
Have a read of [this introduction](http://docs.php.net/manual/en/features.file-upload.php) which should tell you everything you need to know. The user comments are fairly useful as well.
What's the best way to create a single-file upload form using PHP?
[ "", "php", "upload", "file-upload", "" ]
There is a long running habit here where I work that the connection string lives in the web.config, a Sql Connection object is instantiated in a using block with that connection string and passed to the DataObjects constructor (via a CreateInstance Method as the constructor is private). Something like this: ``` using(...
I like to code the classes in my data access layer so that they have one constructor that takes an IDbConnection as a parameter, and another that takes a (connection) string. That way the calling code can either construct its own SqlConnection and pass it in (handy for integration tests), mock an IDbConnection and pas...
Hm, I think I agree that the datalayer should be responsible for managing such connection strings so the higher layers don't need to worry about this. However, I do not think that the SQLConnection should worry where the connection string comes from. I think, I would have a datalayer which provides certain DataInputs,...
In a layered design with a separate DataAccess layer in .NET where should connection string be managed?
[ "", "c#", "asp.net", "database", "" ]
The NUnit documentation doesn't tell me when to use a method with a `TestFixtureSetup` and when to do the setup in the constructor. ``` public class MyTest { private MyClass myClass; public MyTest() { myClass = new MyClass(); } [TestFixtureSetUp] public void Init() { myCla...
I think this has been one of the issues that hasn't been addressed by the nUnit team. However, there is the excellent [xUnit project](http://www.codeplex.com/xunit) that saw this exact issue and decided that constructors were a good thing to use on [test fixture initialization](http://www.codeplex.com/xunit/Wiki/View.a...
Why would you need to use a constructor in your test classes? I use `[SetUp]` and `[TearDown]` marked methods for code to be executed before and after each test, and similarly `[TestFixtureSetUp]` and `[TestFixtureTearDown]` marked methods for code to be executed only once before and after all test in the fixture have...
When do I use the TestFixtureSetUp attribute instead of a default constructor?
[ "", "c#", "unit-testing", "nunit", "" ]
Any suggestions on how to write repeatable unit tests for code that may be susceptible to deadlocks and race conditions? Right now I'm leaning towards skipping unit tests and focusing on stress tests. The problem with that is you can run a stress test 5 times and see five different results. EDIT: I know its probably ...
Take a look at [TypeMock](http://www.typemock.com/typemock-racer-product/) Racer (it's in Beta) edit: actually Alpha <http://www.typemock.com/Typemock_software_development_tools.html>
It is usually possible to force *foreseen* race-conditions and deadlocks by using things like ManualResetEvent to get each thread into the expected state before releasing it - i.e. get thread A to have the lock and wait for a signal... get thread B to request the lock, etc... However - you might typically write such a...
Unit Testing, Deadlocks, and Race Conditions
[ "", "c#", ".net", "vb.net", "parallel-processing", "" ]
I'm trying to test if a given default constraint exists. I don't want to use the sysobjects table, but the more standard INFORMATION\_SCHEMA. I've used this to check for tables and primary key constraints before, but I don't see default constraints anywhere. Are they not there? (I'm using MS SQL Server 2000). EDIT: ...
As I understand it, default value constraints aren't part of the ISO standard, so they don't appear in INFORMATION\_SCHEMA. INFORMATION\_SCHEMA seems like the best choice for this kind of task because it is cross-platform, but if the information isn't available one should use the object catalog views (sys.\*) instead o...
You can use the following to narrow the results even more by specifying the Table Name and Column Name that the Default Constraint correlates to: ``` select * from sysobjects o inner join syscolumns c on o.id = c.cdefault inner join sysobjects t on c.id = t.id where o.xtype = 'D' and c.name = 'Column_Name' and t.name...
How do I find a default constraint using INFORMATION_SCHEMA?
[ "", "sql", "sql-server", "t-sql", "information-schema", "" ]
I would like to know if there is an easy way to detect if the text on the clipboard is in ISO 8859 or UTF-8 ? Here is my current code: ``` COleDataObject obj; if (obj.AttachClipboard()) { if (obj.IsDataAvailable(CF_TEXT)) { HGLOBAL hmem = obj.GetGlobalData(CF_TEXT); ...
Check out the definition of CF\_LOCALE at [this Microsoft page](http://msdn.microsoft.com/en-us/library/ms649013(VS.85).aspx). It tells you the locale of the text in the clipboard. Better yet, if you use CF\_UNICODETEXT instead, Windows will convert to UTF-16 for you.
UTF-8 has a defined structure for non-ASCII bytes. You can scan for bytes >= 128, and if any are detected, check if they form a valid UTF-8 string. The valid UTF-8 byte formats can be found on [Wikipedia](http://en.wikipedia.org/wiki/UTF-8): ``` Unicode Byte1 Byte2 Byte3 Byte...
How to tell if text on the windows clipboard is ISO 8859 or UTF-8 in C++?
[ "", "c++", "windows", "utf-8", "clipboard", "" ]
What is the best way to get a list of all files in a directory, sorted by date [created | modified], using python, on a windows machine?
*Update*: to sort `dirpath`'s entries by modification date in Python 3: ``` import os from pathlib import Path paths = sorted(Path(dirpath).iterdir(), key=os.path.getmtime) ``` (put [@Pygirl's answer](https://stackoverflow.com/a/58772122/4279) here for greater visibility) If you already have a list of filenames `fi...
I've done this in the past for a Python script to determine the last updated files in a directory: ``` import glob import os search_dir = "/mydir/" # remove anything from the list that is not a file (directories, symlinks) # thanks to J.F. Sebastion for pointing out that the requirement was a list # of files (presum...
How do you get a directory listing sorted by creation date in python?
[ "", "python", "windows", "directory", "" ]
In C++, on Linux, how can I write a function to return a temporary filename that I can then open for writing? The filename should be as unique as possible, so that another process using the same function won't get the same name.
Use one of the standard library "mktemp" functions: mktemp/mkstemp/mkstemps/mkdtemp. Edit: plain mktemp can be insecure - mkstemp is preferred.
tmpnam(), or anything that gives you a name is going to be vulnerable to race conditions. Use something designed for this purpose that returns a handle, such as tmpfile(): ``` #include <stdio.h> FILE *tmpfile(void); ```
How can I create a temporary file for writing in C++ on a Linux platform?
[ "", "c++", "linux", "temporary-files", "" ]
Two main ways to deploy a J2EE/Java Web app (in a very simplistic sense): ## Deploy assembled artifacts to production box Here, we create the `.war` (or whatever) elsewhere, configure it for production (possibly creating numerous artifacts for numerous boxes) and place the resulting artifacts on the production server...
I'm firmly against building on the production box, because it means you're using a different build than you tested with. It also means every deployment machine has a different JAR/WAR file. If nothing else, do a unified build just so that when bug tracking you won't have to worry about inconsistencies between servers. ...
Most of the places I've worked have used the first method with environment specific configuration information deployed separately (and updated much more rarely) outside of the war/ear.
Java Web Deployment: build code, or deploy .war?
[ "", "java", "deployment", "jakarta-ee", "" ]
I've seen some Python programmers use the following style fairly consistently (we'll call it style 1): ``` import some_module # Use some_module.some_identifier in various places. ``` For support of this style, you can cite the ["explicit is better than implicit"](http://www.python.org/dev/peps/pep-0020/) maxim. I've ...
There are uses for both cases, so I don't think this is an either-or issue. I'd consider using from module `import x,y,z` when: * There are a fairly small number of things to import * The purpose of the functions imported is obvious when divorced from the module name. If the names are fairly generic, they may clash wi...
With the existence of the following syntax: ``` import some_other_module as some_module ``` the maintainability argument of style 2 is no longer relevant. I tend to use style 1. Normally, I find that I explicitly reference the imported package name only a few times in a typical Python program. Everything else is met...
'from X import a' versus 'import X; X.a'
[ "", "python", "python-import", "maintainability", "duck-typing", "" ]
I would like to use databinding when displaying data in a TextBox. I'm basically doing like: ``` public void ShowRandomObject(IRandomObject randomObject) { Binding binding = new Binding {Source = randomObject, Path = new PropertyPath("Name")}; txtName.SetBinding(TextBox.TextProperty, binding); } `...
When available ``` BindingOperations.ClearBinding(txtName, TextBox.TextProperty) ``` For older SilverLight versions, but not reliable as stated in comments: ``` txtName.SetBinding(TextBox.TextProperty, null); ``` C# 6.0 features enabled ``` this.btnFinish.ClearBinding(ButtonBase.CommandProperty); ```
Alternately: ``` BindingOperations.ClearBinding(txtName, TextBox.TextProperty) ```
Remove binding in WPF using code
[ "", "c#", "wpf", "" ]
This question was inspired by a similar question: [How does delete[] “know” the size of the operand array?](https://stackoverflow.com/questions/197675/how-does-delete-know-the-size-of-the-operand-array) My question is a little different: **Is there any way to determine the size of a C++ array programmatically? And if ...
`delete []` does know the size that was allocated. However, that knowledge resides in the runtime or in the operating system's memory manager, meaning that it is not available to the compiler during compilation. And `sizeof()` is not a real function, it is actually evaluated to a constant by the compiler, which is some...
Well there is actually a way to determine the size, but it's not "safe" and will be diferent from compiler to compiler.... **so it shouldn't be used at all**. When you do: int\* arr = new int[256]; The 256 is irrelevant you will be given 256\*sizeof(int) assuming for this case 1024, this value will be stored probably...
Can you obtain the size of an array allocated with new T[]?
[ "", "c++", "arrays", "pointers", "memory-management", "new-operator", "" ]
``` Object o = new Long[0] System.out.println( o.getClass().isArray() ) System.out.println( o.getClass().getName() ) Class ofArray = ??? ``` Running the first 3 lines emits; ``` true [Ljava.lang.Long; ``` How do I get ??? to be type long? I could parse the string and do a Class.forname(), but thats grotty. What's th...
Just write ``` Class ofArray = o.getClass().getComponentType(); ``` From [the JavaDoc](http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getComponentType--): > `public Class<?> getComponentType()` > > Returns the `Class` representing the component type of an array. If this class does not represent an arr...
[http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getComponentType()](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html#getComponentType()): > ``` > public Class<?> getComponentType() > ``` > > Returns the `Class` representing the component type of an array. If this class does not represent...
In Java, how do I dynamically determine the type of an array?
[ "", "java", "" ]
In the following example should I expect that `values.size()` will be called every time around the loop? In which case it might make sense to introduce a temporary `vectorSize` variable. Or should a modern compiler be able to optimize the calls away by recognising that the vector size cannot change. ``` double sumVect...
Here's one way to do it that makes it explicit - size() is called only once. ``` for (size_t ii = 0, count = values.size(); ii < count; ++ii) ``` **Edit:** I've been asked to actually answer the question, so here's my best shot. A compiler generally won't optimize a function call, because it doesn't know if it wil...
It all depends on what the vector's size implementation is, how aggressive the compiler is and if it listen/uses to inline directives. I would be more defensive and introduce the temporary as you don't have any guarantees about how efficient your compiler will be. Of course, if this routine is called once or twice an...
Is using size() for the 2nd expression in a for construct always bad?
[ "", "c++", "" ]
One of the few annoying things about the Eclipse Java plug-in is the absence of a keyboard shortcut to build the project associated with the current resource. Anyone know how to go about it?
In the Preferences dialog box, under the General section is a dialog box called "Keys". This lets you attach key bindings to many events, including Build Project.
You can assign a keyboard binding to *Build Project* doing the following 1. Open up the Keys preferences, Window> Preferences >General>Keys 2. Filter by type Build Project 3. Highlight the binding field. You can then choose the binding you want i.e. `Ctrl`+`ALt`+`B`, `P`,
How do I add a shortcut key to Eclipse 3.2 Java plug-in to build the current project?
[ "", "java", "eclipse", "eclipse-3.2", "" ]
If I have a datetime field, how do I get just records created later than a certain time, ignoring the date altogether? It's a logging table, it tells when people are connecting and doing something in our application. I want to find out how often people are on later than 5pm. (Sorry - it is SQL Server. But this could ...
For SQL Server: ``` select * from myTable where datepart(hh, myDateField) > 17 ``` See <http://msdn.microsoft.com/en-us/library/aa258265(SQL.80).aspx>.
What database system are you using? Date/time functions vary widely. For Oracle, you could say ``` SELECT * FROM TABLE WHERE TO_CHAR(THE_DATE, 'HH24:MI:SS') BETWEEN '17:00:00' AND '23:59:59'; ``` Also, you probably need to roll-over into the next day and also select times between midnight and, say, 6am.
How to get records after a certain time using SQL datetime field
[ "", "sql", "sql-server", "datetime", "" ]
I'm subclassing a native window (the edit control of a combobox...) oldWndProc = SetWindowLong(HandleOfCbEditControl, GWL\_WNDPROC, newWndProc); In my subclassing wndproc, I'll have code like this, right, but I can't figure out the syntax for calling the oldWndProc. ``` int MyWndProc(int Msg, int wParam, int lPa...
You'll call [CallWindowProc](http://msdn.microsoft.com/en-us/library/aa452919.aspx) by P/Invoke. Just define the parameters as int variables (as it looks like that's how you defined them in the SetWindowLong call), so something like this: [DllImport("CallWindowProc"...] public static extern int CallWindowProc(int prev...
You should use CallWindowProc to call that oldWndProc pointer. ``` [DllImport("user32")] private static extern int CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, int Msg, int wParam, int lParam); ```
In C#, I have a IntPtr to a WIN32 WndProc. What is the syntax for calling it?
[ "", "c#", ".net", "winapi", "" ]
I just figured out that I can actually **store objects in the $\_SESSION** and I find it quite cool because when I jump to another page I still have my object. Now before I start using this approach I would like to find out if it is really such a good idea or if there are **potential pitfalls** involved. I know that i...
I know this topic is old, but this issue keeps coming up and has not been addressed to my satisfaction: Whether you save objects in $\_SESSION, or reconstruct them whole cloth based on data stashed in hidden form fields, or re-query them from the DB each time, you are using state. HTTP is stateless (more or less; but ...
it's OK as long as by the time the session\_start() call is made, the class declaration/definition has already been encountered by PHP or can be found by an already-installed autoloader. otherwise it would not be able to deserialize the object from the session store.
PHP: Storing 'objects' inside the $_SESSION
[ "", "php", "session", "object", "" ]
My current project uses NUnit for unit tests and to drive UATs written with Selenium. Developers normally run tests using ReSharper's test runner in VS.Net 2003 and our build box kicks them off via NAnt. We would like to run the UAT tests in parallel so that we can take advantage of Selenium Grid/RCs so that they will...
There hasn't been a lot of work on this subject. I didn't find anything really relevent. However, your point is well taken. Most machines nowadays have more cores and less powerful cores compared to powerful one core cpu. So I did find something on a Microsoft blog. The technology is called PUnit and is made especial...
I struggled with both these problems myself. In the end I developed a custom Nunit test runner that is capable of running multiple tests in parrallel. This combined with the Taumuon.Rakija extension for nunit allowed the tests to be dynmaically created depending on which browser you want the test to run on. I'm now in...
How can I run NUnit(Selenium Grid) tests in parallel?
[ "", "c#", "selenium", "testing", "nunit", "selenium-grid", "" ]
I've done some Python but have just now starting to use Ruby I could use a good explanation of the difference between "self" in these two languages. **Obvious on first glance:** Self is not a keyword in Python, but there is a "self-like" value no matter what you call it. Python methods receive self as an explici...
Python is designed to support more than just object-oriented programming. Preserving the same interface between methods and functions lets the two styles interoperate more cleanly. Ruby was built from the ground up to be object-oriented. Even the literals are objects (evaluate 1.class and you get Fixnum). The language...
Despite webmat's claim, Guido [wrote](http://markmail.org/message/n6fs5pec5233mbfg) that explicit self is "not an implementation hack -- it is a semantic device". > The reason for explicit self in method > definition signatures is semantic > consistency. If you write > > class C: def foo(self, x, y): ... > > This real...
What is the difference between Ruby and Python versions of"self"?
[ "", "python", "ruby", "language-features", "" ]
I've used lex and yacc (more usually bison) in the past for various projects, usually translators (such as a subset of EDIF streamed into an EDA app). Additionally, I've had to support code based on lex/yacc grammars dating back decades. So I know my way around the tools, though I'm no expert. I've seen positive comme...
### Update/warning: This answer may be out of date! --- One major difference is that ANTLR generates an LL(\*) parser, whereas YACC and Bison both generate parsers that are LALR. This is an important distinction for a number of applications, the most obvious being operators: ``` expr ::= expr '+' expr | expr ...
The most significant difference between YACC/Bison and ANTLR is the type of grammars these tools can process. YACC/Bison handle LALR grammars, ANTLR handles LL grammars. Often, people who have worked with LALR grammars for a long time, will find working with LL grammars more difficult and vice versa. That does not mea...
Advantages of Antlr (versus say, lex/yacc/bison)
[ "", "c++", "antlr", "yacc", "bison", "" ]
While researching this issue, I found multiple mentions of the following scenario online, invariably as unanswered questions on programming forums. I hope that posting this here will at least serve to document my findings. First, the symptom: While running pretty standard code that uses waveOutWrite() to output PCM au...
You're not alone with this issue: <http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100589>
> Now, the reason that GlobalHandle() > bombs is not due to a heap corruption, > as I suspected at first - it's because > waveOutWrite() returned without > setting the first pointer in the > internal structure to a valid pointer. > I suspect that it frees the memory > pointed to by that pointer before > returning, but ...
Why would waveOutWrite() cause an exception in the debug heap?
[ "", "c++", "windows", "audio", "waveoutwrite", "" ]
I have a textarea with many lines of input, and a JavaScript event fires that necessitates I scroll the textarea to line 345. `scrollTop` sort of does what I want, except as far as I can tell it's pixel level, and I want something that operates on a line level. What also complicates things is that, afaik once again, i...
You can stop wrapping with the wrap attribute. It is not part of HTML 4, but most browsers support it. You can compute the height of a line by dividing the height of the area by its number of rows. ``` <script type="text/javascript" language="JavaScript"> function Jump(line) { var ta = document.getElementById("Tex...
If you use .scrollHeight instead of .clientHeight, it will work properly for textareas that are shown with a limited height and a scrollbar: ``` <script type="text/javascript" language="JavaScript"> function Jump(line) { var ta = document.getElementById("TextArea"); var lineHeight = ta.scrollHeight / ta.rows; va...
Cross browser "jump to"/"scroll" textarea
[ "", "javascript", "html", "css", "" ]
I'm trying to get a PHP site working in IIS on Windows Server with MySQL. I'm getting this error… Fatal error: Call to undefined function mysql\_connect() in C:\inetpub...\adodb\drivers\adodb-mysql.inc.php on line 363 --- Update… This link outlines the steps I followed to install PHP on my server: [How do I get ...
I found the solution: [How do I install MySQL modules within PHP?](https://stackoverflow.com/questions/158279/how-do-i-install-mysql-modules-within-php#160746)
Check out phpinfo to see if the mysql functions are compiled with your PHP ``` <?php phpinfo(); ?> ``` Since in some versions of php, its not default with the install. **Edit for the Update:** You should have a full MySQL category in your phpinfo(); See this for example: <https://secure18.easycgi.com/phpinfo.p...
How do I get PHP to work with ADOdb and MySQL?
[ "", "php", "mysql", "windows", "iis", "adodb", "" ]
I have a set of configuration items I need to persist to a "human readable" file. These items are in a hierarchy: ``` Device 1 Name Channel 1 Name Size ... Channel N Name ... Device M Name Channel 1 ``` Each of these item could be stored in a Dictionary with a string Key and a value...
See the [FileHelpers](http://filehelpers.sourceforge.net/) library. It's got tons of stuff for reading from and writing to a lot of different formats - and all you have to do is mark up your objects with attributes and call Save(). Sort of like ORM for flat files.
[YAML for .NET](http://www.codeplex.com/yaml)
Persisting configuration items in .net
[ "", "c#", ".net", "configuration", "" ]
I'd like to find the base url of my application, so I can automatically reference other files in my application tree... So given a file config.php in the base of my application, if a file in a subdirectory includes it, knows what to prefix a url with. ``` application/config.php application/admin/something.php applica...
I use the following in a homebrew framework... Put this in a file in the root folder of your application and simply include it. ``` define('ABSPATH', str_replace('\\', '/', dirname(__FILE__)) . '/'); $tempPath1 = explode('/', str_replace('\\', '/', dirname($_SERVER['SCRIPT_FILENAME']))); $tempPath2 = explode('/', sub...
You can find the base url with the folowing code: ``` define('SITE_BASE_PATH','http://'.preg_replace('/[^a-zA-Z0-9]/i','',$_SERVER['HTTP_HOST']).'/'.str_replace('\\','/',substr(dirname(__FILE__),strlen($_SERVER['DOCUMENT_ROOT']))).'/'); ``` Short and best.
How can I find an application's base url?
[ "", "php", "web-applications", "" ]