Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have been working on a Java project for a class for a while now. It is an implementation of a linked list (here called `AddressList`, containing simple nodes called `ListNode`). The catch is that everything would have to be done with recursive algorithms. I was able to do everything fine sans one method: `public Addr... | There's code in one reply that spells it out, but you might find it easier to start from the bottom up, by asking and answering tiny questions (this is the approach in The Little Lisper):
1. What is the reverse of null (the empty list)? null.
2. What is the reverse of a one element list? the element.
3. What is the re... | I was asked this question at an interview and was annoyed that I fumbled with it since I was a little nervous.
This should reverse a singly linked list, called with reverse(head,NULL);
so if this were your list:
```
1->2->3->4->5->null
it would become:
5->4->3->2->1->null
```
```
//Takes as parameters a node in ... | Reversing a linked list in Java, recursively | [
"",
"java",
"data-structures",
"recursion",
"linked-list",
""
] |
I'm generating a coupon based on dynamic input and a cropped image, and I'm displaying the coupon using ntml and css right now, the problem is, printing this has become an issue because of how backgrounds disappear when printing and other problems, so I think the best solution would be to be able to generate an image b... | What you can do is create an aspx page that changes the response type to be in the format you want and then put the image into the stream. I created a barcode generator that does a similar thing. Excluding all the formalities of generating the image, you'll Page\_Load will look something like this:
```
Bitmap FinalBit... | You can render html to a bitmap using the WebBrowser control in either a winforms or console application.
An example of this can be found here: <http://www.wincustomize.com/articles.aspx?aid=136426&c=1>
The above example can be modified to run in ASP.Net by creating a new STAThread and performing an Application.Run o... | Render HTML as an Image | [
"",
"c#",
"asp.net",
"image",
""
] |
Javascript client side application.
Trying to eliminate memory leaks leads to ugly (to say the least) code.
I am trying to clean up in window.unload instead on messing up all the code trying to avoid them.
We use mostly `element.onevent=function(){..};` pattern, that results in closure (mostly wanted) and memory lea... | The best solution is for you to roll out your own method that manages event handling. Therefore, when attaching an event handler, your method can keep track of all the added events. On unload, it can unregister all the handlers.
I know you said you don't use libraries, but you can use their code as inspiration. Ext-js... | A solution for avoiding memory leaks with events is delegation. In a nutshell, you attach your event handler to a parent object instead of the children. Because of propagation, a click on a child will also register as a click on the parent, triggering your handler. By checking the target attribute of the event, you can... | Javascript memory leak cleanup in window.unload | [
"",
"javascript",
"ajax",
"web-applications",
"memory-leaks",
""
] |
I am reorganizing my source files into a single solution with a single project, due to various reasons:
* a paranoic configured antivirus software;
* [Advices on partitioning code through .NET assemblies](http://codebetter.com/blogs/patricksmacchia/archive/2008/12/08/advices-on-partitioning-code-through-net-assemblies... | Yes - use folders.
If you create a folder within a project, new classes within that folder will automatically use the folder name as the basis for the namespace.
For instance, if you have a project with a default namespace of "Company.Project" and a folder "Foo" containing "Bar.cs" you'll end up with:
```
using Syst... | So the solution is right here. It's Folders. But it's sometimes tricky. First of all it's kind of a good idea to have one file per class. If you will pack several classes into one file - you'll have problems with finding them with time.
Second thing about folders - if you will click on a folder and choose for example ... | C# single project organization | [
"",
"c#",
"visual-studio-2008",
"projects-and-solutions",
"project-organization",
""
] |
Does anyone know a good tool that can be run on a page (for asp.net, for example) to help to minimize the footprint size of the page?
The page will have typical items: HTML, Javascript, etc.
I've heard of Javascript crunchers in the past, that will make the size of the code as compact as possible (and obfuscate it, I... | You could configure your web server to compress the page on the fly (and possibly cache the compressed version) for any client that indicates it can take a gzip or zip (or other) encoding, which is pretty much all of them. | Well, its not a automatic cleaner-upper, but I like [YSlow](http://developer.yahoo.com/yslow/) for optimizing pages. And the [YUI Compressor](http://developer.yahoo.com/yui/compressor/) can minify your javascript.
If you're really interested in javascript, the keyword is "minify".
Also, look at this question just pos... | Good tool to minimize HTML footprint? | [
"",
"asp.net",
"javascript",
"html",
"optimization",
"footprint",
""
] |
How do you open a path in explorer by code in c++. I googled and couldn't find any thing but systems commands to do this, however, i dont want it to block or show the console window. | You probably are looking for the [`ShellExecute()`](http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx) function in `shellapi.h`. It is called with an "action verb", a path, and optional parameters. In your case this will want either "open" or "explore" as follows:
```
ShellExecuteA(NULL, "open", "C:\\", NUL... | This does not show the command window, just opens the directory.
```
system("explorer C:\\");
``` | Open in Explorer | [
"",
"c++",
"windows",
"explorer",
""
] |
Please don't say EHCache or OSCache, etc. Assume for purposes of this question that I want to implement my own using just the SDK (learning by doing). Given that the cache will be used in a multithreaded environment, which datastructures would you use? I've already implemented one using [LinkedHashMap](http://docs.orac... | If I were doing this again from scratch today, I'd use Guava's [`CacheBuilder`](http://google.github.io/guava/releases/snapshot/api/docs/com/google/common/cache/CacheBuilder.html). | I like lots of these suggestions, but for now I think I'll stick with `LinkedHashMap` + `Collections.synchronizedMap`. If I do revisit this in the future, I'll probably work on extending `ConcurrentHashMap` in the same way `LinkedHashMap` extends `HashMap`.
UPDATE:
By request, here's the gist of my current implementa... | How would you implement an LRU cache in Java? | [
"",
"java",
"caching",
"data-structures",
"lru",
""
] |
by default is a class:
1. private ?
2. internal ?
3. sealed ? | internal
see:
<http://msdn.microsoft.com/en-us/library/ms173121.aspx> | The default for non-nested types is internal.
The default for nested types is private.
In both cases the default (for classes) is unsealed.
The general rule for all members is that if you don't specify an access modifier, it's as private as it can be. The single exception for this is properties which can make one part... | Default Class Accessibility in C# | [
"",
"c#",
"oop",
""
] |
I'm using a hosting service which allows me to backup my SQL 2008 database and download the BAK file via a web interface only--and I have access to the database via Management Studio. I can execute the backup command from Management Studio,but I don't have rights to the path where the backups are located. Is there any ... | If you have access via Management Studio, why don't you copy the hosted db on to your local machine (Tasks > Copy DB)?
Once it's been restored to the local system, you can do whatever you want. | Free [SqlBackupAndFTP](http://SqlBackupAndFTP.com) allows to do remote backups using scripting | How to automate SQL backup on a shared hosted server? | [
"",
"sql",
"sql-server",
"backup",
""
] |
How can I delete all the tables in a web page? The tables don't have any ids associated with them. | Very simple version:
```
var tables = document.getElementsByTagName("TABLE");
for (var i=tables.length-1; i>=0;i-=1)
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
``` | Danger! getElementsByTagName returns a ‘live’ NodeList. In Joel's code, removing element 0 moves the items in the list down so that when you remove element 1, you've missed one.
Possible alternatives: if you know you're always going to be removing every element, you can use a while-loop:
```
var tables= document.getE... | How to delete all tables in HTML with JavaScript? | [
"",
"javascript",
"html",
"html-table",
""
] |
How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):
```
while True:
# doing amazing pythonic embedded stuff
# ...
# periodically do a non-blocking check to s... | The standard approach is to use the [select](https://docs.python.org/2/library/select.html) module.
However, this doesn't work on Windows. For that, you can use the [msvcrt](https://docs.python.org/2/library/msvcrt.html#console-i-o) module's keyboard polling.
Often, this is done with multiple threads -- one per devic... | A solution using the curses module. Printing a numeric value corresponding to each key pressed:
```
import curses
def main(stdscr):
# do not wait for input when calling getch
stdscr.nodelay(1)
while True:
# get keyboard input, returns -1 if none available
c = stdscr.getch()
if c !=... | Polling the keyboard (detect a keypress) in python | [
"",
"python",
"console",
"keyboard",
"blocking",
"nonblocking",
""
] |
I've seen this in a few [places](https://stackoverflow.com/questions/221294/how-do-you-get-a-timestamp-in-javascript#221357)
```
function fn() {
return +new Date;
}
```
And I can see that it is returning a timestamp rather than a date object, but I can't find any documentation on what the plus sign is doing.
Can... | That's the `+` unary operator. It's equivalent to:
```
function(){ return Number(new Date); }
```
See <http://xkr.us/articles/javascript/unary-add> and [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus). | JavaScript is loosely typed, so it performs type coercion/conversion in certain circumstances:
<http://blog.jeremymartin.name/2008/03/understanding-loose-typing-in.html>
<http://www.jibbering.com/faq/faq_notes/type_convert.html>
Other examples:
```
>>> +new Date()
1224589625406
>>> +"3"
3
>>> +true
1
>>> 3 == "3"
... | What does the plus sign do in '+new Date' | [
"",
"javascript",
"syntax",
""
] |
Consider the "double-check idiom for lazy initialization of instance fields":
> ```
> // Item 71 in Effective Java copied from this interview with Bloch.
> private volatile FieldType field;
> FieldType getField() {
> FieldType result = field;
> if (result == null) { // First check (no locking)
> synchr... | Yes, this is thread safe.
The synchronized block is to prevent multiple threads from unnecessarily calling `computeFieldValue()`. Since `field` is volatile, the accesses in `reset` and `getField` are all well-ordered.
If the first check is non-null, `getField` is done; `result` is returned.
Otherwise, a lock is acqu... | I think this should be safe, but only because you're storing the field in a local variable. After this is done, there's no way for the local variable reference to magically change to null, even if another thread is resetting field's value half-way through. | Resetting a field lazy-loaded with the double-check idiom | [
"",
"java",
"thread-safety",
"locking",
"double-checked-locking",
""
] |
I am writing a .NET library that for various reasons cannot be registered in the GAC.
This dll (let's call it SDK.dll) depends on other DLLs in order to be loaded.
When writing a program that uses this SDK.dll, I noticed that my program failed loading the dll with a FileNotFoundException thrown. This happens because a... | You can handle this at runtime by subscribing to this event:
```
AppDomain.CurrentDomain.AssemblyResolve
```
It's fired when the runtime fails to resolve an assembly. In your event handler method, write your logic to find the assembly and load it using Assembly.LoadFrom(). It would look something like this:
```
publ... | to register your assembly in GAC it must have be signed with a [strong name](http://msdn.microsoft.com/en-us/library/szdke3d6.aspx).
If it depends on other assemblies, those should be in GAC to.
BeowulfOF | Assembly binding problems in .NET | [
"",
"c#",
".net",
"app-config",
"assembly.load",
""
] |
I have to choose a server pages technology for a few server components that are written in Java and hosted by Tomcat, like Lucene search service and a flex BlazeDS graphic component.
Not sure whether to use JSP or PHP.
On one hand JSP can integrate with the components Java API easily while PHP will require another wa... | JSP all the way in this situation. Firstly you can choose from myriad different frameworks - Struts and Tiles, Spring, Hibernate, etc, to aid in development.
Secondly the speed of development is not that much slower, if at all. In addition many of the frameworks enforce decent MVC coding practices.
I wouldn't recomme... | Given your situation, I would choose for JSP.
PHP-applications might be slightly faster to develop, but only if your not used to Java. Intergrating existing components wirtten in Java, are easily intergrated with JSP.
PHP is supported more by web-hosting companies, if you're looking for cheap low requirements hosting... | JSP or PHP for Java server components? | [
"",
"php",
"jsp",
""
] |
I'm used to passing around string like this in my C++ applications:
```
void foo(const std::string& input)
{
std::cout << input.size() << std::endl;
}
void bar()
{
foo("stackoverflow");
}
```
Now I have a case where I want the string to be NULL:
```
void baz()
{
foo("stackoverflow");
foo(NULL); // very bad ... | If you want the type to be null, then make it a pointer. Pass string pointers around instead of references, since this is precisely what pointers can do, and references cant. References always point to the same valid object. Pointers can be set to null, or be reseated to point to another object. Thus, if you need the t... | Function overloading to the rescue...
```
void foo( const std::string& input )
{
std::cout << input << std::endl;
// do more things ...
}
void foo( const char* input )
{
if ( input != NULL ) foo( std::string(input) );
}
```
This will accept both c-style char arrays and std::strings, and will incur extra... | C++ string that can be NULL | [
"",
"c++",
"string",
"null",
""
] |
I was wondering if there was a way to bind an ArrayList (or any kind of List, for that matter) to a PreparedStatement which will eventually be used to access an Oracle database. I found:
[PreparedStatement IN clause alternatives?](https://stackoverflow.com/questions/178479/alternatives-for-java-sql-preparedstatement-i... | You can't bind a List to a single parameter in a prepared statement.
Generate SQL with the a parameter marker for each element in the list, for example:
```
SELECT NAME FROM ITEM WHERE ID IN (?, ?, ?, ?)
```
Even though you'll generate a new statement for each query, I'd still recommend using a `PreparedStatement`. ... | You can't bind it directly. There is a way to pass an array as a parameter. I have no idea what you want to do with it on the database side so this may not help you.
Basically, you have to create a nested table type in the database; build a Java object based on that type, containing the data from your array; and pass ... | How do I bind an ArrayList to a PreparedStatement in Oracle? | [
"",
"java",
"oracle",
"jdbc",
"arraylist",
"prepared-statement",
""
] |
I've just started to use linq to sql and have run into a problem with inserting a record with an auto incrementing field.
I have created a new instance of a company object defined by linq. it has initialised an auto incrementing field 'companyID' to 0.
InsertOnSubmit() fails with the following invalidOperationExceptio... | Found the answer. It was to do with primary keys. In the linq designer the primary keys were setup as they should be. In the database the relevant fields were not set as primary keys. I fixed the keys in the databse and this resolved the problem. | What is the data-type? int? (int both TSQL and in C#?)
What auto-sync setting do you have? For a primary key, it should be "OnInsert" | Linq to sql error with identitiy increment field | [
"",
".net",
"sql",
"linq",
"auto-increment",
""
] |
If I have several classes with functions that I need but want to store separately for organisation, can I extend a class to have both?
i.e. `class a extends b extends c`
edit: I know how to extend classes one at a time, but I'm looking for a method to instantly extend a class using multiple base classes - AFAIK you c... | # EDIT: 2020 PHP 5.4+ and 7+
As of PHP 5.4.0 there are "[Traits](https://www.php.net/manual/en/language.oop5.traits.php)" - you can use more traits in one class, so the final deciding point would be whether you want **really an inheritance** or you **just** need **some "feature"(trait)**. Trait is, vaguely said, an al... | If you really want to fake multiple inheritance in PHP 5.3, you can use the magic function \_\_call().
This is ugly though it works from class A user's point of view :
```
class B {
public function method_from_b($s) {
echo $s;
}
}
class C {
public function method_from_c($s) {
echo $s;
... | Can I extend a class using more than 1 class in PHP? | [
"",
"php",
"class",
"oop",
"extends",
""
] |
Assuming the following hypothetical inheritance hierarchy:
```
public interface IA
{
int ID { get; set; }
}
public interface IB : IA
{
string Name { get; set; }
}
```
Using reflection and making the following call:
```
typeof(IB).GetProperties(BindingFlags.Public | BindingFlags.Instance)
```
will only yield th... | I've tweaked @Marc Gravel's example code into a useful extension method encapsulates both classes and interfaces. It also add's the interface properties first which I believe is the expected behaviour.
```
public static PropertyInfo[] GetPublicProperties(this Type type)
{
if (type.IsInterface)
{
var pr... | `Type.GetInterfaces` returns the flattened hierarchy, so there is no need for a recursive descent.
The entire method can be written much more concisely using LINQ:
```
public static IEnumerable<PropertyInfo> GetPublicProperties(this Type type)
{
if (!type.IsInterface)
return type.GetProperties();
ret... | GetProperties() to return all properties for an interface inheritance hierarchy | [
"",
"c#",
".net",
"reflection",
""
] |
I can see some options available:
1) Use PEAR's POP3 class --> tried it, having some weird weird issues like FF choking to death on their sample code!!!
2) Use PHPClasses ([here](http://www.phpclasses.org/)) --> seems to be the viable option at the time, still working on it
3) Write my own or use one of the snippets... | I use the PHPClasses version. Works fine for me - I've been working on an AJAX mail client (personal project, learning exercise really). I also found that the sample code they provided was quite good so you should be able to get something working with it. | The native PHP IMAP functions support POP3 mailboxes, and will probably be faster than anything written purely in PHP. There are generally some useful comments and examples in the PHP manual, for example on the [imap\_open](https://www.php.net/imap_open) page. | retrieve email using PHP and pop3 - what is your technique? | [
"",
"php",
"pop3",
""
] |
I have a site that I've developed that makes decent use of Javascript, and minimal use of AJAX for a few things. The site worked fine on the iPhone until I added the [function to create an HttpRequest handle](http://www.w3schools.com/Ajax/ajax_server.asp) at which point all Javascript on the iPhone now silently fails. ... | Of course the iPhone supports ajax, check out <http://developer.apple.com/webapps/> for a BUNCH of resources for developing iPhone webapps. I would recommend using a framework (such as [jQuery](http://www.jquery.com/), or [iUI](http://code.google.com/p/iui/) (for ui)) rather than rolling your own ajax functionality, it... | One useful resource for troubleshooting JavaScript errors like this on the device is the debug console. It should report any parsing errors and can also be used to log messages and exceptions. You can turn it on from Settings > Safari > Developer (scroll to the bottom). | AJAX on the iPhone? | [
"",
"javascript",
"iphone",
"ajax",
""
] |
What is the best way to find the total number of words in a text file in Java? I'm thinking Perl is the best on finding things such as this. If this is true then calling a Perl function from within Java would be the best? What would you have done in condition such as this? Any better ideas? | Congratulations you have stumbled upon one of the biggest linguistic problems! What is a word? It is said that a word is the only word that actually means what it is. There is an entire field of linguistics devoted to words/units of meaning - Morphology.
I assume that you question pertains to counting words in English... | ```
int count = 0;
Scanner sc = new Scanner(new File("my-text-file.txt"));
while (sc.hasNext()) {
++count;
sc.next();
}
``` | What's the best way to determine the total number of words of a file in Java? | [
"",
"java",
"perl",
"file",
"word-count",
""
] |
What does the "class" part of a template statement do?
Example:
```
template <class T>
class Something
{
public:
Something(const T &something);
}
```
And what else can go there? I usually only see "class". | The `class` keyword means the same thing as the `typename` keyword for the most part. They both indicates that T is a type.
The only difference between the keywords `class` and `typename` is that `class` can be used to provide class template template arguments to a template, whereas `typename` can't. Consider:
```
te... | To define a template parameter, you need either to tell the compiler the parameter is a type, or a value.
## In the begining...
If I remember correctly, the C++ committee was reluctant to add a new keyword to the C++ language, and so, they decided to authorize the following notations:
```
template<int I>
int getTwic... | Why is there "class" in "template <class x>"? | [
"",
"c++",
"templates",
"syntax",
""
] |
I just learned something interesting. The add method for the javascript select object in IE 6 takes only one parameter. It throws an error when you pass it two parameters which I believe is the [standard](http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html.html), even as [documented](http://msdn.microsoft... | You can use a try-catch block for doing this :
```
try
{
//Standards compliant
list.add(optionTag, null);
}
catch (err)
{
//IE
list.add(optionTag);
}
``` | Adding a new Option type works at least IE6 and up
```
function addOption(selectID, display, value)
{
var obj = document.getElementById(selectID);
obj.options[obj.options.length] = new Option(display, value);
}
```
Additionally tested in Firefox 2, 3, Opera 8, 9.5, and Safari 4 successfully. IE4 failed :( | Browser Neutral Way to add options to a select element in javascript | [
"",
"javascript",
""
] |
I need to take production data with real customer info (names, address, phone numbers, etc) and move it into a dev environment, but I'd like to remove any semblance of *real* customer info.
Some of the answers to [this question](https://stackoverflow.com/questions/157600/data-generators-for-sql-server) can help me gen... | Anonymizing data can be tricky and if not done correctly can lead you to trouble, like what happened to [AOL when they released search data a while back](http://en.wikipedia.org/wiki/AOL_search_data_scandal). I would attempt to create test data from scratch at all costs before I tried to convert existing customer data.... | This is easier than it sounds if you understand the database. One thing that is necessary is to understand the places where personal info is not normalized. For instance, the customer master file will have a name and address, but the order file will also have a name and address that might be different.
My basic proces... | Anonymizing customer data for development or testing | [
"",
"sql",
"data-scrubbing",
""
] |
I have a string. I need to replace all instances of a given array of strings from this original string - how would I do that?
Currently I am using...
```
var inputString = "this is my original string.";
var replacement = "";
var pattern = string.Join("|", arrayOfStringsToRemove);
Regex.Replace(inputString, pattern, ... | Build the pattern using Regex.Escape:
```
StringBuilder pattern = new StringBuilder();
foreach (string s in arrayOfStringsToRemove)
{
pattern.Append("(");
pattern.Append(Regex.Escape(s));
pattern.Append(")|");
}
Regex.Replace(inputString, pattern.ToString(0, pattern.Length - 1), // remove trailing |
re... | Look at [Regex.Escape](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx) | Remove characters using Regex | [
"",
"c#",
"regex",
"string",
""
] |
I have a table called ApprovalTasks... Approvals has a status column
I also have a view called ApprovalsView
When I try a straight update :
```
update ApprovalTasks set Status = 2 where ApprovalTaskID = 48
```
I'm getting this error message:
```
Msg 2601, Level 14, State 1, Line 1
Cannot insert duplicate key row i... | look at the definition of the index IX\_ApprovalTaskID
Is it possible there is a unique key constraint on ApprovalTaskID, StatusID which would mean there is another row in the table with Status = 2 & ApprovalTaskID = 48
I agree with user Learning, it looks like there's a FOR UPDATE trigger on ApprovalTasks that is ins... | Lucky guess: any update triggers defined?
2nd lucky guess: ApprovalsView is an [indexed view](http://www.microsoft.com/technet/prodtechnol/sql/2005/impprfiv.mspx) whose index is violated after updating the ApprovalTask table. | Very strange SQL update issue | [
"",
"sql",
"sql-update",
""
] |
I write a Text Editor with Java , and I want to add Undo function to it
but without UndoManager Class , I need to use a Data Structure like Stack or LinkedList but the Stack class in Java use Object parameters e.g : push(Object o) , Not Push(String s)
I need some hints or links .
Thanks | Assuming you are using Java 5, Stack is a generic class. You can instantiate it according to the objects it should hold.
You can then use:
```
Stack<String> stack = new Stack<String>();
String string = "someString";
stack.push(string);
```
Also note that in the case you are using Java 1.4 or below, you can still pus... | The "data structure", which in fact is a pattern, is called [Memento](http://en.wikipedia.org/wiki/Memento_pattern). It is helpful when you need to store multiple states and have the option of going back to a previous state. For efficient data storage of the states depends on what kind of a text editor you are doing, i... | I need some help in Undo function in Java | [
"",
"java",
"class",
"function",
"stack",
"undo",
""
] |
This is my code:
```
import datetime
today = datetime.date.today()
print(today)
```
This prints: `2008-11-22` which is exactly what I want.
But, I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:
```
import datetime
mylist = [datetime.date.today()]
print(mylist)
```
Th... | ## The WHY: dates are objects
In Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings or timestamps.
Any object in Python has TWO string representations:
* The regular representation that is used by `print` can be get using the `str()` function. It is most of the time t... | ```
import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
```
**Edit:**
After [Cees' suggestion](https://stackoverflow.com/a/20066760/7487335), I have started using time as well:
```
import time
print time.strftime("%Y-%m-%d %H:%M")
``` | How to print a date in a regular format? | [
"",
"python",
"datetime",
"date",
""
] |
We are in the process of upgrading our projects from C# 2.0 / VS2005 to C# 3.0 / VS2008. As part of the upgrade, we are adding some items to our coding standards document.
How would (or did) you change your coding standards document when upgrading from C# 2.0 / VS2005 to C# 3.0 / VS2008? | You could/should give advice about:
* When to use query expressions vs dot notation
* Any restrictions on the use of lambda expressions (e.g. "don't modify captured variables). (This could also apply to anonymous methods in C# 2 of course.)
* When to write extension methods
* When to use implicitly typed variables (`v... | The updgrade coincided with a new project, so when we moved we started using tools like StyleCop and FxCop which altered our coding standards. Also it handily enforces them too :o) | How has your coding standards document changed when you upgraded to C# 3.0 / VS2008? | [
"",
"c#",
"visual-studio-2008",
"visual-studio-2005",
"coding-style",
"upgrade",
""
] |
I have written a [toolbar](http://osirisdevelopment.com/BatteryBar) that runs on the taskbar. Unfortunately, after it is installed, the user has to enable it manually. Is there a way to tell explorer to open (or close) a given toolbar?
I would like for the installer, NSIS, to turn on the toolbar when the installation ... | * [This CodeProject comment does it by simulating key presses](http://www.codeproject.com/KB/atl/rbdeskband.aspx?display=PrintAll&select=1659628#xx1659628xx)
* Vista+ has API to do this, with [ShowDeskBand](http://msdn.microsoft.com/en-us/library/bb774485(VS.85).aspx) and [HideDeskBand](http://msdn.microsoft.com/en-us/... | You might want to [check out this article](http://blogs.msdn.com/oldnewthing/archive/2009/02/02/9388941.aspx). It looks like you can only do this ("officially" anyway) in Vista using the [ITrayDeskBand interface](http://msdn.microsoft.com/en-us/library/bb774484%28VS.85%29.aspx). | How can I programatically tell Windows taskbar to open (or close) a given toolbar? | [
"",
"c#",
"installation",
"toolbar",
"taskbar",
"deskband",
""
] |
Open source implementation will be preferred. | Obviously, it isn't an easy task, PDF formatting is much richer than HTML's one (plus you must extract images and link them, etc.).
Simple text extraction is much simpler (although not trivial...).
I see in the sidebar of your question a similar question: [Converting PDF to HTML with Python](https://stackoverflow.c... | Only ones I know of have to be paid for.
[BFO](http://bfo.co.uk/)
[JPedal](http://www.jpedal.org/) | Is there any java library for converting document from pdf to html? | [
"",
"java",
"html",
"pdf",
""
] |
How does an application perform a proximity search? For example, a user types in a postal code, then the application lists all the businesses within 20 miles ordered by proximity.
I want to build something like that in PHP and MySQL. Is this approach correct?
1. Get the addresses for locations I'm interested in and s... | If there are enough records for speed to matter, here's a way to index them ahead of time.
Define a grid of bins about 20 miles on a side. Store the bin number with each store's record. At search time, compute the numbers of all bins that intersect a 20-mile radius from your search point. Then retrieve all stores in a... | We use this to do many thousands of points. It is important if you are performing this in SQL to have an index on the Latitude and Longitude column. We tried doing this in SQL 2008 with spatial indexes but we really didn't see the performance increase we expected. Though if you want to calculate within a certain distan... | Proximity Search | [
"",
"php",
"mysql",
"proximity",
""
] |
I need the perfect algorithm or C# function to calculate the difference (distance) between 2 decimal numbers.
For example the difference between:
**100** and **25** is **75**
**100** and **-25** is **125**
**-100** and **-115** is **15**
**-500** and **100** is **600**
Is there a C# function or a very elegant... | You can do it like this
```
public decimal FindDifference(decimal nr1, decimal nr2)
{
return Math.Abs(nr1 - nr2);
}
``` | ```
result = Math.Abs(value1 - value2);
``` | Difference between 2 numbers | [
"",
"c#",
"algorithm",
"math",
"numbers",
""
] |
With Linux/GCC/C++, I'd like to record something to stderr whenever malloc/free/new/delete are called. I'm trying to understand a library's memory allocations, and so I'd like to generate this output while I'm running unit tests. I use valgrind for mem leak detection, but I can't find an option to make it just log allo... | [`malloc_hook(3)`](http://linux.die.net/man/3/malloc_hook) allows you to globally interpose your own `malloc` function. (There's `__realloc_hook` `__free_hook` etc. as well, I've just left them out for simplicity.)
```
#include <stdio.h>
#include <malloc.h>
static void *(*old_malloc_hook)(size_t, const void *);
stat... | You can trace calls to malloc/free with ltrace:
```
#include <stdlib.h>
int main (void)
{
void *ptr = malloc(10);
free(ptr);
return 0;
}
$ g++ test.cpp -o test
$ ltrace -e malloc,free ./test
malloc(10) = 0x804a008
free(0x804a008) = <void>... | Outputting to stderr whenever malloc/free is called | [
"",
"c++",
"linux",
"memory",
"malloc",
"valgrind",
""
] |
This function exists on OS X and allows you to pass custom local to the function. setlocale is not thread-safe, and passing locale as parameter is.
If there is no equivalent, any way of locale-independent printf, or printf just for doubles (%g) will be ok. | There are locale-independent double to string convertion routines at <http://www.netlib.org/fp/>. String to double conversion is available too. The API is not very nice, but the code works. | You might try [`uselocale`](http://refspecs.freestandards.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-generic/baselib-uselocale-3.html), which sets the thread locale (rather than the process locale) before calling `printf`. | How to get equivalent of printf_l on Linux? | [
"",
"c++",
"thread-safety",
"locale",
"printf",
""
] |
Would anyone happen to know how to convert type `LPTSTR` to `char *` in C++? | Depends if it is Unicode or not it appears. LPTSTR is char\* if not Unicode, or w\_char\* if so.
[Discussed better here](http://social.msdn.microsoft.com/Forums/en-US/vclanguage/thread/1b994ff3-da28-46a8-90ef-6c7fab8dcd21/) (accepted answer worth reading) | Here are a lot of ways to do this. MFC or ATL's CString, ATL macros, or Win32 API.
```
LPTSTR szString = _T("Testing");
char* pBuffer;
```
You can use ATL macros to convert:
```
USES_CONVERSION;
pBuffer = T2A(szString);
```
CString:
```
CStringA cstrText(szString);
```
or the Win32 API `WideCharToMultiByte` if `U... | Convert lptstr to char* | [
"",
"c++",
"char",
"lptstr",
""
] |
I want to make a simple server application where people can connect using a browser-based client (which I will make later) to watch streaming video. And I want to use C#.
What do I need to capture video or rapid images through a webcam and send them over the network? | If you want a "capture/streamer in a box" component, there are several out there as others have mentioned.
If you want to get down to the low-level control over it all, you'll need to use DirectShow as thealliedhacker points out. The best way to use DirectShow in C# is through the [DirectShow.Net](http://directshownet... | The usual API for this is DirectShow.
You can use P/Invoke to import the C++ APIs, but I think there are already a few projects out there that have done this.
<http://channel9.msdn.com/forums/TechOff/93476-Programatically-Using-A-Webcam-In-C/>
<http://www.codeproject.com/KB/directx/DirXVidStrm.aspx>
To get the stre... | How can I stream webcam video with C#? | [
"",
"c#",
"video",
"streaming",
"webcam",
""
] |
Can anyone explain to me what this means?
"Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention." | When calling a function, the compiler has to push some arguments on the stack, or put them in some registers. The function body will change some memory location (or a register) to contain the return value. Then it will return to a block of code at a location stored 'somewhere' on the stack.
The calling convention spec... | Possibility #1 is your object got Aliased wrong. That means the compiler mistakenly casted an object incorrectly, most commonly as an optimization.
Possibility #2 your using a reference to an object that isn't valid.
Possibility #3 something totally unrelated broke your stack, likely a buffer overflow.
Without code ... | C++ Visual Studio Runtime Error | [
"",
"c++",
"visual-studio",
"debugging",
""
] |
After trying to setup my site for Google Webmaster Tools I found that my Custom ASP.NET 404 page was not returning the 404 status code. It displayed the correct custom page and told the browser that everything is OK. This is consider a soft 404 or false 404. Google doesn't like this. So I found many articles on the iss... | **Solution:**
The problem, it turned out, was the use of the master page. I got it to work by setting the status code later in the pages lifecycle, obviously the rendering of the master page was resetting it, so I overrode the render method and set it after the render was complete.
```
protected override void Render(... | I had a similar problem I want to show a custom page as a 404 (which is ASPX) and it worked fine on localhost but as soon as a remote visitor connected they would get the generic IIS 404.
The solution to this was to add
```
Response.TrySkipIisCustomErrors = true;
```
Before changing the Response.StatusCode.
Found v... | ASP.NET Custom 404 Returning 200 OK Instead of 404 Not Found | [
"",
"c#",
"asp.net",
"master-pages",
"http-status-code-404",
"custom-errors",
""
] |
I'm working on a Zend Framework (1.7) project with a structure loosely based on the structure of the quickstart application - front controller, action controllers, views & models that use Zend\_Db\_Table to get to the database. One of my main models relies on some expensive joins to pull up its primary listing, so I'm ... | You can provide an interface on your models that accepts `$current_page` and `$per_page` parameters and returns the current page's data set as well as a paginator object.
This way all your pagination code is contained within the model and you are free to use the Db adapters without feeling like you've broken the conce... | There is now a setFilter method for Zend\_Paginator that allows you to load the data from the row object to any model object you want:
```
class Model_UserDataMapper {
public function getUsers($select, $page) {
$pager = Zend_Paginator::factory($select);
$pager->setItemCountPerPage(10)
... | Zend_Paginator blurring MVC lines | [
"",
"php",
"model-view-controller",
"zend-framework",
"zend-paginator",
""
] |
Is there any real reason **not** to make a member function virtual in C++? Of course, there's always the performance argument, but that doesn't seem to stick in most situations since the overhead of virtual functions is fairly low.
On the other hand, I've been bitten a couple of times with forgetting to make a functio... | One way to read your questions is "Why doesn't C++ make every function virtual by default, unless the programmer overrides that default." Without consulting my copy of "Design and Evolution of C++": this would add extra storage to every class unless every member function is made non-virtual. Seems to me this would have... | Stroustrup, the designer of the language, [says](http://www.research.att.com/%7Ebs/bs_faq2.html#virtual):
> Because many classes are not designed to be used as base classes. For example, see [class complex](http://www.research.att.com/%7Ebs/bs_faq2.html#data-in-class).
>
> Also, objects of a class with a virtual funct... | Is there any reason not to make a member function virtual? | [
"",
"c++",
"oop",
"virtual-functions",
""
] |
I'm having an extremely weird problem with a PHP script of mine.
I'm uploading a couple of files and having PHP put them all in one folder.
I've have trouble with random files being sent and random ones not being sent. So I debugged it and I got a very weird result from the $\_FILES[] array.
I tried it with 3 files.
... | Relevent, but probably not going to help: but move\_uploaded\_file is a (slightly) better way to handle uploaded files than copy.
Are any of the files large? PHP has limits on the filesize and the time it can take to upload them ...
Better to send you here than attempt to write up what it says:
<https://www.php.net/... | I'm sorry but it seams to me that you are trying to upload all 3 files with the same variable name? Is this right?
But this will not work because they will overwrite each other.
I think the better an cleaner way it would be to use something like
```
$i = 0;
foreach($_FILES['addFile'.$i] as $addFile) {
if(... | PHP file uploading trouble | [
"",
"php",
"file-upload",
""
] |
I am currently developing a (somewhat large) site for a magazine, the site mainly consists of sections like : news (for various categories), members, and some 'other stuff' (like shoutbox, polls, previous covers, photo galleries that can be tagged, and ad banners system).
Now, since most part of the site is a typical ... | Honestly I think it's a pretty bad idea, at least on the background of my own experience.
The main disadvantages:
* doubles the amount of knowledge an admin/editor has to have/develop
* doubles the amount of security risks
* doubles the amount of updating/patching the CMS installations
* lowers the probability of fin... | I think its too complicated and that problems are likely to arise around the fact there are two systems. Its also not great from a usability perspective.
You should look at some of the beefier CMS options. Drupal has a lot of plugins and functionality available, be suprised if it can't do what you need. Joomla is also... | setting up two CMS for one site, best practice | [
"",
"php",
"architecture",
"content-management-system",
""
] |
I have a template class like below.
```
template<int S> class A
{
private:
char string[S];
public:
A()
{
for(int i =0; i<S; i++)
{
.
.
}
}
int MaxLength()
{
return S;
}
};
```
If i instantiate the above class with different values of S, will the compiler create different in... | The template will be instantiated for each different values of S.
If you move the method implementations to a different file, you'll need to #include that file. (Boost for instance uses the `.ipp` convention for such source files that need to be #included).
If you want to minimise the amount of code that is generated... | Actually this is fully up to the compiler. It's only required to generate *correct* code for its inputs. In order to do so it must follow the C++ standard as that explains what *is* correct. In this case it says that the compiler must at one step in the process instantiate templates with different arguments as differen... | c++ template instantiation | [
"",
"c++",
"templates",
""
] |
I need to create a request for a web page delivered to our web sites, but I need to be able to set the host header information too. I have tried this using HttpWebRequest, but the Header information is read only (Or at least the Host part of it is). I need to do this because we want to perform the initial request for a... | I have managed to find out a more long winded route by using sockets. I found the answer in the MSDN page for IPEndPoint:
```
string getString = "GET /path/mypage.htm HTTP/1.1\r\nHost: www.mysite.mobi\r\nConnection: Close\r\n\r\n";
Encoding ASCII = Encoding.ASCII;
Byte[] byteGetString = ASCII.GetBytes(getString);
Byte... | Although this is a very late answer, maybe someone can get benefit of it
```
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://192.168.1.1"));
request.Headers.GetType().InvokeMember("ChangeInternal", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, request.... | Request Web Page in c# spoofing the Host | [
"",
"c#",
"http",
"http-headers",
""
] |
How can I detect which request type was used (GET, POST, PUT or DELETE) in PHP? | By using
```
$_SERVER['REQUEST_METHOD']
```
### Example
```
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// The request is using the POST method
}
```
For more details please see the [documentation for the $\_SERVER variable](http://php.net/manual/en/reserved.variables.server.php). | REST in PHP can be done pretty simple. Create <http://example.com/test.php> (outlined below). Use this for REST calls, e.g. <http://example.com/test.php/testing/123/hello>. This works with Apache and Lighttpd out of the box, and no rewrite rules are needed.
```
<?php
$method = $_SERVER['REQUEST_METHOD'];
$request = ex... | Detecting request type in PHP (GET, POST, PUT or DELETE) | [
"",
"php",
"http",
"request",
""
] |
I need a byte buffer class in Java for single-threaded use. I should be able to insert data at the back of the buffer and read data at the front, with an amortized cost of O(1). The buffer should resize when it's full, rather than throw an exception or something.
I could write one myself, but I'd be very surprised if ... | Not sure if it is "the best", but you have a nice example of [Circular Byte buffer here](http://ostermiller.org/utils/CircularBuffer.html).
Those [Java Utilities - OstermillerUtils](http://ostermiller.org/utils/) classes are under [GPL license](http://ostermiller.org/utils/licenseFAQ.html).
> This Circular Byte Buffe... | I wonder if this one works well
<https://svn.apache.org/repos/asf/etch/releases/release-1.0.0/util/src/main/java/etch/util/CircularByteBuffer.java>
We will probably try this one since it is apache license. | What is the best resizable circular byte buffer available in Java? | [
"",
"java",
"buffer",
"byte",
""
] |
Why does this test program result in a `java.lang.IllegalMonitorStateException`?
```
public class test {
static Integer foo = new Integer(1);
public static void main(String[] args) {
synchronized(foo) {
foo++;
foo.notifyAll();
}
System.err.println("Success");
... | You have noted correctly that `notifyAll` must be called from a synchronized block.
However, in your case, because of auto-boxing, the object you synchronized on is not the same instance that you invoked `notifyAll` on. In fact, the new, incremented `foo` instance is still confined to the stack, and no other threads c... | You should also be leery of locking or notifying on objects like String and Integer that can be interned by the JVM (to prevent creating a lot of objects that represent the integer 1 or the string ""). | Why does notifyAll() raise IllegalMonitorStateException when synchronized on Integer? | [
"",
"java",
"synchronization",
"notify",
"illegalmonitorstateexcep",
""
] |
I have written a small java application for which I need to obtain performance metrics such as memory usage, running time etc., Is there any simple to use performance measurement tool available? | [Yourkit](http://yourkit.com/) is pretty good (free 30 day trial). Eclipse also has built in [TPTP tools](http://www.eclipse.org/tptp/). | [Apache JMeter](http://jakarta.apache.org/jmeter/) has a ton of features, for benchmarking http requests, JDBC calls, web services, JMS, mail, regular Java requests, etc. | Java benchmarking tool | [
"",
"java",
"performance",
"benchmarking",
""
] |
I'm trying to do the following in python:
In a file called foo.py:
```
# simple function that does something:
def myFunction(a,b,c):
print "call to myFunction:",a,b,c
# class used to store some data:
class data:
fn = None
# assign function to the class for storage.
data.fn = myFunction
```
And then in a file c... | ```
data.fn = staticmethod(myFunction)
```
should do the trick. | What you can do is:
```
d = foo.data()
d.fn = myFunction
d.fn(1,2,3)
```
Which may not be exactly what you want, but does work. | storing unbound python functions in a class object | [
"",
"python",
"function",
""
] |
I have to include many header files, which are in different sub-directories. Is there a way in Visual Studio (I am using 2005 edition) to set one include path that Visual Studio will search also the sub-directories for header files? | Setting the folder search paths in the Visual Studio settings to fix an include issue is generally not really a good idea from a design point of view. Your code will be less portable to different machines with different directory lay-outs.
My suggestion would be to settle on an organisation of your code so that the re... | We haven't found a way of setting a recursive folder search in Visual Studio (though Xcode has no problem setting and using them). What we do is list all the directories in a file, and specify the file in the C/C++ Command Line additional options:
@"IncludeFolders.rsp"
We rarely find problems using recursive search, ... | How to include sub-directories in Visual Studio? | [
"",
"c++",
"visual-studio",
"visual-studio-2005",
"include",
""
] |
How do Window's programmers profile their native C++ code?
On Unix/Linux you have gprof *[thanks Evan]* & valgrind (I personally used this one, although it's not a real profiler), and recently I'm on Mac and Solaris, which means I moved to dTrace. Now when I've had the need to profile on Windows in the past, like at my... | You should give [Xperf](http://blogs.msdn.com/pigscanfly/archive/2008/02/09/xperf-a-new-tool-in-the-windows-sdk.aspx) a try - it's a new system wide performance tool that can drill down to a particular application and what exactly it's doing inside itself as well as what's it's asking of the OS.
It's freely available ... | I got [AMD Code Analyst](http://www.amd.com/codeanalyst/). It's free, and you don't need an AMD CPU ;)
It's a little basic compared to something like Intel's VTune, but the price is right. | What tools do you use to profile (native)C++ on Windows? | [
"",
"c++",
"windows",
"profiling",
""
] |
If i do jQuery(expr).change( function), then I can get an event function to fire when the user makes a change to the value.
Is it possible to get this to fire if it's changed programatically, ie if I call jQuery(expr).val("moo").
or if some Plain old JavaScript changes it's value?
Thanks for any help. | After you've changed the value, you can fire the event yourself, and thus calling all the 'onchange' handlers.
```
jQuery('#element').change();
``` | Changing the value directly in JS doesn't hook into anything which jQuery can listen for to trigger the change event. Like Sander says, you can fire the event handler yourself. If you don't have control over other code modifying these values and that isn't an option, you're kind of out of luck. The only other option wh... | JQuery detecting Programatic change event | [
"",
"javascript",
"jquery",
""
] |
I am looking at depency injection, I can see the benefits but I am having problems with the syntax it creates. I have this example
```
public class BusinessProducts
{
IDataContext _dx;
BusinessProducts(IDataContext dx)
{
_dx = dx;
}
public List<Product> GetProducts()
{
return dx.GetProduc... | I use a factory for my context and inject it, providing a suitable default if the provided factory is null. I do this for two reasons. First, I use the data context as a unit of work scoped object so I need to be able to create them when needed, not keep one around. Second, I'm primarily using DI to increase testabilit... | You can create a factory. DI containers are best for wirings that happen at setup-time - not at runtime (As this looks to be a case of). Factories can be implemented in different ways, depending on how pluggable it needs to be, and how many places you need to use it. | dependency injection alternatives | [
"",
"c#",
"dependency-injection",
""
] |
Related to this question:
[URL characters replacement in JSP with UrlRewrite](https://stackoverflow.com/questions/353207/url-characters-replacement-in-jsp-with-urlrewrite)
I want to have masked URLs in this JSP Java EE web project.
For example if I had this:
```
http://mysite.com/products.jsp?id=42&name=Programming_B... | It's been a while since I mucked about with JSPs, but if memory serves you can add URL patterns to your web.xml (or one of those XML config files) and have the servlet engine automatically route the request to a valid URL with your choice of paramters. I can look up the details if you like.
In your case, map `http://m... | You could use a `URLRewrite filter`. It's like how mod\_rewrite is for Apache's HTTP web server.
<http://tuckey.org/urlrewrite/>
"Redirect one url
```
<rule>
<from>^/some/old/page\.html$</from>
<to type="redirect">/very/new/page.html</to>
</rule>
```
Tiny/Freindly url
```
<rule>
<from>^/zebra$</from>
<to type="red... | Mask urls in JSP | [
"",
"java",
"jsp",
"url",
"jakarta-ee",
""
] |
I'm working with some old PHP code that has a lot of the following:
```
$someVar =& new SomeClass();
```
Did the **new** operator ever return a value, um, not by reference? (That feels strange to type. I feel like I'm losing my mind.) | It was one of those sort of optimization techniques taught in a lot of older books on OOP in PHP 4.
Basically, the initial object created in memory is one the application can't access unless you return the instance by reference. Otherwise you get a copy of the object - the only catch is that the original exists withou... | Thats PHP4 code.
From the documentation: (now removed)
> "new" does not return a reference by
> default, instead it returns a copy.
~~[1]: <http://no.php.net/manual/en/language.oop.newref.php>~~ | PHP new operator returning reference | [
"",
"php",
"reference",
""
] |
Is there a way in SWT to get a monospaced font simply, that works across various operating systems?
For example. this works on Linux, but not Windows:
```
Font mono = new Font(parent.getDisplay(), "Mono", 10, SWT.NONE);
```
or do I need to have a method that tries loading varying fonts (Consolas, Terminal, Monaco, M... | According to the section on [Font Configuration Files](http://java.sun.com/javase/6/docs/technotes/guides/intl/fontconfig.html) in the JDK documentation of [Internationalization Support](http://java.sun.com/javase/6/docs/technotes/guides/intl/)-related APIs, the concept of **Logical Font**s is used to define certain pl... | I spent a while bashing my head against this one until I realised that obviously eclipse must have access to a monospace font for use in its text fields, console etc. A little digging turned up:
```
Font terminalFont = JFaceResources.getFont(JFaceResources.TEXT_FONT);
```
Which works if all you're interested in is ge... | SWT - OS agnostic way to get monospaced font | [
"",
"java",
"fonts",
"swt",
""
] |
I'd like them to be easy to bundle, with few dependencies and easy to use. | Do you want to highlight Java code or use a Java lib to highlight some other code?
I use these two: <https://jhighlight.dev.java.net/> (server-side) for xml and <http://code.google.com/p/syntaxhighlighter/> (js lib) for other stuff. The latter has something called 'brushes' which are "pluggable" .js for several langau... | <http://sourceforge.net/projects/jintilla/>
<http://syntax.jedit.org/> | What code highlighting libs are there for Java? | [
"",
"java",
"syntax-highlighting",
"codehighlighter",
""
] |
My current problem is that I have a JFrame with a 2x2 GridLayout. And inside one of the squares, I have a JPanel that is to display a grid. I am having a field day with the java swing library... take a look
[Image](http://img114.imageshack.us/img114/9683/frameow2.jpg)
Java is automatically expanding each JLabel to fi... | If you want the two checkerboards to stay the same size, then you'll need to have them each contained in their own `JPanel`. Set each of those parent JPanel's to have a layout type of `GridBagLayout`. Set the preferedSize for each checkerboard component and then add them to their respective containers. GridBagLayout sh... | **GridBagLayout** is what you really want to use. The GridLayout will force the same size for each component in the layout no matter what size constraints you put on them. GridBagLayout is a lot more powerful and a lot more complicated. Study up on [the API page](http://java.sun.com/j2se/1.5.0/docs/api/java/awt/GridBag... | Can you set a permanent size for a JPanel inside of a JFrame? | [
"",
"java",
"swing",
"size",
"jlabel",
"grid-layout",
""
] |
I am working on an application which draws a simple dot grid. I would like the mouse to snap between the points on the grid, eventually to draw lines on the grid.
I have a method which takes in the current mouse location (X,Y) and calculates the nearest grid coordinate.
When I create an event and attempt to move the ... | I think I understand where you're coming from. You simply need to be some delta away from the original snap point (the left mouse click) before you snap to the new point.
Here's 50 lines of code illustrating what I mean:
(Start a new VB.NET project, add a new module, copy and paste the code, add a reference, to System... | Don't modify the cursor position. You don't need to.
Instead, *draw* as if it was snapped to the grid. When the user clicks somewhere, just draw the line from the nearest grid points.
For instance, if the user clicks on (197,198), but you know that the nearest point actually is (200,200), just draw a line to (200,200... | Snap to grid mouse locking up | [
"",
"c#",
"grid",
"mouse",
"cursor-position",
"onmousemove",
""
] |
I'm using Django and Python 2.6, and I want to grow my application using a MySQL backend. Problem is that there isn't a win32 package for MySQLdb on Python 2.6.
Now I'm no hacker, but I thought I might compile it myself using MSVC++9 Express. But I run into a problem that the compiler quickly can't find `config_win.h`... | I think that the header files are shipped with MySQL, just make sure you check the appropriate options when installing (I think that sources and headers are under "developer components" in the installation dialog). | Thanks all! I found that I hadn't installed the developer components in MySQL. Once that was done the problem was solved and I easily compiled the MySQLdb for Python 2.6.
I've made the package available at [my site](http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe). | Problem compiling MySQLdb for Python 2.6 on Win32 | [
"",
"python",
"mysql",
"winapi",
""
] |
I am currently working on a web application that uses PHP and MySQL, but I do not have shell access to the server (working on that problem already...). Currently, I have source control with subversion on my local computer and I have a database on the local computer that I make all changes to. Then, once I've tested all... | You can do a subversion export (rather than checkout) to different directory from your working copy, then it will remove all the .svn stuff for you | I'm using [Weex](http://weex.sourceforge.net/) to synchronize a server via FTP. Weex is basically a non-interactive FTP client that automatically uploads and deletes files/directories on the remote server. It can be configured to not upload certain paths (like SVN directories), as well as to keep certain remote paths (... | What is a good solution for deploying a PHP/MySQL site via FTP? | [
"",
"php",
"mysql",
"deployment",
""
] |
Thanks to a library upgrade (easymock 2.2 -> 2.4), we're having tests that have started locking up. I'd like to have a time out on individual tests, all of them. The idea is to identify the locked up tests - we're currently guessing - and fix them.
Is this possible, preferably on a suite-wide level? We have 400 tests,... | The [suite tag](http://code.google.com/p/testng/source/browse/trunk/src/main/org/testng/xml/XmlSuite.java) can have the time-out attribute. This time-out will be used as default for all test methods.
This default time-out can than be overridden on a per test method basis. | If the Suite level turns out to be the wrong approach (i.e. "too wide a net", because you end up marking too much methods with a timeout limit), you need to define a custom [IAnnotationTransformer](http://testng.org/doc/documentation-main.html#annotationtransformers) which, for each illegible function, will give you th... | Timing out tests in TestNG | [
"",
"java",
"multithreading",
"testng",
""
] |
I have a large number of 2D points and I want to quickly get those that lie in a certain rectangle.
Let's say a '.' is any point and 'X' is a point I want to find inside a rectangle which has 'T' as TopLeft and 'B' as BottomRight points:
```
. . . . . .
. T-----+ .
. | X X | .
. +-----B .
. . . . . .
```
I have tried... | You could store the points in a spatial index using quad or r-trees. Then given the rectangle you could find all the nodes of the tree that overlap it, you would then have to compare each point in this subset to see if it falls in the rectangle.
In essence, the spatial tree helps you prune the search space.
You might... | Please see [this question](https://stackoverflow.com/questions/132319/storing-objects-for-locating-by-xy-coordinates#132393).
[The Stony Brook Algorithm Repository](http://www.cs.sunysb.edu/~algorith/files/kd-trees.shtml) has some implementations of KDTrees in C++,
though they are not part of STL nor Boost. | Store 2D points for quick retrieval of those inside a rectangle | [
"",
"c++",
"stl",
"boost",
"spatial",
"point",
""
] |
I have the following regex expression to match html links:
```
<a\s*href=['|"](http:\/\/(.*?)\S['|"]>
```
it kind of works. Except not really. Because it grabs everything after the < a href...
and just keeps going. I want to exclude the quote characters from that last \S match. Is there any way of doing that?
**EDIT... | I don't think your regex is doing what you want.
```
<a\s*href=['|"](http:\/\/(.*?)\S['|"]>
```
This captures anything non-greedily from http:// up to the first non-space character before a quote, single quote, or pipe. For that matter, I'm not sure how it parses, as it doesn't seem to have enough close parens.
If y... | \S matches any character that is not a whitespace character, just like [^\s]
Written like that, you can easily exclude quotes: [^\s"']
Note that you'll likely have to give the .\*? in your regex the same treatment. The dot matches any character that is not a newline, just like [^\r\n]
Again, written like that, you c... | excluding characters in \S regex match | [
"",
"python",
"html",
"regex",
""
] |
I'm already familiar with the standard Java package naming convention of using a domain name to create a unique package name (i.e. package `com.stackoverflow.widgets`). However, I've never seen any recommendations for how to choose package names for personal projects. I assume because this is because this is really a m... | If you're just doing personal projects where nobody else will use the code, then you can make up a package name that you like. Don't make up something that starts with `com.` or `net.` or other top-level domain though, because that would imply that you own the domain name (ie. using `com.john` as your package name just... | I just use my initials: fg.nameofproject.etc
It reduces typing.
It can be prefixed at any time with sf.net or com. or org. or com.google..
As the project is personal treat it special just like your freshly pressed personalized gift shirt - it will feel good. | What package naming convention do you use for personal/hobby projects in Java? | [
"",
"java",
"naming-conventions",
""
] |
I'm trying to upload an image to my site through a form, however it's much more efficient to (rather than bog down the database) just store the location of the image in the database.
I'm having trouble with my form and really don't know where to go:
```
<?=form_open('bro/submit_new');?>
//other form data
Image: <in... | CodeIgniter's file uploading class will do this for you. The [entry in their user guide](http://codeigniter.com/user_guide/libraries/file_uploading.html) explains as well as I could, so I'm going to point you there.
Essentially you'd just need to modify the controller that they have there to include a bit where you pu... | use form\_open\_multipart() not form\_open() | CodeIgniter - Uploading an Image through a form, store the location of the image in database | [
"",
"php",
"mysql",
"file",
"codeigniter",
"upload",
""
] |
Ok, I'm not great in mysql, but I know an index would help me out here, however I've done some plugging and can't find one to help...
Anyone got any ideas?
```
explain
select `users_usr`.`id_usr` AS `id_usr`,
`users_usr`.`firstname_usr` AS `firstname_usr`,
`users_usr`.`lastname_usr` AS `lastname_usr`,`users_usr`... | Your EXPLAIN output shows that you already have indexes that *might* be useful, but the query engine has decided not to use them.
<http://dev.mysql.com/doc/refman/5.0/en/using-explain.html> says:
> **Using temporary**
>
> To resolve the query, MySQL needs to
> create a temporary table to hold the
> result. This typic... | Retract some of that, and start over.
Here is my interpretation of your query.
```
uu.select uu.id_usr,
uu.firstname_usr,
uu.lastname_usr,
uu.social_usr,
uu.address1_usr,
uu.address2_usr,
uu.city_usr,
uu.state_usr,
uu.zip_usr,
uu.email_usr,
ca.given_credit_acc,
ca.credit_used_acc,
ca.date_est... | help with an index | [
"",
"sql",
"mysql",
""
] |
Why does this code:
```
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
};
int main(void)
{
B *b = new B(5);
delete b;
}
```
Result in these errors:
```
main.cpp: In function ‘int main()’:
main.cpp:13: error: no matching function for call to ‘B::B(int)’
main.cpp:8: note: candidat... | If your compiler supports C++11 standard, there is a constructor inheritance using `using` (pun intended). For more see [Wikipedia C++11 article](http://en.wikipedia.org/wiki/C%2B%2B11#Object_construction_improvement). You write:
```
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
usin... | Constructors are not inherited. They are called implicitly or explicitly by the child constructor.
The compiler creates a default constructor (one with no arguments) and a default copy constructor (one with an argument which is a reference to the same type). But if you want a constructor that will accept an int, you h... | Inheriting constructors | [
"",
"c++",
"inheritance",
"gcc",
"constructor",
""
] |
What is the C++ equivalent to `GetObject` in [JavaScript](http://en.wikipedia.org/wiki/JavaScript) and [VBScript](http://en.wikipedia.org/wiki/VBScript)?
The closest match I found to my question is:
<http://codewiz51.blogspot.com/2008/06/vb-script-getobject-c-api-cogetobject.html>
However the sample use an unexistin... | I figured out the issue. The object I wanted to access was
`winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv`
I mistakenly took \\ for an escapement. In C++ the correct query is :
`::CoGetObject(L"winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\default:StdRegProv", NULL, IID_IUnknown, (vo... | The article you linked to is correct. You may be providing the wrong interface ID, or the display name could be wrong. You should check the return value from the `CoGetObject` call. | What is the C++ equivalent to GetObject in JavaScript and VBScript? | [
"",
"c++",
"winapi",
"com",
"vbscript",
"wsh",
""
] |
How do you tell if caps lock is on using JavaScript?
One caveat though: I did google it and the best solution I could find was to attach an `onkeypress` event to every input, then check each time if the letter pressed was uppercase, and if it was, then check if shift was also held down. If it wasn't, therefore caps lo... | You can give it a try.. Added a working example. When focus is on input, turning on caps lock makes the led go red otherwise green. (Haven't tested on mac/linux)
NOTE: Both versions are working for me. Thanks for constructive inputs in the comments.
OLD VERSION: <https://jsbin.com/mahenes/edit?js,output>
Also, here ... | You can use a `KeyboardEvent` to detect numerous keys including the caps lock on most recent browsers.
The [`getModifierState` function](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState) will provide the state for:
* Alt
* AltGraph
* CapsLock
* Control
* Fn (Android)
* Meta
* NumLock
* ... | How do you tell if caps lock is on using JavaScript? | [
"",
"javascript",
"keyboard",
"capslock",
""
] |
How are the java API thread priorities (1-10) gets translated to the OS level priorities since most OS don't have thread priority levels (in terms of number) which match this.
So keeping in mind , can there be a scenario when two or more threads with different priorities eventually get the same priority at OS level.
... | Indeed, some priority levels can map to the same "native" priority level. Here's the list (based on the Hotspot code in OpenJDK 6):
## Solaris
* 1 ⇒ 0
* 2 ⇒ 32
* 3 ⇒ 64
* 4 ⇒ 96
* 5 – 10 ⇒ 127
Of note is that on Solaris, you can't raise the thread priority above normal, only lower it: the priority value for 5 is the... | Your understanding is correct - Java thread priorities do not map cleanly to OS thread priorities.
As a result, if your algorithm relies in any way on the details of thread priority mapping, then it is broken, since it will vary according to so many variables. Upgrading your JRE or applying a patch/service pack to you... | How are Java Thread priorities translated to an OS thread priority? | [
"",
"java",
"multithreading",
"operating-system",
""
] |
I'm porting a relatively simple console program written for Unix to the Windows platform ([Visual C++ 8.0](http://en.wikipedia.org/wiki/Visual_C++#32-bit_versions)). All the source files include "unistd.h", which doesn't exist. Removing it, I get complaints about missing prototypes for 'srandom', 'random', and 'getopt'... | Since we can't find a version on the Internet, let's start one here.
Most ports to Windows probably only need a subset of the complete Unix file.
Here's a starting point. Please add definitions as needed.
```
#ifndef _UNISTD_H
#define _UNISTD_H 1
/* This is intended as a drop-in replacement for unistd.h on Win... | Try including the `io.h` file. It seems to be the Visual Studio's equivalent of `unistd.h`. | Is there a replacement for unistd.h for Windows (Visual C)? | [
"",
"c++",
"c",
"windows",
"portability",
"unistd.h",
""
] |
What is the best tool for Java for aspect-oriented programming?
The requirements for a tool are of course IDE support, expressiveness and proper documentation. | JBossAOP and AspectJ are two commonly used, mature frameworks for AOP. Another popular choice is Spring AOP, but it lacks some of the features of the other two.
Both JBossAOP and AspectJ have similar features, one big difference being that AspectJ relies on extensions to the Java language, whereas JBoss AOP does not.
... | I would say AspectJ. The IDE part, as far as I know, is lacking, but documentation and expressiveness is among the best of the AOP frameworks I have seen. | Aspect-oriented programming in Java | [
"",
"java",
"aop",
""
] |
I have some products that belongs to the some category.
Each category can have different properties.
For example,
* category *cars* has properties *color*,
power, ...
* category *pets* have properties *weight*, *age*, ...
Number of categories is about 10-15.
Number of properties in each category is 3-15.
Number o... | The classic design approach would be (the star denotes the primary key column):
```
Product
ProductId*
CategoryId: FK to Category.CategroyId
Name
Category
CategoryId*
Name
Property
PropertyId*
Name
Type
CategoryProperty
CategoryId*: FK to Category.CategoryId
PropertyId*: FK to Property.PropertyI... | If the user of the application *has* to select a category before they can search, I would separate your products into different database tables by category. This solution is also indicated by the fact that the categories themselves have so little in common. Breaking it down by category will also make each search much f... | What is best practice for this problem (different properties for different categories)? | [
"",
"sql",
"sql-server",
"database",
"database-design",
"entity-attribute-value",
""
] |
This is a somewhat bizarre question. My objectives are to understand the language design decision and to identify the possibilities of reflection in C++.
1. Why C++ language committee did not go towards implementing reflection in the language? Is reflection too difficult in a language that does not run on a virtual ma... | There are several problems with reflection in C++.
* It's a lot of work to add, and the C++ committee is fairly conservative, and don't spend time on radical new features unless they're sure it'll pay off. (A suggestion for adding a module system similar to .NET assemblies has been made, and while I think there's gene... | Reflection requires some metadata about types to be stored somewhere that can be queried. Since C++ compiles to native machine code and undergoes heavy changes due to optimization, high level view of the application is pretty much lost in the process of compilation, consequently, it won't be possible to query them at r... | Why does C++ not have reflection? | [
"",
"c++",
"reflection",
""
] |
I was reading up about NTVDM.exe as I build a quick test console app and it crashed on a friends machine complaining about this EXE.
As I understand it all DOS cmd windows (C# console apps included) run as 16bit not 32bit.
Is this true? Does this mean all my works console app back office apps are running as 16bit rat... | Any .NET app that is compiled for x86 will be 32-bit
C# console apps aren't running in "real" dos - they run in a 32-bit or 64-bit environment - depending on your OS and .NET framework. | > As I understand it all DOS cmd windows
> (C# console apps included) run as
> 16bit not 32bit.
>
> Is this true?
No, not at all.
You can run DOS applications under Windows, and they are 16-bit, but the fact that they look a bit console-like is pretty much just coincidence.
There are no 16-bit .NET applications, and... | C# console applications all 16bit? | [
"",
"c#",
"console-application",
"16-bit",
"ntvdm.exe",
""
] |
I want to create an array with a message.
```
$myArray = array('my message');
```
But using this code, `myArray` will get overwritten if it already existed.
If I use `array_push`, it has to already exist.
```
$myArray = array(); // <-- has to be declared first.
array_push($myArray, 'my message');
```
Otherwise, it... | Check if the array exists first, and if it doesn't, create it...then add the element, knowing that the array will surely be defined before hand :
```
if (!isset($myArray)) {
$myArray = array();
}
array_push($myArray, 'my message');
``` | Here:
```
$myArray[] = 'my message';
```
$myArray have to be an array or not set. If it holds a value which is a string, integer or object that doesn't implement arrayaccess, it will fail. | php: pushing to an array that may or may not exist | [
"",
"php",
"arrays",
"declaration",
"push",
""
] |
I am trying to run a java based tool using a command line syntax as the following: java -cp archive.jar archiveFolder.theMainClassName.Although the class I am searching for, a main class, "theMainClassName" is in the archive.jar and in the archiveFolder given at input, I keep getting the error that my class is not seen... | Here's a concrete example of what *does* work, so you can compare your own situation.
Take this code and put it anywhere, in a file called `MainClass.java`. (I've assumed a directory called `src` later. Normally you'd arrange the source to match the package, of course.)
```
package archiveFolder;
public class MainCl... | Does theMainClassName class have the following package line at the top:
```
package archiveFolder
```
You need the class file to be in the same directory structure as the declared package. So if you had something like:
```
org/jc/tests/TestClass.class
```
its source file would have to look like this:
```
package o... | Java Command Line Trouble with Reading a Class from a Jar Archive | [
"",
"java",
"command-line",
""
] |
What is the shortest chunk of C++ you can come up with to safely clean up a `std::vector` or `std::list` of pointers? (assuming you have to call delete on the pointers?)
```
list<Foo*> foo_list;
```
I'd rather not use Boost or wrap my pointers with smart pointers. | Since we are throwing down the gauntlet here... "Shortest chunk of C++"
```
static bool deleteAll( Foo * theElement ) { delete theElement; return true; }
foo_list . remove_if ( deleteAll );
```
I think we can trust the folks who came up with STL to have efficient algorithms. Why reinvent the wheel? | For `std::list<T*>` use:
```
while(!foo.empty()) delete foo.front(), foo.pop_front();
```
For `std::vector<T*>` use:
```
while(!bar.empty()) delete bar.back(), bar.pop_back();
```
Not sure why i took `front` instead of `back` for `std::list` above. I guess it's the feeling that it's faster. But actually both are co... | Cleaning up an STL list/vector of pointers | [
"",
"c++",
"list",
"vector",
"stl",
""
] |
I type
```
ArrayList memberNames = new ArrayList() { "Jim", "John", "George" };
```
and Visual Studio tells me "ArrayList" cannot be found so I have to manually go to the top of the file and type
```
using System.Collections;
```
Is there a way to get Visual Studio to do this automatically?
In FlashDevelop, for in... | SHIFT-ALT-F10 Will activate the Smart Tag on the class, which will give you the options "using System.Collections", and "System.Collections.ArrayList". It's typically two keystrokes to add a using.
Edit: Seems I had a mangled keyboard profile. Updated the key combo to the default. Thanks to Alan for pointing it out. | `Alt` + `Shift` + `F10` brings up a pop-up menu with "using System.Collections", and "System.Collections.ArrayList".
If you want to find a keyboard shortcut, choose Tools: Options and navigate down to Environment: Keyboard. However, it can be a challenge to figure out what they've called the thing you're looking for. ... | Contextual code generation in Visual C# 2008? | [
"",
"c#",
".net",
"visual-studio",
""
] |
Does anyone know whether the iPhone supports or will soon support the [W3C Geolocation specification](http://dev.w3.org/geo/api/spec-source.html)?
I'm looking to build an app for mobile users, but rather than spend the time developing apps for every different platform (iPhone, Android, etc...), I'd much prefer to crea... | This code worked for me -- on the iPhone web browser **Safari** *and* as an added bonus it even worked with **FireFox 3.5** on my laptop! The Geolocation API Specification is part of the W3 Consortium’s standards **But be warned: it hasn’t been finalized as yet.**
[](htt... | You can now get location from Javascript APIs in the safari browser following the iPhone 3.0 release - we've created a working example @ <http://blog.bemoko.com/2009/06/17/iphone-30-geolocation-javascript-api/> | Geolocation API on the iPhone | [
"",
"javascript",
"iphone",
"geolocation",
"gps",
""
] |
I am building an ObjectQuery like this:
```
string query = "select value obj from Entities.Class as obj " +
"where obj.Property = @Value";
ObjectQuery<Class> oQuery = new ObjectQuery<Class>(query, EntityContext.Instance);
oQuery.Parameters.Add(new ObjectParameter("Value"... | `ObjectQuery<T>` implements `IQueryable<T>`, so can't you simply use the extension method:
```
int count = oQuery.Count();
```
What happens if you execute this? I would have expected the overall query to just do a Count()... (not that I've done much EF...). | The ObjectQuery<T> class implements the IEnumerable<T> interface, which supports the Count() method.
What do you get from this?
```
int count = oQuery.Count();
``` | How to count how many objects will be returned by an ObjectQuery<T>? | [
"",
"c#",
"entity-framework",
""
] |
I have snippets of Html stored in a table. *Not entire pages, no tags or the like, just basic formatting.*
I would like to be able to display that Html as text only, *no formatting*, on a given page (actually just the first 30 - 50 characters but that's the easy bit).
How do I place the "text" within that Html into a... | If you are talking about tag stripping, it is relatively straight forward if you don't have to worry about things like `<script>` tags. If all you need to do is display the text without the tags you can accomplish that with a regular expression:
```
<[^>]*>
```
If you do have to worry about `<script>` tags and the li... | The MIT licensed [HtmlAgilityPack](https://github.com/linezero/HtmlAgilityPack) has [in one of its samples](https://github.com/ceee/ReadSharp/blob/master/ReadSharp/HtmlUtilities.cs) a method that converts from HTML to plain text.
```
var plainText = HtmlUtilities.ConvertToPlainText(string html);
```
Feed it an HTML s... | How do you convert Html to plain text? | [
"",
"c#",
"asp.net",
"html",
""
] |
What's the difference between [`java.lang.ref.WeakReference`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ref/WeakReference.html) and [`java.lang.ref.SoftReference`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ref/SoftReference.html) ? | From [Understanding Weak References](https://web.archive.org/web/20061130103858/http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html), by Ethan Nicholas:
> **Weak references**
>
> A *weak reference*, simply put, is a
> reference that isn't strong enough to
> force an object to remain in memory.
... | Weak references are collected eagerly. If GC finds that an object is
weakly reachable (reachable only through weak references), it'll clear the
weak references to that object immediately. As such, they're good for
keeping a reference to an object for which your program also keeps
(strongly referenced) "associated infor... | What's the difference between SoftReference and WeakReference in Java? | [
"",
"java",
"reference",
"weak-references",
"soft-references",
""
] |
This should be easy for many of you, but for me it's just another bit of rust needing to be chipped away as I get back into basic Java coding. Using bloody associative arrays for so long in other languages have turned me nice and spoiled. :P
My problem is simple: I'm storing a set of objects, each containing a string ... | there is a great [writeup on java collections](http://java.sun.com/docs/books/tutorial/collections/index.html) which covers most of your needs.
short advice concerning this: use a [TreeMap](http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html)(Comparator c) with a custom Comparator.
key ist the string, value... | That sound like a [SortedMap](http://java.sun.com/j2se/1.4.2/docs/api/java/util/SortedMap.html). With the String as the key and the Number as the value. | Data Structure Brushup (Java) | [
"",
"java",
"data-structures",
""
] |
I want to test some PHP on my local machine running Windows XP Professional. I'm familiar with coding PHP for upload, but not with running a web server.
**What is the easiest way to set up a test environment?** Step-by-step instructions would be great if you can give them.
(I see WAMP recommended in [this thread](htt... | [](https://i.stack.imgur.com/8PuYL.gif)
(source: [apachefriends.org](http://www.apachefriends.org/images/1240.jpg))
[Xampp](http://www.apachefriends.org/en/xampp.html) is the simplest. You can setup everything in a Step by Step and if you require further configuration ... | [XAMPP from ApacheFriends](http://www.apachefriends.org/en/xampp.html) is pretty simple to set up and use.
**note** the site appears to be down as at 15:02 UTC on 3rd Dec 2008
**note again** and it is back! | What's the easiest way to test PHP in Windows XP Professional? | [
"",
"php",
"testing",
"windows-xp",
""
] |
What is the proper way to load a `ListBox` in C# .NET 2.0 Winforms?
I thought I could just bind it to a `DataTable`. No such luck.
I thought I could bind it with a `Dictionary`. No luck.
Do I have to write an class called `KeyValuePair`, and then use `List<KeyValuePair>` just to be able to load this thing with obje... | Simple code example. Say you have a `Person` class with 3 properties. `FirstName`, `LastName` and `Age`. Say you want to bind your listbox to a collection of `Person` objects. You want the display to show the first name, but the value to be the age. Here's how you would do it:
```
List<Person> people = new List<Person... | You can [bind a DataTable](http://www.codeproject.com/KB/database/scomlistcontrolbinding.aspx) directly...
```
listbox.ValueMember = "your_id_field";
listbox.DisplayMember = "your_display_field";
listbox.DataSource = dataTable;
``` | What is the proper way to load up a ListBox? | [
"",
"c#",
".net",
"winforms",
""
] |
In SQL server 2005 this query
```
select len(cast('the quick brown fox jumped over the lazy dog' as varchar))
```
returns 30 as length while the supplied string has more characters. This seems to be the default. Why 30, and not 32 or any other power of 2?
**[EDIT]** I am aware that I should always specifiy the lengt... | Why don't you specify the varchar length? ie:
```
SELECT CAST('the quick brown fox jumped over the lazy dog' AS VARCHAR(45))
```
As far as why 30, that's the default length in SQL Server for that type.
From [char and varchar (Transact-SQL)](http://msdn.microsoft.com/en-us/library/ms176089.aspx):
> When n is not spe... | On your question as to why 30 and not 32 or any other power of 2, the storage size is n + 2 bytes for varchar(n), which makes the byte storage size 32 for a string of length 30. Might be that this is what they looked at?
Then just a point of clarity on some of the comments: The default length for an unspecified length... | Why is 30 the default length for VARCHAR when using CAST? | [
"",
"sql",
"sql-server",
"casting",
""
] |
I've been looking for some guidelines on how to layout PHP code. I've found some good references, such as the following:
<http://www.dagbladet.no/development/phpcodingstandard/>
and [this question](https://stackoverflow.com/questions/5214/whats-a-good-standard-code-layout-for-a-php-application) on SO.
However, none ... | There's really not a single, common standard for these things. Most languages are more restrictive than PHP in this sense.
In the later years, a lot of so-called frameworks have emerged, and amongst other things they define a set of rules for everything from naming over where to place files and to which style your cod... | Combining programming code and output data (including HTML) is IMHO a very bad idea. Most of the PHP gurus I know use a template engine such as [Smarty](http://www.smarty.net/) to help keep the two things separate. | PHP coding standards | [
"",
"php",
"coding-style",
""
] |
I have a legacy MS Access 2007 table that contains 52 fields (1 field for each week of the year) representing historical sales data (plus one field for the year actually). I would like to convert this database into a more conventional Time/Value listing.
Does anyone knows how to do that without writing queries with 52... | [Using PIVOT and UNPIVOT](http://msdn.microsoft.com/en-us/library/ms177410%28SQL.90%29.aspx).
> `UNPIVOT` performs almost the reverse
> operation of `PIVOT`, by rotating
> columns into rows. Suppose the table
> produced in the previous example is
> stored in the database as `pvt`, and you
> want to rotate the column i... | As mentioned above, UNPIVOT operator, if available, will do this... If this is not available, then std SQL approach is:
Union multiple select statments (One for each week) that alias the specific week's column with the same column name alias
```
Select 1 as week, Week1Val as value from Table
UNION
Select 2 as... | How to convert fields into rows through SQL in MS Access 2007 or MS SQL Server 2005 | [
"",
"sql",
"sql-server",
"ms-access",
"pivot",
""
] |
If I generate an exception on my own, I can include any info into the exception: a number of code line and name of source file. Something like this:
```
throw std::exception("myFile.cpp:255");
```
But what's with unhandled exceptions or with exceptions that were not generated by me? | It seems everyone is trying to improve your code to throw exceptions in your code, and no one is attempting the actual question you asked.
Which is because it can't be done. If the code that's throwing the exception is only presented in binary form (e.g. in a LIB or DLL file), then the line number is gone, and there's... | A better solution is to use a custom class and a macro. :-)
```
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
class my_exception : public std::runtime_error {
std::string msg;
public:
my_exception(const std::string &arg, const char *file, int line) :
std::runtime_error(arg)... | How to know the exact line of code where an exception has been caused? | [
"",
"c++",
"exception",
""
] |
I saw this the other day (scroll *all the way* down to see some of the clever stuff):
> <http://www.mono-project.com/docs/tools+libraries/tools/repl/>
And wondered whether something like this exists for Python.
So, is there a good Python GUI shell that can do stuff like that C# shell can do?
Edit: Here are links to... | One project I'm aware of that provides similar features (inline plotting, customisable rendering) is [Reinteract](http://fishsoup.net/software/reinteract/). Another (though possibly a bit heavyweight for general usage) is [SAGE](http://www.sagemath.org/) which provides functionality for web-based [notebooks](http://www... | Have you looked at [ipython](http://ipython.scipy.org/moin/)? It's not quite as "gui". No smileys, sorry. ;-) It is a pretty good interactive shell for python though.
edit: I see you revised your question to emphasize the importance **GUI**. In that case, IPython wouldn't be a good match.
Might as well save you anoth... | Is there a good Python GUI shell? | [
"",
"python",
"shell",
"user-interface",
""
] |
I need to find whether the user clicking the browser back button or Refresh button.
I need to redirect the page to Error page when he clicks the back or refresh button. How to do this.
I need to do this in javascript for my ASP.net page | First of all, giving error messages if users use Back or have to refresh a page for whatever reason, is a really bad idea. Instead, you should transparently deal with that. Think about a page not coming up fully because of problems on the transportation level - the only option the user has is to reload or go back.
To ... | You can't. The browser doesn't send it's own ui events to the server. All you get are http requests and one looks pretty much like another. Maybe the clicked the back button or maybe they just retyped the last url in. Tell us what problems it's causing and we can help you adapt your project to work with the http protoc... | How to find whether the user clicks browser back button or Refresh button | [
"",
"javascript",
"asp.net",
"browser",
"back-button",
""
] |
I would like to replace ">" with ">" and "<" with "<" but only when they occur outside "<pre>" and "</pre>". Is this possible?
```
$newText = preg_replace('>', '>', $text);
```
I would be using the preg\_replace in PHP as above. | If you want to do this with a regex, the trick is to make your regex match the things you don't want to replace as well as the things you want to replace, and dynamically calculate the replacement depending on what was matched.
```
$new_text = preg_replace_callback('%<|>|<pre>.*?</pre>%si', compute_replacement, ... | This isn't really an answer because you asked for a regex, but I just wrote a really dirty function to do it:
```
<?php
$html = ' <pre>hello > <</pre>
> <
<pre></pre>';
function stringReplaceThing($str) {
$offset = 0;
$num = 0;
$preContents = array();
$length = st... | Regex to replace text only when occurs outside of two strings? | [
"",
"php",
"regex",
""
] |
I have data from a table in a database (string) that contain text and price. I extract the price from the data but my problem is that sometime I can Convert it to float and sometime not.
I have noticed that :
```
Convert.ToSingle(m.Groups[1].Value);
```
It works but not always because sometime the period is the prob... | You have this problem because the conversion check the language of your PC. You will need to do something like :
```
Convert.ToSingle(m.Groups[1].Value, CultureInfo.InvariantCulture.NumberFormat);
```
This ways, it won't check the language of the PC. You can find more information about [InvariantCulture](http://msdn.... | Or ask for this specific number format explicitly:
```
System.Globalization.NumberFormatInfo nf
= new System.Globalization.NumberFormatInfo ( )
{
NumberGroupSeparator = "."
};
float f = float.Parse ( "5.34534", nf );
``` | Convert Float that has period instead of comma? | [
"",
"c#",
".net",
".net-2.0",
""
] |
Java 1.5, Linux
I do have a screen which contains different textareas and textfields.
I do have acess to the application frame, but not to the components inside the frame, because i only get an implementation of an interface.
When i try to add german umlauts i see a rectangle in the text component, because the charac... | It sounds like a character encoding problem or font problem... Like using "windows" encoding in a Linux environment. You should check the following:
* Can you write those characters in a normal texteditor in your linux distro?
* Are those characters from input files in your java application or is it from the source, i... | My guess is that the desktop (KDE or Gnome) is configured to use a font which doesn't contain umlauts (kind of strange, today, but it happens). Java usually tries to use the system font as a basis to calculate the "Dialog" font (which is always available even if it is not installed; "Dialog" is a virtual font name whic... | TextField "umlauts" are not shown on linux | [
"",
"java",
"linux",
"unix",
"unicode",
"encoding",
""
] |
I have to transform a few hundred images every day in a specific way.
I need the best freeware tool or a piece of C# code that supports batch watermarking, resizing of images and can be automated (old configuration can be reused).
What tool do you suggest? | Dave Winer of [scripting.com](http://scripting.com/) fame has been posting about his success with [ImageMagick](http://www.imagemagick.org/script/index.php). I think its free. | [IrfanView](http://www.irfanview.com/) has pretty decent batch image processing/conversion support. | Batch process images | [
"",
"c#",
"image",
"batch-processing",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.