Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm writting a java application, and I need to quickly discover any other running clients on any wired or wireless local networks in order to establish a TCP connection.
what's the best way of doing this? Are there libraries or code snippets that would do this? | I guess you need to do a scan on your application's port on all IPs in your subnet.
Just what are the available IPs - or what is your subnet for that matter?
I'm afraid determining that could turn out to be impossible as the network is designed to be transparent to your application.
So, i'd use brute force: pick your IP and change the last byte. Might be too much, might be not enough though.
Or you send a broadcast (which usually would be targeted at x.x.x.255) and see who answers.
See [Datagram Broadcasting](http://java.sun.com/docs/books/tutorial/networking/datagrams/broadcasting.html) and [Multicasts](http://www.roseindia.net/java/example/java/net/udp/multicast.shtml). But i think that's not TCP/IP anymore. | Multicast UDP is a good way of doing this. It's used in a couple of technologies that support automatic discovery of networked devices over local IP networks (UPnP and ZeroConf).
Multicast UDP is not TCP, but it is still based on IP and, so, uses the same addressing mechanism i.e. IP addresses. Quite often it is compared to radio broadcasting i.e. a multicast sender only needs to send 1 message (i.e. it is like a broadcast) but only clients that are "tuned-in" to the multicast channel will receive it.
You can do a quick search on google or wikipedia for these as a starter, but the basic idea is as follows:
* when a client starts, it sends out a multicast UDP "hello" message to some pre-specified multicast address and port (e.g. UPnP uses 239.255.255.250:1900)
* existing clients are listening for incoming multicast "hello" messages on the specified address and port - when a client receives one, it sends a response to the sender
* the client sending the "hello" message receives a response from each existing client on the network and is now aware of the IP address of each client
If you are looking for libraries to use, UPnP libraries can tend to be a bit heavyweight and a lot of folk generally don't like them, so ZeroConf might be a little more suitable. I don't know of any java implementations of such things but I'm sure you can find some with a little digging around. | Discovering clients on a wifi network | [
"",
"java",
"networking",
"tcp",
""
] |
I'm looking for a fast way to apply a new palette to an existing 8-bit .png image. How can I do that? Is the .png re-encoded when I save the image? (Own answer: it seems so)
What I have tried (edited):
```
import Image, ImagePalette
output = StringIO.StringIO()
palette = (.....) #long palette of 768 items
im = Image.open('test_palette.png') #8 bit image
im.putpalette(palette)
im.save(output, format='PNG')
```
With my testimage the save function takes about 65 millis. My thought: without the decoding and encoding, it can be a lot faster?? | If you want to change just the palette, then PIL will just get in your way. Luckily, the PNG file format was designed to be easy to deal with when you only are interested in some of the data chunks. The format of the [PLTE chunk](http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.PLTE) is just an array of RGB triples, with a CRC at the end. To change the palette on a file in-place without reading or writing the whole file:
```
import struct
from zlib import crc32
import os
# PNG file format signature
pngsig = '\x89PNG\r\n\x1a\n'
def swap_palette(filename):
# open in read+write mode
with open(filename, 'r+b') as f:
f.seek(0)
# verify that we have a PNG file
if f.read(len(pngsig)) != pngsig:
raise RuntimeError('not a png file!')
while True:
chunkstr = f.read(8)
if len(chunkstr) != 8:
# end of file
break
# decode the chunk header
length, chtype = struct.unpack('>L4s', chunkstr)
# we only care about palette chunks
if chtype == 'PLTE':
curpos = f.tell()
paldata = f.read(length)
# change the 3rd palette entry to cyan
paldata = paldata[:6] + '\x00\xff\xde' + paldata[9:]
# go back and write the modified palette in-place
f.seek(curpos)
f.write(paldata)
f.write(struct.pack('>L', crc32(chtype+paldata)&0xffffffff))
else:
# skip over non-palette chunks
f.seek(length+4, os.SEEK_CUR)
if __name__ == '__main__':
import shutil
shutil.copyfile('redghost.png', 'blueghost.png')
swap_palette('blueghost.png')
```
This code copies redghost.png over to blueghost.png and modifies the palette of blueghost.png in-place.
 ->  | `im.palette` is not callable -- it's an instance of the `ImagePalette` class, in mode `P`, otherwise `None`. `im.putpalette(...)` is a method, so callable: the argument must be a sequence of 768 integers giving R, G and B value at each index. | Changing palette's of 8-bit .png images using python PIL | [
"",
"python",
"image-processing",
"python-imaging-library",
""
] |
There's a real art to designing a website that works for everyone, and Progressive Enhancement is practically a mantra to me...
So I'm wondering, what are some of the best tricks you've used for making websites work for *everyone* regardless of browser, OS, javascript, flash, screen resolution, disabled user accessibility, etc.?
(I know lots about javascript and browser tricks, but will admit to being clueless about flash, etc.)
**EDIT**: I'm not really talking about the 1% of sites that are RIAs that simply cannot function without javascript or flash. I'm not asking how to write Google Docs without js. I'd like to know what people do for sites that *can* do cool things but don't actually *need* to.
I'll offer a couple of my own as an answer... | I try to avoid mantras, except the mantra that the world is a messy place.
I think a lot of desktop functionality will be replaced by web functionality, and it's going to be a tricky transition that will end up with real apps in the browser. Real apps means JavaScript or Flash or Silverlight, or Java or C# or Objective-J compiled into JavaScript.
To me the only trick is identifying the people and the browsers who can't usefully use the apps and providing them with some alternative content.
And that includes detecting mobile and providing appropriate content. There are many websites that just fall to pieces on the iPhone because they are so Flash-heavy and dependent on wide computer monitors.
I **do not** think it's OK to require JavaScript for a website that's a website, but I think it's OK for a web that's an app. I **do not** think it's OK to serve only 960px wide pages. I **do not** think it's ok to serve videos in Flash format only. | Check your stats (or install [Google Analytics](http://www.google.com/analytics/) if you don't have stats) and determine where your users are going and what they are actually doing.
e.g.
1.) Do your users constantly use search because they can't find something? if so maybe you can make the search work better?
2.) Does your 404 page provide some quick options to search for related terms or try and "guess" what they were looking for?
3.) Does your site have a sitemap that provides quick access to meaningful parts of your site?
4.) If all else fails, does the user have an easy means to contact you/technical support to help them find what they need?
5.) Not sure if you "sell" something on your site, but similar to when you reach the checkout at any major bricks n morter retailer... they ask you if you found everything you were looking for today. Consider providing an option where users can make suggestions... maybe you have an un-tapped market waiting to be conquered.
6.) On usability, be sure to surf your site in IE (6,7,8), Safari, etc. and make sure it works everywhere you care about.
7.) There's a great book called "[Don't make me think](http://www.sensible.com/buythebook.html)" which is a great resource on realistic usability. If you haven't read it already... go grab a copy.
In addition, ensure all the other little things are taken care of... e.g. you make good use of caching (JS, CSS, Images) | Progressive enhancement tricks | [
"",
"javascript",
"html",
"progressive-enhancement",
""
] |
I'm learning C++, and know a little bit of Visual Basic and an Delphi.
But I want to know, is there some program like Delphi, but for C++. Something where you can drag a button to a form, double click it, the like in Delphi and VB: opens a code editor and you edit the code of the button, but with a similar code of C++?
I'm using Windows Vista. | Yes, if you use MFC within Visual Studio.
MFC is Visual Studio's C++ class library for writing Windows programs, and for an MFC form Visual Studio behaves exactly as you describe.
As of Visual Studio 2008 with [an upgrade pack](http://www.microsoft.com/downloads/details.aspx?FamilyId=D466226B-8DAB-445F-A7B4-448B326C48E7&displaylang=en) you can create Office 2007 style applications, and Visual Studio style applications, using MFC. | There used to be "C++ Builder", a C++ version of Delphi, I don't know if this product is still being developed or not.
UPDATE: to summarize information from the comments, C++ Builder is actively developed and the product page is <http://www.embarcadero.com/products/cbuilder/> | Visual C++ Development | [
"",
"c++",
"windows",
"visual-c++",
"windows-vista",
""
] |
Is there a sleep function in JavaScript? | You can use the `setTimeout` or `setInterval` functions. | If you are looking to block the execution of code with call to `sleep`, then no, there is no method for that in `JavaScript`.
`JavaScript` does have `setTimeout` method. `setTimeout` will let you **defer** execution of a function for x milliseconds.
```
setTimeout(myFunction, 3000);
// if you have defined a function named myFunction
// it will run after 3 seconds (3000 milliseconds)
```
Remember, this is completely different from how `sleep` method, if it existed, would behave.
```
function test1()
{
// let's say JavaScript did have a sleep function..
// sleep for 3 seconds
sleep(3000);
alert('hi');
}
```
If you run the above function, you will have to wait for 3 seconds (`sleep` method call is blocking) before you see the alert 'hi'. Unfortunately, there is no `sleep` function like that in `JavaScript`.
```
function test2()
{
// defer the execution of anonymous function for
// 3 seconds and go to next line of code.
setTimeout(function(){
alert('hello');
}, 3000);
alert('hi');
}
```
If you run test2, you will see 'hi' right away (`setTimeout` is non blocking) and after 3 seconds you will see the alert 'hello'. | Is there a sleep function in JavaScript? | [
"",
"javascript",
""
] |
> **Possible Duplicate:**
> [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix)
I am working on wrapping a large number of .h and .lib files from native C++ to Managed C++ for eventual use as a referenced .dll in C#.
I have the .lib files linked in and everything has been going smoothly so far. Upon wrapping the latest .h file, I hit a snag when 2 functions came back with the link error:
```
error LNK2019: unresolved external symbol __imp__htonl@4 referenced in function
"public: void __thiscall Field::setCharacter(unsigned char,int)"
(?setCharacter@Field@@QAEXEH@Z) myutils.lib
```
I have referenced `myutils.lib` in the linker options, so that shouldn't be the issue.
What's strange is that I have about 20 functions in this particular .h file and all of the rest are linking just fine except for 3 functions.
Any ideas? | The missing symbol is `__imp__htonl@4`, which is a C++ mangled name for htonl, which is a function that converts a long value from host to network order. The @4 is used to mangle the input parameters and is part of C++ support for overloaded functions to allow the linker to resolve the right function w/o name collisions.
Make sure that you are linked to the network library that you are referencing this symbol from. Presumably your package is using some special definition of this symbol, instead of the MACRO that it usually is. | Are you sure the signatures match? Be sure to checked for signed-ness and const-ness. Also, make sure functions aren't inlined. | Unresolved External Symbol | [
"",
"c++",
"linker",
"unresolved-external",
""
] |
I am a c++ programmer and occasionally I'll come across some code that is using bitwise operators to manipulate things at the bit level, but I have no real understanding of those concepts. So I would like a resource to help me learn it so well that it becomes second nature. Does anyone know of good resources for this? A google search did not provide me much useful information. Maybe I'm not sure what to look for. Thanks! | I absolutely love Henry Warren's [Hacker's Delight](http://www.hackersdelight.org/) book. The website for it offers Chapter 2 ("Basics") as a free sample which, despite the name, offers some fairly sophisticated bit manipulation tricks. It might not be the best place to start, but it's fantastic once you start to get comfortable with bit arithmetic. | You'll have to know the background of the binary system. <http://en.wikipedia.org/wiki/Binary_numeral_system> has a great overview. Look at <http://en.wikipedia.org/wiki/Bitwise_operation> for bitwise operations. | Resources to learn bitwise programming? | [
"",
"c++",
"language-agnostic",
""
] |
Ok, I haven't programmed in C# before but I came upon this code and was wondering what it does. Now, I now that it just searches and find the first occurrence of "." and replaces it with "" but what exactly is in the ""? Would this just delete the period or is there a space character that replaces the "."? I'm trying to figure out how to transfer this method into Objective-C, but I need to know if the period is replaced by no characters or a space character.
```
someString.Replace(".", "")
``` | "" is just an empty string. Your code example replaces all occurrences of the periods with no characters.
(Note that the original string is untouched, and the return value of that line of code will be the modified string.)
It is actually better to use `string.Empty` rather than "". This is because `string.Empty` is much more readable, and is just an alias for "", so there is no performance consideration. Not to mention, if you use StyleCop, it will tell you not to use "". | No characters. This code removes periods from a string... sort of. The way it should REALLY be called is:
```
someString = someString.Replace(".", "");
```
(or as the other guys say, it REALLY should be)
```
someString = someString.Replace(".", String.Empty);
``` | C# Strings - Simple syntax Question | [
"",
"c#",
"objective-c",
"string",
""
] |
I'm using (and referencing) two 3rd party dlls (a.dll, and b.dll) in two of my C# applications. I'm getting a repeatable problem where both applications hang while making a call to a function in the 3rd party library.
I tried to make a copy of a.dll and b.dll (a2.dll, and b2.dll) and use that in the second application, but it turns out that a.dll references b.dll, anb b.dll references a.dll and this does not load properly.
I suspect that there is a deadlock but in the 3rd party library. I can't use locking to prevent this. Each application enforces locking to make sure that that app only has one thread accessing the library at a time, but I can't lock across both programs.
So, my question is how can I solve this problem?
Can I tell the OS (Windows XP) that I don't want the dll to be shared?
Thanks,
Joe | You can restrict access so only a single program at a time by using a named mutex. Named mutexes are restrictable to an entire operating system, so can be used to prevent access from multiple processes.
See the [Mutex class](http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx) for details. | I once had a similar problem with a discontinued 3rd party product.
There I used a disassembler and a hex editor with an integrated assembler to fix the underlying bug, but that was more or less luck because the cause was something trivial which could be derived by looking at the disassembly.
Depending on the actual cause that might be an option for you. | Deadlock in 3rd Party dll | [
"",
"c#",
"dll",
"deadlock",
""
] |
Now this might be a dumb question, but I'm still new to using Visual Studio 2008 but I was wondering if there is a feature like this (I'm using webforms ASP.NET C#).
I create a new method, highlight it in the editor and was wondering if there was a run/test method feature? Where it would exectute the method and prompt me via a UI for any variables the method might need to run?
I just thought this would really increase my productivity / speed in creating applications :S | You can use the console window in VS to test individual methods – provided the surrounding class compiles error-free. The console window can be activated via the `View` menu, IIRC.
Once inside the debug console, just enter the class name, followed by the method name (if it's a `static` method) or create an instance, if not. Printing the result can be done by prefixing the whole thing with `?`, e.g.:
```
> ? MyFancyStringHelperClass.Reverse("Hello")
elloH
``` | I prefer to follow [test driven development](http://en.wikipedia.org/wiki/Test-driven_development) (TDD) when using Visual Studio - or any other language/IDE for that matter. Essentially you assert what you want your code to do *by writing the unit test first*, validate that the test fails, and then fill in the blanks in the method that you are testing. Its much easier to say than do, but once you're used to it, it becomes very natural and fast - not to mention your code has a lot less defects!
For a tool where you can test some code as you go, I recommend [LinqPad](http://www.linqpad.net/) (and there is also [SnippetCompiler](http://www.sliver.com/dotnet/SnippetCompiler/)). While these don't let you highlight code and execute you can copy and paste into them achieving much of the same results.
For writing unit tests in VS you can use [NUnit](http://www.nunit.org/index.php) or any of its clones. I do not recommend the VS for Testers for unit testing.
I use NUnit in my current project and have become a fan of [ReSharper](http://www.jetbrains.com/resharper/) for integrating the test suite into Visual Studio. | Visual Studio 2008 Testing A Method? | [
"",
"c#",
"visual-studio-2008",
"unit-testing",
""
] |
This has been driving me mad for the past hour and a half. I know it's a small thing but cannot find what's wrong (the fact that it's a rainy Friday afternoon, of course, does not help).
I have defined the following class that will hold configuration parameters read from a file and will let me access them from my program:
```
class VAConfig {
friend std::ostream& operator<<( std::ostream& lhs, const VAConfig& rhs);
private:
VAConfig();
static std::string configFilename;
static VAConfig* pConfigInstance;
static TiXmlDocument* pXmlDoc;
std::map<std::string, std::string> valueHash;
public:
static VAConfig* getInstance();
static void setConfigFileName( std::string& filename ) { configFilename = filename; }
virtual ~VAConfig();
void readParameterSet( std::string parameterGroupName );
template<typename T> T readParameter( const std::string parameterName );
template<typename T> T convert( const std::string& value );
};
```
where the method `convert()` is defined in `VAConfig.cpp` as
```
template <typename T>
T VAConfig::convert( const std::string& value )
{
T t;
std::istringstream iss( value, std::istringstream::in );
iss >> t;
return t;
}
```
All quite simple. But when I test from my main program using
```
int y = parameters->convert<int>("5");
```
I get an `undefined reference to 'int VAConfig::convert<int>...'` compilation error. Ditto for `readParameter()`.
Looked at a lot of template tutorials but coul not figure this out. Any ideas? | Templated code implementation should never be in a `.cpp` file: your compiler has to see them at the same time as it sees the code that calls them (unless you use [explicit instantiation](http://www.cplusplus.com/articles/1C75fSEw/) to generate the templated object code, but even then `.cpp` is the wrong file type to use).
What you need to do is move the implementation to either the header file, or to a file such as `VAConfig.t.hpp`, and then `#include "VAConfig.t.hpp"` whenever you use any templated member functions. | If you move the implementation of the templated methods (convert and readParameter) to the header file, it should work.
The compiler must have access to the implementations of templated functions at the points where they're instantiated. | Undefined reference error for template method | [
"",
"c++",
"templates",
"compilation",
"linker",
""
] |
I wanted to have a look at the implementation of different C/C++ functions (like strcpy, stcmp, strstr). This will help me in knowing good coding practices in c/c++. Could you let me know where can I find it?
Thanks. | You could check out a copy of [glibc](http://www.gnu.org/software/libc/), which will have the source code for all C functions in the C standard library. That should be a good starting place. | It's worth pointing out that the source code for the C standard library does not necessarily highlight good coding practices. As the standard library, it has a special status where, for example, it can rely on a lot of unspecified or non-portable behavior simply because they know the exact compiler with which it is used.
And of course, this only tells you about C coding practices.
That has nothing to do with C++ coding practices, which are very different. Don't treat them as one language. There is no such thing as C/C++. C is a language with its own coding practices and common idioms, and C++ is a separate, independent language which also has its own practices and idioms.
Good C code is rarely good C++ code. `strcpy` and other C library functions are *certainly* not good C++ code. | source code of c/c++ functions | [
"",
"c++",
"c",
""
] |
As I understand it, when passing an object to a function that's larger than a register, it's preferable to pass it as a (const) reference, e.g.:
```
void foo(const std::string& bar)
{
...
}
```
This avoids having to perform a potentially expensive copy of the argument.
However, when passing a type that fits into a register, passing it as a (const) reference is at best redundant, and at worst slower:
```
void foo(const int& bar)
{
...
}
```
My problem is, I'd like to know how to get the best of both worlds when I'm using a templated class that needs to pass around either type:
```
template <typename T>
class Foo
{
public:
// Good for complex types, bad for small types
void bar(const T& baz);
// Good for small types, but will needlessly copy complex types
void bar2(T baz);
};
```
Is there a template decision method that allows me to pick the correct type? Something that would let me do,
```
void bar(const_nocopy<T>::type baz);
```
that would pick the better method depending on the type?
---
**Edit:**
After a fair amount of timed tests, the difference between the two calling times is different, but very small. The solution is probably a dubious micro-optimization for my situation. Still, [TMP](http://en.wikipedia.org/wiki/Template_metaprogramming) is an interesting mental exercise. | Use [Boost.CallTraits](http://www.boost.org/doc/libs/1_39_0/libs/utility/call_traits.htm):
```
#include <boost/call_traits.hpp>
template <typename T>
void most_efficient( boost::call_traits<T>::param_type t ) {
// use 't'
}
``` | If variable copy time is significant, the compiler will likely inline that instance of a template anyway, and the const reference thing will be just as efficient.
Technically you already gave yourself an answer.
Just specialize the `no_copy<T>` template for all the nocopy types.
```
template <class T> struct no_copy { typedef const T& type; };
template <> struct no_copy<int> { typedef int type; };
``` | How can I use templates to determine the appropriate argument passing method? | [
"",
"c++",
"templates",
"type-traits",
""
] |
Is there anyway to check if an enum exists by comparing it to a given string? I can't seem to find any such function. I could just try to use the `valueOf` method and catch an exception but I'v been taught that catching runtime exceptions is not good practice. Anybody have any ideas? | I don't think there's a built-in way to do it without catching exceptions. You could instead use something like this:
```
public static MyEnum asMyEnum(String str) {
for (MyEnum me : MyEnum.values()) {
if (me.name().equalsIgnoreCase(str))
return me;
}
return null;
}
```
**Edit:** As Jon Skeet notes, `values()` works by cloning a private backing array every time it is called. If performance is critical, you may want to call `values()` only once, cache the array, and iterate through that.
Also, if your enum has a huge number of values, Jon Skeet's map alternative is likely to perform better than any array iteration. | If I need to do this, I sometimes build a `Set<String>` of the names, or even my own `Map<String,MyEnum>` - then you can just check that.
A couple of points worth noting:
* Populate any such static collection in a static initializer. *Don't* use a variable initializer and then rely on it having been executed when the enum constructor runs - it won't have been! (The enum constructors are the first things to be executed, before the static initializer.)
* Try to avoid using `values()` frequently - it has to create and populate a new array each time. To iterate over all elements, use [`EnumSet.allOf`](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#allOf-java.lang.Class-) which is much more efficient for enums without a large number of elements.
Sample code:
```
import java.util.*;
enum SampleEnum {
Foo,
Bar;
private static final Map<String, SampleEnum> nameToValueMap =
new HashMap<String, SampleEnum>();
static {
for (SampleEnum value : EnumSet.allOf(SampleEnum.class)) {
nameToValueMap.put(value.name(), value);
}
}
public static SampleEnum forName(String name) {
return nameToValueMap.get(name);
}
}
public class Test {
public static void main(String [] args)
throws Exception { // Just for simplicity!
System.out.println(SampleEnum.forName("Foo"));
System.out.println(SampleEnum.forName("Bar"));
System.out.println(SampleEnum.forName("Baz"));
}
}
```
Of course, if you only have a few names this is probably overkill - an O(n) solution often wins over an O(1) solution when n is small enough. Here's another approach:
```
import java.util.*;
enum SampleEnum {
Foo,
Bar;
// We know we'll never mutate this, so we can keep
// a local copy.
private static final SampleEnum[] copyOfValues = values();
public static SampleEnum forName(String name) {
for (SampleEnum value : copyOfValues) {
if (value.name().equals(name)) {
return value;
}
}
return null;
}
}
public class Test {
public static void main(String [] args)
throws Exception { // Just for simplicity!
System.out.println(SampleEnum.forName("Foo"));
System.out.println(SampleEnum.forName("Bar"));
System.out.println(SampleEnum.forName("Baz"));
}
}
``` | Check if enum exists in Java | [
"",
"java",
"string",
"enums",
"compare",
""
] |
I have no idea why this doesn't work
```
#include <iostream>
#include <pthread.h>
using namespace std;
void *print_message(){
cout << "Threading\n";
}
int main() {
pthread_t t1;
pthread_create(&t1, NULL, &print_message, NULL);
cout << "Hello";
return 0;
}
```
The error:
> [Description, Resource, Path, Location, Type] initializing argument 3
> of 'int pthread\_create(pthread\_t\*, const pthread\_attr\_t\*, void\*
> (\*)(void\*), void\*)' threading.cpp threading/src line 24 C/C++
> Problem | You should declare the thread main as:
```
void* print_message(void*) // takes one parameter, unnamed if you aren't using it
``` | Because the main thread exits.
Put a sleep in the main thread.
```
cout << "Hello";
sleep(1);
return 0;
```
The POSIX standard does not specify what happens when the main thread exits.
But in most implementations this will cause all spawned threads to die.
So in the main thread you should wait for the thread to die before you exit. In this case the simplest solution is just to sleep and give the other thread a chance to execute. In real code you would use pthread\_join();
```
#include <iostream>
#include <pthread.h>
using namespace std;
#if defined(__cplusplus)
extern "C"
#endif
void *print_message(void*)
{
cout << "Threading\n";
}
int main()
{
pthread_t t1;
pthread_create(&t1, NULL, &print_message, NULL);
cout << "Hello";
void* result;
pthread_join(t1,&result);
return 0;
}
``` | Simple pthread! C++ | [
"",
"c++",
"pthreads",
""
] |
I need to test some ASP.NET code that handles timeout exceptions from a call to a MS-SQL database.
I'm able to reduce my CommandTimeout parameter on the connection, however this might cause errors before reaching my code.
Is there a simple way to cause the database to timeout 'on cue'? | What you are looking for sir is the [WAITFOR](http://msdn.microsoft.com/en-us/library/ms187331.aspx) command, database timeouts on queue whenever you feel like it. | Begin a transaction in a management studio SQL window, update the table, and don't commit it:
```
BEGIN TRAN
UPDATE table SET ...
```
This will lock any website attempt to read that table. | How can I cause a timeout exception in a database? | [
"",
"sql",
"timeout",
""
] |
I have an ordered sequence like {1, 3, 5, 6, 8, 9} I want to get first missing element(2 in the example) or max() if sequence contains no missing elements.
Now I'm doing it like this:
```
public static int GetRegisterNumber<T>(this IQueryable<T> enumerable, Func<T, bool> whereFunc, Func<T, int?> selectFunc)
{
var regNums = enumerable.OrderBy(selectFunc).Where(whereFunc).ToArray();
if (regNums.Count() == 0)
{
return 1;
}
for (int i = 0; i < regNums.Count(); i++)
{
if (i + 1 != regNums[i])
{
return regNums[i].Value + 1;
}
}
return regNums.Last().Value + 1;
}
```
But i think there are much faster methods. Any suggestions? | **Edit:** I just noticed that `enumerable` is `IQueryable<T>` but `selectFunc` and `whereFunc` are of type `Func<T, _>`. This will cause the `Enumerable` versions of `OrderBy` and `Where` to be called, rather than using database calls. You probably want to switch them to `Expression<Func<T, _>>` instead.
If you don't want to order `regNums` first, here's a O(n) golf-style solution:
```
var max = regNums.Max(i => (int?)i) ?? 0;
return Enumerable.Range(1, max + 1)
.Except(regNums)
.Min();
```
By line:
1. By casting to `int?`, `Max` will return `null` if `regNums` is empty, coalesced to `0`.
2. Build a sequence of all possible registers, including our next value if full.
3. Subtract the current set of registers.
4. Pick the lowest. | Assuming that your `OrderBy` and `Where` have already been applied:
```
int firstMissing = collection.TakeWhile((x, i) => x == ++i).LastOrDefault() + 1;
``` | Efficient way to get first missing element in ordered sequence? | [
"",
"c#",
"linq",
"linq-to-sql",
"search",
""
] |
I have a unordered list:
```
<ul id="sortable">
<li id="1" class="ui-state-default">First <a href='#' title='delete' class="itemDelete">x</a></li>
<li id="2" class="ui-state-default">Second <a href='#' title='delete' class="itemDelete">x</a></li>
<li id="3" class="ui-state-default">Third <a href='#' title='delete' class="itemDelete">x</a></li>
</ul>
```
I want to remove the `<li>` from the `<ul>`. I have handled the click event of the class itemDelete where I try to do a remove but I assume its not working because I can't remove the `<li>` as a child is calling it?
```
$('.itemDelete').live("click", function() {
var id = $(this).parent().get(0).id;
$("#" + id).remove();
});
```
What's the best approach? | Assuming you're using a recent version of jQuery:
```
$('#sortable').on('click', '.itemDelete', function() {
$(this).closest('li').remove();
});
```
`closest` is a little more dynamic than `parent` (although `parent` works here as well.) It gets the `li` that is closest to the current element, upwards in the structure. | Actually, the way you have it as of now, `id` is going to be undefined, because none of the li's have ids.
why not just do
```
$(this).parent().remove()
```
also, don't forget to return false. | jQuery Remove LI from UL with a hyperlink in the LI | [
"",
"javascript",
"jquery",
"jquery-ui",
""
] |
I have a query like this:
```
select foo.*, count(bar.id)
from foo inner join bar on foo.id = bar.foo_id
group by foo.id
```
This worked great with SQLite and MySQL. Postgres however, complains about me not including all columns of foo in the `group by` clause. Why is this? Isn't it enough that foo.id is unique? | Just in case other people stumble over this question:
Starting with PostgreSQL 9.1 it's sufficient to list the columns of the primary key in the group by clause (so the example from the question would work now). | Some databases are more relaxed about this, for good and bad. The query is unspecific, so the result is equally unspecific. If the database allows the query, it will return one record from each group and it won't care which one. Other databases are more specific, and require you to specify which value you want from the group. They won't let you write a query that has an unspecific result.
The only values that you can select without an aggregate is the ones in the `group by` clause:
```
select foo.id, count(bar.id)
from foo inner join bar on foo.id = bar.foo_id
group by foo.id
```
You can use aggregates to get other values:
```
select foo.id, min(foo.price), count(bar.id)
from foo inner join bar on foo.id = bar.foo_id
group by foo.id
```
If you want all the values from the foo table, you can either put them all in the `group by` clause (if that gives the correct result):
```
select foo.id, foo.price, foo.name, foo.address, count(bar.id)
from foo inner join bar on foo.id = bar.foo_id
group by foo.id, foo.price, foo.name, foo.address
```
Or, you can join the table with a subquery:
```
select foo.id, foo.price, foo.name, foo.address, sub.bar_count
from foo
inner join (
select foo.id, bar_count = count(bar.id)
from foo inner join bar on foo.id = bar.foo_id
group by foo.id
) sub on sub.id = foo.id
``` | Why no "SELECT foo.* ... GROUP BY foo.id" in Postgres? | [
"",
"sql",
"postgresql",
""
] |
I have a class:
```
public class PointD
{
public double X
{ get; set; }
public double Y
{ get; set; }
public PointD(double x, double y)
{
X = x;
Y=y;
}
//operator for +,-, * and / are overridden
}
```
Given a `list<PointD>`, how to get the average of it using LINQ? A `for` loop equivalent will be something like this:
```
double xx, yy;
for ( int i=0; i< ptlist.Count; i++)
{
xx+=ptlist[i].X;
yy+=ptlist[i].Y;
}
return new PointD(){X=xx, Y=yy};
```
You can use any **built-in** LINQ function only. You can't define an extension that takes care of this function.
Any idea?
**Edit: Of course, you can use two separate `Sum` extension method to Sum for X and Y component before merging them. But this is not what I want. What I want is a single query/ method that does the job** | The `Aggregate` function would come in handy here.
```
var sum = list.Aggregate((acc, cur) => acc + cur);
var average = list.Aggregate((acc, cur) => acc + cur) / list.Count;
```
Just insure that you have the `/` operator defined for types `PointD` and `int`, and this should do the job.
Note: I'm not quite sure whether you want the sum or average here (your question is somewhat ambiguous about this), but I've included examples for both. | You'll need to use the `Aggregate` method instead so you can provide your own aggregation function (`Sum` is just a convenient specialized case of this method). Something like:
```
points.Aggregate(new PointD(0, 0), (a, p) => a + p);
```
I know you say you don't want any additional methods defined, but if this is a common operation I'd be inclined to write an extension method for this, i.e.
```
public static PointD Sum(this IEnumerable<PointD> source)
{
return source.Aggregate(new PointD(0, 0), (a, p) => a + p);
}
```
Because it's much more readable to be able to write:
```
points.Sum();
``` | Using LINQ to Get Sum/ Average of a List with custom objects | [
"",
"c#",
"linq",
""
] |
I am currently working on an application that parses huge XML files.
For each file, there will be different processes but all of them will be parsed into a single object model.
Currently, the objects parsed from each XML file will go into a single collection.
This collection is also used during parsing, e.g. if a similar object already exists, it will modify the object's property instead, such as adding count.
Looking at the CPU graph when this application is running, it is clear that it only uses part of the CPU (one core at a time on 100%), so I assume that running it on parallel will help shave running time.
I am new into parallel programming, so any help is appreciated. | I would suggest you the following technique: construct a queue of objects that wait to be processed and dequeue them from multiple threads:
1. Create an XmlReader and start reading the file node by node while not EOF.
2. Once you encounter a closing tag you can serialize the contents it into an object.
3. Put the serialized object into a Queue.
4. Verify the number of objects in the Queue and if it is bigger than N, kick a new thread from the ThreadPool which will dequeue <= N objects from the queue and process them.
The access to the queue needs to be synchronized because you will enqueue and dequeue objects from multiple threads.
The difficulty consists in finding N such that all the CPU cores work at the same time. | I suggest that you look at using threads instead of parallel programming.
[Threading Tutorial](http://msdn.microsoft.com/en-us/library/aa645740(VS.71).aspx) | Parallelize A Batch Application | [
"",
"c#",
".net",
"xml",
"parallel-processing",
""
] |
what should the following java code do?
```
public class foo{
public static void main(String[] args){
boolean mybool=false;
assert (mybool==true);
}
}
```
Should this throw an assertion error? and if not why not? (I'm not getting any errors!) | This should be throwing `AssertionErors`.
You need to turn on assertions if you are using Eclipse. It has them disabled by default.
To do this, add -ea to the JVM arguments. | When running the program, you have to enable assertions in the Java VM by adding '-ea' to the command line:
```
java -ea -jar myprogram.jar
``` | java assert gives strange results | [
"",
"java",
"boolean",
"assertions",
""
] |
Ok, this one is driving me completely crazy. I have a table in a PostgreSQL database and I'm trying to get the value a boolean column for a specific record with OdbcDataReader.GetBoolean(int col).
The problem is that GetBoolean() keeps throwing a *cast is not valid* exception even though the same code worked just several days ago. What's even weirder is the same code works fine in another form.
The only change made from the previous working version of my application was adding a column to the table. That said, the index of the column that I need hasn't changed. Oh yeah, getting the value with GetValue() and then calling GetType() on the result returns System.String and the true/false values get translated to 1/0.
I'm all out of ideas. | While I still have no idea what is causing this exception, I've managed to come up with code that works (not actual code from my app):
```
val1 = reader.GetInt32(0);
val2 = reader.GetBoolean(4);
val3 = reader.GetBoolean(8);
```
This, however, does not:
```
val3 = reader.GetBoolean(8);
val1 = reader.GetInt32(0); // causes invalid cast exception
val2 = reader.GetBoolean(4);
```
Apparently, the column order has something to do with it. | I don't think passing a System.String to GetBoolean() is going to work for you - as you can see from your exception you're getting an InvalidCastException, which means that internally somewhere it's trying to do something like this:
```
string s = "true";
bool b = (bool)s;
```
That clearly won't work.
If you can see that ODBC is passing you back a System.String then you want to use either Convert.ToBoolean(), bool.TryParse(), or bool.Parse, depending on what exactly fits best with the rest of your code.
As to why it WAS working and now isn't - has someone else changed the underlying data type on the database field to a character-based type?
This pattern is what we use to get boolean data out of an OdbcDataReader:
```
data.Gender = reader["Gender"] == DBNull.Value ?
false : Convert.ToBoolean(reader["Gender"]);
```
Laborious, yes. But it works well for us. The underlying database for this code is Access ("yes/no" field type) or MS SQL Server ("bit" field type). | weird problem with OdbcDataReader.GetBoolean() throwing cast is not valid exception for bool column | [
"",
"c#",
"postgresql",
"odbc",
""
] |
I just want to know for what `java.util.Collections.checkedList()` is actually used.
I have some code that I know is returning me a `List<String>` but it's being passed through a chain of messaging calls and returned to me as a `java.io.Serializable`. Is that checkedList call good for me to turn my `Serializable` into a `List<String>`? I know I can cast it to a `java.util.List`, but I'd rather not have to check each element and I'm not comfortable with assuming each element is a `String`. | It is used in part as a debugging tool to find where code inserts a class of the wrong type, in case you see that happening, but can't figure out where.
You could use it as part of a public API that provides a collection and you want to ensure the collection doesn't get anything in it of the wrong type (if for example the client erases the generics).
The way you could use it in your case is:
```
Collections.checkedList(
new ArrayList<String>(uncertainList.size()), String.class)
.addAll(uncertainList);
```
If that doesn't throw an exception, then you know you are good. That isn't exactly a performance optimized piece of code, but if the list contents are reasonably small, it should be fine. | Not quite:
`Collections.checkedList` will only decorate the list to prevent any future inserts with objects of the wrong class, it won't check all the elements that are already in the list.
However, you could make a new checkedList, and then call `addAll` and pass in the list you are unsure about - rather than writing the loop yourself. | What is the Collections.checkedList() call for in java? | [
"",
"java",
"generics",
"collections",
""
] |
I'm tempted to add a suffix like "Ex" to differentiate methods (with similar signatures) that throw Exceptions from those that don't.
Is there such a convention? | Yes, you name them the same as methods that don't.
Isn't the exception specification enough?
Edit: If you have similar methods that throw/not throw, I recommend the `Parse`/`TryParse` pattern (`Parse` being replaced by the operation). .NET Framework uses it frequently (`Dictionary<T,K>.TryGetValue`, `Monitor.TryEnter`, `int.TryParse`, etc. etc.).
Edit: [Coding Horror: TryParse and the Exception Tax](http://www.codinghorror.com/blog/archives/000358.html) | Don't do that.
This is like asking "is there a naming convention for methods that take two Strings as parameters".
Java has checked exceptions, which means that you need to declare them anyway.
So you can easily see if an exception will be thrown, and what type of exception.
You cannot even compile code that calls the method without adding exception handling code.
**Update:** It seems your intention is to have methods that check if a certain condition is true, but you do not want to return just false, but throw an Exception if the condition is not met, so that you can also convey an explanation message (in the Exception). I think a prefix of "assert" or "ensure" makes sense:
```
// instead of
if (! isAuthenticated())
throw new NotAuthenticatedException("not sure why at this point...");
// you do
assertAuthentication();
// which will throw NotAuthenticatedException("proper explanation") inside
``` | Is there a particular naming convention for Java methods that throw exceptions? | [
"",
"java",
"coding-style",
"method-names",
""
] |
What is considered the appropriate development for .asmx or wcf service classes regarding how many files, lines of code, responsibilities, etc? Do most people publish separate .asmx service files for the different crud methods for every class? | First of all, the best practice for new development is to use WCF. See [Microsoft: ASMX Web Services are a “Legacy Technology”](http://johnwsaundersiii.spaces.live.com/blog/cns!600A2BE4A82EA0A6!860.entry).
Second, in SOA, one tries to create services with coarsly-grained operations. For instance, you would want an OrderProduct operation, rather than StartOrder, AddLineItem, AddOption, FinishOrder operations. The OrderProduct operation might accept an OrderDTO as follows:
```
public class OrderDTO {
public CustomerInfo Customer {get;set;}
public DateTime OrderTime {get;set}
public DateTime ShipTime {get;set;}
public List<LineItemDTO> LineItems {get; private set;}
}
public class LineItemDTO {
public int LineItemNumber {get;set;}
public string ProductName {get;set;}
public int Quantity {get;set}
public Decimal Amount {get;set}
public Decimal ExtendedAmount {get;set;}
}
```
Rather than a StartOrder method that just creates an empty order, followed by AddLineItem calls to add individual line items (as you might do from a desktop application), I'm recommending a single OrderProduct method that accepts an OrderDTO, which will have a collection of LineItemDTO. You'll send the entire order all at once, add all the pieces in a transaction, and be done.
Finally, I'd say that you should still separate into business and data layers. The service layer should be concerned only with the services side of things, and will call on your business logic layer in order to get things done. | Generally speaking, a service should encapsulate a set of common operations. Regardless of whether you use ASMX or WCF, you shouldn't be creating one "service" for each operation. The general idea behind service-oriented architecture (SOA) is to model real-world business behavior. To give you a dumb, but hopefully effective, example...think of a waitress at a restaurant. The waitress provides a service to customers in the form of taking orders, serving those orders, providing drink refills, providing condiments, and finally handling payment. The service the waitress offers is not a single operation, its an aggregation of related operations.
However, it doesn't stop there. The true nature of SOA is that any given service is likely to rely on other services. The waitress can not do her job without relying on the services of the cook, to provide meals, the person serving the counter, where she can get instances of condiments and drink, and the services provided by the restaurant building itself. There are also some fundamental differences between the kind of service provided by a waitress, and that provided by a cook. To bring it down to technical programming terms...a Waitress is a task service, but a Cook is an entity (or CRUD) service. The waitress handles higher level operations that provide useful functionality to clients, while the cook handles lower level operations that provide fine-grained and complex functionality only to other employees of the restaurant.
I can't really give you a specific answer to your question, other than to say just organize your services however they logically fit. Its probably not a good practice to have one operation per service...however, it is not unheard of for a service to have just one operation. Task services often have just one operation. Entity services often have many operations, usually CRUD based, but sometimes additional services. There are also Utility services that provide lowest level, infrastructural operations (back to the restaurant, utility services would be like stoves, grills, the register, etc.) If you model your services after actual business concepts, then the operations they expose and their dependencies on each other should eventually become clear.
For some GREAT information on SOA, check out the SOA series by Thomas Erl (Prentice Hall), as they are the definitive resource for implementing a service-oriented enterprise. | .net Web services best practice...SRP? | [
"",
"c#",
"wcf",
"web-services",
""
] |
I am using a shared hosting through CIPL.in. They use cpanel. I am trying to deploy a ZEND app on my website. However it keeps giving the error.
```
An error occurred
Application error
Exception information:
Message: The PDO extension is required for this adapter but the extension is not loaded
Stack trace:
#0 /home/cubeeeco/worminc/library/Zend/Db/Adapter/Abstract.php(770): Zend_Db_Adapter_Pdo_Abstract->_connect()
#1 /home/cubeeeco/worminc/library/Zend/Db/Adapter/Abstract.php(840): Zend_Db_Adapter_Abstract->quote('windchimes', NULL)
#2 /home/cubeeeco/worminc/library/Zend/Auth/Adapter/DbTable.php(354): Zend_Db_Adapter_Abstract->quoteInto('`password` = MD...', 'windchimes')
#3 /home/cubeeeco/worminc/library/Zend/Auth/Adapter/DbTable.php(285): Zend_Auth_Adapter_DbTable->_authenticateCreateSelect()
#4 /home/cubeeeco/worminc/library/Zend/Auth.php(117): Zend_Auth_Adapter_DbTable->authenticate()
#5 /home/cubeeeco/worminc/application/controllers/LoginController.php(117): Zend_Auth->authenticate(Object(Zend_Auth_Adapter_DbTable))
#6 /home/cubeeeco/worminc/library/Zend/Controller/Action.php(503): LoginController->processAction()
#7 /home/cubeeeco/worminc/library/Zend/Controller/Dispatcher/Standard.php(285): Zend_Controller_Action->dispatch('processAction')
#8 /home/cubeeeco/worminc/library/Zend/Controller/Front.php(934): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#9 /home/cubeeeco/public_html/worm/index.php(47): Zend_Controller_Front->dispatch()
#10 {main}
```
Also when I try to print out the phpinfo I get:
```
System Linux bear.dnsracks.com 2.6.18-92.1.13.el5PAE #1 SMP Wed Sep 24 20:07:49 EDT 2008 i686
Build Date Jun 8 2009 13:50:29
Configure Command './configure' '--disable-pdo' '--enable-bcmath' '--enable-calendar' '--enable-ftp' '--enable-gd-native-ttf' '--enable-libxml' '--enable-magic-quotes' '--enable-mbstring' '--enable-sockets' '--prefix=/usr' '--with-curl=/opt/curlssl/' '--with-freetype-dir=/usr' '--with-gd' '--with-gettext' '--with-imap=/opt/php_with_imap_client/' '--with-imap-ssl=/usr' '--with-jpeg-dir=/usr' '--with-kerberos' '--with-libxml-dir=/opt/xml2/' '--with-mcrypt=/opt/libmcrypt/' '--with-mysql=/usr' '--with-mysql-sock=/var/lib/mysql/mysql.sock' '--with-mysqli=/usr/bin/mysql_config' '--with-openssl=/usr' '--with-openssl-dir=/usr' '--with-png-dir=/usr' '--with-ttf' '--with-xpm-dir=/usr' '--with-zlib' '--with-zlib-dir=/usr'
Server API CGI
Virtual Directory Support disabled
Configuration File (php.ini) Path /usr/lib
Loaded Configuration File /usr/local/lib/php.ini
Scan this dir for additional .ini files (none)
additional .ini files parsed (none)
PHP API 20041225
PHP Extension 20060613
Zend Extension 220060519
Debug Build no
Thread Safety disabled
Zend Memory Manager enabled
IPv6 Support enabled
Registered PHP Streams php, file, data, http, ftp, compress.zlib, https, ftps
Registered Stream Socket Transports tcp, udp, unix, udg, ssl, sslv3, sslv2, tls
Registered Stream Filters string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, convert.iconv.*, zlib.*
```
This can be seen at <http://cubeee.co.in/worm/tester.php>
However when I get back to my hosting providers, they tell me that they have modified the php.ini to enable the PDO support and they will check again. What is it that I need to do or ask my hosts to do? | The configure command in your PHP output shows:
```
'--disable-pdo'
```
so I think it's safe to assume that they haven't enabled it. | ```
if (!defined('PDO::ATTR_DRIVER_NAME')) {
echo 'PDO unavailable';
}
elseif (defined('PDO::ATTR_DRIVER_NAME')) {
echo 'PDO available';
}
```
I hope this works | How to check if PDO support is enabled in my Apache Installation? | [
"",
"php",
"apache",
"zend-framework",
"hosting",
"pdo",
""
] |
I've inherited some code that uses the `sqlsrv_connect` method to instantiate a connection to a SQL Server database. My personal development machine is an OS X box that I'm running apache an PHP on. I have an instance of SQL Server running in a virtual machine.
When I attempt to connect to the database, I get the following error.
```
Fatal error: Call to undefined function sqlsrv_connect() in ...
```
It appears that `sqlsrv_connect` is not part of standard PHP, and is part of a driver that ships with [SQL Server 2005](http://msdn.microsoft.com/en-us/library/cc296161(SQL.90).aspx). (please correct me if I'm wrong here)
Is there a way to use this function on Non-Windows platforms? I realize I could install/build an Apache/PHP instance on my Windows machine, but if there's a way to get this function working on OS X (or other \*nixes) I'd prefer it. | Is not possible. The SQL Native Driver for PHP is [Windows only product](https://web.archive.org/web/20090714022537/http://www.codeplex.com:80/SQL2K5PHP):
> The SQL Server Driver for PHP relies
> on the Microsoft SQL Server 2005 ODBC
> Driver to handle the low-level
> communication with SQL Server. As a
> result, the SQL Server Driver for PHP
> is only supported on Windows. | You can look here for a [tutorial](https://web.archive.org/web/20210127083156/http://geekswithblogs.net/tkokke/archive/2009/05/08/how-to-let-php-get-data-from-microsoft-sql-server.aspx) on how to install the extension. (Via Google)
I'm not too famillar with the extension, but that source should be able to help you out.
(Updated Link to Better Source, still via Google) | Using sqlsrv_connect on Platforms other than Windows | [
"",
"php",
"sql-server",
"windows",
"sql-server-2005",
"macos",
""
] |
Here is my problem. I'm working on a Jython program and I have to extract numbers from a PyJavaInstance:
[{string1="foo", xxx1, xxx2, ..., xxxN, string2="bar"}]
(where xxx are the floating point numbers).
My question is how can I extract the numbers and put them in a more simple structure like a python list.
Thank you in advance. | A `PyJavaInstance` is a Jython wrapper around a Java instance; how you extract numbers from it depends on what it is. If you need to get a bunch of stuff - some of which are strings and some of which are floats, then:
```
float_list = []
for item in instance_properties:
try:
float_list.append(float(item))
except ValueError:
pass
``` | can you iterate and check whether an item is float? The method you're looking for is [`isinstance`](http://docs.python.org/library/functions.html?highlight=isinstance#isinstance). I hope it's implemented in Jython. | Extract only numbers from data in Jython | [
"",
"python",
"list",
"jython",
"extract",
""
] |
[Template methods](http://en.wikipedia.org/wiki/Template_method_pattern) **as in NOT C++ templates**.
So, say that you would like to do some searching with different algorithms - Linear and Binary for instance. And you would also like to run those searches through some common routines so that you could, for instance, automatically record the time that a given search took and so on.
The template method pattern fills the bill beautifully. The only problem is that as far as I've managed to dig around, **you can't actually implement this behaviour via static methods with C++, 'cause you would also need to make the methods virtual(?)** Which is of course a bit of a bummer because I don't have any need to alter the state of the search object. I would just like to pin all the searching-thingies to its own namespace.
***So the question is:*** *Would one want to use something like function/method pointers instead? Or would one just use namespaces to do the job?*
It's pretty hard to live with this kind of (dare I say) limitations with C++, as something like this would be a breeze with Java.
**Edit:**
Oh yeah, and since this is a school assignment, the use of external libraries (other than STL) isn't really an option. Sorry for the hassle. | I don't see why you'd need the template method pattern.
Why not just define those algorithms as functors that can be passed to your benchmarking function?
```
struct BinarySearch { // functor implementing a specific search algorithm
template <typename iter_type>
void operator()(iter_type first, iter_type last){ ....}
};
template <typename data_type, typename search_type>
void BenchmarkSearch(data_type& data, search_type search){ // general benchmarking/bookkeeping function
// init timer
search(data);
// compute elapsed time
}
```
and then call it like this:
```
int main(){
std::vector<int> vec;
vec.push_back(43);
vec.push_back(2);
vec.push_back(8);
vec.push_back(13);
BenchmarkSearch(vec, BinarySearch());
BenchmarkSearch(vec, LinearSearch()); // assuming more search algorithms are defined
BenchmarkSearch(vec, SomeOtherSearch();
}
```
Of course, another approach, which is a bit closer to what you initially wanted, could be to use [CRTP](http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) (A pretty clever pattern for emulating virtual functions at compile-time - and it works with static methods too):
```
template <typename T>
struct SearchBase { // base class implementing general bookkeeping
static void Search() {
// do general bookkeeping, initialize timers, whatever you need
T::Search(); // Call derived search function
// Wrap up, do whatever bookkeeping is left
}
}
struct LinearSearch : SearchBase<LinearSearch> // derived class implementing the specific search algorithms
{
static void Search(){
// Perform the actual search
}
};
```
Then you can call the static functions:
```
SearchBase<LinearSearch>::Search();
SearchBase<BinarySearch>::Search();
SearchBase<SomeOtherSearch>::Search();
```
As a final note, it might be worth mentioning that both of these approaches should carry zero overhead. Unlike anything involving virtual functions, the compiler is fully aware of which functions are called here, and can and will inline them, resulting in code that is just as efficient as if you'd hand-coded each case. | Here's a simple templatized version that would work
```
template <typename F, typename C>
clock_t timer(F f, C c)
{
clock_t begin = clock();
f(c);
return clock() - begin;
}
void mySort(std::vector<int> vec)
{ std::sort(vec.begin(), vec.end()); }
int main()
{
std::vector<int> vec;
std::cout << timer(mySort, vec) << std::endl;
return 0;
}
``` | C++ w/ static template methods | [
"",
"c++",
""
] |
**Update:** Thanks for everyone who helped out - the answer to this one lay in what I wasn't noticing in my more complex code and what I didn't know about the Java5 covariant return types.
**Original Post:**
I've been playing around with something this morning. While I know that I *could* tackle this whole problem differently, I'm finding myself obsessed with figuring out why it isn't working the way that I was expecting. After spending some time reading around on this, I find I'm no closer to understanding, so I offer it up as a question to see if I'm just being stupid or if there is really something I don't understand going on here.
I have created a custom Event hierarchy like so:
```
public abstract class AbstractEvent<S, T extends Enum<T>>
{
private S src;
private T id;
public AbstractEvent(S src, T id)
{
this.src = src;
this.id = id;
}
public S getSource()
{
return src;
}
public T getId()
{
return id;
}
}
```
With a concrete implementation like so:
```
public class MyEvent
extends AbstractEvent<String, MyEvent.Type>
{
public enum Type { SELECTED, SELECTION_CLEARED };
public MyEvent(String src, Type t)
{
super(src, t);
}
}
```
And then I create an event like so:
```
fireEvent(new MyEvent("MyClass.myMethod", MyEvent.Type.SELECTED));
```
Where my fireEvent is defined as:
```
protected void fireEvent(MyEvent event)
{
for(EventListener l : getListeners())
{
switch(event.getId())
{
case SELECTED:
l.selected(event);
break;
case SELECTION_CLEARED:
l.unselect(event);
break;
}
}
}
```
So I thought that this would be pretty straightforward but it turns out that the call to event.getId() results in the compiler telling me that I cannot switch on Enums, only convertible int values or enum constants.
It is possible to add the following method to MyEvent:
```
public Type getId()
{
return super.getId();
}
```
Once I do this, everything works exactly as I expected it to. I'm not just interested in finding a workaround for this (because I obviously have one), I'm interested in any insight people might have as to WHY this doesn't work as I expected it to right off the bat. | Yishai is right, and the magic phrase is "[covariant return types](http://java.sun.com/developer/JDCTechTips/2004/tt1201.html#2)" which is new as of Java 5.0 -- you can't switch on Enum, but you can switch on your Type class which extends Enum. The methods in AbstractEvent that are inherited by MyEvent are subject to type erasure. By overriding it, you're redirecting the result of `getId()` towards your Type class in a way that Java can handle at run-time. | This is not related to generics. Switch statement for enum in java can only use values of that particular enum, thus it's *prohibited* to actually specify enum name. This should work:
```
switch(event.getId()) {
case SELECTED:
l.selected(event);
break;
case SELECTION_CLEARED:
l.unselect(event);
break;
}
```
**Update**: Ok, here's an actual code (which I had to change a little bit to get it to compile with no dependencies) that I've copy / pasted, compiled and ran - no errors:
AbstractEvent.java
```
public abstract class AbstractEvent<S, T extends Enum<T>> {
private S src;
private T id;
public AbstractEvent(S src, T id) {
this.src = src;
this.id = id;
}
public S getSource() {
return src;
}
public T getId() {
return id;
}
}
```
MyEvent.java
```
public class MyEvent extends AbstractEvent<String, MyEvent.Type> {
public enum Type { SELECTED, SELECTION_CLEARED };
public MyEvent(String src, Type t) {
super(src, t);
}
}
```
Test.java
```
public class Test {
public static void main(String[] args) {
fireEvent(new MyEvent("MyClass.myMethod", MyEvent.Type.SELECTED));
}
private static void fireEvent(MyEvent event) {
switch(event.getId()) {
case SELECTED:
System.out.println("SELECTED");
break;
case SELECTION_CLEARED:
System.out.println("UNSELECTED");
break;
}
}
}
```
This compiles and runs under Java 1.5 just fine. What am I missing here? | Using Java Generics with Enums | [
"",
"java",
"generics",
"enums",
"switch-statement",
""
] |
How can I do a select in linq to entities to select rows with keys from a list? Something like this:
```
var orderKeys = new int[] { 1, 12, 306, 284, 50047};
var orders = (from order in context.Orders
where (order.Key in orderKeys)
select order).ToList();
Assert.AreEqual(orderKeys.Count, orders.Count);
```
I tried using the *Contains* method as mentioned in some of the answers but it does not work and throws this exception:
*LINQ to Entities does not recognize the method 'Boolean Contains[Int32](System.Collections.Generic.IEnumerable`1[System.Int32], Int32)' method, and this method cannot be translated into a store expression.* | ~~Try this:~~
```
var orderKeys = new int[] { 1, 12, 306, 284, 50047};
var orders = (from order in context.Orders
where orderKeys.Contains(order.Key);
select order).ToList();
Assert.AreEqual(orderKeys.Count, orders.Count);
```
**Edit:** I have found some workarounds for this issue - please see [WHERE IN clause?](http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/095745fe-dcf0-4142-b684-b7e4a1ab59f0/):
> The Entity Framework does not
> currently support collection-valued
> parameters ('statusesToFind' in your
> example). To work around this
> restriction, you can manually
> construct an expression given a
> sequence of values using the following
> utility method: | I had the same problem and i solved like this
```
var orderKeys = new int[] { 1, 12, 306, 284, 50047};
var orders = (from order in context.Orders
where (orderKeys.Contains(order.Key))
select order).ToList();
Assert.AreEqual(orderKeys.Count, orders.Count);
``` | How to do an "in" query in entity framework? | [
"",
"c#",
".net",
"linq",
"entity-framework",
""
] |
Isn't this a client side control?
What will happen if the user has disabled javascript? | No, it does not. It is not affected by javascript support. | Funny, I *rarely* use this control, but it plays an important role in an app I'm working on and have open on my desktop right now. So I checked: I disabled javascript for the page with NoScript and it still did exactly what it's supposed to do. | Does the ASP.Net Wizard Control work with javascript disabled? | [
"",
"asp.net",
"javascript",
"controls",
""
] |
I have the following defined in my web.config (
```
<rewriteMaps configSource="Rewrites.config" />
```
I have a CONFIG file that can be regenerated by an administrator via a web page. However when this file changes then the new changes are not picked up until the application recycles.
My queestion is that I want to be able to recycle the application pool automatically when the file changes, is this possible? or is their a better approach?
Maybe the question should be is there another way for the rewrite maps to be dynamically used by the application?
I am using IIS7 in Integrated Mode running under Medium Trust.
Thanks
Richard | A hack way of recycling just your app pool is to add then delete a subfolder. This will trigger an app recycle. | Take a look at this if you are interested in programaticaly recycling the app pool, [Recycle App Pool](http://codinglifestyle.wordpress.com/2006/10/20/programatically-recycle-an-iis-application-pool/), there is also a link at the bottom for recycling via a script | rewritemaps with an external config to force an application pool recycle | [
"",
"c#",
"iis-7",
"mod-rewrite",
"url-rewriting",
""
] |
I have a strongly-typed Partial View that takes a ProductImage and when it is rendered I would also like to provide it with some additional ViewData which I create dynamically in the containing page. How can I pass both my strongly typed object and my custom ViewData to the partial view with the RenderPartial call?
```
var index = 0;
foreach (var image in Model.Images.OrderBy(p => p.Order))
{
Html.RenderPartial("ProductImageForm", image); // < Pass 'index' to partial
index++;
}
``` | RenderPartial takes another parameter that is simply a ViewDataDictionary. You're almost there, just call it like this:
```
Html.RenderPartial(
"ProductImageForm",
image,
new ViewDataDictionary { { "index", index } }
);
```
Note that this will override the default ViewData that all your other Views have by default. If you are adding anything to ViewData, it will not be in this new dictionary that you're passing to your partial view. | To extend on what womp posted, you **can** pass new View Data while retaining the existing View Data if you use the constructor overload of the `ViewDataDictionary` like so:
```
Html.RenderPartial(
"ProductImageForm",
image,
new ViewDataDictionary(this.ViewData) { { "index", index } }
);
``` | Pass Additional ViewData to a Strongly-Typed Partial View | [
"",
"c#",
"asp.net",
"asp.net-mvc",
"asp.net-mvc-partialview",
"viewdata",
""
] |
I have a select tag that is populated with a list of files each time the page loads. I would like the image to change to the selected file each time one is clicked in the select input. This is what I have right now, and it does not work properly. However, when it is clicked, the image and text are visible/hidden as they should be. Any help would be greatly appreciated.
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title> Table Edit The Shakespeare Studio </title>
<link rel="stylesheet" type="text/css" href="../styles.css" />
</head>
<body>
<script language="javascript" type="text/javascript">
function edit_image1()
{
if (document.getElementById('select1').value == "0") {
document.preview1.style.visibility = "hidden";
document.getElementById('random1').style.visibility = "visible";
} else {
var selected = document.getElementById('select1').options[document.getElementById('select1').selectedIndex].value;
document.preview1.style.visibility = "visible";
document.preview1.src = "../resources/uploads/"+selected;
document.getElementById('random1').style.visibility = "hidden";
}
}
</script>
<div id="everything">
<form action='tableEdit.php' method='GET'>
<table border='1' id='cal'>
<tr id='top'><td> Page Name </td><td> Image to Use </td><td> Preview </td></tr>
<tr>
<td> about </td>
<td>
<select name='aboutImage' id='select1' onchange='edit_image1()';>
<option value='0' selected> RANDOM IMAGE</option>
<option value='IMG_6027.JPG'>IMG_6027.JPG</option>
<option value='IMG_6032.JPG'>IMG_6032.JPG</option>
<option value='kissme-1.jpg'>kissme-1.jpg</option>
</select>
</td>
<td>
<img name='preview1' src='../resources/uploads/0'></img>
<h3 id='random1'> Random </h3>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
``` | When I did something similar, I created a new `Image` object in the script. You should be able to do this simply by building an "`<IMG>`" element, and setting the `innerHTML` property of the parent.
Edit: something like this:
```
<html>
<head>
<title>Image Replacement Example</title>
</head>
<body>
<div id="imageHolder">
<img src="http://stackoverflow.com/content/img/so/logo.png">
</div>
<br>
<button onClick="javascript:newImage();return false;">Click Me</button>
<script type="text/javascript">
function newImage()
{
var holder = document.getElementById("imageHolder");
holder.innerHTML = "<img src='http://serverfault.com/content/img/sf/logo.png'>"
}
</script>
``` | Your code has a number of bugs in it, but you are definitely on your way to getting it to work.
YOu are thinking correctly to change the "src" value of the image, this will correctly what appears, but be aware that the server has to connect and download the new image.
using the same HTML you have, use this javascript code:
```
function edit_image(){
var doc = document;
var selectedIndex = doc.getElementById('select1').selectedIndex;
var previewVisible = doc.getElementById("preview1").style.visibility;
var randomVisible= doc.getElementById("random1").style.visibility;
if (selectedIndex === 0){
previewVisible = "hidden";
randomVisible = "visible";
} else {
var previewSrc = doc.getElementById("preview1").src;
var selectValue = doc.getElementById('select1').options[selectedIndex].value;
previewSrc = "../resources/uploads/"+ selectValue;
previewVisible = "visible";
randomVisible = "hidden";
}
```
I figure this would also be a good time to give you some tips on writing efficient Javascript as well. The reason i set all of these local variables is because local variables are a LOT faster for javascript to read and interact with than global objects. the "document" object is part of the global scope, and can get slow to access all the time as your page and functions grow.
I am also setting a variable for each property of the document.getElementById("someid") because making calls to DOM functions are really really slow in the browser.
Also, setting a variable like so:
```
var links = document.getElementsByTagName("A");
```
creates a variable the references a QUERY to the DOM, **NOT** a reference to an array that contains all links on the page. So as you progressively do the following:
```
links.style.visibility = "visible";
links.innerHTML = "some new text";
```
You actually end up making TWO queries to grab every single anchor on the page.
Sorry if this is a lot of information at once, but this example code looked like a good way to give you some tips to write better Javascript and help create better web pages for the internet :-) | Changing Image SRC Based on SELECT | [
"",
"javascript",
"onclick",
"image",
""
] |
I have a simple html page that only uses PHP in two places
```
<?php preg_replace('/(www\.)?([^.]*)\.(com|info)/', '${2}', $_SERVER['HTTP_HOST']); ?>
<?php echo $_SERVER['HTTP_HOST']); ?>
```
In page is loaded on multiple domains, and I just want to display the host name as text in some other static content
I'd like to remove the need for PHP completely, but not repalce it with another full blown compiler or interpreter. I'd like to avoid using javascript. I can live without being able to do a regex to get the second level of the domain name, but would still like that option. Do I have any options for doing this via a simpler apache module than mod\_php?
Theres nothing wrong with mod\_php, I'm just seeing if I can minimalize the needs of this website I am working on. | I’d combine both mod\_rewrite and SSI. Set an environment variable with mod\_rewrite:
```
RewriteCond %{HTTP_HOST} ^(www\.)?([^.]*)\.(com|info)$
RewriteRule ^ - [L,E=HOST:%2]
```
And then access that information in SSI with:
```
<!--#echo var="HOST" -->
``` | I havn't tested it buy you might be able to use htaccess and do a rewrite like this:
```
RewriteRule (.*) $1?httm_host=%{HTTP_HOST} [L]
```
I don't know for sure that the %{HTTP\_HOST} variable is available in a rewrite but it may work. You may need to use a condition to check for the ? in the URL. | Is there an alternative to PHP's $_SERVER['HTTP_HOST']); for apache that does not require a full blown programming language (e.g. SSI) | [
"",
"php",
"apache",
""
] |
I would like the label associated with a radio button 'hot'. I started to implement this using the .siblings() method. I think there must be a better way. The click event on the radio button looks like this:
```
$(".RadioButton").click(function(event) {
var questionId = $(this).find('input').attr('name');
var responseId = $(this).find('input').attr('value');
var answerText = displayPopupQuizAnswer($(this));
```
This works great. I would like the same code to execute when the user clicks on the text label accompanying the radio button. The html looks something like this:
```
<div class="answers">
<span class="radiobutton>
<input type="radio" name="answer1"/>
</span>
<span class="answertextwrapper">
<a href="return false">this is the text</a>
</span>
</div>
```
This is simplified but it's close. What I want is to capture the click event on the element with class="answertextwrapper" i.e. $(".answerwrapper").click
So I need to somehow reference the input when the text is clicked. Make sense?
Any ideas? | Simple, use actual [label elements](http://www.w3schools.com/tags/tag_label.asp);
When you use these, not only do you gain nice usability, but their click event is bound to the radio button's click event. In otherwords, *you don't have to do any additional jQuery*, just update your HTML.
Here it is in action - if you have firebug you can clearly see that $(this) always refers to the `<input>`, regardless of whether or not you actually click on the corresponding `<label>`
```
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(function()
{
$('input.quiz-button').click( function( event )
{
console.log( $(this) );
})
} );
</script>
</head>
<body>
<form id="test" name="tester">
<input class="quiz-button" type="radio" name="answer1" id="answer1"/>
<label for="answer1">this is the text 1</label>
<input class="quiz-button" type="radio" name="answer2" id="answer2"/>
<label for="answer2">this is the text 2</label>
</form>
</body>
</html>
``` | You can come up with some sort of traversing technique to suit your needs, but I recommend you use the [`<label>` element](http://www.w3.org/TR/html401/interact/forms.html#h-17.9.1) instead: not only is it the semantically correct way of doing this, you can then add in the `for` attribute to point it back to the input field it is a label of:
```
<div class="answers">
<span class="radiobutton>
<input type="radio" name="answer1" id="answer1"/>
</span>
<label class="answertextwrapper" for="answer1">
this is the text
</label>
</div>
```
And then your Javascript can look like this:
```
$("span.RadioButton").click(function(event) {
//...
});
```
Note that it is *much* better to prepend the tag name when you are doing class selectors in Javascript (see comments for more). I also removed the empty link as doing it that way is a bad practice as well. You should just add the cursor declaration in your CSS instead if you want the hand to come up. | JQuery Add click event to radio input text | [
"",
"javascript",
"jquery",
"html",
""
] |
I have a question about different versions of an object, their sizes, and allocation. The platform is Solaris 8 (and higher).
Let's say we have programs A, B, and C that all link to a shared library D. Some class is defined in the library D, let's call it 'classD', and assume the size is 100 bytes. Now, we want to add a few members to classD for the next version of program A, without affecting existing binaries B or C. The new size will be, say, 120 bytes. We want program A to use the new definition of classD (120 bytes), while programs B and C continue to use the old definition of classD (100 bytes). A, B, and C all use the operator "new" to create instances of D.
The question is, when does the operator "new" know the amount of memory to allocate? Compile time or run time? One thing I am afraid of is, programs B and C expect classD to be and alloate 100 bytes whereas the new shared library D requires 120 bytes for classD, and this inconsistency may cause memory corruption in programs B and C if I link them with the new library D. In other words, the area for extra 20 bytes that the new classD require may be allocated to some other variables by program B and C. Is this assumption correct?
Thanks for your help. | You are correct the memory size is defined at compile time and applications B/C would be in danger of serious memory corruption problems.
There is no way to handle this explicitly at the language level. You need to work with the OS to get the appropriate shared libraries to the application.
You need to version your libraries.
As there is no explicit way of doing this with the build tools you need to do it with file names. If you look at most products this is approx how they work.
In the lib directory:
```
libD.1.00.so
libD.1.so -> libD.1.00.so // Symbolic link
libD.so -> libD.1.so // Symbolic link
```
Now at compile time you specify -lD and it links against libD.1.00.so because it follows the symbolic links. At run time it knows to use this version as this is the version it compiled against.
So you now update lib D to version 2.0
In the lib directory:
```
libD.1.00.so
libD.2.00.so
libD.1.so -> libD.1.00.so // Symbolic link
libD.2.so -> libD.2.00.so // Symbolic link
libD.so -> libD.2.so // Symbolic link
```
Now when you build with -libD it links against version 2. Thus you re-build A and it will use version 2 of the lib from now on; while B and C will still use version 1. If you rebuild B or C it will use the new version of the library unless you explicitly use an old version of the library when building -libD.1
Some linkers do not know to follow symbolic links very well so there are linker commands that help. gcc use the '-install\_name' flag your linker may have a slightly different named flag.
As a runtime check it is usally a good idea to put version information into your shared objects (global variable/function call etc). Thus at runtime you can retrieve the shared libraries version information and check that your application is compatible. If not you should exit with the appropriate error message.
Also note: If you serialize objects of D to a file. You know need to make sure that version information about D is maintained. Libd.2 may know how to read version 1 D objects (with some explicit work), but the inverse would not be true. | Changing the size of a class is *binary incompatible*. That means that if you change the size of `classD` without recompiling the code that uses it, you get undefined behavior (most likely crashes).
A common trick to get around this limitation is to design `classD` so that it can be safely extended in a binary compatible way, for example by using the [Pimpl](http://en.wikipedia.org/wiki/Opaque_pointer) idiom.
In any case, if you want different programs to use different versions of your class, I think you have no choice but releasing multiple versions of the shared library and have those programs linked to the appropriate version. | C++ operator new, object versions, and the allocation sizes | [
"",
"c++",
"memory-management",
"new-operator",
""
] |
I'm looking for a diff tool that can analyse my code and tell me what has changed on a construct by construct basis.
For instance, if I cut and paste a method from the start of my file and put it at the end but leave that method unchanged, I don't want it flagged. If however I insert a line of code or change something inside that method, it would flag it as changed.
I've used various diff tools, but all of them seem to fall short at telling you that lines have been inserted, removed or changed but couldn't tell what the changes were in any kind of logical fashion. It would be nice if when I periodically rearrange the layout of my code file the diff tool could keep up.
Does anyone have such a tool? | I use <http://winmerge.org/>
I don't think you can do what you are asking, because of the way the [longest common subsequence](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem) algorithms work for these tools.
Even if your functions get re-arranged, and your source file's functionality remains the same, it will still show up as a difference because of the nature of the LCS.
**EDIT:**
This is a bit far fetched, but if you were feeling extra ambitious, you could write your own that tailors to your exact needs.
you could use regular expressions to pull out each method in a source file, and do the LCS diff on each method individually based on its name. You could store your code a Dictionary (key,value) so that the key is the name of the method and the value is the string of the function. Then you just diff your dictionary\_orig['method'] with your dictionary\_new['method'].
Other than that, I don't know how you'd accomplish what you are looking for. | Check out our [Smart Differencer](http://www.semdesigns.com/Products/SmartDifferencer/index.html) tool, which compares abstract syntax trees,
and reports differences in terms of the nonterminals ("language constructs")
that the ASTs represent, and plauible editing actions (insert, delete, move), as well as discovering consistent renaming.
At present, it only handles Java and COBOL, but it is based on DMS, which
has parsers for a wide variaty of languages, including C#.
**EDIT 9/8/2009: C# SmartDifferencer now available for beta testers.**
The tool already handles a consistent rename across the entire file as being
semantically trivial (on the assumption that other files reference
the renamed symbol accordingly), as well as renames within a scope.
We plan on taking into account semantically trivial changes, such
as moving a method declaration around in a class for Java and C#.
**EDIT October 2010: Production versions available.** [Eval downloads
accessible at the website.](http://www.semanticdesigns.com/Products/SmartDifferencer/CSharpSmartDifferencer.html)
**EDIT May 2012**: You can [see a C# example at this page.](http://www.semanticdesigns.com/Products/SmartDifferencer/CSharpSmartDifferencerExample.html)
One of the things it presently does not do is ignore semantically null edits. A particular case in point is shuffling methods about in a class body; we all know this has no impact on semantics for C#. Our tool compares syntax (via ASTs), not semantics, so it doesn't understand this particular nuance, and will consequently tell a user that "this has been moved" rather than being silent. We have plans to handle cases like this sometime in the future, but hey, every product has to have a version 1 :-} [As a subtle point, shuffling methods in a Java class is also semantically null, but shuffling *fields* is not due to order of evaluation of initializers. I don't know if this is true also for C# but it wouldn't surprise me.] | Does anyone know of an advanced diff tool for C#? | [
"",
"c#",
".net",
"asp.net",
"visual-studio",
"diff",
""
] |
This is pretty darn safe right? Something I've missed?
```
$page = sprintf("%s/%s.php", "pages", $_GET['page']);
if (file_exists($page)) {
include $page;
}
else {
echo "The page '$page' does not exist =(";
}
```
(yes you can use it) | The "better" way to do this is to have an array of the allowed pages, then do something like this:
```
$page = $_GET['page'] . '.php';
if(in_array($page, $all_pages)) {
include('pages/' . $page);
}
```
You could easily get a list of all allowed pages by doing something like this:
```
$all_pages = glob('pages/*.php');
```
Documentation: [`in_array`](http://www.php.net/in_array), [`glob`](http://www.php.net/glob) | It's unsafe since a user can arbitrarily load whatever page they feel like. | User input include | [
"",
"php",
""
] |
I'm telling my program to print out line 53 of an output. Is this error telling me that there aren't that many lines and therefore can not print it out? | If you have a list with 53 items, the last one is `thelist[52]` because indexing starts at 0.
---
From [Real Python: Understanding the Python Traceback - `IndexError`](https://realpython.com/python-traceback/#indexerror):
> ### `IndexError`
>
> The `IndexError` is raised when you attempt to retrieve an index from a sequence, like a `list` or a `tuple`, and the index isn’t found in the sequence. The Python documentation defines when this exception is raised:
>
> > Raised when a sequence subscript is out of range. ([Source](https://docs.python.org/3/library/exceptions.html#IndexError))
>
> Here’s an example that raises the `IndexError`:
```
test = list(range(53))
test[53]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-6-7879607f7f36> in <module>
1 test = list(range(53))
----> 2 test[53]
IndexError: list index out of range
```
> The error message line for an `IndexError` doesn’t give you great information. You can see that you have a sequence reference that is `out of range` and what the type of the sequence is, a `list` in this case. That information, combined with the rest of the traceback, is usually enough to help you quickly identify how to fix the issue. | Yes,
You are trying to access an element of the list that does not exist.
```
MyList = ["item1", "item2"]
print MyList[0] # Will work
print MyList[1] # Will Work
print MyList[2] # Will crash.
```
Have you got an off-by-one error? | Does "IndexError: list index out of range" when trying to access the N'th item mean that my list has less than N items? | [
"",
"python",
"list",
"index-error",
""
] |
This has been a pet peeve of mine since I started using .NET but I was curious in case I was missing something. My code snippet won't compile (please forgive the forced nature of the sample) because (according to the compiler) a return statement is missing:
```
public enum Decision { Yes, No}
public class Test
{
public string GetDecision(Decision decision)
{
switch (decision)
{
case Decision.Yes:
return "Yes, that's my decision";
case Decision.No:
return "No, that's my decision";
}
}
}
```
Now I know I can simply place a default statement to get rid of the complier warning, but to my mind not only is that redundant code, its dangerous code. If the enumeration was in another file and another developer comes along and adds *Maybe* to my enumeration it would be handled by my default clause which knows nothing about *Maybe*s and there's a really good chance we're introducing a logic error.
Whereas, if the compiler let me use my code above, it could then identify that we have a problem as my case statement would no longer cover all the values from my enumeration. Sure sounds a lot safer to me.
This is just so fundamentally wrong to me that I want to know if its just something I'm missing, or do we just have to be very careful when we use enumerations in switch statements?
**EDIT:**
I know I can raise exceptions in the default or add a return outside of the switch, but this are still fundamentally hacks to get round a compiler error that shouldn't be an error.
With regards an enum really just being an int, that's one of .NET's dirty little secrets which is quite embarassing really. Let me declare an enumeration with a finite number of possibilities please and give me a compilation for:
```
Decision fred = (Decision)123;
```
and then throw an exception if somebody tries something like:
```
int foo = 123;
Decision fred = (Decision)foo;
```
**EDIT 2:**
A few people have made comments about what happens when the enum is in a different assembly and how this would result in problems. My point is that this is the behaviour I think should happen. If I change a method signature this will lead to issues, my premis is that changing an enumeration should be this same. I get the impression that a lot of people don't think I understand about enums in .NET. I do I just think that the behaviour is wrong, and I'd hoped that someone might have known about some very obscure feature that would have altered my opinion about .NET enums. | Heck, the situation is far worse than just dealing with enums. We don't even do this for bools!
```
public class Test {
public string GetDecision(bool decision) {
switch (decision) {
case true: return "Yes, that's my decision";
case false: return "No, that's my decision";
}
}
}
```
Produces the same error.
Even if you solved all the problems with enums being able to take on any value, you'd still have this issue. The flow analysis rules of the language simply do not consider switches without defaults to be "exhaustive" of all possible code paths, even when you and I know they are.
I would like very much to fix that, but frankly, we have many higher priorities than fixing this silly little issue, so we've never gotten around to it. | Throw an exception in the **default** clause:
```
default:
throw new ArgumentOutOfRangeException("decision");
```
This ensures that all possible paths are covered, while avoiding the logic errors resulting from adding a new value. | Switch statement without default when dealing with enumerations | [
"",
"c#",
".net",
"enums",
"switch-statement",
""
] |
I know this is silly but I can't overcome my curiosity. Is it possible to write a shell script to format a piece of java code?
For example, if a user writes in a code:
```
public class Super{
public static void main(String[] args){
System.out.println("Hello world");
int a=0;
if(a==100)
{
System.out.println("Hello world");
}
else
{
System.out.println("Hello world with else");
}
}
}
```
I would like to write a shell script which would make the code like this.
```
public class Super
{
public static void main(String[] args)
{
System.out.println("Hello world");
int a=0;
if(a==100){
System.out.println("Hello world");
}
else{
System.out.println("Hello world with else");
}
}
```
To be precise, we should change the formatting of flower brackets. If it is try/catch or control structures we should change it to same line and if it is function/method/class it should come in next line.I have little knowledge about sed and awk which can do this task so easily. Also I know this can be done using eclipse. | Well, I've had some free time on my hands, so I decided to relive my good old linux days :]
After reading a bit about awk and sed, I've decided that it might be better to use both, as it is easier to add indentation in awk and parse strings in sed.
Here is the ~/sed\_script that formats the source file:
```
# delete indentation
s/^ \+//g
# format lines with class
s/^\(.\+class.\+\) *\({.*\)$/\1\n\2/g
# format lines with methods
s/^\(public\|private\)\( \+static\)\?\( \+void\)\? \+\(.\+(.*)\) *\({.*\)$/\1\2\3 \4\n\5/g
# format lines with other structures
/^\(if\|else\|for\|while\|case\|do\|try\)\([^{]*\)$/,+1 { # get lines not containing '{'
# along with the next line
/.*{.*/ d # delete the next line with '{'
s/\([^{]*\)/\1 {/g # and add '{' to the first line
}
```
And here is the ~/awk\_script that adds indentation:
```
BEGIN { depth = 0 }
/}/ { depth = depth - 1 }
{
getPrefix(depth)
print prefix $0
}
/{/ { depth = depth + 1 }
function getPrefix(depth) {
prefix = ""
for (i = 0; i < depth; i++) { prefix = prefix " "}
return prefix
}
```
And you use them like that:
```
> sed -f ~/sed_script ~/file_to_format > ~/.tmp_sed
> awk -f ~/awk_script ~/.tmp_sed
```
It is far from proper formatting tool, but I hope it will do OK as a sample script for reference :] Good luck with your learning. | A quick, flawed attempt, but one that works on your sample input:
```
BEGIN {depth = 0;}
/{$/ {depth = depth + 1}
/^}/ {depth = depth - 1}
{prefix = ""; for (i = 0; i < depth; i++) { prefix = prefix " "} print prefix $0 ; }
```
This is an awk script: place it in a file and do
```
awk -f awk_script_file source_file
```
Obvious flaws with this include:
* It doesn't catch braceless places where you'd like indentation like
```
if (foo)
bar();
```
* It will modify the indent depth based on braces in comments and string literals
* It won't detect { braces followed by comments | Java Code formatting using shell script | [
"",
"java",
"unix",
"shell",
"scripting",
""
] |
I have some XML that looks something like the one below
```
<DriveLayout>
<Drive totalSpace="16" VolumeGroup="dg01" />
<Drive totalSpace="32" VolumeGroup="dg01" />
<Drive totalSpace="64" VolumeGroup="dg02" />
<Drive totalSpace="64" VolumeGroup="dg02" />
<VolumeGroups>
<VolumeGroup VolumeGroup="dg01" storageTier="1" />
<VolumeGroup VolumeGroup="dg02" storageTier="2" />
</VolumeGroups>
</DriveLayout>
```
I need a way to go back through the XML and add the attribute storageTier to each individual Drive node. Is there a way to loop through each drive node and grab the VolumeGroup then get the cooresponding storageTier out of the XML in the VolumeGroup node? I then need to inject the correct storageTier back into the XML drive node. I'm using the System.XML that's in C#.
Thanks
Any help would be greatly appreciated | I think you need XPath ( [check this out](http://support.microsoft.com/kb/318499) )
```
var doc = new XmlDocument();
var xml =
@"<DriveLayout>
<Drive totalSpace='16' VolumeGroup='dg01' />
<Drive totalSpace='32' VolumeGroup='dg01' />
<Drive totalSpace='64' VolumeGroup='dg02' />
<Drive totalSpace='64' VolumeGroup='dg02' />
<VolumeGroups>
<VolumeGroup VolumeGroup='dg01' storageTier='1' />
<VolumeGroup VolumeGroup='dg02' storageTier='2' />
</VolumeGroups>
</DriveLayout>
";
doc.LoadXml(xml);
var volumeGroups = doc.SelectNodes("/DriveLayout/VolumeGroups/VolumeGroup");
var storageTiers = new Dictionary<string, string>();
if (volumeGroups != null)
{
foreach (var volumeGroup in volumeGroups)
{
var volumeGroupElement = (XmlElement) volumeGroup;
storageTiers.Add(
volumeGroupElement.Attributes["VolumeGroup"].Value,
volumeGroupElement.Attributes["storageTier"].Value);
}
}
var nodes = doc.SelectNodes("/DriveLayout/Drive");
if (nodes == null)
{
return;
}
foreach (XmlNode node in nodes)
{
var element = (XmlElement) node;
var volumeGroupAttribute = element.Attributes["VolumeGroup"];
if (volumeGroupAttribute == null)
{
continue;
}
var volumeGroup = volumeGroupAttribute.Value;
var newStorageTier = doc.CreateAttribute("storageTier");
newStorageTier.Value = storageTiers[volumeGroup];
element.Attributes.Append(newStorageTier);
}
``` | This task can be done very succinctly using LINQ to XML. What is more, it uses simple LINQ queries and a dictionary to give an algorithm that runs in linear time.
```
var storageTiers = doc.Root.Element("VolumeGroups").Elements().ToDictionary(
el => (string)el.Attribute("VolumeGroup"),
el => (string)el.Attribute("storageTier"));
foreach (var driveElement in doc.Root.Elements("Drive"))
{
driveElement.SetAttributeValue("storageTier",
storageTiers[(string)driveEl.Attribute("VolumeGroup")]);
}
```
If you are using C# 3.0, then this is without doubt the best way to go (unless your XML file is enormous and you need high efficiency, which seems unlikely). | Looping through XML in .NET? | [
"",
"c#",
"xml",
""
] |
Maybe the title is badly phrased but couldn't think of a better way of saying it.
I am working on a login system at the moment (nothing formal, just experimenting) and was planning on using PHPLiveX (an AJAX library) for some features. Basically you create some PHP functions which are then called via JavaScript. You can add parameters (getElementById) to the JavaScript that are transfered to the PHP function.
What I really wanted to know is whether it is safe to just call the function from JavaScript without encrypting the password first, then letting the PHP function encrypt it (SHA256 in this case). Can the data transfered via AJAX be intercepted? If so how likely is this? | No more-or-less safe than a normal HTTP POST request issued by a browser (as in from a `<form>`)
The "fix" for this is the same "fix" for non-AJAX requests - use SSL. | As others have mentioned, it's no more dangerous than sending an HTTP post from a form. In fact, it's the very same thing.
But if HTTPS isn't an option you can always use a challenge/response scheme over an unencrypted connection. Basically it works like this:
* Server has a SHA (or whatever hashing algorithm you prefer) hash of the user's password.
* Client has the password.
* Client requests (using unencrypted AJAX) that the server send a challenge (a random string of bytes; characters are fine.)
* Server creates a challenge and a challenge ID, and saves it with an expiration.
* Client recieves the challenge and challenge ID.
* Client hashes the password using SHA.
* Client hashes the resulting hash with the challenge appended in some way.
* Client sends the challenge ID (not the challenge itself) and the second resulting hash.
* Server looks up challenge using ID if it exists and hasn't expired.
* Server appends the challenge to the stored password hash and creates a hash using the same scheme as the client.
* Server compares its hash with the client. If it's the same, the user is authenticated.
It's actually pretty simple to set up once you get the idea. [Wikipedia](http://en.wikipedia.org/wiki/Challenge-response_authentication) has some additional information on it.
**EDIT:** I noticed I forgot to mention, whether or not the authentication is successful you *must* delete the challenge, regardless. Giving the client multiple attempts on one challenge could lead to security issues. | How safe is it to send a plain text password using AJAX? | [
"",
"php",
"ajax",
"security",
"authentication",
""
] |
The following statement runs fine in the MS SQL server management studio. However when I try to execute via PHP the insert does not occur and no errors are returned. I know my connection is valid, all my select statements return properly. What am I missing?
```
DECLARE @id bigint; SET @id = (SELECT MAX(application_track_id) + 1 FROM application_track_data); INSERT INTO application_track_data (application_track_id,user_id, action_key, action, ip_address, session_id, application) VALUES (@id,1,'584','login','192.168.37.60','05sn3618p61dvmml6pkefuteg2','akamata');
```
Here is the code I am using to execute the sql.
```
$result = mssql_query($sql);
if(!$result)
{
print "Error:" . mssql_get_last_message();
}
else
print "Success";
``` | Ok, I have it working. I switched to using the SQL server driver provided by Microsoft available here <http://www.microsoft.com/downloads/details.aspx?FamilyId=61BF87E0-D031-466B-B09A-6597C21A2E2A&displaylang=en> .
Apparently the mssql driver cannot work with certain data types, like bigint. | You might want to put this in a procedure. Since you have multiple commands in your SQL statement I believe most db drivers only can call a single statement (or single T-SQL statement). So if you need multiple things to happen turn it into a stored procedure or execute each individual statement based on return value etc.
UPDATE: Try this: <https://www.php.net/manual/en/function.mssql-next-result.php>
I guess it does allow multiple queries but you need to get the right one. There are also some db libraries that have a \*\_query\_multiple function but only in the mysqli libraries or maxdb libraries. | PHP SQL Server Insert issue | [
"",
"php",
"sql-server",
""
] |
A lead developer on my project has taken to referring to the project's toString() implementations as "pure cruft" and is looking to remove them from the code base.
I've said that doing so would mean that any clients wishing to display the objects would have to write their own code to convert the object to string, but that was answered with "yes they would".
Now specifically, the objects in this system are graphic elements like rectangles, circles, etc and the current representation is to display x, y, scale, bounds, etc...
So, where does the crowd lie?
When should you and when shouldn't you implement toString? | What harm do they do? Why remove them if you have them? I find toString() extremely useful when emitting debugging statements.
Personally, I would always err on the side of having a workable toString() method. So little work to write. | Removing well-written (or even halfway decently written) toString() methods is pure insanity, IMO. Yes, I am often too lazy to write these (as often the objects don't end up having them used anyway), but they are extremely handy to have.
I really can't think of a good reason to want to get rid of these. | When is it desired to not implement toString() in Java? | [
"",
"java",
"tostring",
""
] |
Im sure there is a better way to do this, but I am quite the newbie so I did it the only way I could figure it out. The thing is, I have a script that updates a textfile with the newest posts from an RSS feed (I got some help from you guys to figure it out). But I want this script to be automated, so I made this:
```
import time
import os
seconds = 3600
kjor = 'python vg.py'
time.sleep(seconds)
os.system(kjor)
time.sleep(seconds)
os.system(kjor)
time.sleep(seconds)
os.system(kjor)
```
I continued with copying those 24x downwards. I know this problably can be done alot better with some loop (while?), but Im afraid I dont have alot of knowledge in that field (yet).
My question, however, is as following: Can the system be damaged in any way if I let this run over a longer period of time? | To answer your question, no, this won't hurt anything. While the time.sleeps are sleeping, the program will take very little processing power and the rest of the system can run normally.
Now, as for your looping issue. If you want the code run forever (or until you stop the program) the code you want is
```
while True:
os.system(kjor)
time.sleep(seconds)
```
This is, literally, and infinite loop, but in this case that (is probably) what you want.
If you are attached to having a particular number of iterations, then you could do something like sunqiang's answer (repeated here)
```
for loop in xrange(240):
os.system(kjor)
time.sleep(seconds)
```
Finally, if you are on a Unix platform (such as Linux or Mac) you should take a look at cron, as it is designed to set up recurring programs to run and particular time periods. You could set it up to run your script every minute and it will happily do so until the end of time (or you remove it, whichever comes first). | Use xrange please, don't copying your code 24x times.
```
for loop in xrange(240):
time.sleep(seconds)
os.system(kjor)
```
It will not damage your system, as far as I know. | Can I damage the system by running time.sleep() with this newbie code in Python? | [
"",
"python",
"while-loop",
""
] |
I have been thinking about how I write classes in Python. More specifically how the constructor is implemented and how the object should be destroyed. I don't want to rely on CPython's reference counting to do object cleanup. This basically tells me I should use with statements to manage my object life times and that I need an explicit close/dispose method (this method could be called from `__exit__` if the object is also a context manager).
```
class Foo(object):
def __init__(self):
pass
def close(self):
pass
```
Now, if all my objects behave in this way and all my code uses with statements or explicit calls to `close()` (or `dispose()`) I don't realy see the need for me to put any code in `__del__`. Should we really use `__del__` to dispose of our objects? | Short answer : No.
Long answer: Using `__del__` is tricky, mainly because it's not guaranteed to be called. That means you can't do things there that absolutely has to be done. This in turn means that `__del__` basically only can be used for cleanups that would happen sooner or later anyway, like cleaning up resources that would be cleaned up when the process exits, so it doesn't matter if `__del__` doesn't get called. Of course, these are also generally the same things Python will do for you. So that kinda makes `__del__` useless.
Also, `__del__` gets called when Python garbage collects, and you didn't want to wait for Pythons garbage collecting, which means you can't use `__del__` anyway.
So, don't use `__del__`. Use `__enter__/__exit__` instead.
FYI: Here is an example of a non-circular situation where the destructor did not get called:
```
class A(object):
def __init__(self):
print('Constructing A')
def __del__(self):
print('Destructing A')
class B(object):
a = A()
```
OK, so it's a class attribute. Evidently that's a special case. But it just goes to show that making sure `__del__` gets called isn't straightforward. I'm pretty sure I've seen more non-circular situations where `__del__` isn't called. | Not necessarily. You'll encounter problems when you have cyclic references. Eli Bendersky does a good job of explaining this in his blog post:
* [Safely using destructors in Python](http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/) | Is it really OK to do object closeing/disposing in __del__? | [
"",
"python",
""
] |
Is it appropriate to fire a "property changed" event when the actual value of a property does not change?
```
public int SomeProperty
{
get { return this.mSomeProperty; }
set
{
this.mSomeProperty = value;
OnPropertyChanged(new PropertyChangedEventArgs("SomeProperty"));
}
}
```
This will trigger the event even when the new value is identical to the old value. Is this bad practice? | Best practice is not to throw the event unless the value changed.
In your case the property is just an 'int', so it's just a simple equality check. If your property was an object in it's own right, there are more cases to consider
1. You set the same instance again - No property change
2. You set a different instance with different values - Throw a property change
3. You set a different, but 'equal' instance ( i.e., the two different objects have the same set of values and can be considered equivalent from your application's point of view ) - Throw a property change.
The last one is subject to some debate... has the property really changed when all of it's attributes are the same? If someone is using that property change to subscribe to changes in the subclass, they will need it to know to unsubscribe from the old class and subscribe to the new one. Therefore I err on the side of announcing the change. | If you had an event called `PropertySetterAccessed`, then it would be appropriate to fire it when the value doesn't change. However, your event is called `PropertyChanged`, so it should only be fired when that actually happened. If your events/methods/classes etc don't do "what they say on the tin", you are creating a maintenance nightmare for someone. | When should a "property changed" event be fired? | [
"",
"c#",
"events",
""
] |
**Problem:** I have a large Visual C++ project that I'm trying to migrate to Visual Studio 2010. It's a huge mix of stuff from various sources and of various ages. I'm getting problems because something is including both `winsock.h` and `winsock2.h`.
**Question:** What tools and techniques are there for displaying the `#include` hierarchy for a Visual Studio C++ source file?
I know about **`cl /P`** for getting the preprocessor output, but that doesn't clearly show which file includes which other files (and in this case the **`/P`** output is 376,932 lines long 8-)
In a perfect world I'd like a hierarchical display of which files include which other files, along with line numbers so I can jump into the sources:
```
source.cpp(1)
windows.h(100)
winsock.h
some_other_thing.h(1234)
winsock2.h
``` | There is a setting:
Project Settings -> Configuration Properties -> C/C++ -> Advanced -> Show Includes
that will generate the tree. It maps to the compiler switch [/showIncludes](https://learn.microsoft.com/en-us/cpp/build/reference/showincludes-list-include-files?view=vs-2019)
---
EDIT (Jan 9 2024)
2022 17.9 will contain a much more useful tool: "#include Diagnostics"; cf. [blog post](https://devblogs.microsoft.com/cppblog/include-diagnostics-in-visual-studio/). | The compiler also supports a /showIncludes switch -- it doesn't give you line numbers, but can give a pretty comprehensive view of which includes come from where.
It's under Project Settings -> Configuration Properties -> C/C++ -> Advanced -> Show Includes. | Displaying the #include hierarchy for a C++ file in Visual Studio | [
"",
"c++",
"visual-studio",
"include",
""
] |
First python script and I'm getting an error I can't seem to get around using a config file. The first part of the script takes user input and puts that into a mysql database with no problem..Then I get to the filesystem work and things go a bit pear shaped..I can get it to work without using the config file options but I'd like to keep it consistent and pull from that file:
```
vshare = str(raw_input('Share the user needs access to: '))
vrights = str(raw_input('Should this user be Read Only? (y/n): '))
f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername), 'wr'))
#f = open("/etc/vsftpd_user_conf/%s" % (vusername) , 'wr' )
f.write("local_root=%s/%s" % (config['vsftp']['local_root_dir'], vshare))
if vrights.lower() in ['y', 'ye', 'yes']:
buffer = []
for line in f.readlines():
if 'write_enable=' in line:
buffer.append('write_enable=NO')
else:
buffer.append(line)
f.writelines(buffer)
f.close()
```
The error I'm getting is:
> TypeError: not all arguments converted during string formatting
If I uncomment the commented line it works and makes it a bit further and errors out as well..But I'll deal with that once I get this hiccup sorted. | Your tuple is misshaped
```
f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername), 'wr'))
```
Should be
```
f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername)), 'wr')
``` | The error is here:
```
open("%s/%s" % (config['vsftp']['user_dir'], (vusername), 'wr'))
```
You have three parameters, but only two %s in the string. You probably meant to say:
```
open("%s/%s" % (config['vsftp']['user_dir'], vusername), 'wr')
```
Although 'wr' is unclear, you probably mean w+ or r+.
<http://docs.python.org/library/functions.html#open> | Python Error: TypeError: not all arguments converted during string formatting | [
"",
"python",
"typeerror",
""
] |
I'm implementing a SOAP client using Apache Axis 2. Since the SOAP client must handle heavy number of requests I am using a connection pool.
To do that I had to set a few transport layer configuration of my stub that was generated from a WSDL file:
```
stub._getServiceClient().getOptions().setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE);
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setDefaultMaxConnectionsPerHost(MAX_CONNECTIONS_PER_HOST);
connectionManager.closeIdleConnections(IDLE_CONNECTION_TIMEOUT);
HttpClient httpClient = new HttpClient(connectionManager);
stub._getServiceClient().getOptions().setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);
```
My client seems to be working just fine. However, I would like to know how can I test if the connection pool is working in a correct way (i.e. the created connections are only destroyed after the time defined by the IDLE\_CONNECTION\_TIMEOUT constant). Any ideas? | Pseudo-code based on JUnit 3.x:
```
setUp() {
initialize connection manager;
initialize connection by creating client;
}
tearDown() {
close connection if necessary;
close connection manager if necessary;
}
testConnectionOpen() {
assert that connection is open;
pause for time of idle connection timeout - 1 second;
assert that connection **is still open**;
}
testConnectionClosed() {
assert that connection is open;
pause for time of idle connection timeout + 1 second;
assert that connection **is closed**;
}
```
Adding 1 second and subtracting 1 second should be adjusted depending on sensitivity of the connection manager. | Write a testbed application which will make a large number of requests, and assert that the number of connections is never more than MAX\_CONNECTIONS. You might be able to check on the latter by attaching jconsole or VisualVM to the process.
You could also look into using [Jakarta JMeter](http://jakarta.apache.org/jmeter/) for generating load on the class/client, and then graphing out several datapoints (not sure how you'd gain access to number of client connections created, though). | How can I test if my connection pool is working in a correct way? | [
"",
"java",
"http",
"soap",
"testing",
"apache-axis",
""
] |
I have a program, where the password to a database is set by a remote user. The program saves the username and password to an encrypted string in an xml file that otherwise should be human readable. Now, this works fine, I use the C# DES encryption with a key, and it get encrypted and decrypted. Now, the problem is that anyone can use reflector to see the key. Even with obfuscation, the key should be readily apparent. So, how does one deal with this? Now, I don't need this to be NSA secure, but I really would like to prevent anyone from peeking. Thanks.
EDIT: Thanks for all of the advice so far, information on this sort of thing is not very widespread, and I really appreciate general tips as well as specific answers. | Try using DPAPI (System.Security.ProtectedData class). This protects your encrypted data using the user or machine credentials. So only the user account that's accessing the data (user credentials) or a user that can log in to the machine (machine credentials) will be able to decrypt your data. | This is not really a problem about relector or not. It is about key management. DES and any other encryption scheme relies on keys being changed on a regular basis. Hard coding the key in code obviously violates this. To get around this, you should look into key management.
EDIT: To elaborate a bit: Depending on you setup, you could store the hashed passwords in the file system and rely on file system/user security or in a database an rely on the database rights. | C# encryption in the age of reflector | [
"",
"c#",
"encryption",
"reflector",
""
] |
Does Spring 2.5 (or 3.0) include support for dynamically populating a select list based on what the user selects from another form element?
For example if you have a form with 2 select for (Car) Make and Model. When the user selects a Make from the first list, the Model select should get populated with the available Models for that Make.
I can do it 'manually' using jquery/Javascript but was wondering whether there was any functionality available in Spring MVC to reduce the required leg work. | Spring does not yet offer any support for dynamically populating lists based on the selection in another list.
The only client side javascript features are provided by SpringJS which includes support for form element decoration. | This is rather about the view and strategies how to populate it. So there are two strategies you could apply:
1. Do a real server roundtrip and evaluate the value given by the first dropdown box to populate the second one. This can be done by the very basic Spring MVC means (either `isFormChangeRequest` of legacy inheritance based controller model or simply provide a method mapped with `@RequestMapping` in the annotations based model.
2. Use a JavaScript library and provide a dedicated URL to just read the values for the second box depending on the value of the first box. JQuery is probably a good start but you also might take a glance at SpringJS (contained in the Spring WebFlow distribution).
You see, actually it's very much a question on how conservative you are regarding the use of JavaScript, Server roundtrips or the amount of data to go over the wire. | Spring MVC support for dynamically populating select box | [
"",
"java",
"model-view-controller",
"spring",
"spring-mvc",
""
] |
How is this done? | This is a good question, and I actually don't think it can be done easily. ([Some discussion on this](http://old.nabble.com/click---dblclick-Problem-td8389800s27240.html))
If it is super duper important for you to have this functionality, you could hack it like so:
```
function singleClick(e) {
// do something, "this" will be the DOM element
}
function doubleClick(e) {
// do something, "this" will be the DOM element
}
$(selector).click(function(e) {
var that = this;
setTimeout(function() {
var dblclick = parseInt($(that).data('double'), 10);
if (dblclick > 0) {
$(that).data('double', dblclick-1);
} else {
singleClick.call(that, e);
}
}, 300);
}).dblclick(function(e) {
$(this).data('double', 2);
doubleClick.call(this, e);
});
```
And here is an [example of it at work](http://jsbin.com/ahezu).
As pointed out in the comments, there is a plugin for this that does what I did above pretty much, but packages it up for you so you don't have to see the ugly: [FixClick](http://plugins.jquery.com/project/FixClick). | Raymond Chen has discussed some of the [implications of single-versus-double clicking](http://blogs.msdn.com/oldnewthing/archive/2004/10/15/242761.aspx) - although he's talking in the context of Windows, what he says is relevant to browser-based UI design.
Basically, the action taken on a double click should be a logical thing to do after a single click. So for example, in a desktop UI, single click selects an item, and double click opens it (e.g. opens the file, or launches the application). The user would have to select the file to open it anyway, so it doesn't matter that the single click action is taken before the double click action.
If you have a UI component whose double click action is completely unrelated to the single click action, such that it becomes necessary to prevent the single click action from occurring once the system realises it was actually a double click, then you really ought to rethink your design. Users will find it awkward and counter-intuitive, in that it will not act in the way they are used to things acting.
If you still want to go that way, then you will either have to use the debouncing technique (in which case all single click actions will be delayed) or else implement some mechanism whereby the double click handler undoes the work done by the single click handler.
You should also be aware that some users set a very long double click time. Somebody with, for example, arthritic hands might have a double click time of more than a second set in their system preferences, so the debouncing technique based on some arbitrary time period of your choosing is going to make your UI component inaccessible to those people if taking the single click action precludes taking the double click action. The "undo what just happened on single click" technique is the only viable workaround for this, as far as I know. | Need to cancel click/mouseup events when double-click event detected | [
"",
"javascript",
"jquery",
"event-handling",
"click",
"double-click",
""
] |
Why won't the following code work?
```
class parent {}
class kid:parent {}
List<parent> parents=new List<kid>;
```
It seems obvious to me. What's going on here? | C# does not currently support [covariance](http://tinyurl.com/58gdgo).
It's [coming](http://tinyurl.com/kko7b7) in .NET 4.0, however, on interfaces and delegates.
[Eric Lippert](http://blogs.msdn.com/ericlippert/) had a very nice [series](http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx) on this subject on his blog awhile back. [Visual Studio Magazine](http://visualstudiomagazine.com/Home.aspx) covers it too in a recent [article](http://visualstudiomagazine.com/articles/2009/05/01/generic-covariance-and-contravariance-in-c-40.aspx). | Besides the lack of generic variance support in C# prior to version 4.0, List is mutable and so cannot safely be covariant. Consider this:
```
void AddOne<T>(List<T> arg) where T : new()
{
arg.Add(new T());
}
void Whoops()
{
List<parent> contradiction = new List<kid>();
AddOne(contradiction); // what should this do?
}
```
This would attempt to add a Parent to a List referenced via a List reference, which is not safe. Arrays are permitted to be covariant by the runtime, but are type-checked at mutation time and an exception is thrown if the new element is not assignable to the array's runtime element type. | Why can't List<parent> = List<child>? | [
"",
"c#",
".net",
"oop",
"inheritance",
""
] |
I know one can use '<alt><shift>J' to create tags for a single code element (class method for example).
But is there a way to automatically create these tags for every class in the entire project? Or even just at package or class level? | Have you looked at [JAutodoc](http://jautodoc.sourceforge.net/)? | Not that I know of.
What would that be good for anyway? Autogenerated Javadoc comments are worse than useless; I'd rather not have them cluttering up my code, and Javadoc will provide as much information even with no comment present. | Can one automatically create javadoc tags for an entire Eclipse project? | [
"",
"java",
"eclipse",
"javadoc",
"autocreate",
""
] |
I've got a class which uses an `XmlSerializer` in its `Read/WriteXml` methods. The Serializer is currently `private readonly`.
```
public class Foo : IXmlSerializable
{
private Bar _bar = new Bar();
private readonly XmlSerializer serBar = new XmlSerializer (typeof (Bar));
public void WriteXml (XmlWriter writer)
{
serBar.Serialize (writer, Bar);
}
// ...
}
```
I'm considering making the Serializer `private static` instead, so one instance is shared between all Foos. Is this a good idea, or are there possible issues? | Yes, it is a good idea. No, there aren't any issues with it. In particular, thread safety is *not* an issue - from [MSDN documentation for `XmlSerializer` class](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx):
> Thread Safety
>
> This type is thread safe. | According to Neal - even more universal and safe through Generics and readonly:
```
public static class Helper<T>
{
public static readonly XmlSerializer Serializer = new XmlSerializer(typeof(T));
}
```
Use as:
```
Helper<My>.Serializer
``` | Should I make this XmlSerializer static? | [
"",
"c#",
"static",
"xml-serialization",
"instance",
""
] |
Using the following code snippet as an illustration to my question:
```
// #includes and other macros
class MyClass : public CFormView
{
private:
DECLARE_DYNCREATE(MyClass)
bool privateContent;
...
public:
bool publicContent;
...
};
class MusicPlayer
{
public:
AppClass *theApp; // which has a pointer accessing the MyClass object instantiated in the program
...
}
```
When I place the keyword "private" in MyClass definition as such, the privateContent member variable doesn't appear to be private when I try to access it in a method of MusicPlayer class. However, if I place the "private" keyword after the DECLARE\_DYNCREATE(MyClass) line, the behavior of privateContent member variable returns to what is expected. Does anyone know why this is the case? Thanks in advance. | If you look at the definition of `DECLARE_DYNCREATE`, you will see that it uses another macro:
```
// not serializable, but dynamically constructable
#define DECLARE_DYNCREATE(class_name) \
DECLARE_DYNAMIC(class_name) \
static CObject* PASCAL CreateObject();
```
And if you look at that macro, `DECLARE_DYNAMIC`, you'll see why your class turns public:
```
#define DECLARE_DYNAMIC(class_name) \
protected: \
static CRuntimeClass* PASCAL _GetBaseClass(); \
public: \
static const CRuntimeClass class##class_name; \
static CRuntimeClass* PASCAL GetThisClass(); \
virtual CRuntimeClass* GetRuntimeClass() const; \
```
When it expands, it's going to add that `public:` keyword, leaving the rest of your class definition public after that.
So when you say say `private:` after `DECLARE_DYNCREATE`, you're then changing it from public to private.
The usual use of this macro would be like this:
```
class MyClass : public CFormView
{
DECLARE_DYNCREATE(MyClass)
private:
bool privateContent;
...
public:
bool publicContent;
...
};
```
The class will implicitly be private at the start, so the effect is the same.
Also, most C++ programmers will agree you should start trying to get into the habit of placing your private variables at the bottom.
The justification is that when people, including yourself, are reading the class, they will want to see what you can do with the class, which is in the public interface, rather than how the class is going to work, which is private.
By putting the public interface first, you won't have to be bothered by all the private stuff.
I used to put my private stuff at the top too (because I came from Visual Basic 6, before C++), and hated being told my privates should be on the bottom, but once you get into the habit you'll wish you changed sooner. | `DECLARE_DYNCREATE` is macro that contains `public` keyword.
Actually it contains macro `DECLARE_DYNAMIC` and there are `public` keyword. | difference of variable in placement of private keyword in a MFC class | [
"",
"c++",
"mfc",
"private-members",
""
] |
I have the following code.
```
QString fileName = QFileDialog::getSaveFileName(
this,
tr("Output Image file"),
(""),
tr("PNG (*.png);;JPEG (*.JPEG);;Windows Bitmap (*.bmp);;All Files (*.*)")
);
if(fileName != "")
{
QwtPlot* pPlot = ...
QSize size = pPlot->size();
QRect printingRect(QPoint(0, 0), size);
QPixmap pixmapPrinter(size);
pixmapPrinter.fill(Qt::white);
{
QPainter painter(&pixmapPrinter);
pPlot->print(&painter, printingRect);
}
bool isOk = pixmapPrinter.save(fileName);
if(!isOk)
{
QString msgText = tr("Failed to write into ") + fileName;
QMessageBox::critical(this, tr("Error Writing"), msgText);
}
}
```
So, the path is like this: - File dialog pops up - users selects format and file - the system draws plot onto QPixmap - Saves QPixmap into the file.
It works for PNG and BMP without a problem, but for JPEG, jpg, JPG, etc it fails.
I was all over Qt documentation but could not find any details. It should just work.
Any ideas?
I am using Qt commercial edition, 4.5.1 for Windows.
I am using dlls, Qt is not on the path.
I just realised that I am linking statically to a classical 3rd party jpeg.lib (The Independent JPEG Group's JPEG software), which is used by other library.
Is it possible that a conflict or something arises because of this?
Or it is simply that plugin is not loaded properly. | probably it cant find the plugin...
you can add library path to project or you can simply put imageformats folder near your binary.
imageformats folder is in plugins..
(probably you cant display jpeg images too) | If you are making a static build, you have to add `QTPLUGIN += qjpeg` to your .pro file, so that the static jpeg library of the imageformats is linked with your application. | Saving QPixmap to JPEG failing (Qt 4.5) | [
"",
"c++",
"qt",
"qt4",
"qpixmap",
""
] |
I'm writing a pretty basic application in python (it's only one file at the moment). My question is how do I get it so the python script is able to be run in /usr/bin without the .py extension?
For example, instead of running
```
python htswap.py args
```
from the directory where it currently is, I want to be able to cd to any directory and do
```
htswap args
```
Thanks in advance! | Simply strip off the `.py` extension by renaming the file. Then, you have to put the following line at the top of your file:
```
#!/usr/bin/env python
```
`env` is a little program that sets up the environment so that the right `python` interpreter is executed.
You also have to make your file executable, with the command
```
chmod a+x htswap
```
And dump it into `/usr/local/bin`. This is cleaner than `/usr/bin`, because the contents of that directory are usually managed by the operating system. | The first line of the file should be
```
#!/usr/bin/env python
```
You should remove the `.py` extension, and make the file executable, using
```
chmod ugo+x htswap
```
**EDIT:** [Thomas](https://stackoverflow.com/users/14637/thomas) points out correctly that such scripts should be placed in `/usr/local/bin` rather than in `/usr/bin`. Please upvote his answer (at the expense of mine, perhaps. Seven upvotes (as we speak) for this kind of stuff is ridiculous) | Python scripts in /usr/bin | [
"",
"python",
"unix",
"scripting",
""
] |
I'm using the Aspose library to create an Excel document. Somewhere in some cell I need to insert a new line between two parts of the text.
I tried "\r\n" but it doesn't work, just displays two square symbols in cell. I can however press Alt+Enter to create a new line in that same cell.
How do I insert a new line programmatically? | From the Aspose Cells forums: [How to use new line char with in a cell?](http://www.aspose.com/community/forums/thread/163248/how-to-use-new-line-char-with-in-a-cell.aspx)
After you supply text you should set the cell's IsTextWrapped style to true
```
worksheet.Cells[0, 0].Style.WrapText = true;
``` | ```
cell.Text = "your firstline<br style=\"mso-data-placement:same-cell;\">your secondline";
```
If you are getting the text from DB then:
```
cell.Text = textfromDB.Replace("\n", "<br style=\"mso-data-placement:same-cell;\">");
``` | How to insert programmatically a new line in an Excel cell in C#? | [
"",
"c#",
".net",
"excel",
"aspose",
""
] |
I have a Query that's supposed to run like this -
```
If(var = xyz)
SELECT col1, col2
ELSE IF(var = zyx)
SELECT col2, col3
ELSE
SELECT col7,col8
FROM
.
.
.
```
How do I achieve this in T-SQL without writing separate queries for each clause? Currently I'm running it as
```
IF (var = xyz) {
Query1
}
ELSE IF (var = zyx) {
Query2
}
ELSE {
Query3
}
```
That's just a lot of redundant code just to select different columns depending on a value.
Any alternatives? | Just a note here that you may actually be better off having 3 separate SELECTS for reasons of optimization. If you have one single SELECT then the generated plan will have to project all columns col1, col2, col3, col7, col8 etc, although, depending on the value of the runtime @var, only some are needed. This may result in plans that do unnecessary clustered index lookups because the non-clustered index Doesn't cover all columns projected by the SELECT.
On the other hand 3 separate SELECTS, each projecting the needed columns only may benefit from non-clustered indexes that cover just your projected column in each case.
Of course this depends on the actual schema of your data model and the exact queries, but this is just a heads up so you don't bring the imperative thinking mind frame of procedural programming to the declarative world of SQL. | You are looking for the CASE statement
<http://msdn.microsoft.com/en-us/library/ms181765.aspx>
Example copied from MSDN:
```
USE AdventureWorks;
GO
SELECT ProductNumber, Category =
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END,
Name
FROM Production.Product
ORDER BY ProductNumber;
GO
``` | SQL Server 2008 - Case / If statements in SELECT Clause | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm working on a specialized HTML stripper. The current stripper replaces <td> tags with tabs then <p> and <div> tags with double carriage-returns. However, when stripping code like this:
```
<td>First Text</td><td style="background:#330000"><p style="color:#660000;text-align:center">Some Text</p></td>
```
It (obviously) produces
```
First Text
Some Text
```
We'd like to have the <p> replaced with nothing in this case, so it produces:
```
First Text (tab) Some Text
```
However, we'd like to keep the double carriage-return replacement for other code where the <p> tag is not surrounded by <td> tags.
Basically, we're trying to replace <td> tags with \t always and <p> and <div> tags with \r\r ONLY when they're not surrounded by <td> tags.
Current code: (C#)
```
// insert tabs in places of <TD> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<td\b(?:[^>""']|""[^""]*""|'[^']*')*>", "\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line paragraphs (double line breaks) in place
// of <P>, <DIV> and <TR> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<(div|tr|p)\b(?:[^>""']|""[^""]*""|'[^']*')*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
```
(there's more code to the stripper; this is the relevant part)
Any ideas on how to do this without completely rewriting the entire stripper?
EDIT:
I'd prefer to not use a library due to the headaches of getting it signed off on and included with the project (which itself is a library to be included in another project), not to mention the legal issues. If there is no other solution, though, I'll probably use the HTML Agility Pack.
Mostly, the stripper just strips out anything it finds that looks like a tag (done with a large regex based on a regex in Regular Expressions Cookbook. This, replacing line break tags with /r, and dealing with multiple tabs is the brunt of the custom stripping code. | Found the answer:
```
// remove p/div/tr inside of td's
result = System.Text.RegularExpressions.Regex.Replace(result, @"<td\b(?:[^>""']|""[^""]*""|'[^']*')*>.*?</td\b(?:[^>""']|""[^""]*""|'[^']*')*>", new MatchEvaluator(RemoveTagsWithinTD));
```
This code calls this separate method for each match:
```
//a separate method
private static string RemoveTagsWithinTD(Match matchResult) {
return Regex.Replace(matchResult.Value, @"<(div|tr|p)\b(?:[^>""']|""[^""]*""|'[^']*')*>", "");
}
```
This code was (again) based on another recipe from the [Regular Expressions Cookbook](http://www.regular-expressions-cookbook.com/) (which was sitting in front of me the whole time, d'oh!). It's really a great book. | Have you thought about looking into the [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack), which would have a lot of parsing options built in in which to manipulate tags? | Replacing <p>, <div> tags within <td> tags? | [
"",
"c#",
".net",
"html",
"regex",
"strip",
""
] |
I often make small websites and use the built in ASP.NET membership functionality in a SQL Server database, using the default "hashing" password storage method.
I'm wondering if there's a way to authenticate a user by hashing his password on the client and not sending it in clear text over the wire without using SSL.
I realize that this would only be applicable for users with Javascript enabled.
Or... possibly, this would be a great built-in capability for Silverlight (is this in the Silverlight roadmap?)
---
EDIT:
I'm also looking for "degrees of security." Meaning, if there is a method that has *some* advantages over simply sending plaintext password, I'd like to know what they are and why.
I know there are lots of people who do small sites with logins (such as a family website or volunteering to make a site for a local cooking club) and don't see the need for purchasing SSL certificates. | This is possible. This is actually what Kerberos authentication does, only with a little bit of added spice. To ensure that your authentication mechanism is secure, you need the following:
1. A common hashing algorithm on both the client and server.
2. A one-time salt value generated on the server and shared with the client.
3. The original password stored in a database.
To securely authenticate a user via hash code, so you avoid sending the actual password across the wire, first generate a random, single-use salt value on the server. Send this salt value to the client, and generate a hash code from the salted version of the password the user has input. Send the resulting hash code to the server, and compare it with a hash code generated from the salted version of the stored password. If the comparison fails, discard the salt, regenerate a new salt value, and repeat the process.
The reason for the single-use salt is to prevent anyone listening to the conversation from capturing the hash code of the users password, which, when you use hash code comparison, is just as good as having the password itself.
Note that you need to keep the original password around, you can't hash it once on the server and save the hash in the database. If you need to ensure that the passwords stored in your database are also secure, then you will need to encrypt them before storing them. I believe that ASP.NET membership providers do allow you to store passwords encrypted, however, if you really wish to have a secure authentication mechanism that is difficult for a hacker to crack, then I would recommend handling password storage and retrieval entirely on your own.
Finally, I should note, that such a complex password transfer mechanism should be largely unnecessary if you use SSL to encrypt your connection during authentication.
References (for those who have never heard of Kerberos or SRP):
<http://en.wikipedia.org/wiki/Kerberos_(protocol)>
<http://en.wikipedia.org/wiki/Secure_remote_password_protocol> | This is a bad idea, security wise. If you send a non-ssl form that contains the hashed password, then anyone capturing traffic has all they need to login. Your javascript has to result in something that indicates success (a redirect, token passed to the server, etc). Whatever it is, the listener now can recreate that without proper authentication.
SSL was built for a reason, by people who tried a lot of other web authentication schemes. It is far safer and cheaper to get a cert than to try write your own safe authentication scheme that works without encryption.
Added for clarity:
Client side hashing alone is not safe. Say I have a form with the following inputs
```
<form action="signin.whatever" method="post">
<input type="text" id="txtUser">
<input type="text" id="txtPass">
<input type="hidden" id="hiddenHash">
<input type="submit" onclick="hashAndSubmit()">
</form>
```
where hashAndSubmit() hashes the password and puts it in hiddenHash, and blanks out the password field. If I sniff your submission and see the following fields:
```
txtUser:joeuser
txtPass:
hiddenHash:xxx345yz // hash result
```
that's all I need as an attacker. I build a form with your user and hash value and I'm all set. The password is not necessary for a replay attack.
To get around this, you have to look at one-time salt values, or other schemes. All of which introduce more cost(don't forget developer time) and risk than SSL. Before you do something like this, ask one question...
*Do I trust myself more than years and years of public testing of the SSL encryption?* | Is it possible to hash a password and authenticate a user client-side? | [
"",
"asp.net",
"javascript",
"silverlight",
"authentication",
"passwords",
""
] |
I have an attribute and i want to load text to the attribute from a resource file.
```
[IntegerValidation(1, 70, ErrorMessage = Data.Messages.Speed)]
private int i_Speed;
```
But I keep getting
"An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type"
It works perfectly if i add a string instead of Data.Messages.Text, like:
```
[IntegerValidation(1, 70, ErrorMessage = "Invalid max speed")]
```
Any ideas? | Attribute values are hard-coded into the assembly when you compile. If you want to do anything at execution time, you'll need to use a constant as the *key*, then put some code into the attribute class itself to load the resource. | Here is my solution. I've added resourceName and resourceType properties to attribute, like microsoft has done in DataAnnotations.
```
public class CustomAttribute : Attribute
{
public CustomAttribute(Type resourceType, string resourceName)
{
Message = ResourceHelper.GetResourceLookup(resourceType, resourceName);
}
public string Message { get; set; }
}
public class ResourceHelper
{
public static string GetResourceLookup(Type resourceType, string resourceName)
{
if ((resourceType != null) && (resourceName != null))
{
PropertyInfo property = resourceType.GetProperty(resourceName, BindingFlags.Public | BindingFlags.Static);
if (property == null)
{
throw new InvalidOperationException(string.Format("Resource Type Does Not Have Property"));
}
if (property.PropertyType != typeof(string))
{
throw new InvalidOperationException(string.Format("Resource Property is Not String Type"));
}
return (string)property.GetValue(null, null);
}
return null;
}
}
``` | C# attribute text from resource file? | [
"",
"c#",
"resources",
"attributes",
""
] |
On this map:
<http://web.pacific.edu/documents/marketing/campus-map/version%202/stockton-campus-2.0.htm>
I have an anchor at the top, and I want the page to jump to the anchor when a link is clicked.
I'm currently using
```
window.location = '#top';
```
It works as expected in FF, Opera, and Chrome, but not in IE 7.
I've tried all permutations like window.location.hash and window.location.assign() and also scrollIntoView(true) and focus().
How can I make it work in IE?
*Edit*: Nothing seems to work, which makes me think it's not the syntax, but something about the JS... here is the click event handler... could it be because it returns false? I'm grasping at straws.
```
// Click handler for each location link
$('#index a').click(function()
{
hideMarkers();
location.href = location.href + "#top";
var marker = showMarker( $(this).attr('data-id') );
GEvent.trigger( marker, "click" );
return false;
});
```
*Edit*: Assignment to window.location.hash breaks in IE7 and IE8 on pages that were loaded as a result of page redirection via the HTTP "Location" header. The solution is to return a page with Javascript that itself will perform the redirection. See the answer by Joe Lapp. | I have this code in production and it works fine in IE7...
```
location.hash = "#top";
```
However, if you are just trying to scroll to the top, this ought to be a lot easier...
```
window.scrollTo(0, 0);
``` | The [`location` object](http://www.w3schools.com/HTMLDOM/dom_obj_location.asp) is broken up into several properties - `href` is only one of them
Another one, `hash`, is what you're looking for.
```
top.location.hash = 'top';
```
You can also do this without using the location/href at all - just use [scrollTo()](https://developer.mozilla.org/en/DOM:window.scrollTo)
```
top.scrollTo( 0, 0 );
``` | window.location = #anchor doesn't work in IE | [
"",
"javascript",
"internet-explorer",
"hash",
"anchor",
"window.location",
""
] |
There's a lot one can find about this googling a bit but I haven't quite found a workable solution to this problem.
Basically what I have is a big CLOB on a particular class that I want to have loaded on demand. The naive way to do this would be:
```
class MyType {
// ...
@Basic(fetch=FetchType.LAZY)
@Lob
public String getBlob() {
return blob;
}
}
```
That doesn't work though, apparently due to the fact I'm using oracle drivers, i.e. Lob objects aren't treated as simple handles but are always loaded. Or so I've been led to believe from my forays. There is one solution that uses special instrumentation for lazy property loading, but as the Hibernate docs seem to suggest they're less than interested in making that work correctly, so I'd rather not go that route. Especially with having to run an extra compile pass and all.
So the next solution I had envisioned was separating out this object to another type and defining an association. Unfortunately, while the docs give conflicting information, it's apparent to me that lazy loading doesn't work on OneToOne associations with shared primary key. I'd set one side of the association as ManyToOne, but I'm not quite sure how to do this when there's a shared primary key.
So can anybody suggest the best way to go about this? | According to [this](https://forum.hibernate.org/viewtopic.php?p=2394911) only PostgreSQL implements Blob as really lazy. So the best solution is to move the blob to another table. Do you have to use a shared primary key? Why don't you do something like this:
```
public class MyBlobWrapper {
@Id
public Long getId() {
return id;
}
@Lob
public String getBlob() {
return blob;
}
@OneToOne(fetch=FetchType.LAZY,optional=false)
public MyClass getParent() {
return parent;
}
}
``` | Instead of doing equilibristics with hibernate annotations, one may just try converting the field from `String` into `Clob` (or `Blob`):
```
@Lob
@Basic(fetch=FetchType.LAZY)
@Column(name = "FIELD_COLUMN")
public Clob getFieldClob() {
return fieldClob;
}
public void setFieldClob(Clob fieldClob) {
this.fieldClob = fieldClob;
}
@Transient
public String getField()
{
if (this.getFieldClob()==null){
return null;
}
try {
return MyOwnUtils.readStream(this.getFieldClob().getCharacterStream());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void setField(String field)
{
this.fieldClob = Hibernate.createClob(field);
}
```
Worked for me (the field started to load lazily, on Oracle). | Lazily loading a clob in hibernate | [
"",
"java",
"hibernate",
"jpa",
"clob",
"lob",
""
] |
At the July 2009 [C++0x meeting in Frankfurt](http://www-949.ibm.com/software/rational/cafe/blogs/cpp-standard/2009/07/20/the-view-or-trip-report-from-the-july-2009-c-standard-meeting), it was decided to [remove concepts](http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=441) from C++0x. Personally, I am disappointed but I'd rather have an implementable C++0x than no C++0x. They said they will be added at a later date.
What are your opinions on this decision/issue? How will it affect you? | Personally I'm not too unhappy of the removal as the purpose of concepts were to mainly improve compile time error messages, as Jeremy Siek, one of the co-authors of the Concepts proposal, writes (<http://lambda-the-ultimate.org/node/3518#comment-50071>):
> While the Concepts proposal was not
> perfect (can any extension to C++
> really ever be perfect?), it would
> have provided a very usable and
> helpful extension to the language, an
> extension that would drastically
> reduce the infamous error messages
> that current users of template
> libraries are plagued with.
Of course concepts had more purpose than just enable the compilers to give shorter error messages, but currently I think we all can live without them.
EDIT: Herb Sutter also writes on his [blog](http://herbsutter.wordpress.com/2009/07/21/trip-report/):
> Q: Wasn’t this C++0x’s one big
> feature?
>
> A: No. Concepts would be great, but
> for most users, the presence or
> absence of concepts will make no
> difference to their experience with
> C++0x except for quality of error
> messages.
>
> Q: Aren’t concepts about adding major
> new expressive power to the language,
> and so enable major new kinds of
> programs or programming styles?
>
> A: Not really. Concepts are almost
> entirely about getting better error
> messages. | I was looking forward to them. Mostly for better error reporting when the compilation failed. Nothing like reading through 1000 character strings to figure out your dumb errors. | C++0x will no longer have concepts. Opinions? How will this affect you? | [
"",
"c++",
"c++11",
"c++-concepts",
""
] |
I'm trying to create a Observable Dictionary Class for WPF DataBinding in C#.
I found a nice example from Andy here: [Two Way Data Binding With a Dictionary in WPF](https://stackoverflow.com/questions/800130/two-way-data-binding-with-a-dictionary-in-wpf/800217)
According to that, I tried to change the code to following:
```
class ObservableDictionary : ViewModelBase
{
public ObservableDictionary(Dictionary<TKey, TValue> dictionary)
{
_data = dictionary;
}
private Dictionary<TKey, TValue> _data;
public Dictionary<TKey, TValue> Data
{
get { return this._data; }
}
private KeyValuePair<TKey, TValue>? _selectedKey = null;
public KeyValuePair<TKey, TValue>? SelectedKey
{
get { return _selectedKey; }
set
{
_selectedKey = value;
RaisePropertyChanged("SelectedKey");
RaisePropertyChanged("SelectedValue");
}
}
public TValue SelectedValue
{
get
{
return _data[SelectedKey.Value.Key];
}
set
{
_data[SelectedKey.Value.Key] = value;
RaisePropertyChanged("SelectedValue");
}
}
}
```
}
Unfortunately I still don't know how to pass "general" Dictionary Objects.. any ideas?
Thank you!
Cheers | If you really want to make an `ObservableDictionary`, I'd suggest creating a class that implements both `IDictionary` and `INotifyCollectionChanged`. You can always use a `Dictionary` internally to implement the methods of `IDictionary` so that you won't have to reimplement that yourself.
Since you have full knowledge of when the internal `Dictionary` changes, you can use that knowledge to implement `INotifyCollectionChanged`. | * [`ObservableDictionary(Of TKey, TValue)`](http://blogs.microsoft.co.il/blogs/shimmy/archive/2010/12/02/observabledictionary-lt-tkey-tvalue-gt.aspx) - VB.NET
* [`ObservableDictionary<TKey, TValue>`](http://blogs.microsoft.co.il/blogs/shimmy/archive/2010/12/26/observabledictionary-lt-tkey-tvalue-gt-c.aspx) - C# | General Observable Dictionary Class for DataBinding/WPF C# | [
"",
"c#",
"wpf",
"data-binding",
""
] |
Suppose I have a search screen that is intended for looking up items. There are various optional search options on the screen that will cause the SQL query statement to vary.
Here are some example searches:
1. Description search
2. Description search + item supplier id
3. Description search + item supplier id + item hierarchy level 1 id
4. Description search + item supplier id + item hierarchy level 1 id + level 2 id
5. item hierarchy level 1 id + level 2 id (no description, no item supplier id)
...you get the idea. There are quite a number of possible combinations. I was hoping to use parameterized queries for the performance benefits and such (plus I'm using them for the rest of the queries throughout the program).
Is there a way to do this or am I forced to either create each possible query and matching SQLiteCommand object or build the query string dynamically with a StringBuilder based on the options selected?
I'm using using the SQLite.NET data provider with C# 3.0 (on the 3.5 compact framework).
---
**UPDATE**
Based on some of the suggestions with null default values for the parameters and using `(@param isnull or column = @param)`, I think I should be able to get this to work. I'll keep you posted.
NOTE: I am avoiding using stored procedures because the rest of the code uses parameterized queries instead of stored procedures. I'd like to keep everything consistent for the sanity of future maintenance programmers. It shouldn't make too much of a difference anyway.
---
**UPDATE 2**
This worked **great** on a desktop system (which is where I did my initial testing for the queries). However, it was very slow on the Windows CE Device I was using. Unusably slow. All the same, I can definitely use this in the future and it's very handy. Just not when running queries on a mobile device.
Thanks | From the stored procedure side you can default values to null then build your where clause to accommodate this null value.
```
ALTER Procedure FooProcedure
@SupplierID INT = NULL,
@LevelOne INT = NULL
AS
BEGIN
SELECT SupplierID, LevelOne
FROM FooTable
WHERE @SupplierID IS NULL OR SupplierID = @SupplierID
AND @LevelOne IS NULL OR LevelOne = @LevelOne
END
``` | You can assign the parameters default values and handle the logic within your stored procedure:
```
create procedure mySproc(@description nvarchar(20) = null, @supplierid int = null, etc...)
```
handle the logic of whether the parameters are null in the body of the sproc. | Is there a way to create a parameterized query or stored procedure that accepts <= N parameters? | [
"",
"c#",
"sqlite",
"parameterized",
""
] |
I'm having some trouble doing a "tree-like" query (what do we call this?) in SQL.
Take a look at my diagram below (table and column names are in danish - sorry about that):
[DB diagram http://img197.imageshack.us/img197/8721/44060572.jpg](http://img197.imageshack.us/img197/8721/44060572.jpg)
Using MSSQL Server 2005, the goal is to find the **most parent group** (Gruppe), for each customer (Kunde).
Each group can have many parent groups and many child groups.
And, I would also like to know how to display the tree like this:
```
Customer 1
- Parent group 1
- Child group 1
- ChildChild group n
- Child group n
- Parent group n
- ...
- ...
Customer n
- ...
```
---
Another question:
How does the query look to get ALL the groups for all the customers? Parent and child groups. | I just can't say it better than Joe Celko. The problem is usually that the models built doesn't lend themselves well to build hierarchies, and that those models have to take in consideration the characteristics of your hierarchy. Is it too deep? Is it too wide? Is it narrow and shallow?
One key to success on wide and shallow trees is to have the full path in the hierarchy in a column, like Celko mentions in the first link.
* <http://onlamp.com/pub/a/onlamp/2004/08/05/hierarchical_sql.html>
* <http://www.dbmsmag.com/9603d06.html> and <http://www.dbmsmag.com/9604d06.html>
* <http://www.ibase.ru/devinfo/DBMSTrees/sqltrees.html> | You can use CTE's to construct "the full path" column on the fly
```
--DROP TABLE Gruppe, Kunde, Gruppe_Gruppe, Kunde_Gruppe
CREATE TABLE Gruppe (
Id INT PRIMARY KEY
, Name VARCHAR(100)
)
CREATE TABLE Kunde (
Id INT PRIMARY KEY
, Name VARCHAR(100)
)
CREATE TABLE Gruppe_Gruppe (
ParentGruppeId INT
, ChildGruppeId INT
)
CREATE TABLE Kunde_Gruppe (
KundeId INT
, GruppeId INT
)
INSERT Gruppe
VALUES (1, 'Group 1'), (2, 'Group 2'), (3, 'Group 3')
, (4, 'Sub-group A'), (5, 'Sub-group B'), (6, 'Sub-group C'), (7, 'Sub-group D')
INSERT Kunde
VALUES (1, 'Kunde 1'), (2, 'Kunde 2'), (3, 'Kunde 3')
INSERT Gruppe_Gruppe
VALUES (1, 4), (1, 5), (1, 7)
, (2, 6), (2, 7)
, (6, 1)
INSERT Kunde_Gruppe
VALUES (1, 1), (1, 2)
, (2, 3), (2, 4)
;WITH CTE
AS (
SELECT CONVERT(VARCHAR(1000), REPLACE(CONVERT(CHAR(5), k.Id), ' ', 'K')) AS TheKey
, k.Name AS Name
FROM Kunde k
UNION ALL
SELECT CONVERT(VARCHAR(1000), REPLACE(CONVERT(CHAR(5), x.KundeId), ' ', 'K')
+ REPLACE(CONVERT(CHAR(5), g.Id), ' ', 'G')) AS TheKey
, g.Name
FROM Gruppe g
JOIN Kunde_Gruppe x
ON g.Id = x.GruppeId
UNION ALL
SELECT CONVERT(VARCHAR(1000), p.TheKey + REPLACE(CONVERT(CHAR(5), g.Id), ' ', 'G')) AS TheKey
, g.Name
FROM Gruppe g
JOIN Gruppe_Gruppe x
ON g.Id = x.ChildGruppeId
JOIN CTE p
ON REPLACE(CONVERT(CHAR(5), x.ParentGruppeId), ' ', 'G') = RIGHT(p.TheKey, 5)
WHERE LEN(p.TheKey) < 32 * 5
)
SELECT *
, LEN(TheKey) / 5 AS Level
FROM CTE c
ORDER BY c.TheKey
```
Performance might be sub-optimal if you have lots of reads vs rare modifications. | SQL "tree-like" query - most parent group | [
"",
"sql",
"tree",
""
] |
I want to know whether unhandled exception will make WCF service crash. I have written the following program which shows unhandled exception in a thread started by WCF service will make the whole WCF service crash.
My question is, I want to confirm whether unhandled exception in threads (started by WCF service) will make WCF crash? My confusion is I think WCF should be stable service which should not crash because of unhandled exception.
I am using VSTS 2008 + C# + .Net 3.5 to develop a self-hosted Windows Service based WCF service.
Here are the related parts of code,
```
namespace Foo
{
// NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.
[ServiceContract]
public interface IFoo
{
[OperationContract]
string Submit(string request);
}
}
namespace Foo
{
// NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config and in the associated .svc file.
public class FooImpl : IFoo
{
public string Submit(string request)
{
return String.Empty;
}
}
}
namespace Foo
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
ServiceHost host = new ServiceHost(typeof(FooImpl));
protected override void OnStart(string[] args)
{
host.Open();
// start a thread which will throw unhandled exception
Thread t = new Thread(Workerjob);
t.Start();
}
protected override void OnStop()
{
host.Close();
}
public static void Workerjob()
{
Thread.Sleep(5000);
throw new Exception("unhandled");
}
}
}
``` | Yes, an unhandled exception in a thread will take the process down.
This process will crash:
```
static void Main(string[] args)
{
Thread t = new Thread(() =>
{
throw new NullReferenceException();
});
t.Start();
Console.ReadKey();
}
```
This one will not:
```
static void Main(string[] args)
{
Thread t = new Thread(() =>
{
try
{
throw new NullReferenceException();
}
catch (Exception exception)
{
Console.WriteLine(exception.ToString());
}
});
t.Start();
Console.ReadKey();
}
``` | An unhandled exception on the service side will cause the channel (the connection between the client and the server) to "fault" - e.g. to be torn down.
From that point on, you cannot call from the client using the same proxy client object instance anymore - you'll have to re-create the proxy client.
Your best bet is to handle all error on the server side whenever possible. Check out the [IErrorHandler](http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx) interface, which you should implement on your service implementation class, to turn all unhandled .NET exceptions into either SOAP faults (which will **NOT** cause the channel to fault), or to report / swallow them entirely.
Marc | unhandled exception will make WCF service crash? | [
"",
"c#",
".net",
"wcf",
"visual-studio-2008",
"windows-services",
""
] |
I was looking over some (C++) code and found something like this:
```
//Foo.cpp
namespace
{
void SomeHelperFunctionA() {}
void SomeHelperFunctionB() {}
void SomeHelperFunctionC() {}
//etc...
class SomeClass //<---
{
//Impl
};
}
```
`SomeHelperFunction[A-Z]` are functions that are only needed in that translation unit, so I understand why they're in an unnamed `namespace`. Similarly, `SomeClass` is also only required in that translation unit, but I was under the impression that you could have classes with identical names in different translation units without any sort of naming collisions provided that you didn't have a global class declaration (e.g., in a commonly included header file).
I should also mention that this particular translation unit does **not** include any headers that might declare a class with an identical name (`SomeClass`).
So, given this information, could someone please shed some light on why the original programmer might have done this? Perhaps just as a precaution for the future?
I'll be honest, I've never seen classes used in unnamed namespaces before. | An anonymous namespace is like the static keyword when it is applied at the global level.
An anonymous namespace makes it so you can't call anything inside the namespace from another file.
Anonymous namespaces allow you to limit the scope of what's within to the current file only.
The programmer would have done this to avoid naming conflicts. No global names will conflict in this way **at linking time**.
Example:
**File: test.cpp**
```
namespace
{
void A()
{
}
void B()
{
}
void C()
{
}
}
void CallABC()
{
A();
B();
C();
}
```
**File: main.cpp**
```
void CallABC();//You can use ABC from this file but not A, B and C
void A()
{
//Do something different
}
int main(int argc, char** argv)
{
CallABC();
A();//<--- calls the local file's A() not the other file.
return 0;
}
```
The above will compile fine. But if you tried to write an `CallABC()` function in your main you would have a linking error.
In this way you can't call `A()`, `B()` and `C()` functions individually, but you can call `CallABC()` that will call all of them one after the other.
You can forward declare `CallABC()` inside your main.cpp and call it. But you can't forward declare test.cpp's A(), B() nor C() inside your main.cpp as you will have a linking error.
As for why there is a class inside the namespace. It is to make sure no external files use this class. Something inside the .cpp probably uses that class. | > I was under the impression that you could have classes with identical names in different translation units without any sort of naming collisions provided that you didn't have a global class declaration
Well, that's not the case. Remember that those "common" global class definitions are in header files. Those are literally included, copying that common global class definition to all translation units. If you use another way of including *exactly* the same class definitions in multiple translation units (eg. macro expansion), it's fine too. But if you have different definitions for the same class name, you risk undefined behavior. Link failures if you're lucky. | What effect does an unnamed namespace have on a class? | [
"",
"c++",
"class",
"namespaces",
"unnamed-namespace",
""
] |
I have some code that runs when a user clicks anywhere in the body of the web page. I only want the JavaScript to run if the click is on a NON-LINK. Any ideas?
Thanks
Mike | ```
document.body.onclick = function(e){
var target = e ? e.target : window.event.srcElement;
if (target.nodeName.toLowerCase() !== 'a') {
// Do something here...
}
};
```
Note that any attempts to stop propagation before the event reaches the **`<body>`** will stop the above handler from running. To avoid this you can use event capturing. | document.body.onclick = function... is a statement.
Hence the closing ';' | How can I execute JavaScript onClick of a NON-LINK? | [
"",
"javascript",
"html",
"css",
""
] |
I been playing around with some custom html helpers and I now I am trying to make one that I can use for jquery AJAX UI Tabs.
So to do ajax tabs you need to have this format in your html code
```
<div id="example">
<ul>
<li><a href="ahah_1.html"><span>Content 1</span></a></li>
<li><a href="ahah_2.html"><span>Content 2</span></a></li>
<li><a href="ahah_3.html"><span>Content 3</span></a></li>
</ul>
</div>
```
so I can't use ActionLink because I don't think I can add anyway the tag to the actionLink.
So I want to make my own html helper that has an actionLink with a span tag in it and possibly build it up later on to have an unordered listed tag with it.
So I am not sure how to use the ActionLink to my benefit. Like the ActionLink has 10 overloaded methods and I don't want to recreate all 10 of them since that just seems pointless. So is there away I can reference it or something like that?
I am using the way that allows my custom html helpers to show up when you do "Html." in intellisense.
for instance I would have:
```
public static string Button(this HtmlHelper helper, string id, string value)
```
So I am not sure how to make use of this HtmlHelper I am passing in.
I also don't understand this part of the line of code "this HtmlHelper helper".
What confuses me is the using the keyword "this" in the parameter. I am not sure what it is refering to and why you need it. I also don't understand how by passing this parameter but not using it somehow allows your customer Html helpers to be accesed by "Html.".
Thanks | [Marc's answer](https://stackoverflow.com/questions/1176557/need-help-building-custom-html-helper-for-asp-net-mvc/1176578#1176578) is excellent. Just adding some code:
**1) Create static class with your helper:**
```
public static class MyHtmlHelpers
{
public static string MySpecialActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues)
{
var innerTagBuilder = new TagBuilder("span") {
InnerHtml = (!String.IsNullOrEmpty(linkText)) ? HttpUtility.HtmlEncode(linkText) : String.Empty
};
TagBuilder tagBuilder = new TagBuilder("a") {
InnerHtml = innerTagBuilder.ToString(TagRenderMode.Normal);
};
var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
var url = urlHelper.Action(actionName, routeValues);
tagBuilder.MergeAttribute("href", url);
return tagBuilder.ToString(TagRenderMode.Normal);
}
}
```
**2) Add namespace of MyHtmlHelpers class to web.config:**
```
<pages>
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Linq" />
<add namespace="System.Collections.Generic" />
<add namespace="MyHtmlHelpers_Namespace" />
</namespaces>
</pages>
```
**3) Enjoy :) :**
```
<div id="example">
<ul>
<li><%= Html.MySpecialActionLink("Content 1", "action1", null) %></li>
<li><%= Html.MySpecialActionLink("Content 2", "action2", new { param2 = "value2" }) %></li>
<li><%= Html.MySpecialActionLink("Content 3", "action3", new { param3 = "value3" }) %></li>
</ul>
</div>
``` | The `this HtmlHelper helper` means it is a C# 3.0 "extension method" on `HtmlHelper`, which is how it becomes available on the `Html` instance in your view (etc). An extension method is a static method that *pretends* (at compile time) to be an instance method available on the type nominated by `this` (in this case `HtmlHelper`). In reality, the compiler calls the static method (`Html.Button({args})`) as though you had typed:
```
MyStaticClass.Button(Html, {args});
```
It is not *necessary* to use the `HtmlHelper` that is passed in if you don't need it (inded, I don't use it [here](https://stackoverflow.com/questions/347528#347621)); it's main job (in this case) is to make the code convenient to consume (as an extension method); but it can be useful in some cases. | Need Help building Custom Html Helper for Asp.net MVC | [
"",
"c#",
"asp.net-mvc",
""
] |
I guys.
Have worked around with cookies in PHP for some time. However something came to my mind.
Does its possible to gather all cookies (without knowing its names), or at least list all cookies names present in a browser?
Regards. | ```
print_r($_COOKIE)
``` | No, you can't. php can only locate cookies created from it self host. This security is from browser side. | Cookie sniffer - PHP | [
"",
"php",
"cookies",
"sniffer",
""
] |
I have a PDF file on a local machine. I want to upload this file into a BINARY BLOB on a SQL database. Other approaches mentioned here [[Binary Data in MySQL](https://stackoverflow.com/questions/17/binary-data-in-mysql]) all use PHP. I want a simple clean way to upload this PDF file on the Linux command line. Unfortunately, I do not have access to the remote filesystem so cannot just store links to the file as mentioned elsewhere... I sort of need to use this MySQL database as a virtual filesystem for these PDF files..
From the PhP example, it seems all that is required is to escape the slashes before using the INSERT command? Is there a simple way to achieve that on a Linux command-line? | Not sure if this completely solves my problem, but I found a filesystem layer implemented on top of MySQL. I guess I can use that to store my PDF files as BLOBs automatically... still need to figure out how to store keys to the PDF file in this filesystem for structured access to the PDF file based on something more meaningful than < inode,seq >.
<http://sourceforge.net/projects/mysqlfs/> and
<http://www.linux.com/archive/feature/127055> | You could use the mysql function [LOAD\_FILE](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_load-file) in conjunction with a small shellscript to do this I guess.
Untested code follows:
```
#!/bin/bash
if [ -z $1 ]
then
echo "usage: insert.sh <filename>"
else
SQL="INSERT INTO file_table (blob_column, filename) VALUES(LOAD_FILE('$1'), '$1')"
echo "$SQL" > /tmp/insert.sql
cat /tmp/insert.sql | mysql -u user -p -h localhost db
fi
```
And you could use it like this:
```
<prompt>./insert.sh /full/path/to/file
```
Better implementation with error checking, proper tempfile creation, escaping and other niceties is left as an exercise to the reader. Note that use of `LOAD_FILE()` requires the FILE privilege in MySQL and a full path the file. | storing binary data in mysql | [
"",
"sql",
"mysql",
"linux",
"blob",
""
] |
I'm trying to create a query on SQL server 2005 that will check if the sum of some fields in some detail records is equal to the total field in a header record. This will be used for creating electronic deposit of checks for the company I'm working for.
The hierarchy looks like this:
Deposits --> Batches --> Checks
Before creating the file for electronic deposit, replication might not have fully completed for each table, so I need to check to ensure that each record is there before creating the file. Basically, I want to select a list of locations and ids from my Deposits table where the correct number of batches and the correct number of checks do exist in their respective tables.
Here is the logic that I want to have.
```
select location, d.id from closing_balance..cb_deposits as d
left outer join closing_balance..cb_checkbatchhf as b on d.id = b.deposit_id and d.location = b.loc
left outer join closing_balance..cb_checkdf as c on b.id = c.batch_id and b.loc = c.loc
where sum(c.check_amt) = b.scanned_subtotal and sum(b.scanned_subtotal) = d.amount and sum(b.num_checks_scanned) = d.count
```
The above doesn't work because you can't have the aggregate function sum in the where clause. I can easily do this programatically, but if there is a clever way to do this quickly in a SQL statement, that would be best.
Any help is greatly appreciated.
Thanks! | You can move your sum check to the having clause, after the where clause:
```
select location, d.id
from closing_balance..cb_deposits as d
left outer join closing_balance..cb_checkbatchhf as b
on d.id = b.deposit_id and d.location = b.loc
left outer join closing_balance..cb_checkdf as c
on b.id = c.batch_id and b.loc = c.loc
group by location, d.id, b.scanned_subtotal, d.amount, d.count
having sum(c.check_amt) = b.scanned_subtotal
and sum(b.scanned_subtotal) = d.amount
and sum(b.num_checks_scanned) = d.count
``` | You can't do a sum in a WHERE clause, but you can use the HAVING clause. for example
```
SELECT
Id
FROM
Table
GROUP BY
Id
HAVING
SUM(Amount) = 100
``` | SQL Server 2005 summation query | [
"",
"sql",
"sql-server",
""
] |
I'm trying to write a program that manipulates unicode strings read in from a file. I thought of two approaches - one where I read the whole file containing newlines in, perform a couple regex substitutions, and write it back out to another file; the other where I read in the file line by line and match individual lines and substitute on them and write them out. I haven't been able to test the first approach because the newlines in the string are not written as newlines to the file. Here is some example code to illustrate:
```
String output = "Hello\nthere!";
BufferedWriter oFile = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("test.txt"), "UTF-16"));
System.out.println(output);
oFile.write(output);
oFile.close();
```
The print statement outputs
> Hello
> there!
but the file contents are
> Hellothere!
Why aren't my newlines being written to file? | You should try using
```
System.getProperty("line.separator")
```
Here is an untested example
```
String output = String.format("Hello%sthere!",System.getProperty("line.separator"));
BufferedWriter oFile = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("test.txt"), "UTF-16"));
System.out.println(output);
oFile.write(output);
oFile.close();
```
> I haven't been able to test the first
> approach because the newlines in the
> string are not written as newlines to
> the file
Are you sure about that? Could you post some code that shows that specific fact? | Use System.getProperty("line.separator") to get the platform specific newline. | Newlines in string not writing out to file | [
"",
"java",
"string",
"unicode",
"file-io",
""
] |
Another question re. Unicode, terminals and now C# and `wc`. If I write this simple piece of code
```
int i=0;
foreach(char c in Console.In.ReadToEnd())
{
if(c!='\n') i++;
}
Console.WriteLine("{0}", i);
```
and input it only the character "€" (3 bytes in utf-8), `wc` returns 3 characters (maybe using wint\_t, though I haven't checked), but `ReadToEnd()` returns 1 (one character). What exactly is the behavior of `ReadToEnd` in this case? How do I know what `ReadToEnd` is doing behind the scenes?
I'm running xterm initialized with utf-8.en.US, running Ubuntu Linux and Mono.
Thank you. | `wc` and most unix-like commands deal with characters in terms of the C `char` data type which is usually an unsigned 8 bit integer. `wc` simply reads the bytes from the standard input one by one with no conversion and determines that there are 3 characters.
.NET deals with characters in terms of its own `Char` data type which is a 16 bit unsigned integer and represents a UTF-16 character. The console class has recieved the 3 bytes of input, determined that the console it is attached to is UTF-8 and has properly converted them to a single UTF-16 euro character. | You need to take into consideration the character encoding. Currently you are merely counting the bytes and `char`s and `byte`s are not necessarily the same size.
```
Encoding encoding = Encoding.UTF8;
string s = "€";
int byteCount = encoding.GetByteCount(s);
Console.WriteLine(byteCount); // prints "3" on the console
byte[] bytes = new byte[byteCount];
encoding.GetBytes(s, 0, s.Length, bytes, 0);
int charCount = encoding.GetCharCount(bytes);
Console.WriteLine(charCount); // prints "1" on the console
``` | TextWriter.ReadToEnd vs. Unix wc Command | [
"",
"c#",
"c",
"unicode",
"mono",
""
] |
I have used *[hashlib](https://docs.python.org/3/library/hashlib.html)* (which replaces *[md5](https://docs.python.org/2/library/md5.html)* in Python 2.6/3.0), and it worked fine if I opened a file and put its content in the [`hashlib.md5()`](https://docs.python.org/2/library/hashlib.html) function.
The problem is with very big files that their sizes could exceed the RAM size.
How can I get the MD5 hash of a file without loading the whole file into memory? | Break the file into 8192-byte chunks (or some other multiple of 128 bytes) and feed them to MD5 consecutively using `update()`.
This takes advantage of the fact that MD5 has 128-byte digest blocks (8192 is 128×64). Since you're not reading the entire file into memory, this won't use much more than 8192 bytes of memory.
In Python 3.8+ you can do
```
import hashlib
with open("your_filename.txt", "rb") as f:
file_hash = hashlib.md5()
while chunk := f.read(8192):
file_hash.update(chunk)
print(file_hash.digest())
print(file_hash.hexdigest()) # to get a printable str instead of bytes
``` | You need to read the file in chunks of suitable size:
```
def md5_for_file(f, block_size=2**20):
md5 = hashlib.md5()
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
return md5.digest()
```
Note: Make sure you open your file with the 'rb' to the open - otherwise you will get the wrong result.
So to do the whole lot in one method - use something like:
```
def generate_file_md5(rootdir, filename, blocksize=2**20):
m = hashlib.md5()
with open( os.path.join(rootdir, filename) , "rb" ) as f:
while True:
buf = f.read(blocksize)
if not buf:
break
m.update( buf )
return m.hexdigest()
```
The update above was based on [the comments provided by Frerich Raabe](https://stackoverflow.com/questions/1131220/get-the-md5-hash-of-big-files-in-python#comment8038619_1131255) - and I tested this and found it to be correct on my Python 2.7.2 Windows installation
I cross-checked the results using the [jacksum](http://www.jonelo.de/java/jacksum/) tool.
```
jacksum -a md5 <filename>
``` | Get the MD5 hash of big files in Python | [
"",
"python",
"md5",
"hashlib",
""
] |
I've been tasked with going through a database and checking all of the links, on a weekly schedule. I normally work in PHP, but doing this in PHP would be very slow (it actually would timeout the page after about 100 URLs), so I decided to make a quick C++ app.
Admitidly, I haven't used C++ since college, so I'm a bit rusty.
I found the ShellExecute function, and that it would open the page no problem. Here is what I have so far:
```
#include <shlobj.h>
#include <iostream>
using namespace std;
int main()
{
if( ShellExecute(NULL,"find","http://example.com/fdafdafda.php",NULL,NULL,SW_SHOWDEFAULT) )
{
cout << "Yes";
} else {
cout << "No";
}
cout << endl;
system("PAUSE");
return 0;
}
```
The problem is that it always returns true, whether it is opening a valid page or not. It appears to be checking if the associated app (a browser in this case) is able to open the document with no problems, then returns true. It isn't looking to see if the browser is getting a 404 or not, it simply sees it open and run and is fine.
Is there a better way to do this? Am I missing a step?
As an aside, I have attempted to use the cURLcpp stuff, but can't seem to figure it out. All of the examples point to header files that don't exist in the download. I have a feeling cURLcpp is the *better* way to do this.
Thanks for any help. | I think you answered your own question. ShellExecute is really not appropriate for this task, and something like CURL would be better. | or if you don't want to use an external library you can check directly with InternetOpen, InternetOpenURL etc. | Link Checker With ShellExecute? | [
"",
"c++",
"winapi",
"hyperlink",
"shellexecute",
""
] |
i want to write a C# lib, or a reference service,
so that if a application reference my lib, and when the application runs,
the function in my function can be run without any invoked?
for example, i got a lib, keep reading the memory usage of the platform,
when the memory was up to 80%, i pop up a message to the user, it is time to close the application.
so..when i create a another application, and want my new application has the mem check feature, i just need to reference it then after my new application run, the mem check will be fired together..
so..how can i do these? | Create a [static constructor](http://msdn.microsoft.com/en-us/library/k9x6w0hc(VS.80).aspx) for your class - this constructor will be run once, and only once, the first time the host application references anything related to your class.
You could create a thread to run some background checking process, hook into an event of the Application object, or whatever you need.
Note however, that you'll need to do more than just add a project reference to your assembly - an assembly is only loaded into an App Domain when something in that assembly is *referenced by existing code*. | The term you're looking for is "Win32 application hook." There's a decent introduction to managed hook injection here: <http://msdn.microsoft.com/en-us/magazine/cc188966.aspx>
I'm not sure you can monitor system memory consumption with an application hook, though. And unfortunately, you cannot write a global hook in managed code because global hooks require a well-defined entry point (a DLL export). This is really something best suited for C++. | How to write a lib in C#, the lib can be run without any invoked? | [
"",
"c#",
"reference",
"invoke",
""
] |
How to Read word comments (Annotation) from microsoft word document ?
please provide some example code if possible ...
Thanking you ... | Finally, I found the answer
here is the code snippet ...
```
File file = null;
FileInputStream fis = null;
HWPFDocument document = null;
Range commentRange = null;
try {
file = new File(fileName);
fis = new FileInputStream(file);
document = new HWPFDocument(fis);
commentRange = document.getCommentsRange();
int numComments = commentRange.numParagraphs();
for (int i = 0; i < numComments; i++) {
String comments = commentRange.getParagraph(i).text();
comments = comments.replaceAll("\\cM?\r?\n", "").trim();
if (!comments.equals("")) {
System.out.println("comment :- " + comments);
}
}
} catch (Exception e) {
e.printStackTrace();
}
```
I am using Poi poi-3.5-beta7-20090719.jar, poi-scratchpad-3.5-beta7-20090717.jar. The other archives - poi-ooxml-3.5-beta7-20090717.jar and poi-dependencies-3.5-beta7-20090717.zip - will be needed if you are hoping to work on the OpenXML based file formats.
I appreciate the help of Mark B who actually found this solution .... | Get the [HWPFDocument](http://poi.apache.org/apidocs/org/apache/poi/hwpf/HWPFDocument.html) object (by passing a Word document in an input stream, say).
Then you can get the summary via [getSummaryInformation()](http://poi.apache.org/apidocs/org/apache/poi/POIDocument.html#getSummaryInformation%28%29), and that will give you a [SummaryInformation](http://poi.apache.org/apidocs/org/apache/poi/hpsf/SummaryInformation.html) object via `getSummary()` | how to read comments in word document from apache poi? | [
"",
"java",
"apache",
"ms-word",
"document",
""
] |
Recommendations please (from experience ideally, but anything is useful).
Searching Google gives me too many choices, and I would like to know if there is a good one people use. | I prefer to use [PHPMailer](http://phpmailer.codeworxtech.com) class. It allow to send email as from your own domain and from remote account (ex.: gmail.com). Attachments, HTML messages, embedded images and many more features. Enjoy! :) | Pear has some mail classes:
<http://pear.php.net/package/Mail> | What is a good php class for SMTP email? | [
"",
"php",
"smtp",
""
] |
I have been trying to make a secure login for my site that I am developing.
I just cant get it to work, I use MySQL databases with PHP.
I can make the form to add the user and their info to the database but I can't seem to make it work with the login.
What type of encryption is used with HTML `<input type="password">`?
How do I keep the User logged in throughout their visit to my site?
I how do I securely check if it is the right password that matches the username?
I have been doing PHP for maybe a year now, I just haven't learned this part yet so it would be nice to know. | > What type of encryption is used with
> html < input type=password >??
None. The input is just masked to protect against "Looking at the monitor" attacks.
If you want security, transmit your data over HTTPS (HTTP with SSL).
> How do I keep the User logged in throughout their visit to my site?
Most people use cookies.
> I how do i securely check if it is the right password that matches the username??
Securely?
Don't use a shared server. Follow the normal steps for keeping data on that server secure. Store passwords as hashes, not as plain text.
Check?
Convert the submitted password to the matching hash, then compare as normal. Assuming you store the data in a database, just SELECT FROM users WHERE user=? AND password=? and count the number of rows you get back. | I'll address the password protection portion of your question.
There is no built in encryption with the password input type. The browser will submit it as plain text just like everything else. There are two ways to protect the password.
The first is to set up a [challenge/response system](http://en.wikipedia.org/wiki/Challenge-response_authentication) but this will require Javascript to work. Basically you take the user's password, apply a hashing function if that's the way it's stored on the server, then you take a server challenge token and salt the password value for a new hash. The server will take it's value of the password and apply the challenge as well. If they match the password is correct and there is no way for anyone to know what the actual password was. This requires javascript because the hash must be produced on the client side if this approach is to be effective.
Another, more simple option, is to require HTTPs for the log in portion of the site. | Making A Secure Login | [
"",
"php",
"mysql",
"password-protection",
""
] |
Is it possible in C/C++ to create my own custom stream of type FILE (stdio.h) that can be used with fputs() for example ? | If your "custom stream" isn't something you can represent with a file descriptor or file handle, then you're out of luck. The `FILE` type is implementation-defined, so there's no standard way to associate other things with one.
If you can get a C file descriptor for whatever it is you're trying to write to, then you can call [`fdopen`](http://opengroup.org/onlinepubs/007908775/xsh/fdopen.html) on it to turn it into a `FILE*`. It's not standard C or C++, but it's provided by Posix. On Windows, it's spelled [`_fdopen`](http://msdn.microsoft.com/en-us/library/dye30d82.aspx).
If you're using Windows and you have a `HANDLE`, then you can use [`_open_osfhandle`](http://msdn.microsoft.com/en-us/library/bdts1c9x.aspx) to associate a file descriptor with it, and then use `_fdopen` from there.
Are you really tied to `fputs`? If not, then replace it with use of a C++ IOStream. Then you can provide your own descendant of `std::basic_streambuf`, wrap it in a `std::ostream`, and use standard C++ I/O on it. | No it isn't. FILE is what is known as an opaque type - it doesn't have anything you can customise. | custom FILE type in C/C++ | [
"",
"c++",
"c",
""
] |
This is a C# 3.0 Winform problem.
I want to clone a big(not very big actually), complicated object. To do it lazily, I seralize it to a MemoryStream and use BinaryFormatter.UnsafeDeserialize(MemoryStream, null) method to get the cloned object. Inside the UnsafeDeserialize() method, there is always an OutOfMemory exception thrown. The memory should be sufficient.
I read a bit about this as a .net bug but not sure whether it is the case here.
Anyone has any idea why this is happening? Any workround? Thanks. | Perhaps a silly question but are you remembering to rewind the MemoryStream to the start of the stream before deserializing it?
It might also help to share some of your code. | Why are you using `UnsafeDeserialize` instead of `Deserialize`? | Deserialize from MemoryStream throws OutOfMemory exception in C# | [
"",
"c#",
"winforms",
"serialization",
"c#-3.0",
""
] |
I'm attempting to use document.location(.href) on the onLoad event to redirect from one page (A) to another (B).
From my understanding, if I use document.location.href (as opposed to .replace), it should add (A) to my history. However, this doesn't appear to be happening.
I've tried setting document.location, document.location.href, and using .assign, and none of these seem to add the first page to the history. Is there any JS technique that can be done via onLoad that will cause (A) to be in the history?
Cheers,
Victor | If you modify document.location.href, it will definitely add to the history.
[Try this demo page →](http://jsbin.com/ohusa)
Code:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #000; font: 16px Helvetica, Arial; color: #fff; }
</style>
<script>
$(document).ready(
function()
{
$('#hello').click( function(ev) { ev.preventDefault(); document.location.href='http://www.google.com';});
}
);
</script>
</head>
<body>
<p>Hello from JS Bin</p>
<a id="hello" href="#">Click Me</a>
</body>
</html>
```
Can you create a sample page where it shows that browser history is not changed? | 'location.href', 'document.location' or any of these variations will only add an entry to the browser history if it came from a user initiated action.
For example, if user clicks a button that fires a function that performs a 'location.href' it will be added to browser history, but if 'location.href' is called by an onload event - which is not a user initiated action, it will not be added to the history. | document.location - Not adding to history | [
"",
"javascript",
""
] |
For the downvote fairies.. I know that php is the wrong language for this... but I am working under outside constraints. Given that:
I have a large flat file that I need to process in php. I convert the flat file into a normalized database in mysql. There are several million lines in the flat file.
I originally tried to use an ORM system while importing the flat file. There was a massive php memory leak problem with that design even with careful freeing of objects. Even if I ensured that there was enough memory, the script would take about 25 days to run on my desktop.
I stripped out the overhead and rewrote the script to directly build mysql commands. I removed AUTO INCREMENT from my design since that required me to as Mysql what the last id entered was in order to make relations between data points. I just use a global counter for database ids instead and I never do any lookups, just inserts.
I use the unix split command to make lots of small files instead of one big one, because there is a memory overhead associated with using a file pointer again and again.
Using these optimizations (hope they help someone else) I got the import script to run in about 6 hours.
I rented a virtual instance with 5 times more RAM and about 5 times more processor power than my desktop and noticed that it went exactly the same speed. The server runs the process but has CPU cycles and RAM to spare. Perhaps the limiting factor is disk speed. But I have lots of RAM. Should I try loading the files into memory somehow? Any suggestions for further optimization of php command line scripts processing large files are welcome! | You won't like it but...sounds like you are using the wrong language for the task in hand. If you want to get some huge leaps in speed then a port to a compiled language would be the next step to go. Compiled languages run much, much faster than a scripting language ever will so you'll see your processing time drop off.
Additionally you might be able to dump the data into the DB using a build in command. Postgres had one (Dump? Load? something like that) which would read in a tab delimited text file who's columns matched up with the columns in the table. That would allow you to just focus on getting a text file in the right format and then spitting it into DB with one command and let it handle the optimisation of that rather than yourself.
You've done the right thing with knocking the ORM on the head, splitting the file should not be needed though as your text file reader should just use a buffer internally so it "should" not matter but I'm not a \*nix guy so could be wrong on that front.
We've done something similar with a .net app that chomps through 20Gb of files every morning doing RegExp on every line, keeps a in memory hash for unique records and then pokes new ones into a DB. From that we then spit out 9000+ JS files using a Ruby Script for ease (this is the slowest part). We used to have the importer written in Ruby too and the whole thing took 3+ hours, re-write in .net runs the whole process in about 30-40 mins and 20 of that is the slow Ruby script (not worth optimising that anymore though it does the job well enough). | A couple of important design recommendations for such a task:
Don't read the entire file into memory at once. Use a file pointer and read in reasonable chunks (say, a few kilobytes .. depends on the average record-size). Then process each record and ditch out the buffer. I'm not sure from your description whether you're already doing this or not.
If your mysql storage type supports transactions (the table must be InnoDB), you can use them for optimisations. Start a transaction and process f.ex. 100k rows, then flush by committing the transaction and opening a new one. This works because MySql will only update the index once, instead of for each row.
Another option is to use bulk insert. If your database isn't local (eg. you connect over network), this can give a boost. I think (not sure though) it also gives the same benefits as transactions - possibly even for MyIsam tables.
Finally, if nothing else works, you can remove php from the equation and use [`LOAD DATA INFILE`](http://dev.mysql.com/doc/refman/5.1/en/load-data.html). You may have to pre-process the file first, using php or some other text-processing language (awk or sed have very good performance profiles) | Optimizing php command line scripts to process large flat files | [
"",
"mysql",
"linux",
"php",
""
] |
I have an ajax application where the client might lookup bunch of data frequently(say by key stroke), the data gets updated on the server side once or twice a day at fixed times by a demon process. To avoid visiting the server frequently, I store the data in a xml file, so the client downloads it once when the page first loads, then look the data up from local data file via javascript.
But the user might load the page shortly before the changes, then start using it without ever refreshing the page, so the data file never gets updated, hence keep telling user the new data is not available.
How do I solve this issue? | You should set the appropriate HTTP cache headers for that generated XML file so any client request past that time will get the new version and cache it locally, like any other static content. | If the data load is not very large... Include the data in the main document as an XML island. Either form it in document generation (aspx, php, whatever) or fill in (via ajax calls) a reserved document node upon loading. This way, your user always has the latest data, you do not have to worry about caching, and life is much simpler.
If it is large, fill in that node as needed via ajax calls. | cache or not to cache | [
"",
"php",
"ajax",
"caching",
""
] |
I have an array list:
```
private ArrayList<PerfStatBean> statFilterResults;
```
I want to iterate through it like:
```
Iterator<PerfStatBean> statsIterator = statFilterResults.iterator();
while(statsIterator.hasNext()){
i++;
PerfStatBean perfBean = statsIterator.next();
.........
```
I would like to delete the bean from statFilterResults after I run through it inside the while loop to free up memory. I believe if I do something like
```
perfBean = null;
```
it won't do the job as the perfBean reference will be null but the object will still be in memory.
Any ideas?
Thanks,
Tam | This probably isn't a great optimisation. If the memory requirements are large, then you probably don't want to store them all in a list in the first place - process the objects as they are created.
However, taking the question literally, `ListIterator.set` is the method for you.
```
for (
ListIterator<PerfStatBean> iter = statFilterResults.listIterator();
iter.hasNext()
) {
++i;
PerfStatBean perfBean = iter.next();
iter.set(null);
...
}
``` | [iterator.remove()](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Iterator.html#remove())? | nullify object that is part of ArrayList java | [
"",
"java",
"collections",
"iterator",
""
] |
Is it possible to return the last row of a table in MS SQL Server.
I am using an auto increment field for the ID and i want to get the last one just added to join it with something else. Any idea?
Here's the code:
```
const string QUERY = @"INSERT INTO Questions (ID, Question, Answer, CategoryID, Permission) "
+ @"VALUES (@ID, @Question, @Answer, @CategoryID, @Permission) ";
using (var cmd = new SqlCommand(QUERY, conn))
{
cmd.Parameters.AddWithValue("@Question", question);
cmd.Parameters.AddWithValue("@Answer", answer);
cmd.Parameters.AddWithValue("@CategoryID", lastEdited);
cmd.Parameters.AddWithValue("@Permission", categoryID);
cmd.ExecuteNonQuery();
}
``` | > using an auto increment field ... and i want to get the last one just added to join it with something else.
The key here is "**just added**". If you have a bunch of different users hit the db at the same time, I don't think you want user A to retrieve the record created by user B. That means you probably want to use the `scope_identity()` function to get that id rather than running a query on the table again right away.
Depending on the context you might also need `@@identity` (would include triggers) or `ident_current('questions')` (limited to a specific table, but not the specific scope). But `scope_identity()` is almost always the right one to use.
---
Here's an example:
```
DECLARE @NewOrderID int
INSERT INTO TABLE [Orders] (CustomerID) VALUES (1234)
SELECT @NewOrderID=scope_identity()
INSERT INTO TABLE [OrderLines] (OrderID, ProductID, Quantity)
SELECT @NewOrderID, ProductID, Quantity
FROM [ShoppingCart]
WHERE CustomerID=1234 AND SessionKey=4321
```
---
Based on the code you posted, you can do something like this:
```
// don't list the ID column: it should be an identity column that sql server will handle for you
const string QUERY = "INSERT INTO Questions (Question, Answer, CategoryID, Permission) "
+ "VALUES (@Question, @Answer, @CategoryID, @Permission);"
+ "SELECT scope_identity();";
int NewQuestionID;
using (var cmd = new SqlCommand(QUERY, conn))
{
cmd.Parameters.AddWithValue("@Question", question);
cmd.Parameters.AddWithValue("@Answer", answer);
cmd.Parameters.AddWithValue("@CategoryID", lastEdited);
cmd.Parameters.AddWithValue("@Permission", categoryID);
NewQuestionID = (int)cmd.ExecuteScalar();
}
```
See my answer to another question here:
[get new SQL record ID](https://stackoverflow.com/questions/590927/get-new-sql-record-id/591030#591030)
The problem now is that you'll likely want subsequent sql statements to be in the same transaction. You could do this with client code, but I find keeping it all on the server to be cleaner. You could do that by building a very long sql string, but I tend to prefer a stored procedure at this point.
I'm also not a fan of the `.AddWithValue()` method — I prefer explicitly defining the parameter types — but we can leave that for another day.
Finally, it's kind of late now, but I want to emphasize that it's really better to try to keep this all on the db. It's okay to run multiple statements in one sql command, and you want to reduce the number of round trips you need to make to the db and the amount of data you need to pass back and forth between the db and your app. It also makes it easier to get the transactions right and keep things atomic where they need to be. | Not safe - could have multiple inserts going on at the same time and the last row you'd get might not be yours. You're better off using SCOPE\_IDENTITY() to get the last key assigned for your transaction. | Select the last row in a SQL table | [
"",
"sql",
"sql-server",
""
] |
I'm working with a Python development team who is experienced with programming in Python, but is just now trying to pick up TDD. Since I have some experience working with TDD myself, I've been asked to give a presentation on it. Mainly, I'm just wanting to see articles on this so that I can see how other people are teaching TDD and get some ideas for material to put in my presentation.
Preferably, I'd like the intro to be for Python, but any language will do as long as the examples are easy to read and the concepts transfer to Python easily. | One suggestion I'd make is to start a [coding Dojo](http://codingdojo.org/) group. It helps to start TDD from scratch with a group, with most of recommended best-practices and focus on TDD.
Its basic ideas is to take a simple challenge (like a program that transforms roman algarisms strings into ints), and start to code it, starting from simple inputs, and coding only when there's a test failing. It's not the focus of this to end the problem, but to start making it the right way.
Here's another [link](http://web.cs.wpi.edu/~gpollice/Dojo.html) about it, from which I retrieved the following part:
* There is a coding challenge that is announced beforehand.
* There is a room with one computer attached to video screen.
* The presenter explains the coding challenge and starts the coding. The presenter may or may not choose to have a co-pilot. If this is a Randori session, a co-pilot is usually assigned so that when the switch occurs, the co-pilot takes over for the coder.
* One half of the pair is changed every 5 minutes if the session is Randori.
* The coder should continuously explain what she or he is doing.
* The coder should stop when someone from the audience falls off the sled (has a question about understanding what the pair is doing) -- and only continue when that someone is back on track again.
* **All coders use TDD (Test-Driven Development).**
* All produced code will be made publicly available using the Eclipse Common Public License.
* The programming language to be used is announced in advance per session. | I was very pleased with the two-part article "Test Driven Development in Python" on O'Reilly's site:
<http://www.onlamp.com/pub/a/python/2004/12/02/tdd_pyunit.html> - [waybackmachine](https://web.archive.org/web/20140804160053/http://www.onlamp.com/pub/a/python/2004/12/02/tdd_pyunit.html)
<http://www.onlamp.com/pub/a/python/2005/02/03/tdd_pyunit2.html> - [waybackmachine](https://web.archive.org/web/20140804142354/http://www.onlamp.com/pub/a/python/2005/02/03/tdd_pyunit2.html) [2/3](https://web.archive.org/web/20140215194252/http://www.onlamp.com/pub/a/python/2005/02/03/tdd_pyunit2.html?page=2) and [3/3](https://web.archive.org/web/20131127001859/http://www.onlamp.com/pub/a/python/2005/02/03/tdd_pyunit2.html?page=3)
These really cleared up how to use Python's unittest module for TDD, as well as giving me a good dose of the TDD mindset. | Are there any good online tutorials to TDD for an experienced programmer who is new to testing? | [
"",
"python",
"unit-testing",
"testing",
"tdd",
""
] |
Does anyone know why a client-side javascript handler for asp:CheckBox needs to be an OnClick="" attribute rather than an OnClientClick="" attribute, as for asp:Button?
For example, this works:
```
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
```
and this doesn't (no error):
```
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
```
but this works:
```
<asp:Button runat="server" OnClientClick="alert('Hi');" />
```
and this doesn't (compile time error):
```
<asp:Button runat="server" OnClick="alert('hi');" />
```
(I know what Button.OnClick is for; I'm wondering why CheckBox doesn't work the same way...) | That is very weird. I checked the [CheckBox documentation page](http://msdn.microsoft.com/en-us/library/4s78d0k1(VS.71).aspx) which reads
```
<asp:CheckBox id="CheckBox1"
AutoPostBack="True|False"
Text="Label"
TextAlign="Right|Left"
Checked="True|False"
OnCheckedChanged="OnCheckedChangedMethod"
runat="server"/>
```
As you can see, there is no OnClick or OnClientClick attributes defined.
Keeping this in mind, I think this is what is happening.
When you do this,
```
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
```
ASP.NET doesn't modify the OnClick attribute and renders it as is on the browser. It would be rendered as:
```
<input type="checkbox" OnClick="alert(this.checked);" />
```
Obviously, a browser can understand 'OnClick' and puts an alert.
And in this scenario
```
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
```
Again, ASP.NET won't change the OnClientClick attribute and will render it as
```
<input type="checkbox" OnClientClick="alert(this.checked);" />
```
As browser won't understand OnClientClick nothing will happen. It also won't raise any error as it is just another attribute.
You can confirm above by looking at the rendered HTML.
And yes, this is not intuitive at all. | Because they are two different kinds of controls...
You see, your web browser doesn't know about server side programming. it only knows about it's own DOM and the event models that it uses... And for click events of objects rendered to it. You should examine the final markup that is actually sent to the browser from ASP.Net to see the differences your self.
```
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
```
renders to
```
<input type="check" OnClick="alert(this.checked);" />
```
and
```
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
```
renders to
```
<input type="check" OnClientClick="alert(this.checked);" />
```
Now, as near as i can recall, there are no browsers anywhere that support the "OnClientClick" event in their DOM...
When in doubt, always view the source of the output as it is sent to the browser... there's a whole world of debug information that you can see. | OnClick vs OnClientClick for an asp:CheckBox? | [
"",
"asp.net",
"javascript",
"checkbox",
"onclick",
"onclientclick",
""
] |
I have a C# .NET 2.0 WinForms app. My app has a control that is a container for two child controls: a label, and some kind of edit control. You can think of it like this, where the outer box is the parent control:
```
+---------------------------------+
| [Label Control] [Edit Control] |
+---------------------------------+
```
I am trying to do something when the mouse enters or leaves the parent control, but I don't care if the mouse moves into one of its children. I want a single flag to represent "the mouse is somewhere inside the parent or children" and "the mouse has moved outside of the parent control bounds".
I've tried handling MouseEnter and MouseLeave on the parent and both child controls, but this means the action begins and ends multiple times as the mouse moves across the control. In other words, I get this:
```
Parent.OnMouseEnter (start doing something)
Parent.OnMouseLeave (stop)
Child.OnMouseEnter (start doing something)
Child.OnMouseLeave (stop)
Parent.OnMouseEnter (start doing something)
Parent.OnMouseLeave (stop)
```
The intermediate OnMouseLeave events cause some undesired effects as whatever I'm doing gets started and then stopped. I want to avoid that.
I don't want to capture the mouse as the parent gets the mouse over, because the child controls need their mouse events, and I want menu and other shortcut keys to work.
Is there a way to do this inside the .NET framework? Or do I need to use a Windows mouse hook? | After more research, I discovered the [Application.AddMessageFilter method](http://msdn.microsoft.com/en-us/library/system.windows.forms.application.addmessagefilter.aspx). Using this, I created a .NET version of a mouse hook:
```
class MouseMessageFilter : IMessageFilter, IDisposable
{
public MouseMessageFilter()
{
}
public void Dispose()
{
StopFiltering();
}
#region IMessageFilter Members
public bool PreFilterMessage(ref Message m)
{
// Call the appropriate event
return false;
}
#endregion
#region Events
public class CancelMouseEventArgs : MouseEventArgs
{...}
public delegate void CancelMouseEventHandler(object source, CancelMouseEventArgs e);
public event CancelMouseEventHandler MouseMove;
public event CancelMouseEventHandler MouseDown;
public event CancelMouseEventHandler MouseUp;
public void StartFiltering()
{
StopFiltering();
Application.AddMessageFilter(this);
}
public void StopFiltering()
{
Application.RemoveMessageFilter(this);
}
}
```
Then, I can handle the MouseMove event in my container control, check to see if the mouse is inside my parent control, and start the work. (I also had to track the last moused over parent control so I could stop the previously started parent.)
---- Edit ----
In my form class, I create and hookup the filter:
```
public class MyForm : Form
{
MouseMessageFilter msgFilter;
public MyForm()
{...
msgFilter = new MouseMessageFilter();
msgFilter.MouseDown += new MouseMessageFilter.CancelMouseEventHandler(msgFilter_MouseDown);
msgFilter.MouseMove += new MouseMessageFilter.CancelMouseEventHandler(msgFilter_MouseMove);
}
private void msgFilter_MouseMove(object source, MouseMessageFilter.CancelMouseEventArgs e)
{
if (CheckSomething(e.Control)
e.Cancel = true;
}
}
``` | I feel I found a much better solution than the currently top accepted solution.
The problem with other proposed solutions is that they are either fairly complex (directly handling lower level messages).
Or they fail corner cases: relying on the mouse position on MouseLeave can cause you to miss the mouse exiting if the mouse goes straight from inside a child control to outside the container.
While this solution isn't entirely elegant, it is straightforward and works:
Add a transparent control that takes up the entire space of the container that you want to receive MouseEnter and MouseLeave events for.
I found a good transparent control in Amed's answer here: [Making a control transparent](https://stackoverflow.com/questions/9358500/winforms-making-a-control-transparent)
Which I then stripped down to this:
```
public class TranspCtrl : Control
{
public TranspCtrl()
{
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
SetStyle(ControlStyles.Opaque, true);
this.BackColor = Color.Transparent;
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle = cp.ExStyle | 0x20;
return cp;
}
}
}
```
Example usage:
```
public class ChangeBackgroundOnMouseEnterAndLeave
{
public Panel Container;
public Label FirstLabel;
public Label SecondLabel;
public ChangeBackgroundOnMouseEnterAndLeave()
{
Container = new Panel();
Container.Size = new Size(200, 60);
FirstLabel = new Label();
FirstLabel.Text = "First Label";
FirstLabel.Top = 5;
SecondLabel = new Label();
SecondLabel.Text = "Second Lable";
SecondLabel.Top = 30;
FirstLabel.Parent = Container;
SecondLabel.Parent = Container;
Container.BackColor = Color.Teal;
var transparentControl = new TranspCtrl();
transparentControl.Size = Container.Size;
transparentControl.MouseEnter += MouseEntered;
transparentControl.MouseLeave += MouseLeft;
transparentControl.Parent = Container;
transparentControl.BringToFront();
}
void MouseLeft(object sender, EventArgs e)
{
Container.BackColor = Color.Teal;
}
void MouseEntered(object sender, EventArgs e)
{
Container.BackColor = Color.Pink;
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var test = new ChangeBackgroundOnMouseEnterAndLeave();
test.Container.Top = 20;
test.Container.Left = 20;
test.Container.Parent = this;
}
}
```
Enjoy proper MouseLeave and MouseEnter events! | Parent Control Mouse Enter/Leave Events With Child Controls | [
"",
"c#",
".net",
"winforms",
"events",
"mouse",
""
] |
I have a `JFrame` with `BorderLayout` as the layout manager.
In the south border, I have a `JPanel`, I want this `JPanel`'s size to be adjustable by the user, i.e. the user can click on the edge of the border and drag it up to make it larger.
Is there any way you know that I can do this? | In order to make panels in a frame individually resizable you need to add them onto a [`JSplitPane`](http://java.sun.com/javase/6/docs/api/javax/swing/JSplitPane.html).
Instead of putting it in the South portion of the Frame, put the `JSplitPane` in the Center. The split pane will make the bottom panel in the split seem like it is in the South, and the top panel in the split will be in the Center of the frame.
Make sure you set the orientation of the two panels with `setOrientation(JSplitPane.VERTICAL_SPLIT )`.
Then, you can resize the panels that are in the pane. | I think you meant to say JPanel. You can add a custom mouseListener and handle mouse clicks, drags and mouse releases and then resize the panel programmaticaly.
This will demonstrate this. Note that the jframe does NOT resize automatically with the JPanel. To make the effect more visible i painted the panel red and added a beveled border :
```
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;
@SuppressWarnings("serial")
public class ResizablePanel extends JPanel {
private boolean drag = false;
private Point dragLocation = new Point();
public ResizablePanel() {
setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
setPreferredSize(new Dimension(500, 500));
final JFrame f = new JFrame("Test");
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
drag = true;
dragLocation = e.getPoint();
}
@Override
public void mouseReleased(MouseEvent e) {
drag = false;
}
});
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
if (drag) {
if (dragLocation.getX()> getWidth()-10 && dragLocation.getY()>getHeight()-10) {
System.err.println("in");
setSize((int)(getWidth()+(e.getPoint().getX()-dragLocation.getX())),
(int)(getHeight()+(e.getPoint().getY()-dragLocation.getY())));
dragLocation = e.getPoint();
}
}
}
});
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(this,BorderLayout.CENTER);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
new ResizablePanel();
}
public void paintComponent(Graphics g) {
g.setColor(Color.red);
g.fillRect(0, 0, getWidth(), getHeight());
}
}
``` | Making a JPanel manually resizable | [
"",
"java",
"swing",
"jframe",
"jpanel",
"jsplitpane",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.