Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
When overriding the equals() function of java.lang.Object, the javadocs suggest that,
> it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
The hashCode... | It doesn't say the hashcode for an object has to be completely unique, only that the hashcode for two equal objects returns the same hashcode. It's entirely legal to have two non-equal objects return the same hashcode. However, the more unique a hashcode distribution is over a set of objects, the better performance you... | I won't go in to the details of hashCode uniqueness as Marc has already addressed it. For your `People` class, you first need to decide what equality of a person means. Maybe equality is based solely on their name, maybe it's based on name and age. It will be domain specific. Let's say equality is based on name and age... | How to ensure hashCode() is consistent with equals()? | [
"",
"java",
"object",
"equals",
"hashcode",
""
] |
I'm trying to write a small wsgi application which will put some objects to an external queue after each request. I want to make this in batch, ie. make the webserver put the object to a buffer-like structure in memory, and another thread and/or process for sending these objects to the queue in batch, when buffer is bi... | Examine <https://docs.python.org/library/queue.html> to see if it meets your needs. | Since you write "thread and/or *process*", see also [multiprocessing.Queue and multiprocessing.JoinableQueue](http://docs.python.org/library/multiprocessing.html#pipes-and-queues) from 2.6. Those are interprocess variants of Queue. | Implementing a buffer-like structure in Python | [
"",
"python",
"multithreading",
"data-structures",
"message-queue",
""
] |
What language is Sun's `JVM` written in? | Sun actually has multiple JVMs. The [HotSpot JVM](http://OpenJDK.Java.Net/groups/hotspot/) is written largely in C++, because HotSpot is heavily based on the [Animorphic Smalltalk VM](http://Strongtalk.Org/) which is [written in C++](http://Code.Google.Com/p/strongtalk/source/browse/#svn/trunk/vm).
More interesting th... | Strictly speaking, C++ (the JVM code does make use of C++ OO facilities). | What is Java written in? | [
"",
"java",
"jvm",
""
] |
Is there a way I can write text to a file from a certain point in the file?
For example, I open a file of 10 lines of text but I want to write a line of text to the 5th line.
I guess one way is to get the lines of text in the file back as an array using the readalllines method, and then add a line at a certain index ... | Oh, sigh. Look up the "master file update" algorithm.
here's pseudocode:
```
open master file for reading.
count := 0
while not EOF do
read line from master file into buffer
write line to output file
count := count + 1
if count = 5 then
write added line to output file
fi
od
rename outpu... | If you're reading/writing small files (say, under 20 megabytes--yes I consider 20M "small") and not writing them that often (as in, not several times a second) then just read/write the whole thing.
Serial files like text documents aren't designed for random access. That's what databases are for. | Writing text to the middle of a file | [
"",
"c#",
""
] |
What are some of the biggest design flaws in C# or the .NET Framework in general?
Example: there is no non-nullable string type and you have to check for DBNull when fetching values from an IDataReader. | I agree emphatically with [this post](https://stackoverflow.com/questions/411906/c-net-design-flaws/413093#413093) (for those poo-pooing the lack of ToString, there is a debugger attribute to provide a custom format for your class).
On top of the above list, I would also add the following reasonable requests:
1. non-... | * the `Reset()` method on `IEnumerator<T>` was a mistake (for iterator blocks, the language spec even *demands* that this throws an exception)
* the reflection methods that return arrays were, in Eric's view, [a mistake](http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx)
* arr... | C# (.NET) Design Flaws | [
"",
"c#",
".net",
""
] |
Which one is recommended considering readability, memory usage, other reasons?
**1.**
```
String strSomething1 = someObject.getSomeProperties1();
strSomething1 = doSomeValidation(strSomething1);
String strSomething2 = someObject.getSomeProperties2();
strSomething2 = doSomeValidation(strSomething2);
String strSomeRe... | I would probably go in-between:
```
String strSomething1 = doSomeValidation(someObject.getSomeProperties1());
String strSomething2 = doSomeValidation(someObject.getSomeProperties2());
someObject.setSomeProperties(strSomething1 + strSomething2);
```
Option #2 seems like a lot to do in one line. It's readable, but take... | I'd go with:
```
String strSomething1 = someObject.getSomeProperties1();
String strSomething2 = someObject.getSomeProperties2();
// clean-up spaces
strSomething1 = removeTrailingSpaces(strSomething1);
strSomething2 = removeTrailingSpaces(strSomething2);
someObject.setSomeProperties(strSomething1 + strSomething2);
``... | What is preferred option for assignment and formatting? | [
"",
"java",
"optimization",
"refactoring",
"coding-style",
""
] |
I have been tasked with creating a program what will create take files in specified folders and create an installer based on those files.
For example, having a folder for "All User's Desktop", "Start menu", "Application Data", and "Program Files"
My boss wants to put the files into each folder, then click a button an... | I know it goes completely against what you're asking for, but depending on your usage it'd probably be many times more efficient to just buy a product that creates windows installers. Installer software does so much more, and if you build something with limited functionality now the chances are that your boss will then... | Well, with C# on its own an VS2005 its going to be hard.
But you could use [WiX](http://wix.sourceforge.net/) as way to go, complete the XML for the installer with c# and build it from your tool using candle and light from the wix-toolkit. | C# Generic Setup Wizard | [
"",
"c#",
"windows-installer",
""
] |
I'm interested in how much up front validation people do in the Python they write.
Here are a few examples of simple functions:
```
def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def sum(nums):
"""Sa... | For calculations like sum, factorial etc, pythons built-in type checks will do fine. The calculations will end upp calling **add**, **mul** etc for the types, and if they break, they will throw the correct exception anyway. By enforcing your own checks, you may invalidate otherwise working input. | I `assert` what's absolutely essential.
Important: What's *absolutely* essential. Some people over-test things.
```
def factorial(num):
assert int(num)
assert num > 0
```
Isn't completely correct. long is also a legal possibility.
```
def factorial(num):
assert type(num) in ( int, long )
assert num ... | How much input validation should I be doing on my python functions/methods? | [
"",
"python",
"validation",
""
] |
I have the following code, which will not work. The javascript gives no errors and appears to load fine. but clicking on a link will do nothing. An example of a link is:
```
<a href="#" onclick="updateByQuery('Layer3', "Ed Hardy");">Link 1</a><li>Link 2</li>
```
and the code:
```
var xmlHttp
var layername
var url
fu... | It may probably be due to the double-quote characters surrounding 'Ed Hardy'. Does this work:
```
<a href="#" onclick="updateByQuery('Layer3', 'Ed Hardy');">Link 1</a><li>Link 2</li>
``` | From the wonderful [JSLint](http://jslint.com)
You are missing semicolons after these
```
var xmlHttp
var layername
var url
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
document.getElementById(layer).innerHTML=xmlHttp.responseText;
... | javascript wont load, no clear error | [
"",
"javascript",
""
] |
I would like to parse a document using SAX, and create a subdocument from some of the elements, while processing others purely with SAX. So, given this document:
```
<DOC>
<small>
<element />
</small>
<entries>
<!-- thousands here -->
</entries>
</DOC>
```
I would like to parse the DOC... | One approach is to create a `ContentHandler` that watches for events that signal the entry or exit from a `<small>` element. This handler acts as a proxy, and in "normal" mode passes the SAX events straight through to the "real" `ContentHandler`.
However, when entry into a `<small>` element is detected, the proxy is r... | Seems to me the answer depends on whether you need the 'new document' in memory. If you do then use DOM, alternatively if you're just going to stream the 'new document' then StAX would probably fit better with the event-driven nature of SAX. | Nesting SAX ContentHandlers | [
"",
"java",
"xml",
"dom",
"parsing",
"sax",
""
] |
I have a bunch of Spring beans which are picked up from the classpath via annotations, e.g.
```
@Repository("personDao")
public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao {
// Implementation omitted
}
```
In the Spring XML file, there's a [PropertyPlaceholderConfigurer](http://static.springf... | You can do this in Spring 3 using EL support. Example:
```
@Value("#{systemProperties.databaseName}")
public void setDatabaseName(String dbName) { ... }
@Value("#{strategyBean.databaseKeyGenerator}")
public void setKeyGenerator(KeyGenerator kg) { ... }
```
`systemProperties` is an implicit object and `strategyBean` ... | Personally I love this new way in Spring 3.0 [from the docs](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/new-in-3.html):
```
private @Value("${propertyName}") String propertyField;
```
No getters or setters!
With the properties being loaded via the config:
```
<bean class="org.s... | How can I inject a property value into a Spring Bean which was configured using annotations? | [
"",
"java",
"spring",
"dependency-injection",
""
] |
This is driving me nuts. I am using some 3rd-party code in a Windows .lib that, in debug mode, is causing an error similar to the following:
```
Run-Time Check Failure #2 - Stack around the variable 'foo' was corrupted.
```
The error is thrown when either the object goes out of scope or is deleted. Simply allocating ... | OK, I tracked the problem down and it's a cracker, if anyone's interested. Basically, my .LIB, which exhibited the problem. had defined `_WIN32_WINNT` as `0x0501` (Windows 2000 and greater), but my EXE and the 3rd-party LIB had it defined as `0x0600` (Vista). Now, one of the headers included by the 3rd-party lib is `ss... | One possibility is that it's a [calling convention](http://en.wikipedia.org/wiki/Calling_convention) mismatch - make sure that your libraries and executables are all set to use the same default calling convention (usually \_\_cdecl). To set that, open up your project properties and go to **Configuration Properties > C/... | Trouble tracking down a potential memory overwrite. Windows weirdness | [
"",
"c++",
"windows",
""
] |
How can I build a numpy array out of a generator object?
Let me illustrate the problem:
```
>>> import numpy
>>> def gimme():
... for x in xrange(10):
... yield x
...
>>> gimme()
<generator object at 0x28a1758>
>>> list(gimme())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numpy.array(xrange(10))
array([0, 1, 2, 3, 4, 5,... | Numpy arrays require their length to be set explicitly at creation time, unlike python lists. This is necessary so that space for each item can be consecutively allocated in memory. Consecutive allocation is the key feature of numpy arrays: this combined with native code implementation let operations on them execute mu... | One google behind this stackoverflow result, I found that there is a [`numpy.fromiter(data, dtype, count)`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromiter.html). The default `count=-1` takes all elements from the iterable. It requires a `dtype` to be set explicitly. In my case, this worked:
`numpy.... | How do I build a numpy array from a generator? | [
"",
"python",
"numpy",
"generator",
""
] |
I've been reading Bruce Eckel's [Thinking In Java](http://www.mindview.net/Books/TIJ/) and in the chapter on generics, he briefly mentions the [Nice programming language](http://nice.sourceforge.net/index.html) as something that handles parametrized types better than Java, but compiles into Java bytecode.
Does anyone ... | I'd also suggest looking at [Scala](http://www.scala-lang.org/), a multi-paradigm (OO and functional) language that runs on the JVM. Martin Odersky, the "father of Scala" was also a primary contributor to the implementation of generics in Java, including his work on the Pizza and GJ implementations.
The current type-e... | Maybe the question to ask is, "Why do generics make your head hurt?" How are you using them that causes such pain?
I'll agree that there are flaws with generics in Java, and there are situations (e.g., extends) that do cause problems, but what exactly is your issue?
Using another language that compiles to byte code m... | the Nice programming language as an alternative to Java generics | [
"",
"java",
"generics",
"nice-language",
""
] |
Is that possible to have a single PHP SOAP server which will handle requests to several classes (services)?
If yes, could you please show an example implementation?
If not, could you please describe why? | Could you wrap the other services in a single class? Completely untested, it was just a thought...
```
class MySoapService
{
public function __construct()
{
$this->_service1 = new Service1();
$this->_service2 = new Service2();
}
// You could probably use __call() here and intercept any calls,
// ... | If both classes had methods with identical names (but different parameters) then you could use func\_get\_args() to analyze the arguments and differentiate between the methods that way.
If they take the same arguments... then you're kinda stuck.
Why can't you just use two separate Web Services? | Handle requests to several classes within the same PHP SOAP server | [
"",
"php",
"web-services",
"soap",
"wsdl",
""
] |
Consider the following table:
```
mysql> select * from phone_numbers;
+-------------+------+-----------+
| number | type | person_id |
+-------------+------+-----------+
| 17182225465 | home | 1 |
| 19172225465 | cell | 1 |
| 12129876543 | home | 2 |
| 13049876543 | cell | 2 |
| 15... | In the second SQL, the condition h.type = 'home' is part of the outer join conditions, and is not a filter on the results. For all records where h.type='cell', the condition h.type = 'home' is FALSE and so no "matching" c row is found - so c.number is null, which is your only filtering (WHERE) condition.
In pseudo-cod... | When doing left joins I approach things this way. In the join you need to specify anny fields that actually link the two tables together and any filtering condition from the right side (2nd table in the join) of the join (with one exception, I'll get to shortly). Filtering conditions from the left side of the join(1st ... | self join query | [
"",
"sql",
"mysql",
"join",
"self-join",
""
] |
Hopefully, this will be an easy answer for someone with Javascript time behind them...
I have a log file that is being watched by a script that feeds new lines in the log out to any connected browsers. A couple people have commented that what they want to see is more of a 'tail -f' behavior - the latest lines will alw... | ```
x = 0; //horizontal coord
y = document.height; //vertical coord
window.scroll(x,y);
``` | To scroll the whole document use this:
```
window.scrollTo(0, document.body.scrollHeight);
```
if you have just a single scrollable div or something then the process is different:
```
var obj = $('id');
obj.scrollTop = obj.scrollHeight;
``` | Javascript mechanism to autoscroll to the bottom of a growing page? | [
"",
"javascript",
"browser",
"scroll",
""
] |
Wish to simultaneously call a function multiple times. I wish to use threads to call a function which will utilize the machines capability to the fullest. This is a 8 core machine, and my requirement is to use the machine cpu from 10% to 100% or more.
My requirement is to use the boost class. Is there any way I can ac... | I suggest that you read up on the documentation for the functions you use. From your comment in James Hopkin's answer, it seems like you don't know what boost::bind does, but simply copy-pasted the code.
boost::bind takes a function (call it f), and optionally a number of parameters, and returns a function which, when... | You're binding parameters to functions that don't take parameters:
```
int threadedAPI1( );
boost::bind(&threadedAPI1,0)
```
Just pass the function directly if there are no parameters:
```
threads.schedule(&threadedAPI1)
``` | Multithreading using the boost library | [
"",
"c++",
"multithreading",
"boost-thread",
"boost-bind",
""
] |
I am looking at improving a package that I believe not to be threadsafe when its input is shared between multiple worker threads. According to TDD principles, I should write some tests that fail in the first instance, and these would certainly be useful in assessing the problem.
I realise that this is not a simple thi... | Forget getting good results by testing for concurrency problems. Attempt to reduce synchronization and make the problem smaller. Then use as high as possible library support to do synchronization. And only if you really have then try to handle the concurrency yourself. When you know each worker does its work correct an... | [Java Concurrency in Practice](http://jcip.net/) has some great information about how to write tests for concurrency issues. However they are not true unit tests. It is nearly impossible to write a true unit test for a concurrency issue.
Basically it boils down to this. Create a bunch of test threads and start them. E... | Any satisfactory approaches to unit testing thread safety in Java? | [
"",
"java",
"multithreading",
"thread-safety",
""
] |
I am currently writing some unit tests for a business-logic class that includes validation routines. For example:
```
public User CreateUser(string username, string password, UserDetails details)
{
ValidateUserDetails(details);
ValidateUsername(username);
ValidatePassword(password);
// create and retu... | Every test should only fail for one reason and only one test should fail for that reason.
This helps a lot with writing a maintainable set of unit tests.
I'd write a couple of tests each for ValidateUserDetails, ValidateUsername and ValidateUserPassword. Then you only need to test that CreateUser calls those function... | You definitely need to test *validation* methods.
There is no need to test other methods for all possible combinations of arguments just to make sure validation is performed.
You seem to be mixing Validation and Design by Contract.
**Validation** is usually performed to friendly notify user that his input is incorre... | Unit-tests and validation logic | [
"",
"c#",
".net",
"unit-testing",
"validation",
"tdd",
""
] |
I was wondering which was better:
```
$lookup = array( "a" => 1, "b" => 2, "c" => 3 );
return $lookup[$key];
```
or
```
if ( $key == "a" ) return 1
else if ( $key == "b" ) return 2
else if ( $key == "c" ) return 3
```
or maybe just a nice switch...
```
switch($key){
case "a": return 1;
case "b": return 2;
case "c"... | For anything with measurable performance (not only 3 entries) lookup is fastest way. That's what hash tables are for. | First, it's easy to test it yourself.
Second, and more importantly, which is most appropriate for the code you're using? The amount of time you'll save is negligible in any case. | What's quicker, an array lookup (including array build) or an IF stack? | [
"",
"php",
""
] |
Are there any what in the Java community would be called "application servers" for .NET? Similar to Tomcat, Resin, and Jetty. I'm not interested in a JSP equivalent, I'm looking for a servlet-based technology for XML/HTTP transaction processing (no UI).
If there is not a product like this, what would a good stack be t... | [WCF](http://msdn.microsoft.com/en-us/netframework/aa663324.aspx) or web services (ASMX) both seem like good candidates for what you want. WCF is probably more appropriate if you don't want to go the full SOAP route. You can host WCF in IIS, a console app, or a windows service. Depending on what you need it can use SOA... | [Dublin](http://www.microsoft.com/net/Dublin.aspx) will be what you’re looking for, I guess. | Is there a .NET analogue for Java app servers? | [
"",
"java",
".net",
"servlets",
""
] |
I am using hudson CI to manage a straight java web project, using ant to build.
I would like to mandate that the unit test coverage never be worse than the previous build, thereby making sure any new code is always tested, or at least the coverage is continually improving.
Is there a hudson plugin that works this way... | Yes. Which coverage tool are you using?
The Cobertura plugin for Hudson definitely supports this. On the project configuration screen you can specify thresholds.
Alternatively, you can make Ant fail the build (rather than Hudson), by using the cobertura-check task.
**EDIT:** I'm not sure you can do precisely what yo... | This is kind of a hack, but we use it for similar reasons with Findbugs and Checkstyle. You can set up an Ant task to do the following (this can be split out into multiple tasks, but I'm combining them for brevity):
1. Run tests with coverage
2. Parse the coverage results and get the coverage percentage
3. Read tmp/la... | Can my build stipulate that my code coverage never get worse? | [
"",
"java",
"hudson",
"code-coverage",
"continuous-integration",
""
] |
```
var insInvoice = new NpgsqlCommand(
@"INSERT INTO invoice_detail(
invoice_id,
invoice_detail_id,
product_id,
qty,
price,
amount)
VALUES (
:_invoice_id,
:_invoice_detail_id,
:_product_id,
:_qty,
:_price,
:_qty * :_price)", c);
with(var p = insInvoice.Paramete... | As you've got an "Add" method with the right form, you can use a collection initialiser for the parameters:
```
var insInvoice = new NpgsqlCommand(sql)
{
Parameters =
{
{ "_invoice_id", NpgsqlDbType.Uuid, 0, "invoice_id" },
{ "_invoice_detail_id", NpgsqlDbType.Uuid, 0, "invoice_detail_id" },
... | What's the point of it, to scope the "p" variable?
In that case just create a scope with curly braces and remove the with-statement all together, move the variable declaration of "p" into the new scope. This way the "p" variable is only available within the scope of the curly braces. This you can do today without need... | if the with keyword is bad (for C#), is this a nice alternative? | [
"",
"c#",
"syntactic-sugar",
""
] |
Hi im learning LISP and well, all day i program php for a living, so i was messing around with php.net and found the eval function... so i started playing around!
I would love to know more about how to use eval to do crazy stuff, i know you can make functions with this and everything... but i wanted to ask why the nex... | Your statement comes out to 'eval("eval("echo"FOZZ";");")'. Your double quotes are interfering with each other and causing the error.
You might want to try changin the first line to $var = "echo \'FOZZ\';";
Note: Please be careful using eval. | For the common case of web programming Ive developed a library called xilla\_tags that makes it easy to write lisp-flavoured PHP code, which can be much more readable that the traditional approach.
For xilla\_tags see [xilla tags sample](http://quantblog.wordpress.com/2009/10/01/xilla_tags-php-library-make-html-with-l... | Php and macros(lisp style)? | [
"",
"php",
"macros",
"eval",
""
] |
I am trying to return an array Data Member from one smaller 2D Array Object, and trying to insert the array into a larger 2D array object. But when attempting this, I came into two problems.
First problem is that I want to return the name of the 2D array, but I do not know how to properly syntax to return 2D Array nam... | When passing your array around, you have to decide whether or not you want to make a copy of the array, or if you just want to return a pointer to the array. For returning arrays, you can't (easily) return a copy - you can only return a pointer (or reference in C++). For example:
```
// Piece::returnPiece is a functio... | It seems like you need to read up more on pointers in C++ and on pass by reference vs. pass by value.
Your returnPiece method is defined as returning the value of a single cell. Given the index (e.g., [4][4]) you return a copy of the contents of that cell, so you won't be able to change it, or more correctly, changing... | C++ Returning and Inserting a 2D array object | [
"",
"c++",
"arrays",
"syntax",
"2d",
""
] |
I am considering releasing one of my class libraries written in C# as open source. Before doing that, I am trying to do some refactoring so that it meets the demands of the general public :)
I wonder what would be the best namespace schema to use? Basically, I see the following options:
* namespace **MyTool**: This j... | I'd go with something like:
```
namespace OpenSourceProjectCodeName.MajorFunctionalArea
```
For example:
```
namespace VideoWizardMagicThing.Audio
namespace VideoWizardMagicThing.Audio.Codecs
namespace VideoWizardMagicThing.Video
namespace VideoWizardMagicThing.Video.Codecs
```
You don't have to go completely mad w... | **`MyTool`** has the problem that names aren't unique; you’re heading for name conflicts. **`MyCompany.MyTool`** doesn’t apply in your case if you don’t want to give yourself some label.
I actually rather like the Java convention of reversing the URI associated with the product. For companies, this is the company webs... | C# Open Source Project Namespace | [
"",
"c#",
".net",
"open-source",
"namespaces",
""
] |
I'd like to periodically run an arbitrary .NET exe under a specified user account from a Windows Service.
So far I've got my windows service running with logic to decide what the target process is, and when to run it.
The target process is started in the following manner:
1. The Windows Service is started using "admi... | I seem to have a working implementation (Works On My Machine(TM)) for the following scenarios:
Batch File, .NET Console Assembly, .NET Windows Forms application.
Here's how:
I have a windows service running as the Administrator user.
I add the following policies to the Administrator user:
* Log on as a service
* Ac... | Just a guess - are you using LoadUserProfile=true with the start info? CreateProcessWithLogonW does not load user registry hive by default, unless you tell it to. | Using Process.Start() to start a process as a different user from within a Windows Service | [
"",
"c#",
".net",
"windows-services",
"process",
"service",
""
] |
Lets say I have a concrete class Class1 and I am creating an anonymous class out of it.
```
Object a = new Class1(){
void someNewMethod(){
}
};
```
Now is there any way I could overload the constructor of this anonymous class. Like shown below
```
Object a = new Class1(){
void someNewMe... | From the [Java Language Specification](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9.5.1), section 15.9.5.1:
> An anonymous class cannot have an
> explicitly declared constructor.
Sorry :(
EDIT: As an alternative, you can create some final local variables, and/or include an instance initializ... | That is not possible, but you can add an anonymous initializer like this:
```
final int anInt = ...;
Object a = new Class1()
{
{
System.out.println(anInt);
}
void someNewMethod() {
}
};
```
Don't forget final on declarations of local variables or parameters used by the anonymous class, as i did it for an... | Accessing constructor of an anonymous class | [
"",
"java",
"constructor",
"overloading",
"anonymous-types",
""
] |
What is the "cleanest" way to implement an command-line UI, similar to git's, for example:
```
git push origin/master
git remote add origin git://example.com master
```
Ideally also allowing the more flexible parsing, for example,
```
jump_to_folder app theappname v2
jump_to_folder app theappname source
jump_to_fold... | [argparse](http://docs.python.org/library/argparse.html#sub-commands) is perfect for this, specifically ["sub-commands"](http://docs.python.org/library/argparse.html#sub-commands) and positional args
```
import argparse
def main():
arger = argparse.ArgumentParser()
# Arguments for top-level, e.g "subcmds.py... | The `cmd` module would probably work well for this.
Example:
```
import cmd
class Calc(cmd.Cmd):
def do_add(self, arg):
print sum(map(int, arg.split()))
if __name__ == '__main__':
Calc().cmdloop()
```
Run it:
```
$python calc.py
(Cmd) add 4 5
9
(Cmd) help
Undocumented commands:
==================... | Implementing a "[command] [action] [parameter]" style command-line interfaces? | [
"",
"python",
"command-line",
"user-interface",
""
] |
I'm writing a script in python which basically queries WMI and updates the information in a mysql database. One of those "write something you need" to learn to program exercises.
In case something breaks in the middle of the script, for example, the remote computer turns off, it's separated out into functions.
Query ... | "However, opening and closing the connection with each update seems more 'neat'. "
It's also a huge amount of overhead -- and there's no actual benefit.
Creating and disposing of connections is relatively expensive. More importantly, what's the actual reason? How does it improve, simplify, clarify?
Generally, most a... | I don't think that there is "better" solution. Its too early to think about resources. And since wmi is quite slow ( in comparison to sql connection ) the db is not an issue.
Just make it work. And then make it better.
The good thing about working with open connection here, is that the "natural" solution is to use ob... | Mysql Connection, one or many? | [
"",
"python",
"mysql",
""
] |
Is there an easy way write to a file asynchronously in Python?
I know the [file io that comes with Python](https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files) is blocking; which is fine in most cases. For this particular case, I need writes not to block the application at all, or at least as... | Twisted has [non-blocking writes on file descriptors](http://twistedmatrix.com/documents/8.1.0/api/twisted.internet.fdesc.html). If you're writing async code, I'd expect you to be using twisted, anyway. :) | As I understand things, asynchronous I/O is not quite the same as non-blocking I/O.
In the case of non-blocking I/O, once a file descriptor is setup to be "non-blocking", a `read()` system call (for instance) will return `EWOULDBLOCK` (or `EAGAIN`) if the read operation would block the calling process in order to comp... | Asynchronous file writing possible in python? | [
"",
"python",
"asynchronous",
"aio-write",
""
] |
I have a Div Tag which contains 4 child Div Tags
```
<Div id="Parent">
<div id="childOne">ChildOne </div>
<div id="childOne">ChildTwo </div>
<div id="childOne">ChildThree </div>
<div id="childOne">ChildFour </div>
</Div>
```
Now I would like to access these Child Div's using up and Down Arrow... | Are you looking for what is known as [auto-completion](http://www.javascript-examples.com/autocomplete-demo/) or suggestions? | Here's a library free solution to get you started.
You might like to add events that hide and show the div when the textbox gains or loses focus. Perhaps [esc] should clear the selection?
( I haven't tested it in ie )
```
<style>div.active{ background: red }</style>
<input type="text" id="tb">
<div id="Parent">
... | Access Div Contents using Up and Down Arrow Keys using javascript | [
"",
"javascript",
"html",
"keyboard",
""
] |
I have a generic Callback object which provides a (primitive) callback capability for Java, in the absence of closures. The Callback object contains a Method, and returns the parameter and return types for the method via a couple of accessor methods that just delegate to the equivalent methods in Method.
I am trying t... | Looking more closely at the documentation for Class.isAssignableFrom(), it specifically states that the types for a primitive do not match any class except themselves. So I will need to specifically check for == equality to Byte.TYPE, Double.TYPE, Float.TYPE, Integer.TYPE, Long.TYPE, and Short.TYPE for the return type. | Why not have the compiler do it?
```
public interface F<A, B> {
public B $(A a);
}
```
Then you can pass an `F<Double, Double>` to a method that expects an `F<? extends Number, ? extends Number>`.
**EDIT:**
You say you want to provide a single class for the type of a function with any number of arguments. This *... | Validate reflected method return type and parms in Java | [
"",
"java",
"reflection",
"types",
"closures",
"callback",
""
] |
I am building stats for my users and dont wish the visits from bots to be counted.
Now I have a basic php with mysql increasing 1 each time the page is called.
But bots are also added to the count.
Does anyone can think of a way?
Mainly is just the major ones that mess things up. Google, Yahoo, Msn, etc. | You should filter by user-agent strings. You can find a list of about 300 common user-agents given by bots here: <http://www.robotstxt.org/db.html> Running through that list and ignoring bot user-agents before you run your SQL statement should solve your problem for all practical purposes.
If you don't want the search... | You can check the User Agent string, empty strings, or strings containing 'robot', 'spider', 'crawler', 'curl' are likely to be robots.
> `preg_match('/robot|spider|crawler|curl|^$/i', $_SERVER['HTTP_USER_AGENT']));` | How to recognize bots with php? | [
"",
"php",
"bots",
"statistics",
""
] |
I would like to use java to get the source of a website (secure) and then parse that website for links that are in it. I have found how to connect to that url, but then how can i easily get just the source, preferraby as the DOM Document oso that I could easily get the info I want.
Or is there a better way to connect ... | You can get low level and just request it with a socket. In java it looks like
```
// Arg[0] = Hostname
// Arg[1] = File like index.html
public static void main(String[] args) throws Exception {
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslsock = (SSLSocket) factor... | Extremely similar questions:
* [How do I retrieve a URL from a website using Java?](https://stackoverflow.com/questions/359439/how-do-i-retrieve-a-url-from-a-web-site-using-java)
* [How do you Programmatically Download a Webpage in Java](https://stackoverflow.com/questions/238547/how-do-you-programmatically-download-a... | Get source of website in java | [
"",
"java",
"url",
""
] |
Today I was looking at some code atually from Nikhil Kothari's Facebook.NET API. I just wanted to check out how he was doing some things in there for ideas.
One of the things I came across was a Property that just seemed really weird to me.
check this out:
FacebookRequest.cs defines a property and sets it in the con... | I don't think it's odd at all. It saves the client the trouble of having to instantiate the `FacebookRequestParameterList` instance, and the `FacebookRequest` class is guaranteed that `_parameters` contains a valid instance of the `FacebookRequestParameterList` class, and isn't `null`.
It's a matter of convenience for... | The usage is perfectly valid. The class simply uses a `Dictionary<string,string>` internally and exposes that as a property. There's presumably no need to pass in a pre-baked dictionary to the constructor.
What may be better would be to expose it as `IDictionary<string,string>` instead of an instance of a concrete cla... | Exposing a null Object Instance as a Property | [
"",
"c#",
"coding-style",
""
] |
My objective is to retry an asynchronous HttpWebRequest when it fails.
When I [Abort()](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.abort.aspx) an HttpWebRequest, I cannot BeginGetResponse() again. So the only way to request again probably is recreate the HttpWebRequest object. It seems to requir... | ### It's possible!
You just need to create a new `HttpWebRequest` and copy all of the properties over to it from the old object via reflection.
Here's an **extension method** that does this:
```
/// <summary>
/// Clones a HttpWebRequest for retrying a failed HTTP request.
/// </summary>
/// <param name="original"></... | It's not possible.
An HTTPWebRequest instance represents literally one request instance (although there are edge cases where it will retry internally), and is therefore not something which can logically be repeated. It is capable of returning exactly one response (request/response being a logical pair), and although y... | How to request an aborted HttpWebRequest again? | [
"",
"c#",
".net",
"httpwebrequest",
""
] |
I have a fixed-length data file need to persistence into database. I use a XML file to define the length for the fields and use a list of FieldItem class to store the data.
```
class FieldItem
{
public string ObjectName {get; set;}
public string ObjectProperty {get; set;}
public string Ob... | RE: "What should I do if I only like my rule expression like: "Company.CompanyName = 'ABC Corp' and Product.ProductCode = 'XYZ001'"?
Map this user-friendly query: "Company.CompanyName = 'ABC Corp' **AND** Product.ProductCode = 'XYZ001'" to something that is friendly to your data structure(FieldItem):
"ObjectName = 'C... | Consider using the [FileHelpers](http://www.filehelpers.com) library to parse your file directly into regular .NET domain objects. I believe this, combined with your Dynamic Linq approach, will provide you with the syntax that you're looking for. | C# Dynamically apply evaluation rule on a collection | [
"",
"c#",
""
] |
For my Swing project, I need to support both **Java 5** and **Java 6**.
I have defined a custom `JComponent` (call it `Picture`) and, after embedding it in a `JScrollPane`, I put it in a `JPanel` that uses DesignGridLayout manager.
DesignGridLayout supports baseline alignment thanks to **swing-layout** open source lib... | I would make a subclass of Picture, perhaps called PictureJava6, which implemented the getBaselineResizeBehaviour(), and when creating instances of Picture, do:
```
public Component pictureFactory() {
if(javaVersion > "1.6") {
return new PictureJava6();
} else {
return new Picture();
}
}
``... | > how can I implement (or simulate?)
> getBaselineResizeBehavior() so that my
> class can still **compile** and run in a
> Java5 environment?
You cannot compile this method declaration with the Java 5 library because the type [Component.BaselineResizeBehaviour](http://java.sun.com/javase/6/docs/api/java/awt/Component.... | Override JComponent.getBaselineResizeBehavior() but keep Java5 compatibility | [
"",
"java",
"swing",
"baseline",
""
] |
For a newcomer to .NET Web Development and programming in general, who chooses C# as there preferred language?
Is it better to learn C# first, without trying to apply it to web development? It seems most literature for C# uses Console or Windows Forms as a learning platform. So would that be the best direction?
Or sh... | You need to understand the fundamentals of C# in order to develop anything useful, be it an ASP.NET website, windows client or web service.
I would start with some good tutorials around the basics of types, classes, methods, events and so on to get to grips with C#. C# Station has some good introductory tutorials [her... | I've helped several people go both from previous languages (like C++) as well as no experience to using C#.
Definately learn C# before you try any particular kind of development (like Web stuff). It will only confuse the newcomer.
If you already know a language, reimplementing a small application from the old languag... | C# / Web Development learning strategy | [
"",
"c#",
""
] |
Is it possible to specify my own default object instead of it being null? I would like to define my own default properties on certain objects.
For example, if I have an object foo with properties bar and baz, instead of default returing null, I'd like it to be an instance of foo with bar set to "abc" and baz set to "d... | You have to use a constructor to get that functionality. So, you can't use default.
But if your goal is to ensure a certain state of the passed type in a generic class, there may still be hope. If you want to ensure the passed type is instanti-able, use a generic constraint. The new() constraint. This ensures that the... | No you cant. Sorry. | C#: Specifying behavior for the "default" keyword when using generics | [
"",
"c#",
"generics",
""
] |
Can I call a function from lisp from a library written in c or c++? How can I extend lisp?
This is useful when you want to do some system calls or stuff like that. | It is unusual to call non-lisp code from lisp, and rarely necessary. CLX (the X11 client implementation for CL) doesn't link to the Xlib implementation but "speaks" X11 directly. On any system, your CL implementation is likely to already have excellent operating system hooks rendering this unnecessary.
That said, the ... | See [UFFI](http://uffi.b9.com/) and [CFFI](http://common-lisp.net/project/cffi/) and the [slicker Clozure FFI](http://trac.clozure.com/openmcl/wiki/OpenMclFfi) | Can I extend lisp with c++? | [
"",
"c++",
"lisp",
"extend",
""
] |
I was working with a online game website. There are some event which call a javascript function and the function have some action with callback.
something like this,
```
<input type="button" onclick="changeSomething"/>
function changeSomething() {
/// some call back, which changes something
}
```
now ... | You will never be able to get 100% protected from any technique you try. It's a losing game.
Having said that one way to get closer to your goal is to remove the onclick attribute altogether, and bind your click handler (ie "changeSomething") via javascript:
html:
```
<input id="foo" type="button" />
```
js:
```
a... | I dont think that there is anything you can do about this. The client can run whatever they want within their own browser. The only thing to do is validate everything on the server side. This is an important concept in all web programming. Client side code can be freely modified and should be treated as an additional c... | Not allowing javascript function call from the address bar | [
"",
"javascript",
"web-applications",
"web",
""
] |
I'm about to start a project where I will be the only one doing actual code and two less experienced programmers (scary to think of myself as experienced!) will be watching and making suggestions on the program in general.
Is there a good (free) system that I can use to provide documentation for classes and functions ... | I have used [epydoc](http://epydoc.sourceforge.net/) to generate documentation for Python modules from embedded docstrings. It's pretty easy to use and generates nice looking output in multiple formats. | python.org is now using [sphinx](http://sphinx.pocoo.org/) for it's documentation.
I personally like the output of sphinx over epydoc. I also feel the restructured text is easier to read in the docstrings than the epydoc markup. | Producing documentation for Python classes | [
"",
"python",
"data-structures",
"documentation",
""
] |
I'm running into an issue where granting EXECUTE permissions on a specific Stored Procedure in SQL Server 2005 is not working. Some of the testers messed around with the permissions - and found that if they also granted CONTROL permissions on the Stored Procedure - then it ran fine. They are now convinced that granting... | If the stored procedure was created using EXECUTE AS CALLER (which I believe is the default), then the caller must have all of the permissions necessary to do whatever the stored procedure does in addition to EXECUTE on the procedure.
From the SQL Server documentation for EXECUTE AS:
> CALLER Specifies the statements... | Execute should be all that is needed.
Is the stored procedure accessing a table outside of the database it is located in?
If so, try setting the appropriate user permissions on the tables the stored procedure is using outside of the same database. | Should CONTROL permission be given on a Stored Procedure in SQL Server 2005? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"permissions",
"controls",
""
] |
Are there some practical programming situations for someone to declare a class abstract when all the methods in it are concrete? | Well you could be using a template method pattern where there are multiple override points that all have default implementations but where the combined default implementations by themselves are not legal - any functional implementation must subclass.
(And yes, I dislike the template method pattern ;)) | An abstract class is a class that is declared abstract - it may or may not include abstract methods. They cannot be instantiated so if you have an abstract class with concrete methods then it can be subclassed and the subclass can then be instantiated. | Abstract class with all concrete methods | [
"",
"java",
"abstract-class",
""
] |
I'm looking for a way to serialize **generic** Python objects between a CherryPy-based server and a Python client running on a Symbian phone.. Since pyS60 doesn't implement the pickle module, how would you do it?
I know about [Cerealizer](http://home.gna.org/oomadness/en/cerealizer) but it requires you to register cla... | What's wrong with using the pickle module? | There is a json module someone wrote for PyS60. I'd simply grab that, serialize things into json and use that as the transfer method between the web/client app.
For the json lib and a decent book on PyS60:
<http://www.mobilepythonbook.org/> | Serializing a Python object to/from a S60 phone | [
"",
"python",
"serialization",
"pickle",
"pys60",
""
] |
Using [NumPy](https://numpy.org/), a matrix A has n rows and m columns, and I want add a guard ring to matrix A. That guard ring is all zero.
What should I do? Use Reshape? But the element is not enough to make a n+1 m+1 matrix.
Or etc.?
Thanks in advance
###### I mean an extra ring of cells that always contain 0 s... | Following up on your [comment](https://stackoverflow.com/questions/362489/how-do-i-add-a-guard-ring-to-a-matrix-in-numpy#362576):
```
>>> import numpy
>>> a = numpy.array(range(9)).reshape((3,3))
>>> b = numpy.zeros(tuple(s+2 for s in a.shape), a.dtype)
>>> b[tuple(slice(1,-1) for s in a.shape)] = a
>>> b
array([[0, 0... | This is a less general but easier to understand version of [Alex's answer](https://stackoverflow.com/questions/362489/how-do-i-add-a-guard-ring-to-a-matrix-in-numpy#363040):
```
>>> a = numpy.array(range(9)).reshape((3,3))
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> b = numpy.zeros(a.shape + numpy... | How do I add a guard ring to a matrix in NumPy? | [
"",
"python",
"numpy",
""
] |
I'm a NetBeans 6.5 user and am searching for a way of generating a list of methods/classes that are not used within a set project group.
I know I can right click on each method and select "Find Usages" but I'm looking for an automation to that process.
I'm willing to look at something that runs outside of netbeans, a... | Obfuscators like [proguard](http://proguard.sourceforge.net/) can shrink your jars by removing unused methods/classes. Maybe it is possible to get a verbose output which contains the list of removed (hence unused) classes/methods.
[Here](http://proguard.sourceforge.net/manual/examples.html#deadcode) you can find more ... | You can switch on the [unused code rules](http://pmd.sourceforge.net/rules/unusedcode.html) in PMD (there's a NetBeans plugin), then run PMD over a whole project. | Detecting Java Project Cruft | [
"",
"java",
"netbeans",
"refactoring",
""
] |
Do class, method and variable **names get included in the MSIL** after compiling a Windows App project into an EXE?
* For **obfuscation** - less names, harder to reverse engineer.
* And for **performance** - shorter names, faster access.
*e.g.* So if methods ARE called via name:
* Keep names **short**, better perfor... | Yes, they're in the IL - fire up [Reflector](http://www.red-gate.com/products/reflector/) and you'll see them. If they didn't end up in the IL, you couldn't build against them as libraries. (And yes, you can reference .exe files as if they were class libraries.)
However, this is all resolved once in JIT.
Keep names *... | Yes, they do. I do not think that there will be notable performance gain by using shorter names. There is no way that gain overcomes the loss of readability. | Do method names get compiled into the EXE? | [
"",
"c#",
"methods",
"performance",
"obfuscation",
"cil",
""
] |
I'm trying to make a form invisible for x amount of time in c#.
Any ideas?
Thanks,
Jon | BFree has posted similar code in the time it took me to test this, but here's my attempt:
```
this.Hide();
var t = new System.Windows.Forms.Timer
{
Interval = 3000 // however long you want to hide for
};
t.Tick += (x, y) => { t.Enabled = false; this.Show(); };
t.Enabled = true;
``` | Quick and dirty solution taking advantage of closures. No `Timer` required!
```
private void Invisibilize(TimeSpan Duration)
{
(new System.Threading.Thread(() => {
this.Invoke(new MethodInvoker(this.Hide));
System.Threading.Thread.Sleep(Duration);
this.Invoke(new Metho... | Using a Timer in C# | [
"",
"c#",
"timer",
""
] |
I've been profiling an application all day long and, having optimized a couple bits of code, I'm left with this on my todo list. It's the activation function for a neural network, which gets called over a 100 million times. According to dotTrace, it amounts to about 60% of the overall function time.
How would you opti... | Try:
```
public static float Sigmoid(double value) {
return 1.0f / (1.0f + (float) Math.Exp(-value));
}
```
**EDIT:** I did a quick benchmark. On my machine, the above code is about 43% faster than your method, and this mathematically-equivalent code is the teeniest bit faster (46% faster than the original):
```... | If it's for an activation function, does it matter terribly much if the calculation of e^x is completely accurate?
For example, if you use the approximation (1+x/256)^256, on my Pentium testing in Java (I'm assuming C# essentially compiles to the same processor instructions) this is about 7-8 times faster than e^x (Ma... | Math optimization in C# | [
"",
"c#",
"optimization",
"neural-network",
"performance",
""
] |
I have a stored procedure in my database that calculates the distance between two lat/long pairs. This stored procedure is called "DistanceBetween". I have a SQL statement allows a user to search for all items in the Items table ordered by the distance to a supplied lat/long coordinate. The SQL statement is as follows:... | There are basically three approaches that can be used, some of which have already been discussed:
1. Use an HQL query or `CreateCriteria`/`ICriteria` query; *downsides:* it is not part of the entities/DAL; *upsides:* it is flexible;
2. Use a property mapping with a `formula`; *downsides:* it is not always feasible or ... | You could try:
```
session.CreateSqlQuery(@"SELECT {item.*}, dbo.DistanceBetween(:lat1, :lat2, {item}.Latitude, {item}.Longitude) AS Distance
FROM Items {item}
ORDER BY Distance")
.AddEntity("item", typeof(Item))
.SetDecimal("lat1", lat1)
.SetDecimal("lat2", lat2)
.List<Item>()
... | NHibernate query with distance calculation stored proc | [
"",
"sql",
"nhibernate",
""
] |
Let's say I have a table *tbl* with columns *id* and *title*.
I need to change all values of title column:
1. from 'a-1' to 'a1',
2. from 'a.1' to 'a1',
3. from 'b-1' to 'b1',
4. from 'b.1' to 'b1'.
Right now, I'm performing two UPDATE statements:
```
UPDATE tbl SET title='a1' WHERE title IN ('a-1', 'a.1')
UPDATE tb... | In a more general case, where there could be many hundreds of mappings to each of the new values, you would create a separate table of the old and new values, and then use that in the UPDATE statement. In one dialect of SQL:
```
CREATE TEMP TABLE mapper (old_val CHAR(5) NOT NULL, new_val CHAR(5) NOT NULL);
...multiple... | You can use one statement and a number of case statements
```
update tbl
set title =
case
when title in ('a-1', 'a.1') then 'a1'
when title in ('b-1', 'b.1') then 'b1'
else title
end
```
Of course, this will cause a write on every record, and with indexes, it can be an issue, so you can f... | Is it possible to perform multiple updates with a single UPDATE SQL statement? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
"optimization",
""
] |
I work at a company that has some very non-standardized SQL conventions (They were written by Delphi Developers years ago). Where is the best place that I can find SQL industry standard convention definitions that are most commonly used? | In his book "[SQL Programming Style](https://rads.stackoverflow.com/amzn/click/com/0120887975)," Joe Celko suggests a number of conventions, for example that a collection (e.g. a table) should be named in the plural, while a scalar data element (e.g. a column) should be named in the singular.
He cites [ISO-11179-4](ht... | 1. there aren't any
2. it there were, they'd be obsolete
3. if they're not obsolete, you won't like them
4. if you like them, they're insufficient
5. if they're sufficient, no one else will like them
seriously, strive for readability, i.e. use meaningful field and table names; nothing else is really necessary
(ok som... | Where can I find/learn industry standard SQL Conventions? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I just started with the WCF REST Starter Kit.
I created a simple service that return an array of an object.
Using the browser, everything works fine but when I use a WCF client, I get an ArgumentException.
I'm not using IIS and here is the code:
**The contract:**
```
[ServiceContract]
public interface IGiftSer... | Had the same problem, disabled the help page and it fixed it. The exception was being thrown if some REST urls were called in a sequence very quickly. It was fine when waiting between the calls.
```
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
return new... | I had the same probem, but I wanted to see the help page so disabling it wasn't a solution for me. I found out that URITemplating in the WCF REST Toolkit is causing those problem, when it sees that it already have this template in the template tables. Basically you will only need a template when the URL to your method ... | WCF REST Starter Kit - A property with the name 'UriTemplateMatchResults' already exists | [
"",
"c#",
"wcf",
"rest",
"wcf-client",
""
] |
How should exceptions be dispatched so that error handling and diagnostics can be handled in a centralized, user-friendly manner?
For example:
* A DataHW class handles communication with some data acquisition hardware.
* The DataHW class may throw exceptions based on a number of possible errors: intermittent signal, ... | Avoid duplicating the catch blocks at each call site by catching (...) and calling a shared handler function which rethrows and dispatches:
```
f()
{
try
{
// something
}
catch (...)
{
handle();
}
}
void handle()
{
try
{
throw;
}
catch (const Foo& e)
... | An idea I keep running into is that exceptions should be caught by levels which can handle them. For example, a CRC error might be caught by the function that transmits the data, and upon catching this exception, it might try to retransmit, whereas a "no signal" exception might be caught in a higher level and drop or d... | Dispatching exceptions in C++ | [
"",
"c++",
"oop",
"exception",
""
] |
In a Swing app a method should continue only after user enters a correct answer. The correct answer is stored in a `String` with user answer being set by a listener to another `String`. So, the code is
```
while (!correctAnswer.equals(currentAnswer)) {
// wait for user to click the button with the correct answer ... | Are you new to UI programming? The reason I ask is that your answer is predicated on a procedural style of coding, which isn't what UIs are about. It tends to be event-driven.
In this case the solution is pretty easy: add an event listener (`ActionListener`) to the submit button and check the result there. If its OK, ... | As others have suggested, you'll want to use assign a listener to the button, which will be called when the button is pressed.
Here's a incomplete example illustrating how to use an [`ActionListener`](http://java.sun.com/javase/6/docs/api/java/awt/event/ActionListener.html) and implementing its [`actionPerformed`](htt... | The correct way of waiting for strings to become equal | [
"",
"java",
"while-loop",
"cpu-cycles",
""
] |
I have a very simple html page here:
<http://www.nomorepasting.com/getpaste.php?pasteid=22407>
And I have 4 layers on the page. The reason for this is it is the framework oif a much more complicated site, I have simplified it to ask my question. Basically, I want to be able to click on different links in layer 2 and ... | (In response to Joshxtothe4's comment... I needed more space to respond)
Changing the class back to class1 will not show the text again, unfortunately. The code I gave will hide the text, always, if it's found in a span. You could do something like below, and add another CSS statement that will hide the span if class4... | Tables are for tabular data (think Excel). If you have a grid of data to display use a table. When it comes to page lyouts, use CSS positioning.
Also, obsessive DIV use isn't the best way to use CSS. Getting into the habit of wrapping everything up in a DIV is a practice known as "div mania" and you can Google for rea... | An image and text query | [
"",
"javascript",
"html",
"css",
""
] |
I've been learning C++, coming from C#, where I've gotten used to using service providers: basically a Dictionary<Type, object>. Unfortunately, I can't figure out how to do this in C++. So the questions are basically:
1. How would I make a dictionary in C++.
2. How would I use 'Type' with it, as far as I know there is... | I'm assuming that you're trying to map a type to a single object instance. You could try something along these lines:
```
#include <typeinfo>
#include <map>
#include <string>
using namespace std;
class SomeClass
{
public:
virtual ~SomeClass() {} // virtual function to get a v-table
};
struct type_info_less
{
... | You probably want to look at the [STL map template](http://www.cplusplus.com/reference/stl/map/). C++ certainly does have types (hard to have inheritance without it), just no specific defined "Type" class. | C++ Service Providers | [
"",
"c++",
"dictionary",
"service",
""
] |
I want to convert function object to function.
I wrote this code, but it doesn't work.
```
#include <iostream>
typedef int (*int_to_int)(int);
struct adder {
int n_;
adder (int n) : n_(n) {}
int operator() (int x) { return x + n_; }
operator int_to_int () {
return this->*&adder::operator();
... | **Update**: You told us what you want. I found this question here on SO: [Best method for storing this pointer for use in WndProc](https://stackoverflow.com/questions/117792/best-method-for-storing-this-pointer-for-use-in-wndproc) . I'm not a Windows Programmer, but the Adam Rosenfield guy seem to be right in using Set... | Instance method pointers are a bit tricky and are completely different beasts compared to 'normal' function pointers.
See what the [C++ FAQ lite section 33](http://www.parashift.com/c++-faq-lite/pointers-to-members.html) has to say about it. Also see [this](http://www.goingware.com/tips/member-pointers.html) and [this... | On writing win32 api wrapper with C++, how to pass this pointer to static function | [
"",
"c++",
"winapi",
"function",
"pointers",
""
] |
Does using Multiple .NET Languages (Delphi, VB.NET, C#) into the same application (but in differents class library of course) can **down peformances** compared to a **full C# application** for example ? | I'm not an expert on the CLR, but I would guess that you will have very similar performance. All the languages compile to MSIL which runs on the CLR. There could be differences in performance depending on the MSIL generated from the compilers. i.e. It's possible that similar code in VB.NET would compile to less (or mor... | Although I don't have any benchmarks off hand, I would say that for the most part it shouldn't. Those different languages all compile the code into CIL, so you should be fine.
One place where this would be different is with the languages that are run on the DLR (IronPython, IronRuby, etc.). They're compiling in the us... | Cross .NET Languages Performances | [
"",
"c#",
".net",
""
] |
I currently have a unittest.TestCase that looks like..
```
class test_appletrailer(unittest.TestCase):
def setup(self):
self.all_trailers = Trailers(res = "720", verbose = True)
def test_has_trailers(self):
self.failUnless(len(self.all_trailers) > 1)
# ..more tests..
```
This works fine,... | How about using a class member that only gets initialized once?
```
class test_appletrailer(unittest.TestCase):
all_trailers = None
def setup(self):
# Only initialize all_trailers once.
if self.all_trailers is None:
self.__class__.all_trailers = Trailers(res = "720", verbose = Tru... | An alternative to the proposed solution would be to use a more featured test runner like [Nose](https://nose.readthedocs.io/en/latest/). With Nose, you can have module-level setup functions which will be run once for a test module. Since it is entirely compatible with unittest, you wouldn't have to change any code.
Fr... | Caching result of setUp() using Python unittest | [
"",
"python",
"unit-testing",
""
] |
Currently I am working on a project where goto statements are heavely used. The main purpose of goto statements is to have one cleanup section in a routine rather than multiple return statements.
Like below:
```
BOOL foo()
{
BOOL bRetVal = FALSE;
int *p = NULL;
p = new int;
if (p == NULL)
{
cout<<... | I am not sure what do you mean by clean up code but in C++ there is a concept called "*resource acquisition is initialization*" and it should be the responsibility of your destructors to clean up stuff.
(Note that in C# and Java, this is usually solved by try/finally)
For more info check out this page:
<http://www.re... | I've never had to use a goto in C++. Ever. EVER. If there is a situation it should be used, it's incredibly rare. If you are actually considering making goto a standard part of your logic, something has flown off the tracks. | To GOTO or not to GOTO? | [
"",
"c++",
"goto",
""
] |
I have a `Dictionary<string,int>` that has the potential to contain upwards of 10+ million unique keys. I am trying to reduce the amount of memory that this takes, while still maintaining the functionality of the dictionary.
I had the idea of storing a hash of the string as a long instead, this decreases the apps memo... | So I have done something similar recently and for a certain set of reasons that are fairly unique to my application did not use a database. In fact I was try to stop using a database. I have found that GetHashCode is significantly improved in 3.5. One important note, NEVER STORE PERSISTENTLY THE RESULTS FROM GetHashCod... | With 10 million-odd records, have you considered using a database with a non-clustered index? Databases have a lot more tricks up their sleeve for this type of thing.
Hashing, by definition, and under any algorithm, has the potential of collisions - especially with high volumes. Depending on the scenario, I'd be very ... | C# Dictionary Memory Management | [
"",
"c#",
"data-structures",
"memory-management",
"dictionary",
""
] |
I'm trying to connect to an Oracle DB which is currently offline. When it's online it's not a problem, however, now that it's offline my program is getting hung up on the $connection = oci\_connect() line and timing out. How do I simply check the connectio and bail out if it's not there? | Try this (fill in your ip and port):
```
if ( @fsockopen($db_ip,$db_port ) ) {
//connect to database
} else {
// didn't work
}
``` | This gives you both a manual error, plus will return the actual error.
```
$connection = oci_connect() or die("Critical Error: Could not connect to database.\n\n". oci_error());
```
Make sure to test this as hopefully the Oracle error doesn't do something stupid like return the connection string (with your DB passwor... | How do I test for an Oracle connection | [
"",
"php",
"oracle",
""
] |
My application performs time consuming work independently on several files. I created a BackgroundWorker to pass the work off to on each file, but it appears the backgroundworker is only capable of performing asynchronous work. Is it possible to do several asynchronous tasks in unison with it, or is there a similar obj... | The background worker is usually used to update the UI and/or to pass off work so you don't freeze the UI when a long running process takes place. This means that you "pass" the background worker process the "file work" and then use a callback to update the UI(usually) all during which your APP remains responsive.
If ... | While you can use the BackgroundWorker, I think you should simply spin off a few threads to do the work. One thread (probably the main thread) will create and start these worker threads and then perform a Join on all the workers in order to wait for processing to complete.
Alternatively, have a look a the [Parallel Ex... | Synchronous work in a BackgroundWorker | [
"",
"c#",
"multithreading",
"backgroundworker",
""
] |
Why is the compiler unable to infer the correct type for the result from Collections.emptySet() in the following example?
```
import java.util.*;
import java.io.*;
public class Test {
public interface Option<A> {
public <B> B option(B b, F<A,B> f);
}
public interface F<A,B> {
public B f(A... | Java needs a lot of hand holding with its inference. The type system could infer better in a lot of cases but in your case the following will work:
```
print("Collections.<String>emptySet();");
``` | First you can narrow down your problem to this code:
```
public class Test {
public void option(Collection<String> b) {
}
public void getColl() {
option(Collections.emptySet());
}
}
```
This does not work, you need a temporary variable or else the compiler cannot infer the type. Here is a go... | Why can't the Java compiler figure this out? | [
"",
"java",
"generics",
"collections",
""
] |
Using SQL Server 2005 and Management Studio how do I insert a picture into an `Image` type column of a table?
Most importantly how do I verify if it is there? | ```
CREATE TABLE Employees
(
Id int,
Name varchar(50) not null,
Photo varbinary(max) not null
)
INSERT INTO Employees (Id, Name, Photo)
SELECT 10, 'John', BulkColumn
FROM Openrowset( Bulk 'C:\photo.bmp', Single_Blob) as EmployeePicture
``` | For updating a record:
```
UPDATE Employees SET [Photo] = (SELECT
MyImage.* from Openrowset(Bulk
'C:\photo.bmp', Single_Blob) MyImage)
where Id = 10
```
**Notes:**
* Make sure to add the 'BULKADMIN' Role Permissions for the login you are using.
* Paths are not pointing to your computer when using SQL Server Mana... | Insert Picture into SQL Server 2005 Image Field using only SQL | [
"",
"sql",
"sql-server",
"sql-server-2005",
"image",
""
] |
I have an asp:ImageButton that is supposed to popup a save dialog when clicked. When I put it outside the UpdatePanel, it works fine, but when I put it inside the UpdatePanel, the dialog does not popup. | I had a similar problem in a GridView, but solved it by uing an Image inside a LinkButton. <http://netpl.blogspot.com/2008/01/imagebutton-in-templatefield-does-not.html> for more information. | Response.Write often doesn't work inside of UpdatePanels. Assuming you're just running some javascript in the onclick event on the client, you're probably better off just adding your javascript code server-side to the OnClientClick property. | asp:ImageButton is not firing in an asp.net UpdatePanel? | [
"",
"c#",
"asp.net",
""
] |
I have a set of files. The set of files is read-only off a NTFS share, thus can have many readers. Each file is updated occasionally by one writer that has write access.
How do I ensure that:
1. If the write fails, that the previous file is still readable
2. Readers cannot hold up the single writer
I am using Java a... | According to the [JavaDoc](http://java.sun.com/javase/6/docs/api/java/nio/channels/FileLock.html):
> This file-locking API is intended to
> map directly to the native locking
> facility of the underlying operating
> system. Thus the locks held on a file
> should be visible to all programs that
> have access to the fil... | I don't know if this is applicable, but if you are running in a pure Vista/Windows Server 2008 solution, I would use TxF (transactional NTFS) and then make sure you open the file handle and perform the file operations by calling the appropriate file APIs through JNI.
If that is not an option, then I think you need to ... | How to safely update a file that has many readers and one writer? | [
"",
"java",
"concurrency",
"filesystems",
"ntfs",
"atomic",
""
] |
I've just upgraded some old Java source which has been running on a Sun Java 1.4.2 VM to Sun Java (JRE) 6 VM. More or less the only thing I had to change was to add explicit datatypes for some abstract objects (Hashmap's, Vector's and so on). The code itself it quite memory intensive, using up to 1G of heap memory (usi... | Not much information here. But here are a couple of things you might want to explore:
* Start the VM with Xmx and Xms as the same value (in your case 1024M)
* Ensure that the server jvm dll is being used to start the virtual machine.
* Run a profiler to see what objects are hogging memory or what objects are not being... | If your application nearly runs out of free space, garbage collection time may dominate computation time.
Enable gc debugging to look for this. Or, even better, simply start jconsole and attach it to your program. | Updating from Java 1.4.2 to Java 6 (both Sun VMs) results in slower performance | [
"",
"java",
"performance",
"jvm",
"sun",
""
] |
I wanted to set a CSS class in my master page, which depends on the current controller and action. I can get to the current controller via `ViewContext.Controller.GetType().Name`, but how do I get the current action (e.g. `Index`, `Show` etc.)? | Use the `ViewContext` and look at the `RouteData` collection to extract both the controller and action elements. But I think setting some data variable that indicates the application context (e.g., "editmode" or "error") rather than controller/action reduces the coupling between your views and controllers. | In the RC you can also extract route data like the action method name like this
```
ViewContext.Controller.ValueProvider["action"].RawValue
ViewContext.Controller.ValueProvider["controller"].RawValue
ViewContext.Controller.ValueProvider["id"].RawValue
```
---
### Update for MVC 3
```
ViewContext.Controller.ValuePro... | How can I return the current action in an ASP.NET MVC view? | [
"",
"c#",
"asp.net-mvc",
""
] |
I am trying to work out a code sample to demonstrate the debugging functionality in Visual Studio 2008 with C#. I'm trying to build a code sample which would have a 'not so obvious' mistake in it, which would result in unexpected output.
A non working example would be:
```
static void Main(string[] args) {
int a,... | Here's a snippet you can throw in...
```
string a = "foo";
a.Replace("foo", "bar");
Console.WriteLine(a);
``` | You could use a common programming error like:
* [fencepost error](http://en.wikipedia.org/wiki/Off-by-one_error)
* forgetting about [immutable objects](http://codebetter.com/blogs/patricksmacchia/archive/2008/01/13/immutable-types-understand-them-and-use-them.aspx)
* using [== instead of Equals()](http://dotnetguts.b... | C#/Visual Studio Debugging example | [
"",
"c#",
"visual-studio",
"debugging",
""
] |
I'm writng a small application in PHP + MySQL and have come to the point where there is an object that has a couple (8 so far but not expected to increase) of flags associated with it. The flags are pretty much unrelated although there are some combinations that would make no sense. The object represents a row in a DB ... | In your [model](http://en.wikipedia.org/wiki/Entity-relationship_model), the object has 8 boolean properties. That implies 8 boolean (TINYINT for MySQL) columns in your database table and 8 getter/setter methods in your object. Simple and conventional.
Rethink your current approach. Imagine what the next guy who has t... | If you really have to use bit flags, then use a SET column to store them in the DB, an associative array in the code, and methods to turn flags on/off. Add separate methods to convert the array to/from a single integer if you need it in that format.
There's nothing to be gained by using low-level bit operators, so you... | Best practices for bit flags in PHP | [
"",
"php",
"mysql",
"flags",
""
] |
I need to generate random text strings of a particular format. Would like some ideas so that I can code it up in Python. The format is <8 digit number><15 character string>. | ```
#!/usr/bin/python
import random
import string
digits = "".join( [random.choice(string.digits) for i in xrange(8)] )
chars = "".join( [random.choice(string.letters) for i in xrange(15)] )
print digits + chars
```
EDIT: liked the idea of using random.choice better than randint() so I've updated the code to reflect... | See an example - [Recipe 59873: Random Password Generation](http://code.activestate.com/recipes/59873/) .
Building on the recipe, here is a solution to your question :
```
from random import choice
import string
def GenPasswd2(length=8, chars=string.letters + string.digits):
return ''.join([choice(chars) for i i... | Generating random text strings of a given pattern | [
"",
"python",
"string",
"random",
""
] |
Quite often, in programming we get situations where `null` checks show up in particularly large numbers. I'm talking about things like:
```
if (doc != null)
{
if (doc.Element != null)
{
... and so on
}
else
throw new Exception("Element cannot be null");
} else {
throw new Exception("document cannot b... | Check out this article: [A fluent approach to C# parameter validation](http://blog.getpaint.net/2008/12/06/a-fluent-approach-to-c-parameter-validation)
It's written by one of the Paint.NET Developers. He uses extension methods to simplify and clean up null checking code. | Push them forward to the beginning of the function, and keep them out of the part of the code that does the work. Like this:
```
if (doc == null)
throw new ArgumentNullException("doc");
if (doc.Element == null)
throw new ArgumentException("Element cannot be null");
AndSoOn();
``` | How can I manage the onslaught of null checks? | [
"",
"c#",
".net",
""
] |
Let's say I have a page called `display.php` and the user is viewing `display.php?page=3`. I want to allow the user to do an action like voting via a POST request and then bring them back to the page they were on. So, If I do a POST request to `display.php?page=3` would the page information also be available to the scr... | The simple answer is 'yes'. You can use a GET-style URL as the submission URL for a POST form. PHP will have both the POST and GET information available to it in the usual ways when the form is submitted.
This is not to say that you *should* do this, but it will work. | In PHP, you can get request variables from the special global arrays:
```
$_GET['page'] (for GET requests)
$_POST['page'] (for POST requests)
$_REQUEST['page'] (for either)
```
It sounds like you are looking for "Redirect after Post", I would suggest separating display.php and vote.php into separate files. Vote looks... | What happens if you go to a GET style url with a POST request? | [
"",
"php",
"post",
"get",
""
] |
I've built a form with Netbeans's visual editor. When I press one of the buttons it should do the following :
* set it to disabled
* perform a task that takes some time
* when the task finishes the button will be enabled again
However, the following happens:
* the button remains in a pressed state until the task fin... | When you do work in a button callback, you are stalling the GUI painting thread until it completes.
What you need to do is spawn a thread to do the long running task, and then have that thread use `SwingUtilities.invokeLater()` to update the UI when it completes. Not using `invokeLater` is not thread safe, and is gene... | When you do things in a button callback, you are essentially stalling the gui painting thread - not just for the button, but for ANY gui painting. (Try covering the interface with another window and then exposing it again - it won't repaint until the task is finished!)
What you need to do is spawn a thread to do the l... | Swing buttons don't react immediately! How can I change that? | [
"",
"java",
"swing",
""
] |
I'm looking for an implementation of CRC32 in C or C++ that is explicitly licensed as being no cost or public domain. The implementation [here](http://www.networkdls.com/Software/View/CRC32) seems nice, but the only thing it says about the license is "source code", which isn't good enough. I'd prefer non LGPL so I don'... | Use the [Boost C++ libraries](http://www.boost.org/). There is a [CRC](http://www.boost.org/doc/libs/release/libs/crc/index.html) included there and the [license](http://www.boost.org/LICENSE_1_0.txt) is good. | The [SNIPPETS C Source Code Archive](http://web.archive.org/web/20080217222203/http://c.snippets.org/) has a [CRC32 implementation](http://web.archive.org/web/20080303102530/http://c.snippets.org/snip_lister.php?fname=crc_32.c) that is freely usable:
```
/* Copyright (C) 1986 Gary S. Brown. You may use this program, ... | CRC32 C or C++ implementation | [
"",
"c++",
"c",
"crc32",
""
] |
I created a custom autocomplete control, when the user press a key it queries the database server (using Remoting) on another thread. When the user types very fast, the program must cancel the previously executing request/thread.
I previously implemented it as AsyncCallback first, but i find it cumbersome, too many ho... | No, it **is not** safe. `Thread.Abort()` is sketchy enough at the best of times, but in this case your control has no (heh) control over what's being done in the delegate callback. You don't know what state the rest of the app will be left in, and may well find yourself in a world of hurt when the time comes to call th... | [There](http://blogs.msdn.com/ankur/archive/2005/11/30/498293.aspx) [are](http://msmvps.com/blogs/senthil/archive/2008/12/17/the-dangers-of-thread-abort.aspx) [many](http://www.manning-sandbox.com/message.jspa?messageID=33703) [warnings](http://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation) [all over](http://h... | Is this thread.abort() normal and safe? | [
"",
"c#",
"multithreading",
""
] |
Basically like using the out keyword. But the problem is with the out keyword, you still have to declare a variable outside the method call, like:
```
double result;
Double.TryParse ( "76", out result );
```
where as I want something like:
```
Double.TryParse ( "76", out result );
```
and there I get a new variable... | You can use [C# tuples](http://rabdullin.com/journal/2008/9/30/using-tuples-in-c-functions-and-dictionaries.html) to **compose multiple variables into one**. | No, you have to declare the variable first because you are passing it to the method, the only difference is that you are explicitly requiring the method to fill it out before returning. | Is there a way to create and return new variables from a method in C#? | [
"",
"c#",
".net",
""
] |
We are invoking Asp.Net ajax web service from the client side. So the JavaScript functions have calls like:
// The function to alter the server side state object and set the selected node for the case tree.
```
function JSMethod(caseId, url)
{
Sample.XYZ.Method(param1, param2, OnMethodReturn);
}
function OnM... | You have a callback method (OnMethodReturn) specified in the WebMethod call, but not an error handler method. You need to create one and pass it into as you do the callback method. Then you can handle your failed WebMethod calls in there. | This problem occurs even before the Ajax framework can invoke the target method, it fails while creating the web proxy. Anyway I solved the problem by enabling Anonymous access to the Web Service folder and checking for Session explicitly in the Web Service methods | How do I fix: InvalidOperationException upon Session timeout in Ajax WebService call | [
"",
"javascript",
"web-services",
"exception",
"session",
"asp.net-ajax",
""
] |
In the Java snippet:
```
SyndFeedInput fr = new SyndFeedInput();
SyndFeed sf = fr.build(new XmlReader(myInputStream));
List<SyndEntry> entries = sf.getEntries();
```
the last line generates the warning
"The expression of type `List` needs unchecked conversion to conform to `List<SyndEntry>`"
What's an appropriate w... | Since `getEntries` returns a raw `List`, it could hold anything.
The warning-free approach is to create a new `List<SyndEntry>`, then cast each element of the `sf.getEntries()` result to `SyndEntry` before adding it to your new list. `Collections.checkedList` does *not* do this checking for you—although it would have ... | This is a common problem when dealing with pre-Java 5 APIs. To automate the [solution from erickson](https://stackoverflow.com/questions/367626/how-do-i-fix-the-expression-of-type-list-needs-unchecked-conversion/367673#367673), you can create the following generic method:
```
public static <T> List<T> castList(Class<?... | How do I fix "The expression of type List needs unchecked conversion...'? | [
"",
"java",
"warnings",
"unchecked-conversion",
""
] |
What are all the common undefined behaviours that a C++ programmer should know about?
Say, like:
```
a[i] = i++;
``` | ### Pointer
* Dereferencing a `NULL` pointer
* Dereferencing a pointer returned by a "new" allocation of size zero
* Using pointers to objects whose lifetime has ended (for instance, stack allocated objects or deleted objects)
* Dereferencing a pointer that has not yet been definitely initialized
* Performing pointer ... | The order that function parameters are evaluated is ***unspecified* behavior**. (This won't make your program crash, explode, or order pizza... unlike ***undefined* behavior**.)
The only requirement is that all parameters must be fully evaluated before the function is called.
---
This:
```
// The simple obvious one... | What are all the common undefined behaviours that a C++ programmer should know about? | [
"",
"c++",
"undefined",
"undefined-behavior",
"c++-faq",
""
] |
I was reading some Java recently and came across something (an idiom?) new to me: in the program, classes with multiple constructors would also always include a blank constructor. For example:
```
public class Genotype {
private boolean bits[];
private int rating;
private int length;
private Random random;
... | I am not sure that the code you were reading was high quality (I've reviewed some bioinformatics code in the past and it is unfortunately often not written by professional developers). For example, that third constructor is not a copy constructor and generally there are problems in this code, so I wouldn't "read too mu... | Is the object [Serializable](http://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html)?
> To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subty... | Why might one also use a blank constructor? | [
"",
"java",
"coding-style",
"constructor",
""
] |
I am dynamically creating a table which I want to have clickable rows. When the user clicks on one of the rows I want to redirect to a page specific to the item of that row. My question is how on the server side can I wire the "onclick" event to a routine that will then allow me to build a url based on some of the data... | It sounds like your actual goal is simply to display/edit the row on another page. If this is the case, you could simply add a javascript event handler to the table row when you create it.
```
<tr onclick="window.location='DetailPage.aspx?id=<%= IdFromDb %>'">
<!-- etc......-->
</tr>
```
If you use a GridView to ... | I would build the link in the table as an actual anchor tag to your SomePage.aspx (while you're building your table, you should know what the query string would be for each table row), opposed to a server side control that redirects on postback | Working with the "onclick" of a server side dynamically created TableRow | [
"",
"c#",
"asp.net",
"controls",
""
] |
I'm trying to write a notification service (for completely legit non-spam purposes) in .NET using SmtpClient. Initially I just looped through each message and sent it, however this is slow and I would like to improve the speed. So, I switched to using 'SendAsync', but now get the following error on the second call:
``... | According to the [documentation](http://msdn.microsoft.com/en-us/library/x5x13z6h.aspx):
> After calling SendAsync, you must wait
> for the e-mail transmission to
> complete before attempting to send
> another e-mail message using Send or
> SendAsync.
So to send multiple mails at the same time you need multiple SmtpC... | You might be able to use the following:
```
ThreadPool.QueueUserWorkItem(state => client.Send(msg));
```
This should allow your messages to be queued and sent as threads become available. | Why can SmtpClient.SendAsync only be called once? | [
"",
"c#",
"smtpclient",
"system.net.mail",
""
] |
In Z80 machine code, a cheap technique to initialize a buffer to a fixed value, say all blanks. So a chunk of code might look something like this.
```
LD HL, DESTINATION ; point to the source
LD DE, DESTINATION + 1 ; point to the destination
LD BC, DESTINATION_SIZE - 1 ; copying this many bytes
... | I believe this goes to the design philosophy of C and C++. As [Bjarne Stroustrup](http://en.wikipedia.org/wiki/Bjarne_Stroustrup) once [said](http://www.research.att.com/~bs/crc.pdf), one of the major guiding principles of the design of C++ is "What you don’t use, you don’t pay for". And while [Dennis Ritchie](http://e... | There was a quicker way of blanking an area of memory using the stack. Although the use of LDI and LDIR was very common, David Webb (who pushed the ZX Spectrum in all sorts of ways like full screen number countdowns including the border) came up with this technique which is 4 times faster:
* saves the Stack Pointer an... | Why is there no Z80 like LDIR functionality in C/C++/rtl? | [
"",
"c++",
"c",
"z80",
""
] |
Okay so a continuation from [this question](https://stackoverflow.com/questions/409913/can-php-be-installed-on-a-local-machine), where you experts intro'd me to [WAMP](http://www.wampserver.com/en/presentation.php), which can basically execute PHP within a Windows XP environment.
So now I've got it installed, but the ... | Skype reserves port 80 for its incoming connection which conflicts with WAMP, so simply configure Skype to use another port by doing the following:
In Skype go to Tools|Options|Advanced|Connection uncheck the option --> Use port 80 and 443 as alternatives for incoming connections, that's it
For this change to take ef... | Got it! Under the **WAMP tray icon**, left-click context menu > **Apache** > **Service** > **Test Port 80**, it said :
> "Your **port 80 is actually used** by - Info not available, Must be **Skype**"
Well, so **off** goes Skype, **WAMP > Restart All Services**, and [Localhost](http://localhost/) shows ["WAMP5 Homepag... | WAMP Server not working | [
"",
"php",
"localhost",
"wamp",
""
] |
When you run a php script in the command line, does is execute with the read/write permissions of the current user or what? | Yes, it does. | Yes, it runs with the permissions of the current user. Just like executing any other command-line program. | PHP-CLI + File Permissions | [
"",
"file-permissions",
"php",
""
] |
I'm curious as I begin to adopt more of the boost idioms and what appears to be best practices I wonder at what point does my c++ even remotely look like the c++ of yesteryear, often found in typical examples and in the minds of those who've not been introduced to "Modern C++"? | Just a few off the top of my head:
* Navigating around in memory-mapped files.
* Windows API calls where you have to over-allocate (like a LPBITMAPINFOHEADER).
* Any code where you're munging around in arbitrary memory (VirtualQuery() and the like).
* Just about any time you're using reinterpret\_cast<> on a pointer.
... | I don't use `shared_ptr` almost at all, because I avoid shared ownership in general. Therefore, I use something like `boost::scoped_ptr` to "own" an object, but all other references to it will be raw pointers. Example:
```
boost::scoped_ptr<SomeType> my_object(new SomeType);
some_function(my_object.get());
```
But `s... | Once you've adopted boost's smart pointers, is there any case where you use raw pointers? | [
"",
"c++",
"boost",
"smart-pointers",
""
] |
What's the best way to merge 2 or more dictionaries (`Dictionary<TKey, TValue>`) in C#?
(3.0 features like LINQ are fine).
I'm thinking of a method signature along the lines of:
```
public static Dictionary<TKey,TValue>
Merge<TKey,TValue>(Dictionary<TKey,TValue>[] dictionaries);
```
or
```
public s... | This partly depends on what you want to happen if you run into duplicates. For instance, you could do:
```
var result = dictionaries.SelectMany(dict => dict)
.ToDictionary(pair => pair.Key, pair => pair.Value);
```
Or, more succintly, in .NET 8:
```
var result = dictionaries.SelectMany(dict ... | I would do it like this:
```
dictionaryFrom.ToList().ForEach(x => dictionaryTo.Add(x.Key, x.Value));
```
Simple and easy. According to [this blog post](https://codeblog.jonskeet.uk/2009/01/29/for-vs-foreach-on-arrays-and-lists/) it's even faster than most loops as its underlying implementation accesses elements by in... | Merging dictionaries in C# | [
"",
"c#",
"dictionary",
"merge",
""
] |
An integer's max value in Java is 2147483647, since Java integers are signed, right?
0xff000000 has a numeric value of 4278190080.
Yet I see Java code like this:
```
int ALPHA_MASK = 0xff000000;
```
Can anyone enlighten me please? | The high bit is a sign bit. Setting it denotes a negative number: -16777216.
Java, like most languages, stores signed numbers in [2's complement](http://en.wikipedia.org/wiki/Two%27s_complement) form. In this case, subtracting 231, or 2147483648 from 0x7F000000, or 2130706432, yields -16777216. | Just an addition to erickson's answer:
As he said, signed integers are stored as two's complements to their respective positive value on most computer architectures.
That is, the whole 2^32 possible values are split up into two sets: one for positive values starting with a 0-bit and one for negative values starting w... | Why is Java able to store 0xff000000 as an int? | [
"",
"java",
"hex",
"int",
""
] |
I came across some Enumerators that inherited `uint`. I couldn't figure out why anyone would do this.
Example:
```
Enum myEnum : uint
{
...
}
```
Any advantage or specific reason someone would do this? Why not just leave it as defaultint? | One reason I can think of is that range checking is easier. Given that most enumerations start at 0, you'd only have to check the upper bound. | if the enumeration values are greater than 2,147,483,647 and non-negative. | What is the reason for specifying an Enum as uint? | [
"",
"c#",
""
] |
Learning from my [last question](https://stackoverflow.com/questions/413311/c-do-method-names-get-compiled-into-the-exe), most **member names** seem to get included in the Project Output.
Looking at some decompilers like [9rays](http://www.9rays.net/products/Spices.Decompiler/), [Salamander](http://www.remotesoft.com/... | Obfuscating source-code is going to be self-defeating in terms of maintenance.
If your project is so 'secret', I guess you have two choices:
* Place the 'secret' proprietry code behind a service on a server that you control
* Code it in a language so not easy to decompile such as C/C++ | Maybe, debatably, but you'll destroy maintainability to do so.
Is this really worth it?
Actually this just comes down to **security through obscurity**, i.e. it's not security at all it's just an inconvenience. you should work fromt he assumption that any party interested enough *will* decompile your code if they can... | Obfuscation at source-code level more effective than obfuscators? | [
"",
"c#",
"obfuscation",
""
] |
I am creating an ATL 8.0 based ActiveX control in C++ using Visual Studio 2008. I need to create a sub-window and attach it to the ActiveX control.
How do I get access to the HWND that is owned by the ActiveX control?
Which ATL function can I override in order to use the HWND after the control's window has been creat... | After some trial and error and I found the answer I was after.
In the constructor of your ATL ActiveX control you to add the following line of code:
```
m_bWindowOnly = true;
```
This causes the window for the control to be created (rather than just reusing the HWND of the parent window). After this the m\_hWnd memb... | ActiveX would allow you to define your own methods on your own interface (to address Brians assumption), but that likely won't help here. The ActiveX control might very well be created by another component.
ATL too is irrelevant - it's a C++ template library that wraps COM interfaces.
The function you need here is IOl... | How do I get the HWND for an ActiveX control after the control has been initialised/activated? | [
"",
"c++",
"activex",
"atl",
""
] |
I have the following situation I think would be best to show in sample program code. I have a Java class that extends `JPanel`. In this class are two objects which are two more `JPanels`. In one of the `JPanel` objects is a `JTable` object. I added a listener to this `JTable` that detects a double click. When it detect... | One way to solve this is to use composition instead of inheritance. You could pass the JPanel into your subclass of the JTable.
```
public class TopPanel extends JPanel
{
private TheTable table;
public TopPanel()
{
table = new TheTable(this);
}
public void methodToFire() { }
}
public class TheTable e... | To access a method on the Outer class, you need to use the syntax of Outer.this.method().
So in this case, to access a method on the "TheTable" class from the listener, you should use `TheTable.this.callMethod()`.
I assume that `TopPanel` has added to it the `TheTable`. In this case, you could do something like:
```... | Calling methods of "parent" component in Java | [
"",
"java",
"class",
"methods",
""
] |
Yes, I do understand the difference between them. What I want to know is: why OVERRIDE a method? What is the good in doing it?
In case of overload: the only advantage is you haven't to think in different names to functions? | *Overloading* generally means that you have two or more functions in the same scope having the same name. The function that better matches the arguments when a call is made wins and is called. Important to note, as opposed to calling a virtual function, is that the function that's called is selected at compile time. It... | This will add some more clarity to thoughts. | Override and overload in C++ | [
"",
"c++",
"overriding",
"overloading",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.