Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I looking for a way, specifically in PHP that I will be guaranteed to always get a unique key. I have done the following: ``` strtolower(substr(crypt(time()), 0, 7)); ``` But I have found that once in a while I end up with a duplicate key (rarely, but often enough). I have also thought of doing: ``` strtolower(substr(crypt(uniqid(rand(), true)), 0, 7)); ``` But according to the PHP website, uniqid() could, if uniqid() is called twice in the same microsecond, it could generate the same key. I'm thinking that the addition of rand() that it rarely would, but still possible. After the lines mentioned above I am also remove characters such as L and O so it's less confusing for the user. This maybe part of the cause for the duplicates, but still necessary. One option I have a thought of is creating a website that will generate the key, storing it in a database, ensuring it's completely unique. Any other thoughts? Are there any websites out there that already do this that have some kind of API or just return the key. I found <http://userident.com> but I'm not sure if the keys will be completely unique. This needs to run in the background without any user input.
There are only 3 ways to generate unique values, rather they be passwords, user IDs, etc.: 1. Use an effective GUID generator - these are long and cannot be shrunk. If you only use part **you FAIL**. 2. At least part of the number is sequentially generated off of a single sequence. You can add fluff or encoding to make it look less sequential. Advantage is they start short - disadvantage is they require a single source. The work around for the single source limitation is to have numbered sources, so you include the [source #] + [seq #] and then each source can generate its own sequence. 3. Generate them via some other means and then check them against the single history of previously generated values. Any other method is not guaranteed. Keep in mind, fundamentally you are generating a binary number (it is a computer), but then you can encode it in Hexadecimal, Decimal, Base64, or a word list. Pick an encoding that fits your usage. Usually for user entered data you want some variation of Base32 (which you hinted at). **Note about GUIDS**: They gain their strength of uniqueness from their length and the method used to generate them. *Anything less than 128-bits is not secure.* Beyond random number generation there are characteristics that go into a GUID to make it more unique. Keep in mind they are only practically unique, not completely unique. It is possible, although practically impossible to have a duplicate. **Updated Note about GUIDS**: Since writing this I learned that many GUID generators use a cryptographically secure random number generator (difficult or impossible to predict the next number generated, and a not likely to repeat). There are actually 5 different [UUID algorithms](http://en.wikipedia.org/wiki/Universally_Unique_Identifier#Definition). Algorithm 4 is what Microsoft currently uses for the Windows GUID generation API. A [GUID](http://en.wikipedia.org/wiki/Globally_unique_identifier) is Microsoft's implementation of the UUID standard. **Update**: If you want 7 to 16 characters then you need to use either method 2 or 3. **Bottom line**: Frankly there is no such thing as completely unique. Even if you went with a sequential generator you would eventually run out of storage using all the atoms in the universe, thus looping back on yourself and repeating. Your only hope would be the heat death of the universe before reaching that point. Even the best random number generator has a possibility of repeating equal to the total size of the random number you are generating. Take a quarter for example. It is a completely random bit generator, and its odds of repeating are 1 in 2. So it all comes down to your threshold of uniqueness. You can have 100% uniqueness in 8 digits for 1,099,511,627,776 numbers by using a sequence and then base32 encoding it. Any other method that does not involve checking against a list of past numbers only has odds equal to n/1,099,511,627,776 (where n=number of previous numbers generated) of not being unique.
**Any algorithm will result in duplicates**. Therefore, might I suggest that you use your existing algorithm\* and simply check for duplicates? \*Slight addition: If `uniqid()` can be non-unique based on time, also include a global counter that you increment after every invocation. That way something is different even in the same microsecond.
Unique key generation
[ "", "php", "web-services", "security", "passwords", "" ]
Consider these two function definitions: ``` void foo() { } void foo(void) { } ``` Is there any difference between these two? If not, why is the `void` argument there? Aesthetic reasons?
**Historical note:** this answer applies to C17 and older editions. C23 and later editions treat `void foo()` differently. --- In **C**: * `void foo()` means "a function `foo` taking an unspecified number of arguments of unspecified type" * `void foo(void)` means "a function `foo` taking no arguments" In **C++**: * `void foo()` means "a function `foo` taking no arguments" * `void foo(void)` means "a function `foo` taking no arguments" By writing `foo(void)`, therefore, we achieve the same interpretation across both languages and make our headers multilingual (though we usually need to do some more things to the headers to make them truly cross-language; namely, wrap them in an `extern "C"` if we're compiling C++).
I realize your question pertains to C++, but when it comes to C the answer can be found in [K&R](https://en.wikipedia.org/wiki/The_C_Programming_Language), pages 72-73: > Furthermore, if a function declaration does not include arguments, as > in > > ``` > double atof(); > ``` > > that too is taken to mean that nothing is to be assumed about the > arguments of atof; all parameter checking is turned off. This special > meaning of the empty argument list is intended to permit older C > programs to compile with new compilers. But it's a bad idea to use it > with new programs. If the function takes arguments, declare them; if > it takes no arguments, use void.
Is there a difference between foo(void) and foo() in C++ or C?
[ "", "c++", "c", "arguments", "function-declaration", "" ]
When compiling my C++ .Net application I get 104 warnings of the type: ``` Warning C4341 - 'XX': signed value is out of range for enum constant ``` Where XX can be * WCHAR * LONG * BIT * BINARY * GUID * ... I can't seem to remove these warnings whatever I do. When I double click on them it takes me to a part of my code that uses OdbcParameters - any when I try a test project with all the rest of my stuff but no OdbcParameters it doesn't give the warnings. Any idea how I can get rid of these warnings? They're making real warnings from code I've actually written hard to see - and it just gives me a horrible feeling knowing my app has 104 warnings!
This is a [compiler bug](http://forums.msdn.microsoft.com/en-US/vclanguage/thread/7bc77d72-c223-4d5e-b9f7-4c639c68b624/). Here's [another post](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=159519&SiteID=1) confirming it's a known issue. I've got the same issue in one of my projects and there's no way to prevent it from being triggered unless you have some way of avoiding the use of OdbcParameter. The most conservative way to suppress only the buggy warnings is to use ``` #pragma warning( push ) #pragma warning( disable: 4341 ) // code affected by bug #pragma warning( pop ) ```
In Visual Studio you can always disable specific warnings by going to: > Project settings -> C/C++ -> Advanced -> Disable Specific warnings: 4341
Warning C4341 - 'XX': signed value is out of range for enum constant
[ "", ".net", "c++", "visual-c++", "" ]
What is the best way of implementing a cache for a PHP site? Obviously, there are some things that shouldn't be cached (for example search queries), but I want to find a good solution that will make sure that I avoid the 'digg effect'. I know there is WP-Cache for WordPress, but I'm writing a custom solution that isn't built on WP. I'm interested in either writing my own cache (if it's simple enough), or you could point me to a nice, light framework. I don't know much Apache though, so if it was a PHP framework then it would be a better fit. Thanks.
If a proxy cache is out of the question, and you're serving complete HTML files, you'll get the best performance by bypassing PHP altogether. Study how [WP Super Cache](http://ocaoimh.ie/wp-super-cache/) works. Uncached pages are copied to a cache folder with similar URL structure as your site. On later requests, mod\_rewrite notes the existence of the cached file and serves it instead. other RewriteCond directives are used to make sure commenters/logged in users see live PHP requests, but the majority of visitors will be served by Apache directly.
You can use [output buffering](https://www.php.net/manual/en/function.ob-get-contents.php) to selectively save parts of your output (those you want to cache) and display them to the next user if it hasn't been long enough. This way you're still rendering other parts of the page on-the-fly (e.g., customizable boxes, personal information).
How do I implement a HTML cache for a PHP site?
[ "", "php", "html", "caching", "" ]
Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month? If the standard library doesn't support that, does the dateutil package support this?
[`calendar.monthrange`](https://docs.python.org/library/calendar.html#calendar.monthrange) provides this information: > calendar.**monthrange**(year, month) >     Returns weekday of first day of the month and number of days in month, for the specified *year* and *month*. ``` >>> import calendar >>> calendar.monthrange(2002, 1) (1, 31) >>> calendar.monthrange(2008, 2) # leap years are handled correctly (4, 29) >>> calendar.monthrange(2100, 2) # years divisible by 100 but not 400 aren't leap years (0, 28) ``` so: ``` calendar.monthrange(year, month)[1] ``` seems like the simplest way to go.
If you don't want to import the `calendar` module, a simple two-step function can also be: ``` import datetime def last_day_of_month(any_day): # The day 28 exists in every month. 4 days later, it's always next month next_month = any_day.replace(day=28) + datetime.timedelta(days=4) # subtracting the number of the current day brings us back one month return next_month - datetime.timedelta(days=next_month.day) ``` Outputs: ``` >>> for month in range(1, 13): ... print(last_day_of_month(datetime.date(2022, month, 1))) ... 2022-01-31 2022-02-28 2022-03-31 2022-04-30 2022-05-31 2022-06-30 2022-07-31 2022-08-31 2022-09-30 2022-10-31 2022-11-30 2022-12-31 ```
Get the last day of the month
[ "", "python", "date", "" ]
Anyone who writes client-side JavaScript is familiar with the DOM - the tree structure that your browser references in memory, generated from the HTML it got from the server. JavaScript can add, remove and modify nodes on the DOM tree to make changes to the page. I find it very nice to work with (browser bugs aside), and very different from the way my server-side code has to generate the page in the first place. My question is: what server-side frameworks/languages build a page by treating it as a DOM tree from the beginning - inserting nodes instead of echoing strings? I think it would be very helpful if the client-side and server-side code both saw the page the same way. You could certainly hack something like this together in any web server language, but a framework dedicated to creating a page this way could make some very nice optimizations. Open source, being widely deployed and having been around a while would all be pluses.
You're describing [Rhino on Rails](http://www.youtube.com/watch?v=1QD9XQm_Jd4), which is not out but will be soon. Similarly, [Aptana Jaxer](http://www.aptana.com/jaxer/), however RnR will include an actual framework (Rails) whereas Jaxer is just the server technology.
Aptana's Jaxer AJAX server might be something for you to check out, as it uses JS server-side, as well. That being said, I would argue that you're better off not generating your markup with print statements or echos, but rather template and hook in your dynamic content.
Tree-Based (vs. HTML-Based) Web Framework?
[ "", "javascript", "html", "dom", "" ]
I have a bunch of legacy documents that are HTML-like. As in, they look like HTML, but have additional made up tags that aren't a part of HTML ``` <strong>This is an example of a <pseud-template>fake tag</pseud-template></strong> ``` I need to parse these files. PHP is the only only tool available. The documents don't come close to being well formed XML. My original thought was to use the loadHTML methods on PHPs DOMDocument. However, these methods choke on the make up HTML tags, and will refuse to parse the string/file. ``` $oDom = new DomDocument(); $oDom->loadHTML("<strong>This is an example of a <pseud-template>fake tag</pseud-template></strong>"); //gives us DOMDocument::loadHTML() [function.loadHTML]: Tag pseud-template invalid in Entity, line: 1 occured in .... ``` The only solution I've been able to come up with is to pre-process the files with string replacement functions that will remove the invalid tags and replace them with a valid HTML tag (maybe a span with an id of the tag name). Is there a more elegant solution? A way to let DOMDocument know about additional tags to consider as valid? Is there a different, robust HTML parsing class/object out there for PHP? (if it's not obvious, I don't consider regular expressions a valid solution here) **Update**: The information in the fake tags is part of the goal here, so something like Tidy isn't an option. Also, I'm after something that does the some level, if not all, of well-formedness cleanup for me, which is why I was looking the DomDocument's loadHTML method in the first place.
You can suppress warnings with [`libxml_use_internal_errors`](http://www.php.net/manual/en/function.libxml-use-internal-errors.php), while loading the document. Eg.: ``` libxml_use_internal_errors(true); $doc = new DomDocument(); $doc->loadHTML("<strong>This is an example of a <pseud-template>fake tag</pseud-template></strong>"); libxml_use_internal_errors(false); ``` If, for some reason, you need access to the warnings, use [`libxml_get_errors`](http://www.php.net/manual/en/function.libxml-get-errors.php)
I wonder if passing the "bad" HTML through [HTML Tidy](http://www.w3.org/People/Raggett/tidy/) might help as a first pass? Might be worth a look, if you can get the document to be well formed, maybe you could load it as a regular XML file with DomDocument.
Error Tolerant HTML/XML/SGML parsing in PHP
[ "", "php", "html", "xml", "parsing", "" ]
I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.
You can also define signals inside the class definition: ``` class MyGObjectClass(gobject.GObject): __gsignals__ = { "some-signal": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), } ``` The contents of the tuple are the the same as the three last arguments to `gobject.signal_new`.
Here is how: ``` import gobject class MyGObjectClass(gobject.GObject): ... gobject.signal_new("signal-name", MyGObjectClass, gobject.SIGNAL_RUN_FIRST, None, (str, int)) ``` Where the second to last argument is the return type and the last argument is a tuple of argument types.
How do I create a new signal in pygtk
[ "", "python", "gtk", "pygtk", "gobject", "" ]
I'm a pretty new C# and .NET developer. I recently created an MMC snapin using C# and was gratified by how easy it was to do, especially after hearing a lot of horror stories by some other developers in my organisation about how hard it is to do in C++. I pretty much went through the whole project at some point and made every instance of the "public" keyword to "internal", except as required by the runtime in order to run the snapin. What is your feeling on this, should you generally make classes and methods public or internal?
I believe in blackboxes where possible. As a programmer, I want a well defined blackbox which I can easily drop into my systems, and have it work. I give it values, call the appropriate methods, and then get my results back out of it. To that end, give me only the functionality that the class needs to expose to work. Consider an elevator. To get it to go to a floor, I push a button. That's the public interface to the black box which activates all the functions needed to get the elevator to the desired floor.
What you did is exactly what you should do; give your classes the most minimal visibility you can. Heck, if you want to really go whole hog, you can make *everything* `internal` (at most) and use the [`InternalsVisibleTo` attribute](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.internalsvisibletoattribute), so that you can separate your functionality but still not expose it to the unknown outside world. The only reason to make things public is that you're packaging your project in several DLLs and/or EXEs and (for whatever reason) you don't care to use `InternalsVisibleTo`, or you're creating a library for use by third parties. But even in a library for use by third parties, you should try to reduce the "surface area" wherever possible; the more classes you have available, the more confusing your library will be. In C#, one good way to ensure you're using the minimum visibility possible is to leave off the visibility modifiers until you need them. Everything in C# defaults to the least visibility possible: internal for classes, and private for class members and inner classes.
Should I use internal or public visibility by default?
[ "", "c#", ".net", "public", "internals", "" ]
I've been trying to figure out a regex to allow me to search for a particular string while automatically skipping comments. Anyone have an RE like this or know of one? It doesn't even need to be sophisticated enough to skip `#if 0` blocks; I just want it to skip over `//` and `/*` blocks. The converse, that is only search inside comment blocks, would be very useful too. Environment: VS 2003
This is a harder problem than it might at first appear, since you need to consider comment tokens inside strings, comment tokens that are themselves commented out etc. I wrote a string and comment parser for C#, let me see if I can dig out something that will help... I'll update if I find anything. EDIT: ... ok, so I found my old 'codemasker' project. Turns out that I did this in stages, not with a single regex. Basically I inch through a source file looking for start tokens, when I find one I then look for an end-token and mask everything in between. This takes into account the context of the start token... if you find a token for "string start" then you can safely ignore comment tokens until you find the end of the string, and vice versa. Once the code is masked (I used guids as masks, and a hashtable to keep track) then you can safely do your search and replace, then finally restore the masked code. Hope that helps.
Be especially careful with strings. Strings often have escape sequences which you also have to respect while you're finding the end of them. So e.g. `"This is \"a test\""`. You cannot blindly look for a double-quote to terminate. Also beware of ``"This is \"`, which shows that you cannot just say "unless double-quote is preceded by a backslash." In summary, make some brutal unit tests!
Regex's For Developers
[ "", "c++", "regex", "visual-c++", "utilities", "" ]
So I have an object which has some fields, doesn't really matter what. I have a generic list of these objects. ``` List<MyObject> myObjects = new List<MyObject>(); myObjects.Add(myObject1); myObjects.Add(myObject2); myObjects.Add(myObject3); ``` So I want to remove objects from my list based on some criteria. For instance, `myObject.X >= 10.` I would like to use the `RemoveAll(Predicate<T> match)` method for to do this. I know I can define a delegate which can be passed into RemoveAll, but I would like to know how to define this inline with an anonymous delegate, instead of creating a bunch of delegate functions which are only used in once place.
There's two options, an explicit delegate or a delegate disguised as a lamba construct: explicit delegate ``` myObjects.RemoveAll(delegate (MyObject m) { return m.X >= 10; }); ``` lambda ``` myObjects.RemoveAll(m => m.X >= 10); ``` --- Performance wise both are equal. As a matter of fact, both language constructs generate the same IL when compiled. This is because C# 3.0 is basically an extension on C# 2.0, so it compiles to C# 2.0 constructs
The lambda C# 3.0 way: ``` myObjects.RemoveAll(m => m.x >= 10); ``` The anonymous delegate C# 2.0 way: ``` myObjects.RemoveAll(delegate (MyObject m) { return m.x >= 10; }); ``` And, for the VB guys, the VB 9.0 lambda way: ``` myObjects.RemoveAll(Function(m) m.x >= 10) ``` Unfortunately, VB doesn't support an anonymous delegate.
How do you declare a Predicate Delegate inline?
[ "", "c#", "delegates", "" ]
What would be the best way to develop a text box that remembers the last x number of entries that were put into it. This is a standalone app written with C#.
[@Ethan](https://stackoverflow.com/questions/42966/google-suggestish-text-box#45014) I forgot about the fact that you would want to save that so it wasn't a per session only thing :P But yes, you are completely correct. This is easily done, especially since it's just basic strings, just write out the contents of AutoCompleteCustomSource from the TextBox to a text file, on separate lines. I had a few minutes, so I wrote up a complete code example...I would've before as I always try to show code, but didn't have time. Anyway, here's the whole thing (minus the designer code). ``` namespace AutoComplete { public partial class Main : Form { //so you don't have to address "txtMain.AutoCompleteCustomSource" every time AutoCompleteStringCollection acsc; public Main() { InitializeComponent(); //Set to use a Custom source txtMain.AutoCompleteSource = AutoCompleteSource.CustomSource; //Set to show drop down *and* append current suggestion to end txtMain.AutoCompleteMode = AutoCompleteMode.SuggestAppend; //Init string collection. acsc = new AutoCompleteStringCollection(); //Set txtMain's AutoComplete Source to acsc txtMain.AutoCompleteCustomSource = acsc; } private void txtMain_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { //Only keep 10 AutoComplete strings if (acsc.Count < 10) { //Add to collection acsc.Add(txtMain.Text); } else { //remove oldest acsc.RemoveAt(0); //Add to collection acsc.Add(txtMain.Text); } } } private void Main_FormClosed(object sender, FormClosedEventArgs e) { //open stream to AutoComplete save file StreamWriter sw = new StreamWriter("AutoComplete.acs"); //Write AutoCompleteStringCollection to stream foreach (string s in acsc) sw.WriteLine(s); //Flush to file sw.Flush(); //Clean up sw.Close(); sw.Dispose(); } private void Main_Load(object sender, EventArgs e) { //open stream to AutoComplete save file StreamReader sr = new StreamReader("AutoComplete.acs"); //initial read string line = sr.ReadLine(); //loop until end while (line != null) { //add to AutoCompleteStringCollection acsc.Add(line); //read again line = sr.ReadLine(); } //Clean up sr.Close(); sr.Dispose(); } } } ``` This code will work exactly as is, you just need to create the GUI with a TextBox named txtMain and hook up the KeyDown, Closed and Load events to the TextBox and Main form. Also note that, for this example and to make it simple, I just chose to detect the Enter key being pressed as my trigger to save the string to the collection. There is probably more/different events that would be better, depending on your needs. Also, the model used for populating the collection is not very "smart." It simply deletes the oldest string when the collection gets to the limit of 10. This is likely not ideal, but works for the example. You would probably want some sort of rating system (especially if you really want it to be Google-ish) A final note, the suggestions will actually show up in the order they are in the collection. If for some reason you want them to show up differently, just sort the list however you like. Hope that helps!
This is actually fairly easy, especially in terms of showing the "AutoComplete" part of it. In terms of remembering the last x number of entries, you are just going to have to decide on a particular event (or events) that you consider as an entry being completed and write that entry off to a list... an AutoCompleteStringCollection to be precise. The TextBox class has the 3 following properties that you will need: * AutoCompleteCustomSource * AutoCompleteMode * AutoCompleteSource Set AutoCompleteMode to SuggestAppend and AutoCompleteSource to CustomSource. Then at runtime, every time a new entry is made, use the Add() method of AutoCompleteStringCollection to add that entry to the list (and pop off any old ones if you want). You can actually do this operation directly on the AutoCompleteCustomSource property of the TextBox as long as you've already initialized it. Now, every time you type in the TextBox it will suggest previous entries :) See this article for a more complete example: <http://www.c-sharpcorner.com/UploadFile/mahesh/AutoCompletion02012006113508AM/AutoCompletion.aspx> AutoComplete also has some built in features like FileSystem and URLs (though it only does stuff that was typed into IE...)
Google Suggestish text box (autocomplete)
[ "", "c#", "winforms", "autocomplete", "" ]
Can you please tell me how much is `(-2) % 5`? According to my Python interpreter is 3, but do you have a wise explanation for this? I've read that in some languages the result can be machine-dependent, but I'm not sure though.
By the way: most programming languages would disagree with Python and give the result `-2`. Depending on the interpretation of modulus this is correct. However, the most agreed-upon mathematical definition states that the modulus of *a* and *b* is the (strictly positive) rest *r* of the division of *a* / *b*. More precisely, 0 <= *r* < *b* by definition.
Your Python interpreter is correct. One (stupid) way of calculating a modulus is to subtract or add the modulus until the resulting value is between 0 and (modulus − 1). e.g.: 13 mod 5 = (13 − 5) mod 5 = (13 − 10) mod 5 = 3 or in your case: −2 mod 5 = (−2 + 5) mod 5 = 3
Modulus operation with negatives values - weird thing?
[ "", "python", "math", "modulo", "" ]
I have a class: ``` class MyClass: def __init__(self, foo): if foo != 1: raise Error("foo is not equal to 1!") ``` and a unit test that is supposed to make sure the incorrect arg passed to the constructor properly raises an error: ``` def testInsufficientArgs(self): foo = 0 self.assertRaises((Error), myClass = MyClass(Error, foo)) ``` But I get... ``` NameError: global name 'Error' is not defined ``` Why? Where should I be defining this Error object? I thought it was built-in as a default exception type, no?
'Error' in this example could be any exception object. I think perhaps you have read a code example that used it as a metasyntatic placeholder to mean, "The Appropriate Exception Class". The baseclass of all exceptions is called 'Exception', and most of its subclasses are descriptive names of the type of error involved, such as 'OSError', 'ValueError', 'NameError', 'TypeError'. In this case, the appropriate error is 'ValueError' (the value of foo was wrong, therefore a ValueError). I would recommend replacing 'Error' with 'ValueError' in your script. Here is a complete version of the code you are trying to write, I'm duplicating everything because you have a weird keyword argument in your original example that you seem to be conflating with an assignment, and I'm using the 'failUnless' function name because that's the non-aliased name of the function: ``` class MyClass: def __init__(self, foo): if foo != 1: raise ValueError("foo is not equal to 1!") import unittest class TestFoo(unittest.TestCase): def testInsufficientArgs(self): foo = 0 self.failUnlessRaises(ValueError, MyClass, foo) if __name__ == '__main__': unittest.main() ``` The output is: ``` . ---------------------------------------------------------------------- Ran 1 test in 0.007s OK ``` There is a flaw in the unit testing library 'unittest' that other unit testing frameworks fix. You'll note that it is impossible to gain access to the exception object from the calling context. If you want to fix this, you'll have to redefine that method in a subclass of UnitTest: This is an example of it in use: ``` class TestFoo(unittest.TestCase): def failUnlessRaises(self, excClass, callableObj, *args, **kwargs): try: callableObj(*args, **kwargs) except excClass, excObj: return excObj # Actually return the exception object else: if hasattr(excClass,'__name__'): excName = excClass.__name__ else: excName = str(excClass) raise self.failureException, "%s not raised" % excName def testInsufficientArgs(self): foo = 0 excObj = self.failUnlessRaises(ValueError, MyClass, foo) self.failUnlessEqual(excObj[0], 'foo is not equal to 1!') ``` I have copied the failUnlessRaises function from unittest.py from python2.5 and modified it slightly.
How about this: ``` class MyClass: def __init__(self, foo): if foo != 1: raise Exception("foo is not equal to 1!") import unittest class Tests(unittest.TestCase): def testSufficientArgs(self): foo = 1 MyClass(foo) def testInsufficientArgs(self): foo = 2 self.assertRaises(Exception, MyClass, foo) if __name__ == '__main__': unittest.main() ```
How do I unit test an __init__() method of a python class with assertRaises()?
[ "", "python", "unit-testing", "exception", "" ]
Any recommendations for a javascript form validation library. I could try and roll my own (but I'm not very good at javascript). Needs to support checking for required fields, and preferably regexp validation of fields.
I've used [this library](http://tetlaw.id.au/view/javascript/really-easy-field-validation) for a couple of personal projects. It's pretty good, though I have had to make my own modifications to it a couple of times - nothing major, though, and it's easy enough to do so. I'm sure you already do this, but also validate all of your information on the server-side, as well. Client-side-only validation is rarely, if ever, a good idea.
I am about to start implementing javascript validation in my forms using [jQuery Validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/). I think that StackOverflow users this jQuery plugin as well. It seems to be a very mature validation library, however it does build on top of jQuery, so it might not fit for you. Like Tom said, don't forget that server side validation.
Recommendation for javascript form validation library
[ "", "javascript", "forms", "validation", "" ]
I have a web report that uses a Django form (new forms) for fields that control the query used to generate the report (start date, end date, ...). The issue I'm having is that the page should work using the form's initial values (unbound), but I can't access the cleaned\_data field unless I call `is_valid()`. But `is_valid()` always fails on unbound forms. It seems like Django's forms were designed with the use case of editing data such that an unbound form isn't really useful for anything other than displaying HTML. For example, if I have: ``` if request.method == 'GET': form = MyForm() else: form = MyForm(request.method.POST) if form.is_valid(): do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) ``` is\_valid() will fail if this is a GET (since it's unbound), and if I do: ``` if request.method == 'GET': form = MyForm() do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) else: form = MyForm(request.method.POST) if form.is_valid(): do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) ``` the first call to do\_query triggers exceptions on form.cleaned\_data, which is not a valid field because `is_valid()` has not been called. It seems like I have to do something like: ``` if request.method == 'GET': form = MyForm() do_query(form['start_date'].field.initial, form['end_date'].field.initial) else: form = MyForm(request.method.POST) if form.is_valid(): do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) ``` that is, there isn't a common interface for retrieving the form's values between a bound form and an unbound one. Does anyone see a cleaner way to do this?
If you add this method to your form class: ``` def get_cleaned_or_initial(self, fieldname): if hasattr(self, 'cleaned_data'): return self.cleaned_data.get(fieldname) else: return self[fieldname].field.initial ``` you could then re-write your code as: ``` if request.method == 'GET': form = MyForm() else: form = MyForm(request.method.POST) form.is_valid() do_query(form.get_cleaned_or_initial('start_date'), form.get_cleaned_or_initial('end_date')) ```
*Unbound* means there is no data associated with form (either initial or provided later), so the validation may fail. As mentioned in other answers (and in your own conclusion), you have to provide initial values and check for both bound data and initial values. The use case for forms is form processing **and** validation, so you must have some data to validate before you accessing `cleaned_data`.
How to use form values from an unbound form
[ "", "python", "django", "" ]
I have an Java desktop application which connects directly with the DB (an Oracle). The application has multiple user accounts. What is the correct method to send the user's password (not DB password) over the network? I don't want to send it in plain text.
You could connect over a secure socket connection, or hash the password locally before sending it to the database (or better, both) - Ideally, the only time the password should exist in plain text form is prior to hashing. If you can do all of that on the client side, more the better.
You can use SSL connection between Oracle client and Oracle database. To configure SSL between oracle client and server using JDBC: At server side: 1) First of all, the listener must be configured to use the TCPS protocol: ``` LISTENER = (ADDRESS_LIST= (ADDRESS=(PROTOCOL=tcps)(HOST=servername)(PORT=2484))) WALLET_LOCATION=(SOURCE=(METHOD=FILE)(METHOD_DATA=(DIRECTORY=/server/wallet/path/))) ``` At client side: 1) following jars needs to be classpath `ojdb14.jar`, `oraclepki.jar`, `ojpse.jar` 2) URL used for connection should be: ``` jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=servername)(PORT=2484))(CONNECT_DATA=(SERVICE_NAME=servicename))) ``` 3) Following properties needs to be set (either as System property (-D options) or properties to connection) ``` javax.net.ssl.trustStore, javax.net.ssl.trustStoreType, javax.net.ssl.trustStorePassword ``` Reference: <http://www.oracle.com/technology/tech/java/sqlj_jdbc/pdf/wp-oracle-jdbc_thin_ssl_2007.pdf>
In a client-server application: How to send to the DB the user's application password?
[ "", "java", "oracle", "security", "passwords", "" ]
I am writing picture editing windows forms application using vb.net/c#. i have a client requirement to capture the photo from digital still camera attached to computer. how can i capture a photo from USB connected digital still camera device in my windows application ?
If you use the Windows Image Acquisition Library, you'll see events there for capturing camera new picture events. I had a similar requirement and wrote a test rig; we went down to the local camera store and tried every camera they had. The only cameras we could find that supported this functionality were the Nikon D-series cameras. We found that with most cameras, you can't even take a picture when they are plugged in. When you plug them in to the USB port, most cameras will switch into a mode where the only thing they'll do is transfer data. The quick way to find out if a camera will work at all is to plug it into a PC, then try to snap a picture. If it lets you do that you have a chance. It also needs to support PTP.
I assume you want to activate the action of taking a picture from the computer which the camera is attached to. If that is the case then the first thing I would do is search for an API for that particular camera model. I don't believe there is a standard protocol/framework for interacting with digital cameras besides accessing the memory card within the camera.
how do i take picture from a digital camera attached to my computer throught USB cable using vb.net or asp.net or C#?
[ "", "c#", "vb.net", "image-capture", "" ]
Let's say I write a DLL in C++, and declare a global object of a class with a non-trivial destructor. Will the destructor be called when the DLL is unloaded?
In a Windows C++ DLL, all global objects (including static members of classes) will be constructed just before the calling of the DllMain with DLL\_PROCESS\_ATTACH, and they will be destroyed just after the call of the DllMain with DLL\_PROCESS\_DETACH. Now, you must consider three problems: 0 - Of course, global non-const objects are evil (but you already know that, so I'll avoid mentionning multithreading, locks, god-objects, etc.) 1 - The order of construction of objects or different compilation units (i.e. CPP files) is not guaranteed, so you can't hope the object A will be constructed before B if the two objects are instanciated in two different CPPs. This is important if B depends on A. The solution is to move all global objects in the same CPP file, as inside the same compilation unit, the order of instanciation of the objects will be the order of construction (and the inverse of the order of destruction) 2 - There are things that are forbidden to do in the DllMain. Those things are probably forbidden, too, in the constructors. So avoid locking something. See Raymond Chen's excellent blog on the subject: * [Some reasons not to do anything scary in your DllMain](https://devblogs.microsoft.com/oldnewthing/20040127-00/?p=40873) * [Another reason not to do anything scary in your DllMain: Inadvertent deadlock](https://devblogs.microsoft.com/oldnewthing/20040128-00/?p=40853) * [Some reasons not to do anything scary in your DllMain, part 3](https://devblogs.microsoft.com/oldnewthing/20140821-00/?p=183) In this case, lazy initialization could be interesting: The classes remain in an "un-initialized" state (internal pointers are NULL, booleans are false, whatever) until you call one of their methods, at which point they'll initialize themselves. If you use those objects inside the main (or one of the main's descendant functions), you'll be ok because they will be called after execution of DllMain. 3 - Of course, if some global objects in DLL A depend on global objects in DLL B, you should be very very careful about DLL loading order, and thus dependancies. In this case, DLLs with direct or indirect circular dependancies will cause you an insane amount of headaches. The best solution is to break the circular dependancies. P.S.: Note that in C++, constructor can throw, and you don't want an exception in the middle of a DLL loading, so be sure your global objects won't be using exception without a very, very good reason. As correctly written destructors are not authorized to throw, the DLL unloading should be ok in this case.
This page from Microsoft goes into the details of DLL initialization and destruction of globals: <http://msdn.microsoft.com/en-us/library/988ye33t.aspx>
What happens to global variables declared in a DLL?
[ "", "c++", "windows", "dll", "" ]
Here is a quick test program: ``` public static void main( String[] args ) { Date date = Calendar.getInstance().getTime(); System.out.println("Months:"); printDate( "MMMM", "en", date ); printDate( "MMMM", "es", date ); printDate( "MMMM", "fr", date ); printDate( "MMMM", "de", date ); System.out.println("Days:"); printDate( "EEEE", "en", date ); printDate( "EEEE", "es", date ); printDate( "EEEE", "fr", date ); printDate( "EEEE", "de", date ); } public static void printDate( String format, String locale, Date date ) { System.out.println( locale + ": " + (new SimpleDateFormat( format, new Locale( locale ) )).format( date ) ); } ``` The output is: `Months: en: September es: septiembre fr: septembre de: September Days: en: Monday es: lunes fr: lundi de: Montag` How can I control the capitalization of the names. For some reason the Spanish and French always seem to return names that start with a lowercase letter.
Not all languages share english capitalization rules. I guess you'd need to alter the data used by the API, but your non-english clients might not appreciate it... [about.com on french capitalization](http://french.about.com/library/writing/bl-capitalization.htm)
Capitalisation rules are different for different languages. In French, month names [should not be capitalised](http://french.about.com/library/writing/bl-capitalization.htm).
How to control the capitalization of month and day names returned by DateFormat?
[ "", "java", "date", "internationalization", "" ]
I want to point a file dialog at a particular folder in the current user's Local Settings folder on Windows. What is the shortcut to get this path?
How about this, for example: ``` String appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); ``` I don't see an enum for just the Local Settings folder. <http://web.archive.org/web/20080303235606/http://dotnetjunkies.com/WebLog/nenoloje/archive/2007/07/07/259223.aspx> has a list with examples.
``` string localPath = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)).FullName; ``` is the simple answer.
How do I get the current user's Local Settings folder path in C#?
[ "", "c#", ".net", "windows", "" ]
I'm having a little trouble figuring out exactly how const applies in a specific case. Here's the code I have: ``` struct Widget { Widget():x(0), y(0), z(0){} int x, y, z; }; struct WidgetHolder //Just a simple struct to hold four Widgets. { WidgetHolder(Widget a, Widget b, Widget c, Widget d): A(a), B(b), C(c), D(d){} Widget& A; Widget& B; Widget& C; Widget& D; }; class Test //This class uses four widgets internally, and must provide access to them externally. { public: const WidgetHolder AccessWidgets() const { //This should return our four widgets, but I don't want anyone messing with them. return WidgetHolder(A, B, C, D); } WidgetHolder AccessWidgets() { //This should return our four widgets, I don't care if they get changed. return WidgetHolder(A, B, C, D); } private: Widget A, B, C, D; }; int main() { const Test unchangeable; unchangeable.AccessWidgets().A.x = 1; //Why does this compile, shouldn't the Widget& be const? } ``` Basically, I have a class called test. It uses four widgets internally, and I need it to return these, but if test was declared const, I want the widgets returned const also. Can someone explain to me why the code in main() compiles? Thank you very much.
This compiles because although the WidgetHolder is a const object, this const-ness does not automatically apply to objects pointed to (referenced by) the WidgetHolder. Think of it at a machine level - if the WidgetHolder object itself were held in read-only memory, you could still write to things that were pointed to by the WidgetHolder. The problem appears to lie in this line: ``` WidgetHolder(Widget a, Widget b, Widget c, Widget d): A(a), B(b), C(c), D(d){} ``` As Frank mentioned, your references inside the WidgetHolder class are going to hold invalid references after the constructor returns. Therefore, you should change this to: ``` WidgetHolder(Widget &a, Widget &b, Widget &c, Widget &d): A(a), B(b), C(c), D(d){} ``` After you do that, it won't compile, and I leave it as an exercise for the reader to work out the rest of the solution.
You need to create a new type specifically for holding const Widget& objects. Ie: ``` struct ConstWidgetHolder { ConstWidgetHolder(const Widget &a, const Widget &b, const Widget &c, const Widget &d): A(a), B(b), C(c), D(d){} const Widget& A; const Widget& B; const Widget& C; const Widget& D; }; class Test { public: ConstWidgetHolder AccessWidgets() const { return ConstWidgetHolder(A, B, C, D); } ``` You will now get the following error (in gcc 4.3): ``` widget.cc: In function 'int main()': widget.cc:51: error: assignment of data-member 'Widget::x' in read-only structure ``` A similar idiom is used in the standard library with iterators ie: ``` class vector { iterator begin(); const_iterator begin() const; ```
Const Struct&
[ "", "c++", "constants", "" ]
When using the php include function the include is succesfully executed, but it is also outputting a char before the output of the include is outputted, the char is of hex value 3F and I have no idea where it is coming from, although it seems to happen with every include. At first I thbought it was file encoding, but this doesn't seem to be a problem. I have created a test case to demonstrate it: (**link no longer working**) <http://driveefficiently.com/testinclude.php> this file consists of only: ``` <? include("include.inc"); ?> ``` and include.inc consists of only: ``` <? echo ("hello, world"); ?> ``` and yet, the output is: *"?hello, world"* where the ? is a char with a random value. It is this value that I do not know the origins of and it is sometimes screwing up my sites a bit. Any ideas of where this could be coming from? At first I thought it might be something to do with file encoding, but I don't think its a problem.
What you are seeing is a UTF-8 Byte Order Mark: > The UTF-8 representation of the BOM is the byte sequence EF BB BF, which appears as the ISO-8859-1 characters  in most text editors and web browsers not prepared to handle UTF-8. > > [Byte Order Mark on Wikipedia](http://en.wikipedia.org/wiki/Byte_Order_Mark) PHP does not understand that these characters should be "hidden" and sends these to the browser as if they were normal characters. To get rid of them you will need to open the file using a "proper" text editor that will allow you to save the file as UTF-8 without the leading BOM. [You can read more about this problem here](http://juicystudio.com/article/utf-byte-order-mark.php)
Your web server (or your text editor) apparently includes a [BOM](http://en.wikipedia.org/wiki/Byte_order_mark) into the document. I don't see the rogue character in my browser except when I set the site's encoding explicitly to Latin-1. Then, I see two (!) UTF-8 BOMs. /EDIT: From the fact that there are *two* BOMs I conclude that the BOM is actually included by your editor at the beginning of the file. What editor do you use? If you use Visual Studio, you've got to say “Save As …” in the File menu and then choose the button “Save with encoding …”. There, choose “UTF-8 without BOM” or something similar.
PHP Include function outputting unknown char
[ "", "php", "encoding", "byte-order-mark", "" ]
I have a members table in MySQL ``` CREATE TABLE `members` ( `id` int(10) unsigned NOT NULL auto_increment, `name` varchar(65) collate utf8_unicode_ci NOT NULL, `order` tinyint(3) unsigned NOT NULL default '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB; ``` And I would like to let users order the members how they like. I'm storing the order in `order` column. I'm wondering how to insert new user to be added to the bottom of the list. This is what I have today: ``` $db->query('insert into members VALUES (0, "new member", 0)'); $lastId = $db->lastInsertId(); $maxOrder = $db->fetchAll('select MAX(`order`) max_order FROM members'); $db->query('update members SET `order` = ? WHERE id = ?', array( $maxOrder[0]['max_order'] + 1, $lastId )); ``` But that's not really precise while when there are several users adding new members at the same time, it might happen the `MAX(order)` will return the same values. How do you handle such cases?
You can do the SELECT as part of the INSERT, such as: ``` INSERT INTO members SELECT 0, "new member", max(`order`)+1 FROM members; ``` Keep in mind that you are going to want to have an index on the `order` column to make the SELECT part optimized. In addition, you might want to reconsider the tinyint for order, unless you only expect to only have 255 orders ever. Also order is a reserved word and you will always need to write it as `order`, so you might consider renaming that column as well.
Since you already automatically increment the id for each new member, you can order by id.
How to determine order for new item?
[ "", "php", "mysql", "" ]
For example which is better: ``` select * from t1, t2 where t1.country='US' and t2.country=t1.country and t1.id=t2.id ``` or ``` select * from t1, t2 where t1.country'US' and t2.country='US' and t1.id=t2.id ``` better as in less work for the database, faster results. **Note:** Sybase, and there's an index on both tables of `country+id`.
I had a situation similar to this and this was the solution I resorted to: Select \* FROM t1 INNER JOIN t2 ON t1.id = t2.id AND t1.country = t2.country AND t1.country = 'US' I noticed that my query ran faster in this scenario. I made the assumption that joining on the constant saved the engine time because the WHERE clause will execute at the end. Joining and then filtering by 'US' means you still pulled all the other countries from your table and then had to filter out the ones you wanted. This method pulls less records in the end, because it will only find US records.
I don't think there is a global answer to your question. It depends on the specific query. You would have to compare the execution plans for the two queries to see if there are significant differences. I personally prefer the first form: select \* from t1, t2 where t1.country='US' and t2.country=t1.country and t1.id=t2.id because if I want to change the literal there is only one change needed.
Is it better to join two fields together, or to compare them each to the same constant?
[ "", "sql", "join", "" ]
Is anyone using the Obout controls in C# .Net? How would you rate these controls, especially the Grid Control?
I was thoroughly impressed with them. Of all the other control sets out there (infragistics, telerik) this is the only (more than) respectable one I've worked with that was 1) free! and 2) lightweight!. The only caveat to Obout is I had trouble with merging some of these controls and some of the stock AJAX components. Infragistics is by far my favorite (my comment about Obout being "lightweight" is in comparison with the heavy use of viewstate in some of the Infragistics controls) but it's around 1000-1500 a seat, so it can get expensive if you have a larger team.
I like obout for their lightweight'ness. Their licensing policy is very fair (pay once free updates for life) and they also give (free) educational licenses. However, I had to use Developer Express on one of my projects and never looked back since. Very powerful and not as bloated as Infragistics. Basically, if you decide to go obout way, you probably will not regret it.
Obout controls in C# .Net
[ "", "c#", ".net", "obout", "" ]
I am calling, through reflection, a method which may cause an exception. How can I pass the exception to my caller without the wrapper reflection puts around it? I am rethrowing the InnerException, but this destroys the stack trace. Example code: ``` public void test1() { // Throw an exception for testing purposes throw new ArgumentException("test1"); } void test2() { try { MethodInfo mi = typeof(Program).GetMethod("test1"); mi.Invoke(this, null); } catch (TargetInvocationException tiex) { // Throw the new exception throw tiex.InnerException; } } ```
In **.NET 4.5** there is now the [`ExceptionDispatchInfo`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.exceptionservices.exceptiondispatchinfo) class. This lets you capture an exception and re-throw it without changing the stack-trace: ``` using ExceptionDispatchInfo = System.Runtime.ExceptionServices.ExceptionDispatchInfo; try { task.Wait(); } catch(AggregateException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); } ``` This works on any exception, not just `AggregateException`. It was introduced due to the `await` C# language feature, which unwraps the inner exceptions from `AggregateException` instances in order to make the asynchronous language features more like the synchronous language features.
It **is** possible to preserve the stack trace before rethrowing without reflection: ``` static void PreserveStackTrace (Exception e) { var ctx = new StreamingContext (StreamingContextStates.CrossAppDomain) ; var mgr = new ObjectManager (null, ctx) ; var si = new SerializationInfo (e.GetType (), new FormatterConverter ()) ; e.GetObjectData (si, ctx) ; mgr.RegisterObject (e, 1, si) ; // prepare for SetObjectData mgr.DoFixups () ; // ObjectManager calls SetObjectData // voila, e is unmodified save for _remoteStackTraceString } ``` This wastes a lot of cycles compared to calling `InternalPreserveStackTrace` via cached delegate, but has the advantage of relying only on public functionality. Here are a couple of common usage patterns for stack-trace preserving functions: ``` // usage (A): cross-thread invoke, messaging, custom task schedulers etc. catch (Exception e) { PreserveStackTrace (e) ; // store exception to be re-thrown later, // possibly in a different thread operationResult.Exception = e ; } // usage (B): after calling MethodInfo.Invoke() and the like catch (TargetInvocationException tiex) { PreserveStackTrace (tiex.InnerException) ; // unwrap TargetInvocationException, so that typed catch clauses // in library/3rd-party code can work correctly; // new stack trace is appended to existing one throw tiex.InnerException ; } ```
How to rethrow InnerException without losing stack trace in C#?
[ "", "c#", ".net", "exception", "" ]
I have never "hand-coded" object creation code for SQL Server and foreign key decleration is seemingly different between SQL Server and Postgres. Here is my sql so far: ``` drop table exams; drop table question_bank; drop table anwser_bank; create table exams ( exam_id uniqueidentifier primary key, exam_name varchar(50), ); create table question_bank ( question_id uniqueidentifier primary key, question_exam_id uniqueidentifier not null, question_text varchar(1024) not null, question_point_value decimal, constraint question_exam_id foreign key references exams(exam_id) ); create table anwser_bank ( anwser_id uniqueidentifier primary key, anwser_question_id uniqueidentifier, anwser_text varchar(1024), anwser_is_correct bit ); ``` When I run the query I get this error: > Msg 8139, Level 16, State 0, Line 9 > Number of referencing columns in > foreign key differs from number of > referenced columns, table > 'question\_bank'. Can you spot the error?
``` create table question_bank ( question_id uniqueidentifier primary key, question_exam_id uniqueidentifier not null, question_text varchar(1024) not null, question_point_value decimal, constraint fk_questionbank_exams foreign key (question_exam_id) references exams (exam_id) ); ```
And if you just want to create the constraint on its own, you can use ALTER TABLE ``` alter table MyTable add constraint MyTable_MyColumn_FK FOREIGN KEY ( MyColumn ) references MyOtherTable(PKColumn) ``` I wouldn't recommend the syntax mentioned by Sara Chipps for inline creation, just because I would rather name my own constraints.
How do I create a foreign key in SQL Server?
[ "", "sql", "sql-server", "t-sql", "" ]
I've created a custom exception for a very specific problem that can go wrong. I receive data from another system, and I raise the exception if it bombs while trying to parse that data. In my custom exception, I added a field called "ResponseData", so I can track exactly what my code couldn't handle. In custom exceptions such as this one, should that extra response data go into the exception "message"? If it goes there, the message could be huge. I kind of want it there because I'm using Elmah, and that's how I can get at that data. So the question is either: - How can I get Elmah to record extra information from a field in a custom exception OR - Should extra exception details go into the "message" property?
You shouldn't fill `.Message` with debug information, but rather with a concise, helpful piece of text. <http://msdn.microsoft.com/en-us/library/system.exception.message.aspx> > **The text of Message should completely describe the error and should, when possible, explain how to correct it.** The value of the Message property is included in the information returned by ToString. > > The Message property is set only when creating an Exception. If no message was supplied to the constructor for the current instance, the system supplies a default message that is formatted using the current system culture. > > [..] > > Notes to Inheritors: > > The Message property is overridden in classes that require control over message content or format. Application code typically accesses this property when it needs to display information about an exception that has been caught. > > The error message should be localized. Response data does not qualify as a description. Not being familiar with elmah, I can't tell you how to extend the `Exception` class while using it. Does elmah implement its own subclass to `Exception`? Or an interface? Can you subclass it yourself?
> In custom exceptions such as this one, > should that extra response data go > into the exception "message"? No, as [Sören already pointed out](https://stackoverflow.com/questions/48773/adding-extra-information-to-a-custom-exception#48792). However, your exception type could override `ToString` and sensibly add the response data information there. This is a perfectly normal practice followed by many of the exception types in the BCL (Base Class Library) so you will not find yourself swimming against the tide. For example, have a look at the [System.IO.FileNotFoundException.ToString](http://www.google.com/codesearch?hl=en&q=show:T8QZEzhIHj0:bi5mSZyUmjY:tTHW9DnNeHw&sa=N&ct=rd&cs_p=http://download.microsoft.com/download/.netframesdk/cli3/1.0/wxp/en-us/sscli_20021101.tgz&cs_f=sscli/clr/src/bcl/system/io/filenotfoundexception.cs#l100) implementation in [SSCLI (Rotor)](http://research.microsoft.com/sscli/): ``` public override String ToString() { String s = GetType().FullName + ": " + Message; if (_fileName != null && _fileName.Length != 0) s += Environment.NewLine + String.Format(Environment.GetResourceString("IO.FileName_Name"), _fileName); if (InnerException != null) s = s + " ---> " + InnerException.ToString(); if (StackTrace != null) s += Environment.NewLine + StackTrace; try { if(FusionLog!=null) { if (s==null) s=" "; s+=Environment.NewLine; s+=Environment.NewLine; s+="Fusion log follows: "; s+=Environment.NewLine; s+=FusionLog; } } catch(SecurityException) { } return s; } ``` As you can see, it appends the content of [FusionLog](http://msdn.microsoft.com/en-us/library/system.io.filenotfoundexception.fusionlog.aspx) property, which represent *extra* information in case of assembly load failures. > How can I get Elmah to record extra > information from a field in a custom > exception [ELMAH](http://code.google.com/p/elmah/) stores the result of calling `ToString` on an exception as the details of the error so if you have `ToString` implemented as prescribed, the information would get logged without further work. The only issue is that the logged detail will be *unstructured* text.
Adding extra information to a custom exception
[ "", "c#", ".net", "exception", "elmah", "" ]
Are there any prebuilt modules for this? Is there an event thats called everytime a page is loaded? I'm just trying to secure one of my more important admin sections.
As blowdart said, simple IP Address logging is handled by IIS already. Simply right-click on the Website in Internet Information Services (IIS) Manager tool, go to the Web Site tab, and check the Enable Logging box. You can customize what information is logged also. If you want to restrict the site or even a folder of the site to specific IP's, just go to the IIS Site or Folder properties that you want to protect in the IIS Manager, right click and select Properties. Choose the Directory Security tab. In the middle you should see the "IP Addresses and domain name restrictions. This will be where you can setup which IP's to block or allow. If you want to do this programatically in the code-behind of ASP.Net, you could use the page preinit event.
A little more information please; do you want to log IPs or lock access via IP? Both those functions are built into IIS rather than ASP.NET; so are you looking for how to limit access via IP programatically?
Asp.net c# and logging ip access on every page and frequency
[ "", "c#", "logging", "ip-address", "" ]
Do you know any open source/free software C++ libraries to manipulate images in these formats: .jpg .gif .png .bmp ? The more formats it supports, the better. I am implementing a free program in C++ which hides a text file into one or more images, using [steganography](http://en.wikipedia.org/wiki/Steganography). I am working under Unix.
[ImageMagick](http://www.imagemagick.org/) can manipulate about anything and has interfaces for a [dozen of languages](https://imagemagick.org/script/develop.php), including the [Magick++](http://www.imagemagick.org/Magick++/) API for C++.
@lurks: I assume that you are looking for LSB shifting? I did some stego work a couple of years ago, and that's how it appeared most apps worked. It appears that ImageMagick (suggested by others) allows you to identify and manipulate the LSBs.
C++ libraries to manipulate images
[ "", "c++", "image", "steganography", "" ]
Is there any way in the Servlet API to access properties specified in web.xml (such as initialization parameters) from within a Bean or Factory class that is not associated at all with the web container? For example, I'm writing a Factory class, and I'd like to include some logic within the Factory to check a hierarchy of files and configuration locations to see which if any are available to determine which implementation class to instantiate - for example, 1. a properties file in the classpath, 2. a web.xml parameter, 3. a system property, or 4. some default logic if nothing else is available. I'd like to be able to do this without injecting any reference to `ServletConfig` or anything similiar to my Factory - the code should be able to run ok outside of a Servlet Container. This might sound a little bit uncommon, but I'd like for this component I'm working on to be able to be packaged with one of our webapps, and also be versatile enough to be packaged with some of our command-line tools without requiring a new properties file just for my component - so I was hoping to piggyback on top of other configuration files such as web.xml. If I recall correctly, .NET has something like `Request.GetCurrentRequest()` to get a reference to the currently executing `Request` - but since this is a Java app I'm looking for something simliar that could be used to gain access to `ServletConfig`.
One way you could do this is: ``` public class FactoryInitialisingServletContextListener implements ServletContextListener { public void contextDestroyed(ServletContextEvent event) { } public void contextInitialized(ServletContextEvent event) { Properties properties = new Properties(); ServletContext servletContext = event.getServletContext(); Enumeration<?> keys = servletContext.getInitParameterNames(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); String value = servletContext.getInitParameter(key); properties.setProperty(key, value); } Factory.setServletContextProperties(properties); } } public class Factory { static Properties _servletContextProperties = new Properties(); public static void setServletContextProperties(Properties servletContextProperties) { _servletContextProperties = servletContextProperties; } } ``` And then have the following in your web.xml ``` <listener> <listener-class>com.acme.FactoryInitialisingServletContextListener<listener-class> </listener> ``` If your application is running in a web container, then the listener will be invoked by the container once the context has been created. In which case, the \_servletContextProperties will be replaced with any context-params specified in the web.xml. If your application is running outside a web container, then \_servletContextProperties will be empty.
Have you considered using the Spring framework for this? That way, your beans don't get any extra cruft, and spring handles the configuration setup for you.
Is there a way to access web.xml properties from a Java Bean?
[ "", "java", "servlets", "" ]
Using reflection, I need to investigate a user DLL and create an object of a class in it. What is the simple way of doing it?
Try [Activator.CreateInstance](http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx).
`System.Reflection.Assembly` is the class you will want to use. It contains many method for iterating over the types contained with a user DLL. You can iterate through each class, perhaps see if it inherits from a particular interface etc. <http://msdn.microsoft.com/en-us/library/system.reflection.assembly_members.aspx> Investigate `Assembly.GetTypes()` method for getting the list of types, or `Assembly.GetExportedTypes()` for the public ones only.
Creating an object without knowing the class name at design time
[ "", "c#", "reflection", "" ]
This might be a bit on the silly side of things but I need to send the contents of a DataTable (unknown columns, unknown contents) via a text e-mail. Basic idea is to loop over rows and columns and output all cell contents into a StringBuilder using .ToString(). Formatting is a big issue though. Any tips/ideas on how to make this look "readable" in a text format ? I'm thinking on "padding" each cell with empty spaces, but I also need to split some cells into multiple lines, and this makes the StringBuilder approach a bit messy ( because the second line of text from the first column comes after the first line of text in the last column,etc.)
Would converting the datatable to a HTML-table and sending HTML-mail be an alternative? That would make it much nicer on the receiving end if their client supports it.
This will sound like a really horrible solution, but it just might work: Render the DataTable contents into a DataGrid/GridView (assuming ASP.NET) and then screen scrape that. I told you it would be messy.
DataTable to readable text string
[ "", "c#", "formatting", "datatable", "" ]
``` EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text) ? null : Convert.ToInt32(employeeNumberTextBox.Text), ``` I often find myself wanting to do things like this (`EmployeeNumber` is a `Nullable<int>` as it's a property on a LINQ-to-SQL dbml object where the column allows NULL values). Unfortunately, the compiler feels that > There is no implicit conversion between 'null' and 'int' even though both types would be valid in an assignment operation to a nullable int on their own. Using the null coalescing operator is not an option as far as I can see because of the inline conversion that needs to happen on the `.Text` string if it's not null. As far as I know the only way to do this is to use an if statement and/or assign it in two steps. In this particular case I find that very frustrating because I wanted to use the object initializer syntax and this assignment would be in the initialization block... Does anyone know a more elegant solution?
The problem occurs because the conditional operator doesn't look at how the value is used (assigned in this case) to determine the type of the expression -- just the true/false values. In this case, you have a `null` and an `Int32`, and the type can not be determined (there are real reasons it can't just assume `Nullable<Int32>`). If you really want to use it in this way, you must cast one of the values to `Nullable<Int32>` yourself, so C# can resolve the type: ``` EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text) ? (int?)null : Convert.ToInt32(employeeNumberTextBox.Text), ``` or ``` EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text) ? null : (int?)Convert.ToInt32(employeeNumberTextBox.Text), ```
I think a utility method could help make this cleaner. ``` public static class Convert { public static T? To<T>(string value, Converter<string, T> converter) where T: struct { return string.IsNullOrEmpty(value) ? null : (T?)converter(value); } } ``` then ``` EmployeeNumber = Convert.To<int>(employeeNumberTextBox.Text, Int32.Parse); ```
Conditional operator assignment with Nullable<value> types?
[ "", "c#", "conditional-operator", "nullable", "" ]
Is there any way to convert a bmp image to jpg/png without losing the quality in C#? Using Image class we can convert bmp to jpg but the quality of output image is very poor. Can we gain the quality level as good as an image converted to jpg using photoshop with highest quality?
``` var qualityEncoder = Encoder.Quality; var quality = (long)<desired quality>; var ratio = new EncoderParameter(qualityEncoder, quality ); var codecParams = new EncoderParameters(1); codecParams.Param[0] = ratio; var jpegCodecInfo = <one of the codec infos from ImageCodecInfo.GetImageEncoders() with mime type = "image/jpeg">; bmp.Save(fileName, jpegCodecInfo, codecParams); // Save to JPG ```
``` public static class BitmapExtensions { public static void SaveJPG100(this Bitmap bmp, string filename) { EncoderParameters encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); bmp.Save(filename, GetEncoder(ImageFormat.Jpeg), encoderParameters); } public static void SaveJPG100(this Bitmap bmp, Stream stream) { EncoderParameters encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); bmp.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters); } public static ImageCodecInfo GetEncoder(ImageFormat format) { ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders(); foreach (ImageCodecInfo codec in codecs) { if (codec.FormatID == format.Guid) { return codec; } } return null; } } ```
Bmp to jpg/png in C#
[ "", "c#", "image-manipulation", "" ]
For many questions the answer seems to be found in "the standard". However, where do we find that? Preferably online. Googling can sometimes feel futile, again especially for the C standards, since they are drowned in the flood of discussions on programming forums. To get this started, since these are the ones I am searching for right now, where are there good online resources for: * C89 * C99 * C11 * C++98 * C++03 * C++11 * C++14 * C++17
## PDF versions of the standard As of 1st September 2014 March 2022, the best locations by price for the official C and C++ standards documents in PDF seem to be: * C++20 – ISO/IEC 14882:2020: [212 CAD (about $165 US) from csagroup.org](https://www.csagroup.org/store/product/CSA%20ISO%25100IEC%2014882%3A21/?format=PDF) * C++17 – ISO/IEC 14882:2017: [$90 NZD (about $65 US) from Standards New Zealand](https://www.standards.govt.nz/shop/isoiec-148822017/) * C++14 – ISO/IEC 14882:2014: [$90 NZD (about $65 US) from Standards New Zealand](https://www.standards.govt.nz/shop/isoiec-148822014/) * C++11 – ISO/IEC 14882-2011: [$60 from ansi.org](https://webstore.ansi.org/Standards/INCITS/INCITSISOIEC148822012) or [$60 from Techstreet](https://www.techstreet.com/standards/incits-iso-iec-14882-2011-2012?product_id=1852925) * C++03 – INCITS/ISO/IEC 14882:2003: [$30 from ansi.org](https://webstore.ansi.org/standards/incits/incitsisoiec148822003) * C++98 – ISO/IEC 14882:1998: [$95 NZD (about $65 US) from Standards New Zealand](https://www.standards.govt.nz/shop/asnzs-148821999/) * C17/C18 – INCITS/ISO/IEC 9899:2018: [$116 from INCITS/ANSI](https://webstore.ansi.org/Standards/INCITS/INCITSISOIEC989920182019) / [N2176 / c17\_updated\_proposed\_fdis.pdf draft from November 2017](http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf) (Link broken, see [Wayback Machine N2176](https://web.archive.org/web/20181230041359if_/http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf)) * C11 – ISO/IEC 9899:2011: [$60 from ansi.org](https://webstore.ansi.org/Standards/INCITS/INCITSISOIEC989920112012) / [WG14 draft version N1570](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) * C99 – INCITS/ISO/IEC 9899-1999(R2005): [$60 from ansi.org](https://webstore.ansi.org/Standards/INCITS/INCITSISOIEC98991999R2005) / [WG14 draft version N1256](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf) * C90 – ISO/IEC 9899:1990: [$90 NZD (about $65 USD) from Standards New Zealand](https://www.standards.govt.nz/shop/isoiec-98991990/) ## Non-PDF electronic versions of the standard ***Warning: most copies of standard drafts are published in PDF format, and errors may have been introduced if the text/HTML was transcribed or automatically generated from the PDF.*** * latest C standard – ISO Online Browsing Platform, viewable but not downloadable: (<https://www.iso.org/obp/ui/#iso:std:iso-iec:9899>) * C89 – Draft version in ANSI text format: (<https://web.archive.org/web/20161223125339/http://flash-gordon.me.uk/ansi.c.txt>) * C89 – Draft version as HTML document: ([http://port70.net/~nsz/c/c89/c89-draft.html](http://port70.net/%7Ensz/c/c89/c89-draft.html)) * C90 TC1; ISO/IEC 9899 TCOR1, single-page HTML document: (<http://www.open-std.org/jtc1/sc22/wg14/www/docs/tc1.htm>) * C90 TC2; ISO/IEC 9899 TCOR2, single-page HTML document: (<http://www.open-std.org/jtc1/sc22/wg14/www/docs/tc2.htm>) * C99 – Draft version (N1256) as HTML document: ([http://port70.net/~nsz/c/c99/n1256.html](http://port70.net/%7Ensz/c/c99/n1256.html)) * C11 – Draft version (N1570) as HTML document: ([http://port70.net/~nsz/c/c11/n1570.html](http://port70.net/%7Ensz/c/c11/n1570.html)) * C++11 – Working draft (N3337) as plain text document: ([http://port70.net/~nsz/c/c%2B%2B/c%2B%2B11\_n3337.txt](http://port70.net/%7Ensz/c/c%2B%2B/c%2B%2B11_n3337.txt)) *(The site hosting the plain text version of the C++11 working draft also has some C++14 drafts in this format. But none of them are copies of the final working draft, N4140.)* ## Print versions of the standard Print copies of the standards are available from national standards bodies and [ISO](https://www.iso.org/home.html) but are very expensive. If you want a hardcopy of the C90 standard for much less money than above, you may be able to find a cheap used copy of [Herb Schildt](http://www.catb.org/jargon/html/B/bullschildt.html)'s book [*The Annotated ANSI Standard*](http://www.davros.org/c/schildt.html) at [Amazon](https://rads.stackoverflow.com/amzn/click/com/0078819520), which contains the actual text of the standard (useful) and commentary on the standard (less useful - it contains several dangerous and misleading errors). The C99 and C++03 standards are available in book form from Wiley and the BSI (British Standards Institute): * [C++03 Standard](https://rads.stackoverflow.com/amzn/click/com/0470846747) on Amazon * [C99 Standard](https://rads.stackoverflow.com/amzn/click/com/0470845732) on Amazon ## Standards committee draft versions (free) The working drafts for future standards are often available from the committee websites: * [C++ committee website](http://www.open-std.org/jtc1/sc22/wg21/) * [C committee website](http://www.open-std.org/jtc1/sc22/wg14/) If you want to get drafts from the current or earlier C/C++ standards, there are some available for free on the internet: ### For C: * ANSI X3.159-198 (C89): I cannot find a PDF of C89, but it is almost the same as C90. The only major differences are in the boilerplate and section numbering, although there are some slight textual differences * ISO/IEC 9899:1990 (C90): (Almost the same as ANSI X3.159-198 (C89) except for the frontmatter and section numbering. There is at least one textual difference in section 6.5.7 (previously 3.5.7), where *"a list"* became *"a brace-enclosed list"*. Note that the conversion between ANSI and ISO/IEC Standard is seen inside this document, the document refers to its name as "ANSI/ISO: 9899/99" although this isn't the right name of the later made standard of it, the right name is "ISO/IEC 9899:1990") * TC1 for C90: <http://www.open-std.org/jtc1/sc22/wg14/www/docs/n423.pdf> * There isn't a PDF link for TC2 on the [WG14 website](http://www.open-std.org/jtc1/sc22/wg14/www/wg14_document_log.htm), sadly. * ISO/IEC 9899:1999 (C99 incorporating all three Technical Corrigenda): <http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf> * An earlier version of C99 incorporating only TC1 and TC2: <http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf> * Working draft for the original (i.e. pre-corrigenda) C99: <http://www.open-std.org/jtc1/sc22/wg14/www/docs/n843.htm> (HTML) and <http://www.dkuug.dk/JTC1/SC22/WG14/www/docs/n843.pdf> (PDF). Note that there were two later working drafts: N869 and N878, but they seem to have been removed from the WG14 website, so this is the latest one available. * List of changes between C89/C90 and C99: [http://port70.net/~nsz/c/c89/c9x\_changes.html](http://port70.net/%7Ensz/c/c89/c9x_changes.html) * TC1 for C99 (only the TC, not the standard incorporating it): <http://www.open-std.org/jtc1/sc22/wg14/www/docs/9899tc1/n32071.PDF> * TC2 for C99 (only the TC, not the standard incorporating it): <http://www.open-std.org/jtc1/sc22/wg14/www/docs/9899-1999_cor_2-2004.pdf> * ISO/IEC 9899:2011 (C11): <http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf> For information on the differences between N1570 and the final, published version of C11, see [Latest changes in C11](https://stackoverflow.com/questions/8631228/latest-changes-in-c11/15737472#15737472) and <https://groups.google.com/g/comp.std.c/c/v5hsWOu5vSw> * ISO/IEC 9899:2011/Cor 1:2012 (C11's only technical corrigendum): This can be viewed at <https://www.iso.org/obp/ui/#iso:std:iso-iec:9899:ed-3:v1:cor:1:v1:en> but cannot be downloaded. It is the actual corrigendum, not a draft. * ISO/IEC 9899:2018 (C17/C18): <https://web.archive.org/web/20181230041359if_/http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf> (N2176) * C23 work-in-progress - latest working draft as of 1st April 2023 (N3096): <https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3096.pdf> ### For C++: * ISO/IEC 14882:1998 (C++98): [http://www.lirmm.fr/~ducour/Doc-objets/ISO+IEC+14882-1998.pdf](http://www.lirmm.fr/%7Educour/Doc-objets/ISO+IEC+14882-1998.pdf) * ISO/IEC 14882:2003 (C++03): <https://web.archive.org/web/20180922024431/https://cs.nyu.edu/courses/fall11/CSCI-GA.2110-003/documents/c++2003std.pdf> * ISO/IEC 14882:2011 (C++11): <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf> * ISO/IEC 14882:2014 (C++14): <https://github.com/cplusplus/draft/blob/master/papers/n4140.pdf?raw=true> * ISO/IEC 14882:2017 (C++17): <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4659.pdf> * ISO/IEC 14882:2020 (C++20): <https://isocpp.org/files/papers/N4860.pdf> * ISO/IEC 14882:2023 (C++23): <https://open-std.org/jtc1/sc22/wg21/docs/papers/2023/n4950.pdf> Note that these documents are not the same as the standard, though the versions just prior to the meetings that decide on a standard are usually very close to what is in the final standard. The FCD (Final Committee Draft) versions are password protected; you need to be on the standards committee to get them. Even though the draft versions might be very close to the final ratified versions of the standards, some of this post's editors would strongly advise you to get a copy of the actual documents — especially if you're planning on quoting them as references. Of course, starving students should go ahead and use the drafts if strapped for cash. --- It appears that, if you are willing and able to wait a few months after ratification of a standard, to search for "INCITS/ISO/IEC" instead of "ISO/IEC" when looking for a standard is the key. By doing so, one of this post's editors was able to find the C11 and C++11 standards at reasonable prices. For example, if you search for "INCITS/ISO/IEC 9899:2011" instead of "ISO/IEC 9899:2011" on [webstore.ansi.org](https://webstore.ansi.org) you will find the reasonably priced PDF version. --- The site <https://wg21.link/> provides short-URL links to the C++ current working draft and draft standards, and committee papers: * <https://wg21.link/std11> - C++11 * <https://wg21.link/std14> - C++14 * <https://wg21.link/std17> - C++17 * <https://wg21.link/std20> - C++20 * <https://wg21.link/std> - current working draft (as of May 2022 still points to the 2021 version) --- The current draft of the standard is maintained as LaTeX sources on [Github](https://github.com/cplusplus/draft). These sources can be converted to HTML using [cxxdraft-htmlgen](https://github.com/Eelis/cxxdraft-htmlgen). The following sites maintain HTML pages so generated: * Tim Song - [Current working draft](https://timsong-cpp.github.io/cppwp/) - [C++11](https://timsong-cpp.github.io/cppwp/n3337/) - [C++14](https://timsong-cpp.github.io/cppwp/n4140/) - [C++17](https://timsong-cpp.github.io/cppwp/n4659/) - [C++20](https://timsong-cpp.github.io/cppwp/n4861/) * Eelis - [Current working draft](http://eel.is/c++draft/) [Tim Song](https://github.com/timsong-cpp/cppwp) also maintains generated HTML and PDF versions of the Networking TS and Ranges TS. ## POSIX extensions to the C standard The [POSIX](https://en.wikipedia.org/wiki/POSIX) standard (IEEE 1003.1) requires a compliant operating system to include a C compiler. This compiler must in turn be compliant with the C standard, and must also support various extensions defined in the "System Interfaces" section of POSIX (such as the `off_t` data type, the `<aio.h>` header, the `clock_gettime()` function and the `_POSIX_C_SOURCE` macro.) So if you've tried to look up a particular function, been informed "This function is part of POSIX, not the C standard", and wondered why an operating system standard was mandating compiler features and language extensions... now you know! * POSIX.1-2001: The System Interfaces section can be downloaded as a separate document from <https://mirror.math.princeton.edu/pub/oldlinux/download/c951.pdf>. Section 1.7 states that the relevant version of the C standard is C99. The "Shell and Utilities" section (<https://mirror.math.princeton.edu/pub/oldlinux/download/c952.pdf>) mandates not only that a C99-compliant compiler should exist, but that it should be invokable from the command line under the name "c99". One way in which this can be implemented is to place a shell script called "c99" in /usr/bin, which calls gcc with the `-std=c99` option added to the list of command-line parameters, and blocks any competing standards from being specified. POSIX.1-2001 had two technical corrigenda, one dated 2002 and one dated 2004. I don't think they're incorporated into the documents as linked above. There's an online HTML version incorporating the corrigenda at <https://pubs.opengroup.org/onlinepubs/009695399/> - but I should add that I've had some trouble with the search box and so using Google to search the site is probably your best bet. There is a paywalled link to download the first corrigendum at <https://standards.ieee.org/standard/1003_1-2001-Cor1-2002.html>. There is also a paywalled link for the second at <https://standards.ieee.org/standard/1003_1-2001-Cor2-2004.html> * There is a draft version of POSIX.1-2008 at <http://www.open-std.org/jtc1/sc22/open/n4217.pdf>. POSIX.1-2008 also had two technical corrigenda, the latter of the two being dated 2016. There is an online HTML version of the standard incorporating the corrigenda at <https://pubs.opengroup.org/onlinepubs/9699919799.2016edition/> - though, again, I have had situations where the site's own search box wasn't good for finding information. * There is an online HTML version of POSIX.1-2017 at <https://pubs.opengroup.org/onlinepubs/9699919799/> - though, again, I recommend using Google instead of that site's searchbox. According to the [Open Group website](https://www.opengroup.org/austin/) "IEEE 1003.1-2017 ... is a revision to the 1003.1-2008 standard to rollup the standard including its two technical corrigenda (as-is)". [Linux manpages](https://man7.org/linux/man-pages/man7/standards.7.html) describe it as "technically identical" to POSIX.1-2008 with Technical Corrigenda 1 and 2 applied. This is therefore not a major revision and does not change the value of the `_POSIX_C_SOURCE` macro.
Online versions of the standard can be found: ### Working Draft, Standard for Programming Language C++ ***The following all draft versions of the standard***: All the following are freely downloadable 2023-12-18: [N4971](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/n4971.pdf) 2023-10-15: [N4964](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/n4964.pdf) 2023-08-14: [N4958](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/n4958.pdf) ***This is the C++23 Standard:*** 2023-05-10: [N4950](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/n4950.pdf) As a source for the above, see [N4951](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/n4951.html), which states: *"N4950 is the current and final working draft for C++23. It replaces N4944, and it forms the basis of the Draft International Standard for C++23. ... The next working draft will be for C++26."* ***The following all draft versions of the standard***: All the following are freely downloadable 2023-03-22: [N4944](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/N4944.pdf) 2022-12-18: [N4928](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/n4928.pdf) 2022-09-05: [N4917](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/n4917.pdf) 2022-03-17: [N4910](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/n4910.pdf) 2021-10-22: [N4901](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/n4901.pdf) 2021-06-18: [N4892](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/n4892.pdf) 2021-03-17: [N4885](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/n4885.pdf) 2020-12-15: [N4878](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/n4878.pdf) 2020-10-18: [N4868](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/n4868.pdf) 2020-04-08: [N4861](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/n4861.pdf) ***This is the C++20 Standard:*** 2020-04-08: [N4860](https://isocpp.org/files/papers/N4860.pdf) ***Note regarding N4860 and N4861:*** According to [N4859](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/n4859.html): *"The contents of N4860 and N4861 are identical except for the cover sheet, page headers and footers, and except that N4861 does not contain an index of cross references from ISO C++ 2017."* ***The following all draft versions of the standard***: All the following are freely downloadable (many of these can be found at this [main GitHub link](https://github.com/cplusplus/draft/tree/master/papers)) 2020-01-14: [N4849](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/n4849.pdf) 2019-11-27: [N4842](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/n4842.pdf) 2019-10-08: [N4835](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/n4835.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4835.pdf) 2019-08-15: [N4830](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/n4830.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers//n4830.pdf) 2019-06-17: [N4820](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/n4820.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4820.pdf) 2019-03-15: [N4810](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/n4810.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4810.pdf) 2019-01-21: [N4800](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/n4800.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4800.pdf) 2018-11-26: [N4791](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4791.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4791.pdf) 2018-10-08: [N4778](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4778.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4778.pdf) 2018-07-07: [N4762](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4762.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4762.pdf) 2018-05-07: [N4750](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4750.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4750.pdf) 2018-04-02: [N4741](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4741.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4741.pdf) 2018-02-12: [N4727](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4727.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4727.pdf) 2017-11-27: [N4713](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4713.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4713.pdf) 2017-10-16: [N4700](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4700.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4700.pdf) 2017-07-30: [N4687](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4687.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4687.pdf) ***This is the old C++17 Standard:*** This version requires authentication: 2017-03-21: [N4660](http://www.open-std.org/jtc1/sc22/wg21/prot/14882fdis/n4660.pdf) This version does not require authentication: 2017-03-21: [N4659](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4659.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4659.pdf) [N4661](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4661.html) explicitly states that: *"The contents of N4659 and N4660 are identical except for the cover sheet and page headings."* ***The following all draft versions of the standard***: All the following are freely downloadable 2017-02-06: [N4640](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4640.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4640.pdf) 2016-11-28: [N4618](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4618.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4618.pdf) 2016-07-12: [N4606](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4606.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4606.pdf) 2016-05-30: [N4594](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4594.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4594.pdf) 2016-03-19: [N4582](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4582.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4582.pdf) 2015-11-09: [N4567](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4567.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4567.pdf) 2015-05-22: [N4527](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4527.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4527.pdf) 2015-04-10: [N4431](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4431.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4431.pdf) 2014-11-19: [N4296](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4296.pdf) ***This is the old C++14 standard***: These version requires Authentication 2014-10-07: [N4140](http://www.open-std.org/jtc1/sc22/wg21/prot/14882fdis/n4140.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/n4140.pdf) Essentially C++14 with minor errors and typos corrected 2014-09-02: [N4141](http://www.open-std.org/jtc1/sc22/wg21/prot/14882fdis/n4141.pdf) [git](https://github.com/cplusplus/draft/tree/n4141) Standard C++14 2014-03-02: [N3937](http://www.open-std.org/jtc1/sc22/wg21/prot/14882fdis/n3937.pdf) 2014-03-02: [N3936](http://www.open-std.org/jtc1/sc22/wg21/prot/14882fdis/n3936.pdf) [git](https://github.com/cplusplus/draft/blob/b7b8ed08ba4c111ad03e13e8524a1b746cb74ec6/papers/N3936.pdf) ***The following all draft versions of the standard***: All the following are freely downloadable 2013-10-13: [N3797](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf) [git](https://github.com/cplusplus/draft/blob/master/papers/N3797.pdf) 2013-05-16: [N3691](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3691.pdf) 2013-05-15: [N3690](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3690.pdf) 2012-11-02: [N3485](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3485.pdf) 2012-02-28: [N3376](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3376.pdf) 2012-01-16: [N3337](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf) [git](https://github.com/cplusplus/draft/tree/n3337) Essentially C++11 with minor errors and typos corrected ***This is the old C++11 Standard***: This version requires Authentication 2011-04-05: [N3291](http://www.open-std.org/Jtc1/sc22/wg21/prot/14882fdis/n3291.pdf) ***The following all draft versions of the standard***: All the following are freely downloadable 2011-02-28: [N3242](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2011/n3242.pdf) (differences from N3291 very minor) 2010-11-27: [N3225](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2010/n3225.pdf) 2010-08-21: [N3126](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2010/n3126.pdf) 2010-03-29: [N3090](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2010/n3090.pdf) 2010-02-16: [N3035](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2010/n3035.pdf) 2009-11-09: [N3000](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2009/n3000.pdf) 2009-09-25: [N2960](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2009/n2960.pdf) 2009-06-22: [N2914](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2009/n2914.pdf) 2009-03-23: [N2857](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2009/n2857.pdf) 2008-10-04: [N2798](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2008/n2798.pdf) 2008-08-25: [N2723](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2008/n2723.pdf) 2008-06-27: [N2691](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2008/n2691.pdf) 2008-05-19: [N2606](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2008/n2606.pdf) 2008-03-17: [N2588](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2008/n2588.pdf) 2008-02-04: [N2521](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2008/n2521.pdf) 2007-10-22: [N2461](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2007/n2461.pdf) 2007-08-06: [N2369](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2007/n2369.pdf) 2007-06-25: [N2315](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2007/n2315.pdf) 2007-05-07: [N2284](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2007/n2284.pdf) 2006-11-03: [N2134](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2006/n2134.pdf) 2006-04-21: [N2009](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2006/n2009.pdf) 2005-10-19: [N1905](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2005/n1905.pdf) 2005-04-27: [N1804](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2005/n1804.pdf) **This is the old C++03 Standard:** All the below versions require Authentication 2004-11-05: [N1733](http://www.open-std.org/Jtc1/sc22/wg21/prot/14882fdis/n1733.pdf) 2004-07-16: [N1655](http://www.open-std.org/Jtc1/sc22/wg21/prot/14882fdis/n1655.pdf) Unofficial 2004-02-07: [N1577](http://www.open-std.org/Jtc1/sc22/wg21/prot/14882fdis/n1577.pdf) C++03 (Or Very Close) 2001-09-13: [N1316](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2001/n1316) Draft Expanded Technical Corrigendum 1997-00-00: N1117 Draft Expanded Technical Corrigendum ***The following all draft versions of the standard***: All the following are freely downloadable 1996-00-00: [N0836](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/1996/N0836.pdf) Draft Expanded Technical Corrigendum 1995-00-00: N0785 Working Paper for Draft Proposed International Standard for Information Systems - Programming Language C++ ### Other Interesting Papers: [2024](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/) / [2023](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/) / [2022](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/) / [2021](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/) / [2020](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/) / [2019](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/) / [2018](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/) / [2017](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/) / [2016](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/) / [2015](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/) / [2014](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/) / [2013](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/) / [2012](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/) / [2011](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/)
Where do I find the current C or C++ standard documents?
[ "", "c++", "c", "standards", "c++-faq", "" ]
I assumed that the C# margin property had a meaning like in CSS - the spacing around the outside of the control. But Margin values seem to be ignored to matter what values I enter. Then I read on the SDK: > Setting the Margin property on a > docked control has no effect on the > distance of the control from the the > edges of its container. Given that I'm placing controls on forms, and perhaps docking them, what does the Margin property get me?
The margin property is used by whatever layout engine your control host (Panel, for example) is using, in whatever way that layout engine sees fit. However, it is best used for spacing just as you assume. Just read the documentation for that specific layout engine. It can be very handy when using a FlowLayoutPanel or TableLayoutPanel, for example - to either reduce the default padding or space things out a bit. Obviously, if you write a custom layout provider, you can use Margin however you see fit.
Like Philip Rieck said, the margin property is only respected by container controls that perform layout. Here's an example that makes it fairly clear how the `TableLayoutPanel` respects the Margin property: ``` using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); TableLayoutPanel pnl = new TableLayoutPanel(); pnl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); pnl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); pnl.Dock = DockStyle.Fill; this.Controls.Add(pnl); Button btn1 = new Button(); btn1.Text = "No margin"; btn1.Dock = DockStyle.Fill; Button btn2 = new Button(); btn2.Margin = new Padding(25); btn2.Text = "Margin"; btn2.Dock = DockStyle.Fill; pnl.Controls.Add(btn1, 0, 0); pnl.Controls.Add(btn2, 1, 0); } } } ``` I believe the only .NET 2.0 built-in controls that respect this property are `FlowLayoutPanel` and `TableLayoutPanel`; hopefully third-party components respect it as well. It has basically no effect in other scenarios.
What is the .NET Control.Margin property for?
[ "", "c#", "controls", "margin", "" ]
While searching the interweb for a solution for my VB.net problems I often find helpful articles on a specific topic, but the code is C#. That is no big problem but it cost some time to convert it to VB manually. There are some sites that offer code converters from C# to VB and vice versa, but to fix all the flaws after the code-conversion is nearly as time-consuming as doing it by myself in the first place. Till now I am using <http://labs.developerfusion.co.uk/convert/csharp-to-vb.aspx> Do you know something better?
If you cannot find a good converter, you could always compile the c# code and use the dissasembler in [Reflector](http://www.red-gate.com/products/reflector/) to see Visual Basic code. Some of the variable names will change.
Telerik has [a good converter](http://converter.telerik.com/) that is based on SharpDevelop that has worked pretty well over the years, though it has not been updated in years (due to it being based on SharpDevelop). I've recently come across a [roslyn based converter as well](http://web.archive.org/web/20180312203225/http://roslyncodeconverter.azurewebsites.net:80/). I don't know how well it works or how well maintained it is, but as it's open source you can always fork it and update it as needed.
What is the best C# to VB.net converter?
[ "", "c#", "vb.net", "converters", "" ]
I am curious if anyone have used UnderC, Cint, Cling, Ch, or any other C++ interpreter and could share their experience.
There is **[cling](http://cern.ch/cling) Cern's project** of C++ interpreter based on [clang](http://clang.llvm.org/) - it's *new approach* based on 20 years of experience in *ROOT cint* and it's quite stable and recommended by Cern guys. Here is nice [Google Talk: Introducing cling, a C++ Interpreter Based on clang/LLVM](http://www.youtube.com/watch?v=f9Xfh8pv3Fs).
**NOTE:** what follows is rather CINT specific, but given that its probably the most [widely used](http://www.google.com/search?hl=en&q=c%2b%2b%20interpreter) C++ interpreter it may be valid for them all. As a graduate student in particle physics who's used CINT extensively, I should warn you away. While it does "work", it [is in the process of being phased out](http://root.cern.ch/drupal/content/do-we-need-yet-another-custom-c-interpreter), and those who spend more than a year in particle physics typically learn to avoid it for a few reasons: 1. Because of its roots as a C interpretor, it fails to interpret some of the most critical components of C++. Templates, for example, don't always work, so you'll be discouraged from using things which make C++ so flexible and usable. 2. It is slower (by at least a factor of 5) than minimally optimized C++. 3. Debugging messages are much more cryptic than those produced by g++. 4. Scoping is inconsistent with compiled C++: it's quite common to see code of the form ``` if (energy > 30) { float correction = 2.4; } else { float correction = 6.3; } somevalue += correction; ``` whereas any working C++ compiler would complain that `correcton` has gone out of scope, CINT allows this. The result is that CINT code isn't really C++, just something that looks like it. In short, CINT has none of the advantages of C++, and all the disadvantages plus some. The fact that CINT is still used at all is likely more of a historical accident owing to its inclusion in the ROOT framework. Back when it was written (20 years ago), there was a real need for an interpreted language for interactive plotting / fitting. Now there are many packages which fill that role, many which have hundreds of active developers. None of these are written in C++. Why? Quite simply, C++ is not meant to be interpreted. Static typing, for example, buys you great gains in optimization during compilation, but mostly serves to clutter and over-constrain your code if the computer is only allowed to see it at runtime. If you have the luxury of being able to use an interpreted language, learn Python or Ruby, the time it takes you to learn will be less than that you loose stumbling over CINT, even if you already know C++. In my experience, the older researchers who work with ROOT (the package you must install to run CINT) end up compiling the ROOT libraries into normal C++ executables to avoid CINT. Those in the younger generation either follow this lead or use Python for scripting. Incidentally, ROOT (and thus CINT) takes roughly half an hour to compile on a fairly modern computer, and will occasionally fail with newer versions of gcc. It's a package that served an important purpose many years ago, but now it's clearly showing it's age. Looking into the source code, you'll find hundreds of deprecated c-style casts, huge holes in type-safety, and heavy use of global variables. If you're going to write C++, write C++ as it's meant to be written. If you absolutely must have a C++ interpretor, CINT is probably a good bet.
Have you used any of the C++ interpreters (not compilers)?
[ "", "c++", "interpreter", "read-eval-print-loop", "" ]
Is there any complete guidance on doing AppBar docking (such as locking to the screen edge) in WPF? I understand there are InterOp calls that need to be made, but I'm looking for either a proof of concept based on a simple WPF form, or a componentized version that can be consumed. Related resources: * <http://www.codeproject.com/KB/dotnet/AppBar.aspx> * <http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/05c73c9c-e85d-4ecd-b9b6-4c714a65e72b/>
**Please Note:** This question gathered a good amount of feedback, and some people below have made great points or fixes. Therefore, while I'll keep the code here (and possibly update it), I've also **created a [WpfAppBar project on github](https://github.com/PhilipRieck/WpfAppBar)**. Feel free to send pull requests. That same project also builds to a [WpfAppBar nuget package](https://www.nuget.org/packages/WpfAppBar/) --- I took the code from the first link provided in the question ( <http://www.codeproject.com/KB/dotnet/AppBar.aspx> ) and modified it to do two things: 1. Work with WPF 2. Be "standalone" - if you put this single file in your project, you can call AppBarFunctions.SetAppBar(...) without any further modification to the window. This approach doesn't create a base class. To use, just call this code from anywhere within a normal wpf window (say a button click or the initialize). Note that you can not call this until AFTER the window is initialized, if the HWND hasn't been created yet (like in the constructor), an error will occur. Make the window an appbar: ``` AppBarFunctions.SetAppBar( this, ABEdge.Right ); ``` Restore the window to a normal window: ``` AppBarFunctions.SetAppBar( this, ABEdge.None ); ``` Here's the full code to the file - **note** you'll want to change the namespace on line 7 to something apropriate. ``` using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; using System.Windows.Threading; namespace AppBarApplication { public enum ABEdge : int { Left = 0, Top, Right, Bottom, None } internal static class AppBarFunctions { [StructLayout(LayoutKind.Sequential)] private struct RECT { public int left; public int top; public int right; public int bottom; } [StructLayout(LayoutKind.Sequential)] private struct APPBARDATA { public int cbSize; public IntPtr hWnd; public int uCallbackMessage; public int uEdge; public RECT rc; public IntPtr lParam; } private enum ABMsg : int { ABM_NEW = 0, ABM_REMOVE, ABM_QUERYPOS, ABM_SETPOS, ABM_GETSTATE, ABM_GETTASKBARPOS, ABM_ACTIVATE, ABM_GETAUTOHIDEBAR, ABM_SETAUTOHIDEBAR, ABM_WINDOWPOSCHANGED, ABM_SETSTATE } private enum ABNotify : int { ABN_STATECHANGE = 0, ABN_POSCHANGED, ABN_FULLSCREENAPP, ABN_WINDOWARRANGE } [DllImport("SHELL32", CallingConvention = CallingConvention.StdCall)] private static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData); [DllImport("User32.dll", CharSet = CharSet.Auto)] private static extern int RegisterWindowMessage(string msg); private class RegisterInfo { public int CallbackId { get; set; } public bool IsRegistered { get; set; } public Window Window { get; set; } public ABEdge Edge { get; set; } public WindowStyle OriginalStyle { get; set; } public Point OriginalPosition { get; set; } public Size OriginalSize { get; set; } public ResizeMode OriginalResizeMode { get; set; } public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg == CallbackId) { if (wParam.ToInt32() == (int)ABNotify.ABN_POSCHANGED) { ABSetPos(Edge, Window); handled = true; } } return IntPtr.Zero; } } private static Dictionary<Window, RegisterInfo> s_RegisteredWindowInfo = new Dictionary<Window, RegisterInfo>(); private static RegisterInfo GetRegisterInfo(Window appbarWindow) { RegisterInfo reg; if( s_RegisteredWindowInfo.ContainsKey(appbarWindow)) { reg = s_RegisteredWindowInfo[appbarWindow]; } else { reg = new RegisterInfo() { CallbackId = 0, Window = appbarWindow, IsRegistered = false, Edge = ABEdge.Top, OriginalStyle = appbarWindow.WindowStyle, OriginalPosition =new Point( appbarWindow.Left, appbarWindow.Top), OriginalSize = new Size( appbarWindow.ActualWidth, appbarWindow.ActualHeight), OriginalResizeMode = appbarWindow.ResizeMode, }; s_RegisteredWindowInfo.Add(appbarWindow, reg); } return reg; } private static void RestoreWindow(Window appbarWindow) { RegisterInfo info = GetRegisterInfo(appbarWindow); appbarWindow.WindowStyle = info.OriginalStyle; appbarWindow.ResizeMode = info.OriginalResizeMode; appbarWindow.Topmost = false; Rect rect = new Rect(info.OriginalPosition.X, info.OriginalPosition.Y, info.OriginalSize.Width, info.OriginalSize.Height); appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new ResizeDelegate(DoResize), appbarWindow, rect); } public static void SetAppBar(Window appbarWindow, ABEdge edge) { RegisterInfo info = GetRegisterInfo(appbarWindow); info.Edge = edge; APPBARDATA abd = new APPBARDATA(); abd.cbSize = Marshal.SizeOf(abd); abd.hWnd = new WindowInteropHelper(appbarWindow).Handle; if( edge == ABEdge.None) { if( info.IsRegistered) { SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd); info.IsRegistered = false; } RestoreWindow(appbarWindow); return; } if (!info.IsRegistered) { info.IsRegistered = true; info.CallbackId = RegisterWindowMessage("AppBarMessage"); abd.uCallbackMessage = info.CallbackId; uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd); HwndSource source = HwndSource.FromHwnd(abd.hWnd); source.AddHook(new HwndSourceHook(info.WndProc)); } appbarWindow.WindowStyle = WindowStyle.None; appbarWindow.ResizeMode = ResizeMode.NoResize; appbarWindow.Topmost = true; ABSetPos(info.Edge, appbarWindow); } private delegate void ResizeDelegate(Window appbarWindow, Rect rect); private static void DoResize(Window appbarWindow, Rect rect) { appbarWindow.Width = rect.Width; appbarWindow.Height = rect.Height; appbarWindow.Top = rect.Top; appbarWindow.Left = rect.Left; } private static void ABSetPos(ABEdge edge, Window appbarWindow) { APPBARDATA barData = new APPBARDATA(); barData.cbSize = Marshal.SizeOf(barData); barData.hWnd = new WindowInteropHelper(appbarWindow).Handle; barData.uEdge = (int)edge; if (barData.uEdge == (int)ABEdge.Left || barData.uEdge == (int)ABEdge.Right) { barData.rc.top = 0; barData.rc.bottom = (int)SystemParameters.PrimaryScreenHeight; if (barData.uEdge == (int)ABEdge.Left) { barData.rc.left = 0; barData.rc.right = (int)Math.Round(appbarWindow.ActualWidth); } else { barData.rc.right = (int)SystemParameters.PrimaryScreenWidth; barData.rc.left = barData.rc.right - (int)Math.Round(appbarWindow.ActualWidth); } } else { barData.rc.left = 0; barData.rc.right = (int)SystemParameters.PrimaryScreenWidth; if (barData.uEdge == (int)ABEdge.Top) { barData.rc.top = 0; barData.rc.bottom = (int)Math.Round(appbarWindow.ActualHeight); } else { barData.rc.bottom = (int)SystemParameters.PrimaryScreenHeight; barData.rc.top = barData.rc.bottom - (int)Math.Round(appbarWindow.ActualHeight); } } SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData); SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData); Rect rect = new Rect((double)barData.rc.left, (double)barData.rc.top, (double)(barData.rc.right - barData.rc.left), (double)(barData.rc.bottom - barData.rc.top)); //This is done async, because WPF will send a resize after a new appbar is added. //if we size right away, WPFs resize comes last and overrides us. appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new ResizeDelegate(DoResize), appbarWindow, rect); } } } ```
There is an excellent MSDN article from 1996 which is entertainingly up to date: [Extend the Windows 95 Shell with Application Desktop Toolbars](http://web.archive.org/web/20170704171718/https://www.microsoft.com/msj/archive/S274.aspx). Following its guidance produces an WPF based appbar which handles a number of scenarios that the other answers on this page do not: * Allow dock to any side of the screen * Allow dock to a particular monitor * Allow resizing of the appbar (if desired) * Handle screen layout changes and monitor disconnections * Handle `Win` + `Shift` + `Left` and attempts to minimize or move the window * Handle co-operation with other appbars (OneNote et al.) * Handle per-monitor DPI scaling I have both a [demo app and the implementation of `AppBarWindow` on GitHub](https://github.com/mgaffigan/WpfAppBar) and as a [Nuget module](https://www.nuget.org/packages/Itp.WpfAppBar). Example use: ``` <apb:AppBarWindow x:Class="WpfAppBarDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:apb="clr-namespace:WpfAppBar;assembly=WpfAppBar" DataContext="{Binding RelativeSource={RelativeSource Self}}" Title="MainWindow" DockedWidthOrHeight="200" MinHeight="100" MinWidth="100"> <Grid> <Button x:Name="btClose" Content="Close" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="23" Margin="10,10,0,0" Click="btClose_Click"/> <ComboBox x:Name="cbMonitor" SelectedItem="{Binding Path=Monitor, Mode=TwoWay}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" Margin="10,38,0,0"/> <ComboBox x:Name="cbEdge" SelectedItem="{Binding Path=DockMode, Mode=TwoWay}" HorizontalAlignment="Left" Margin="10,65,0,0" VerticalAlignment="Top" Width="120"/> <Thumb Width="5" HorizontalAlignment="Right" Background="Gray" x:Name="rzThumb" Cursor="SizeWE" DragCompleted="rzThumb_DragCompleted" /> </Grid> </apb:AppBarWindow> ``` Codebehind: ``` public partial class MainWindow { public MainWindow() { InitializeComponent(); this.cbEdge.ItemsSource = new[] { AppBarDockMode.Left, AppBarDockMode.Right, AppBarDockMode.Top, AppBarDockMode.Bottom }; this.cbMonitor.ItemsSource = MonitorInfo.GetAllMonitors(); } private void btClose_Click(object sender, RoutedEventArgs e) { Close(); } private void rzThumb_DragCompleted(object sender, DragCompletedEventArgs e) { this.DockedWidthOrHeight += (int)(e.HorizontalChange / VisualTreeHelper.GetDpi(this).PixelsPerDip); } } ``` Changing docked position: > [![AppBar docked to edges](https://i.stack.imgur.com/f13P8.gif)](https://i.stack.imgur.com/f13P8.gif) Resizing with thumb: > [![Resize](https://i.stack.imgur.com/ifgn8.gif)](https://i.stack.imgur.com/ifgn8.gif) Cooperation with other appbars: > [![Coordination](https://i.stack.imgur.com/PiydR.gif)](https://i.stack.imgur.com/PiydR.gif) Clone [from GitHub](https://github.com/mgaffigan/WpfAppBar) if you want to use it. The library itself is only three files, and can easily be dropped in a project.
How do you do AppBar docking (to screen edge, like WinAmp) in WPF?
[ "", "c#", "wpf", "dock", "docking", "appbar", "" ]
Is there a way of getting the process id of my C++ application? I am using the Carbon framework, but not Cocoa…
can you use the getpid() function found in unistd.h ? [osx reference](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getpid.2.html)
Note that you don't actually need to call GetCurrentProcess, you can use the constant kCurrentProcess. (But getpid is a lot less work if you're not trying to access another process's PID, anyway.)
Is there a way of getting the process id of my C++ application?
[ "", "c++", "macos", "macos-carbon", "" ]
I've got some Java code using a servlet and Apache Commons FileUpload to upload a file to a set directory. It's working fine for character data (e.g. text files) but image files are coming out garbled. I can open them but the image doesn't look like it should. Here's my code: Servlet ``` protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String customerPath = "\\leetest\\"; // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if (item.isFormField()) { // Form field. Ignore for now } else { BufferedInputStream stream = new BufferedInputStream(item .openStream()); if (stream == null) { LOGGER .error("Something went wrong with fetching the stream for field " + name); } byte[] bytes = StreamUtils.getBytes(stream); FileManager.createFile(customerPath, item.getName(), bytes); stream.close(); } } } } catch (Exception e) { throw new UploadException("An error occured during upload: " + e.getMessage()); } } ``` StreamUtils.getBytes(stream) looks like: ``` public static byte[] getBytes(InputStream src, int buffsize) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); byte[] buff = new byte[buffsize]; while (true) { int nBytesRead = src.read(buff); if (nBytesRead < 0) { break; } byteStream.write(buff); } byte[] result = byteStream.toByteArray(); byteStream.close(); return result; } ``` And finally FileManager.createFile looks like: ``` public static void createFile(String customerPath, String filename, byte[] fileData) throws IOException { customerPath = getFullPath(customerPath + filename); File newFile = new File(customerPath); if (!newFile.getParentFile().exists()) { newFile.getParentFile().mkdirs(); } FileOutputStream outputStream = new FileOutputStream(newFile); outputStream.write(fileData); outputStream.close(); } ``` Can anyone spot what I'm doing wrong? Cheers, Lee
One thing I don't like is here in this block from StreamUtils.getBytes(): ``` 1 while (true) { 2 int nBytesRead = src.read(buff); 3 if (nBytesRead < 0) { 4 break; 5 } 6 byteStream.write(buff); 7 } ``` At line 6, it writes the entire buffer, no matter how many bytes are read in. I am not convinced this will always be the case. It would be more correct like this: ``` 1 while (true) { 2 int nBytesRead = src.read(buff); 3 if (nBytesRead < 0) { 4 break; 5 } else { 6 byteStream.write(buff, 0, nBytesRead); 7 } 8 } ``` Note the 'else' on line 5, along with the two additional parameters (array index start position and length to copy) on line 6. I could imagine that for larger files, like images, the buffer returns before it is filled (maybe it is waiting for more). That means you'd be unintentionally writing old data that was remaining in the tail end of the buffer. This is almost certainly happening most of the time at EoF, assuming a buffer > 1 byte, but extra data at EoF is probably not the cause of your corruption...it is just not desirable.
I'd just use [commons io](http://commons.apache.org/io/) Then you could just do an IOUtils.copy(InputStream, OutputStream); It's got lots of other useful utility methods.
Why is my image coming out garbled?
[ "", "java", "file-io", "apache-commons-fileupload", "" ]
I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools? Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However it's written in Python which means there's little real support in the way of deployment/packaging, debugging, profilers and other tools that make building and maintaining applications much easier. Ruby has similar issues and although I do like Ruby **much** better than I like Python, I get the impression that Rails is roughly in the same boat at Django when it comes to managing/supporting the app. Has anyone here tried both Django and Grails (or other web frameworks) for non-trivial projects? How did they compare?
You asked for someone who used both Grails and Django. I've done work on both for big projects. Here's my Thoughts: **IDE's:** Django works really well in Eclipse, Grails works really well in IntelliJ Idea. **Debugging:** Practically the same (assuming you use IntelliJ for Grails, and Eclipse for Python). Step debugging, inspecting variables, etc... never need a print statement for either. Sometimes django error messages can be useless but Grails error messages are usually pretty lengthy and hard to parse through. **Time to run a unit test:** django: 2 seconds. Grails: 20 seconds (the tests themselves both run in a fraction of a second, it's the part about loading the framework to run them that takes the rest... as you can see, Grails is frustratingly slow to load). **Deployment:** Django: copy & paste one file into an apache config, and to redeploy, just change the code and reload apache. Grails: create a .war file, deploy it on tomcat, rinse and repeat to redeploy. **Programming languages:** Groovy is TOTALLY awesome. I love it, more so than Python. But I certainly have no complaints. **Plugins:** Grails: lots of broken plugins (and can use every java lib ever). Django: a few stable plugins, but enough to do most of what you need. **Database:** Django: schema migrations using South, and generally intuitive relations. Grails: no schema migrations, and by default it deletes the database on startup... WTF **Usage:** Django: startups (especially in the Gov 2.0 space), independent web dev shops. Grails: enterprise Hope that helps!
> However it's written in Python which > means there's little real support in > the way of deployment/packaging, > debugging, profilers and other tools > that make building and maintaining > applications much easier. Python has: 1. a [great interactive debugger](http://docs.python.org/lib/module-pdb.html), which makes very good use of Python [REPL](http://en.wikipedia.org/wiki/REPL). 2. [easy\_install](http://peak.telecommunity.com/DevCenter/EasyInstall) anv [virtualenv](http://pypi.python.org/pypi/virtualenv) for dependency management, packaging and deployment. 3. [profiling features](http://docs.python.org/lib/profile.html) comparable to other languages So IMHO you shouldn't worry about this things, use Python and Django and live happily :-) Lucky for you, newest version of [Django runs on Jython](http://blog.leosoto.com/2008/08/django-on-jython-its-here.html), so you don't need to leave your whole Java ecosystem behind. Speaking of frameworks, I evaluated this year: 1. [Pylons](http://pylonshq.com/) (Python) 2. [webpy](http://webpy.org/) (Python) 3. [Symfony](http://www.symfony-project.org/) (PHP) 4. [CakePHP](http://www.cakephp.org/) (PHP) None of this frameworks comes close to the power of Django or Ruby on Rails. Based on my collegue opinion I could recommend you [kohana](http://www.kohanaphp.com/home) framework. The downside is, it's written in PHP and, as far as I know, PHP doesn't have superb tools for debugging, profiling and packaging of apps. **Edit:** Here is a very good [article about packaging and deployment of Python apps](http://bud.ca/blog/pony) (specifically Django apps). It's a hot topic in Django community now.
Django -vs- Grails -vs-?
[ "", "python", "django", "frameworks", "" ]
Is there a built in function in .NET 2.0 that will take two arrays and merge them into one array? The arrays are both of the same type. I'm getting these arrays from a widely used function within my code base and can't modify the function to return the data in a different format. I'm looking to avoid writing my own function to accomplish this if possible.
If you can manipulate one of the arrays, you can resize it before performing the copy: ``` T[] array1 = getOneArray(); T[] array2 = getAnotherArray(); int array1OriginalLength = array1.Length; Array.Resize<T>(ref array1, array1OriginalLength + array2.Length); Array.Copy(array2, 0, array1, array1OriginalLength, array2.Length); ``` Otherwise, you can make a new array ``` T[] array1 = getOneArray(); T[] array2 = getAnotherArray(); T[] newArray = new T[array1.Length + array2.Length]; Array.Copy(array1, newArray, array1.Length); Array.Copy(array2, 0, newArray, array1.Length, array2.Length); ``` [More on available Array methods on MSDN](http://msdn.microsoft.com/en-us/library/system.array.aspx).
In C# 3.0 you can use LINQ's [Concat](https://msdn.microsoft.com/en-us/library/vstudio/bb302894%28v=vs.100%29.aspx) method to accomplish this easily: ``` int[] front = { 1, 2, 3, 4 }; int[] back = { 5, 6, 7, 8 }; int[] combined = front.Concat(back).ToArray(); ``` In C# 2.0 you don't have such a direct way, but Array.Copy is probably the best solution: ``` int[] front = { 1, 2, 3, 4 }; int[] back = { 5, 6, 7, 8 }; int[] combined = new int[front.Length + back.Length]; Array.Copy(front, combined, front.Length); Array.Copy(back, 0, combined, front.Length, back.Length); ``` This could easily be used to implement your own version of `Concat`.
Merging two arrays in .NET
[ "", "c#", ".net", "arrays", "" ]
I would like to display an RTF document in an SWT (actually Eclipse RCP) application. I know there is a Swing widget for displaying and editing RTF text, but it is Swing and quite alien in look and feel when used in the otherwise platform (not to mention that to the last of my knowledge it did not display images and had only limited support for formatting) Other options is to use COM interface on windows, but that works only on the windows platform and requires that an ActiveX RichEdit contol be installed on the customer machine... which can make the deployment of the application quite horrendous... What are the other options for displaying rich documents inside Eclipse/SWT application?
Actuall, I've just found another widget that is quite promising atm: <http://onpositive.com/richtext>
You may use swt.custom.StyledText. That has many features to change the look of the text. But I don't think it can load or save RTF right now. I once wrote an HTML editor with it, but it is quite difficult, since the StyledText model to add styles to a part of the text is so alien compared to the way HTML/RTF works. AFAIK you can directly print from this control, which internally creates an RTF representation of the contents. But that's not exactly what you asked for.
Is there an RTF display widget in SWT
[ "", "java", "eclipse", "swt", "rtf", "" ]
I am looking for an easy way to check if an object in C# is serializable. As we know you make an object serializable by either implementing the *ISerializable* interface or by placing the *[Serializable]* at the top of the class. What I am looking for is a quick way to check this without having to reflect the class to get it's attributes. The interface would be quick using an *is* statement. Using @Flard's suggestion this is the code that I have come up with, scream is there is a better way. ``` private static bool IsSerializable(T obj) { return ((obj is ISerializable) || (Attribute.IsDefined(typeof (T), typeof (SerializableAttribute)))); } ``` Or even better just get the type of the object and then use the IsSerializable property on the type: ``` typeof(T).IsSerializable ``` Remember though this this seems to only just the class that we are dealing with if the class contains other classes you probably want to check them all or try and serialize and wait for errors as @pb pointed out.
You have a lovely property on the `Type` class called `IsSerializable`.
You're going to have to check all types in the graph of objects being serialized for the serializable attribute. The easiest way is to try to serialize the object and catch the exception. (But that's not the cleanest solution). Type.IsSerializable and checking for the serializalbe attribute don't take the graph into account. *Sample* ``` [Serializable] public class A { public B B = new B(); } public class B { public string a = "b"; } [Serializable] public class C { public D D = new D(); } [Serializable] public class D { public string d = "D"; } class Program { static void Main(string[] args) { var a = typeof(A); var aa = new A(); Console.WriteLine("A: {0}", a.IsSerializable); // true (WRONG!) var c = typeof(C); Console.WriteLine("C: {0}", c.IsSerializable); //true var form = new BinaryFormatter(); // throws form.Serialize(new MemoryStream(), aa); } } ```
How to check if an object is serializable in C#
[ "", "c#", "serialization", "" ]
Is there a setting in ReSharper 4 (or even Visual Studio itself...) that forces a warning if I forget to wrap code in a `using` block, or omit the proper Dispose call in a `finally` block?
Correct automatic Dispose analysis requires DFA (Data Flow Analysis) in a global way. It is unlikely that you create an IDisposable object and doesn't call any method on it and do not pass it around as an argument. If disposable object is passed to other methods (including calling its members, when "this" is implicitly passed), the tool should analyse if Dispose is not called within, or that object is not stored somewhere for later disposal. That said, naive implementation of checking if disposable object is in fact disposed with "using" construct or in any other way would yield too much false positives, and render analysis useless.
Discontent with current methods, I created my own: [EyeDisposable](https://github.com/kizzx2/EyeDisposable). It's an IL instrumenter so it should catch many leaks not caught by static analysis. It's still in its early stage, inputs are welcome.
Can ReSharper be set to warn if IDisposable not handled correctly?
[ "", "c#", ".net", "resharper", "static-analysis", "" ]
What's the simplest SQL statement that will return the duplicate values for a given column and the count of their occurrences in an Oracle database table? For example: I have a `JOBS` table with the column `JOB_NUMBER`. How can I find out if I have any duplicate `JOB_NUMBER`s, and how many times they're duplicated?
Aggregate the column by COUNT, then use a HAVING clause to find values that appear more than once. ``` SELECT column_name, COUNT(column_name) FROM table_name GROUP BY column_name HAVING COUNT(column_name) > 1; ```
Another way: ``` SELECT * FROM TABLE A WHERE EXISTS ( SELECT 1 FROM TABLE WHERE COLUMN_NAME = A.COLUMN_NAME AND ROWID < A.ROWID ) ``` Works fine (quick enough) when there is index on `column_name`. And it's better way to delete or update duplicate rows.
How do I find duplicate values in a table in Oracle?
[ "", "sql", "oracle", "duplicate-data", "" ]
Are there any good solutions to represent a parameterized enum in `C# 3.0`? I am looking for something like [OCaml](http://www.ocaml.org) or [Haxe](http://www.haxe.org) has. I can only think of class hierarchy with a simple enum field for easy switching for now, maybe there are better ideas? See Ocaml example below in one of the replies, a Haxe code follows: ``` enum Tree { Node(left: Tree, right: Tree); Leaf(val: Int); } ```
Not being familiar with OCaml or Haxe, and not being clever enough to understand the other explanations, I went and looked up the [Haxe enum documentation](https://haxe.org/manual/types-enum-instance.html) - the 'Enum Type Parameters' bit at the bottom seems to be the relevant part. My understanding based on that is as follows: A 'normal' enum is basically a value which is restricted to the things that you have defined in your enum definition. C# Example: ``` enum Color{ Red, Green, Yellow, Blue }; Color c = Color.Red; ``` `c` can either be `Red`, `Green`, `Yellow`, or `Blue`, but nothing else. In Haxe, you can add complex types to enums, Contrived example from their page: ``` enum Cell<T>{ empty; cons( item : T, next : Cell<T> ) } Cell<int> c = <I don't know>; ``` What this *appears* to mean is that `c` is restricted to either being the literal value `empty` (like our old fashioned C# enums), or it can also be a complex type `cons(item, next)`, where `item` is a `T` and `next` is a `Cell<T>`. Not having ever used this it looks like it is probably generating some anonymous types (like how the C# compiler does when you do `new { Name='Joe'}`. Whenever you 'access' the enum value, you have to declare `item` and `next` when you do so, and it looks like they get bound to temporary local variables. Haxe example - You can see 'next' being used as a temporary local variable to pull data out of the anonymous cons structure: ``` switch( c ) { case empty : 0; case cons(item,next): 1 + cell_length(next); } ``` To be honest, this blew my mind when I 'clicked' onto what it seemed to be doing. It seems incredibly powerful, and I can see why you'd be looking for a similar feature in C#. C# enums are pretty much the same as C/++ enums from which they were originally copied. It's basically a nice way of saying `#define Red 1` so the compiler can do comparisons and storage with integers instead of strings when you are passing `Color` objects around. My stab at doing this in C# would be to use generics and interfaces. Something like this: ``` public interface ICell<T> { T Item{ get; set; } ICell<T>{ get; set; } } class Cons<T> : ICell<T> { public T Item{ get; set; } /* C#3 auto-backed property */ public Cell<T> Next{ get; set; } } class EmptyCell<T> : ICell<T>{ public T Item{ get{ return default(T); set{ /* do nothing */ }; } public ICell<T> Next{ get{ return null }; set{ /* do nothing */; } } ``` Then you could have a `List<ICell<T>>` which would contain items and next cell, and you could insert `EmptyCell` at the end (or just have the `Next` reference explicitly set to null). The advantages would be that because `EmptyCell` contains no member variables, it wouldn't require any storage space (like the `empty` in Haxe), whereas a `Cons` cell would. The compiler may also inline / optimize out the methods in `EmptyCell` as they do nothing, so there may be a speed increase over just having a `Cons` with it's member data set to null. I don't really know. I'd welcome any other possible solutions as I'm not particularly proud of my one :-)
Use a **class** that with static properties to represent the enumeration values. You can, optionally, use a private constructor to force all references to the class to go through a static property. Take a look at the `System.Drawing.Color` class. It uses this approach.
Best way to represent a parameterized enum in C#?
[ "", "c#", "enums", "ocaml", "haxe", "" ]
I'm having an issue with a query that currently uses ``` LEFT JOIN weblog_data AS pwd ON (pwd.field_id_41 != '' AND pwd.field_id_41 LIKE CONCAT('%', ewd.field_id_32, '%')) ``` However I'm discovering that I need it to only use that if there is no exact match first. What's happening is that the query is double dipping due to the use of `LIKE`, so if it tests for an exact match first then it will avoid the double dipping issue. Can anyone provide me with any further guidance?
It sounds like you want to join the tables aliased as pwd and ewd in your snippet based first on an exact match, and if that fails, then on the like comparison you have now. Try this: ``` LEFT JOIN weblog_data AS pwd1 ON (pwd.field_id_41 != '' AND pwd.field_id_41 = ewd.field_id_32) LEFT JOIN weblog_data AS pwd2 ON (pwd.field_id_41 != '' AND pwd.field_id_41 LIKE CONCAT('%', ewd.field_id_32, '%')) ``` Then, in your select clause, use something like this: ``` select isnull(pwd1.field, pwd2.field) ``` however, if you are dealing with a field that can be null in pwd, that will cause problems, this should work though: ``` select case pwd1.nonnullfield is null then pwd2.field else pwd1.field end ``` You'll also have to make sure to do a group by, as the join to pwd2 will still add rows to your result set, even if you end up ignoring the data in it.
you're talking about short circuit evaluation. Take a look at this article it might help you: <http://beingmarkcohen.com/?p=62>
SQL Query - Use Like only if no exact match exists?
[ "", "sql", "left-join", "" ]
I have a simple type that explicitly implemets an Interface. ``` public interface IMessageHeader { string FromAddress { get; set; } string ToAddress { get; set; } } [Serializable] public class MessageHeader:IMessageHeader { private string from; private string to; [XmlAttribute("From")] string IMessageHeade.FromAddress { get { return this.from;} set { this.from = value;} } [XmlAttribute("To")] string IMessageHeade.ToAddress { get { return this.to;} set { this.to = value;} } } ``` Is there a way to Serialize and Deserialize objects of type IMessageHeader?? I got the following error when tried "Cannot serialize interface IMessageHeader"
You cannot serialize IMessageHeader because you can't do Activator.CreateInstance(typeof(IMessageHeader)) which is what serialization is going to do under the covers. You need a concrete type. You can do typeof(MessageHeader) or you could say, have an instance of MessageHeader and do ``` XmlSerializer serializer = new XmlSerializer(instance.GetType()) ```
No, because the serializer needs a concrete class that it can instantiate. Given the following code: ``` XmlSerializer ser = new XmlSerializer(typeof(IMessageHeader)); IMessageHeader header = (IMessageHeader)ser.Deserialize(data); ``` What class does the serializer create to return from Deserialize()? In theory it's possible to serialize/deserialize an interface, just not with XmlSerializer.
XMLSerialization in C#
[ "", "c#", ".net", "serialization", "interface", "" ]
When I do a clean build my C# project, the produced dll is different then the previously built one (which I saved separately). No code changes were made, just clean and rebuild. Diff shows some bytes in the DLL have changes -- few near the beginning and few near the end, but I can't figure out what these represent. Does anybody have insights on why this is happening and how to prevent it? This is using Visual Studio 2005 / WinForms. **Update:** Not using automatic version incrementing, or signing the assembly. If it's a timestamp of some sort, how to I prevent VS from writing it? **Update:** After looking in Ildasm/diff, it seems like the following items are different: * Two bytes in PE header at the start of the file. * <PrivateImplementationDetails>{*guid*} section * Cryptic part of the string table near the end (wonder why, I did not change the strings) * Parts of assembly info at the end of file. No idea how to eliminate any of these, if at all possible...
My best guess would be the changed bytes you're seeing are the internally-used metadata columns that are automatically generated at build-time. Some of the Ecma-335 Partition II (CLI Specification Metadata Definition) columns that can change per-build, even if the source code doesn't change at all: * Module.Mvid: A build-time-generated GUID. Always changes, every build. * AssemblyRef.HashValue: Could change if you're referencing another assembly that has also been rebuilt since the old build. If this really, really bothers you, my best tip on finding out exactly what is changing would be to diff the actual metadata tables. The way to get these is to use the ildasm MetaInfo window: ``` View > MetaInfo > Raw:Header,Schema,Rows // important, otherwise you get very basic info from the next step View > MetaInfo > Show! ```
I think that would be the TimeDateStamp field in the IMAGE\_FILE\_HEADER header of the [PE32 specifications](http://msdn.microsoft.com/en-us/library/ms809762.aspx).
Why is a different dll produced after a clean build, with no code changes?
[ "", "c#", ".net", "visual-studio", "build-process", "" ]
To complete some testing I need to load the 64 bit version of an assembly even though I am running a 32 bit version of Windows. Is this possible?
I'm not sure why you would want to do this, but I suppose you could. If you don't do anything to tell it otherwise, the CLR will load the version of the assembly that is specific to the CPU you are using. That's usually what you want. But I have had an occasion where I needed to load the neutral IL version of an assembly. I used the [Load method](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.load(VS.71).aspx) to specify the version. I haven't tried it (and others here suggest it won't work for an executable assembly), but I suppose you can do the same to specify you want to load the 64 bit version. (You'll have to specify if you want the AMD64 or IA64 version.)
From CLR Via C# (Jeff Richter): "If your assembly files contain only type-safe managed code, you are writing code that should work on both 32-bit and 64-bit versions of Windows. No source code changes are required for your code to run on either version of Windows. In fact, the resulting EXE/DLL file produced by the compiler will run on 32-bit Windows as well as the x64 and IA64 versions of 64-bit Windows! In other words, the one file will run on any machine that has a version of the .NET Framework installed on it." " The C# compiler offers a /platform command-line switch. This switch allows you to specify whether the resulting assembly can run on x86 machines running 32-bit Windows versions only, x64 machines running 64-bit Windows only, or Intel Itanium machines running 64-bit Windows only. If you don't specify a platform, the default is anycpu, which indicates that the resulting assembly can run on any version of Windows.
How to load a specific version of an assembly
[ "", "c#", ".net", "assemblies", "64-bit", "" ]
After reading [this description](http://www.colder.ch/news/08-24-2007/28/late-static-bindings-expl.html) of late static binding (LSB) I see pretty clearly what is going on. Now, under which sorts of circumstances might that be most useful or needed?
I needed LSB this for the following scenario: * Imagine you're building a "mail processor" daemon that downloads the message from an email server, classifies it, parses it, saves it, and then does something, depending on the type of the message. * Class hierarchy: you have a base Message class, with children "BouncedMessage" and "AcceptedMessage". * Each of the message types has its own way to persist itself on disk. For example, all messages of type BouncedMessage try to save itself as BouncedMessage-id.xml. AcceptedMessage, on the other hand, needs to save itself differently - as AcceptedMessage-timestamp.xml. The important thing here is that the logic for determining the filename pattern is different for different subclasses, but **shared** for all items within the subclass. That's why it makes sense for it to be in a static method. * Base Message class has an abstract static method (yes, abstract *AND* static) "save". BouncedMessage implements this method with a concrete static method. Then, inside the class that actually retrieves the message, you can call "::save()" If you want to learn more about the subject: * <http://www.qcodo.com/forums/topic.php/2356> * <http://community.livejournal.com/php/585907.html> * <http://bugs.php.net/bug.php?id=42681>
One primary need I have for late static binding is for a set of static instance-creation methods. This [DateAndTime class](http://harmoni.sourceforge.net/harmoniDoc/phpdoc/harmoni/primitives.chronology/DateAndTime.html) is part of a chronology library that I ported to PHP from Smalltalk/Squeak. Using static instance-creation methods enables creation of instances with a variety of argument types, while keeping parameter checking in the static method so that the consumer of the library is unable to obtain an instance that is not fully valid. Late static binding is useful in this case so that the implementations of these static instance-creation methods can determine what class was originally targeted by the call. Here is an example of usage: **With LSB:** ``` class DateAndTime { public static function now() { $class = static::myClass(); $obj = new $class; $obj->setSeconds(time()); return $obj; } public static function yesterday() { $class = static::myClass(); $obj = new $class; $obj->setSeconds(time() - 86400); return $obj; } protected static function myClass () { return 'DateAndTime'; } } class Timestamp extends DateAndTime { protected static function myClass () { return 'Timestamp'; } } // Usage: $date = DateAndTime::now(); $timestamp = Timestamp::now(); $date2 = DateAndTime::yesterday(); $timestamp2 = Timestamp::yesterday(); ``` Without late static binding, [as in my current implementation] each class must implement every instance creation method as in this example: **Without LSB:** ``` class DateAndTime { public static function now($class = 'DateAndTime') { $obj = new $class; $obj->setSeconds(time()); return $obj; } public static function yesterday($class = 'DateAndTime') { $obj = new $class; $obj->setSeconds(time() - 86400); return $obj; } } class Timestamp extends DateAndTime { public static function now($class = 'Timestamp') { return self::now($class); } public static function yesterday($class = 'Timestamp') { return self::yesterday($class); } } ``` As the number of instance-creation methods and class-hierarchy increases the duplication of methods becomes a real pain in the butt. LSB reduces this duplication and allows for much cleaner and more straight-forward implementations.
When would you need to use late static binding?
[ "", "php", "oop", "" ]
I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username) For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this? Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2]) ...but that doesn't scale nicely when you have 15...20 fields or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)
I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the tuple to a dictionary and the code that actually makes use of the new values. For example: ``` job={} job['jobid'], job['label'], job['username']=<querycode> ```
@Staale There is a better way: ``` job = dict(zip(keys, values)) ```
Splitting tuples in Python - best practice?
[ "", "python", "tuples", "" ]
I'm trying to build a better username/password field for my workplace and would like to be able to complain when they have their caps lock on. Is this possible? And if so I'd like to have it detected before the client types their first letter. Is there a non-platform specific way to do this?
Try this, from java.awt.Toolkit, returns a boolean: ``` Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK) ```
here is some info on the class <http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Toolkit.html#getLockingKeyState(int)>
How can I detect if caps lock is toggled in Swing?
[ "", "java", "swing", "" ]
Can you specialize a template method within a template class without specializing the class template parameter? Please note that the specialization is on the *value* of the template parameter, not its type. This seems to compile under Visual Studio 2008 SP1 complier, but not GCC 4.2.4. ``` #include <iostream> using namespace std; template <typename T> class A { private: template <bool b> void testme(); template <> void testme<true>() { cout << "true" << endl; }; template <> void testme<false>() { cout << "false" << endl; }; public: void test(); }; template<typename T> struct select {}; template<> struct select<int> { static const bool value = true; }; template<> struct select<double> { static const bool value = false; }; template <class T> void A<T>::test() { testme<select<T>::value>(); } int main(int argc, const char* argv[]) { A<int> aInt; A<double> aDouble; aInt.test(); aDouble.test(); return 0; } ``` GCC tells me:"error: explicit specialization in non-namespace scope ‘class A’" If it is not supported in the standard, can anyone tell me why?
Here is another workaround, also useful when you need to partialy specialize a function (which is not allowed). Create a template functor class (ie. class whose sole purpose is to execute a single member function, usually named operator() ), specialize it and then call from within your template function. I think I learned this trick from Herb Sutter, but do not remember which book (or article) was that. For your needs it is probably overkill, but nonetheless ... ``` template <typename T> struct select; template <bool B> struct testme_helper { void operator()(); }; template <typename T> class A { private: template <bool B> void testme() { testme_helper<B>()(); } public: void test() { testme<select<T>::value>(); } }; template<> void testme_helper<true>::operator()() { std::cout << "true" << std::endl; } template<> void testme_helper<false>::operator()() { std::cout << "false" << std::endl; } ```
It is not supported in the standard (and it is apparently a known bug with Visual Studio that you *can* do it). The standard doesn't allow an inner template (member function *or* class) to be specialized without the outer template being specialized as well. One of the reasons for this is that you can normally just overload the function: ``` template<typename ty> class A { public: void foo(bool b); void foo(int i); }; ``` Is equivalent to: ``` template<typename ty> class A { public: template<typename ty2> void foo(ty2); template<> void foo(bool b); template<> void foo(int i); }; ```
C++ method expansion
[ "", "c++", "templates", "" ]
In C++, can member function pointers be used to point to derived (or even base) class members? EDIT: Perhaps an example will help. Suppose we have a hierarchy of three classes `X`, `Y`, `Z` in order of inheritance. `Y` therefore has a base class `X` and a derived class `Z`. Now we can define a member function pointer `p` for class `Y`. This is written as: ``` void (Y::*p)(); ``` (For simplicity, I'll assume we're only interested in functions with the signature `void f()` ) This pointer `p` can now be used to point to member functions of class `Y`. This question (two questions, really) is then: 1. Can `p` be used to point to a function in the derived class `Z`? 2. Can `p` be used to point to a function in the base class `X`?
C++03 std, [§4.11 2 Pointer to member conversions](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem): > An rvalue of type “pointer to member of B of type *cv* T,” where B is a class type, can be converted to an rvalue of type “pointer to member of D of type *cv* T,” where D is a derived class (clause 10) of B. If B is an inaccessible (clause 11), ambiguous (10.2) or virtual (10.1) base class of D, a program that necessitates this conversion is ill-formed. The result of the conversion refers to the same member as the pointer to member before the conversion took place, but it refers to the base class member as if it were a member of the derived class. The result refers to the member in D’s instance of B. Since the result has type “pointer to member of D of type *cv* T,” it can be dereferenced with a D object. The result is the same as if the pointer to member of B were dereferenced with the B sub-object of D. The null member pointer value is converted to the null member pointer value of the destination type. 52) > > 52)The rule for conversion of pointers to members (from pointer to member of base to pointer to member of derived) appears inverted compared to the rule for pointers to objects (from pointer to derived to pointer to base) (4.10, clause 10). This inversion is necessary to ensure type safety. Note that a pointer to member is not a pointer to object or a pointer to function and the rules for conversions of such pointers do not apply to pointers to members. In particular, a pointer to member cannot be converted to a void\*. In short, you can convert a pointer to a member of an accessible, non-virtual base class to a pointer to a member of a derived class as long as the member isn't ambiguous. ``` class A { public: void foo(); }; class B : public A {}; class C { public: void bar(); }; class D { public: void baz(); }; class E : public A, public B, private C, public virtual D { public: typedef void (E::*member)(); }; class F:public E { public: void bam(); }; ... int main() { E::member mbr; mbr = &A::foo; // invalid: ambiguous; E's A or B's A? mbr = &C::bar; // invalid: C is private mbr = &D::baz; // invalid: D is virtual mbr = &F::bam; // invalid: conversion isn't defined by the standard ... ``` Conversion in the other direction (via `static_cast`) is governed by [§ 5.2.9](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/expr.html#expr.static.cast) 9: > An rvalue of type "pointer to member of D of type *cv1* T" can be converted to an rvalue of type "pointer to member of B of type *cv2* T", where B is a base class (clause [10 class.derived](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/derived.html#class.derived)) of D, if a valid standard conversion from "pointer to member of B of type T" to "pointer to member of D of type T" exists ([4.11 conv.mem](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem)), and *cv2* is the same cv-qualification as, or greater cv-qualification than, *cv1*.11) The null member pointer value ([4.11 conv.mem](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem)) is converted to the null member pointer value of the destination type. If class B contains the original member, or is a base or derived class of the class containing the original member, the resulting pointer to member points to the original member. Otherwise, the result of the cast is undefined. [Note: although class B need not contain the original member, the dynamic type of the object on which the pointer to member is dereferenced must contain the original member; see [5.5 expr.mptr.oper](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/expr.html#expr.mptr.oper).] > > 11) Function types (including those used in pointer to member function > types) are never cv-qualified; see [8.3.5 dcl.fct](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/decl.html#dcl.fct). In short, you can convert from a derived `D::*` to a base `B::*` if you can convert from a `B::*` to a `D::*`, though you can only use the `B::*` on objects that are of type D or are descended from D.
I'm not 100% sure what you are asking, but here is an example that works with virtual functions: ``` #include <iostream> using namespace std; class A { public: virtual void foo() { cout << "A::foo\n"; } }; class B : public A { public: virtual void foo() { cout << "B::foo\n"; } }; int main() { void (A::*bar)() = &A::foo; (A().*bar)(); (B().*bar)(); return 0; } ```
C++ inheritance and member function pointers
[ "", "c++", "inheritance", "oop", "pointer-to-member", "" ]
No, this is not a question about generics. I have a Factory pattern with several classes with internal constructors (I don't want them being instantiated if not through the factory). My problem is that `CreateInstance` fails with a "No parameterless constructor defined for this object" error unless I pass "true" on the non-public parameter. Example ``` // Fails Activator.CreateInstance(type); // Works Activator.CreateInstance(type, true); ``` I wanted to make the factory generic to make it a little simpler, like this: ``` public class GenericFactory<T> where T : MyAbstractType { public static T GetInstance() { return Activator.CreateInstance<T>(); } } ``` However, I was unable to find how to pass that "true" parameter for it to accept non-public constructors (internal). Did I miss something or it isn't possible?
To get around this, couldnt you just alter your usage as such: ``` public class GenericFactory<T> where T : MyAbstractType { public static T GetInstance() { return Activator.CreateInstance(typeof(T), true); } } ``` Your factory method will still be generic, but the call to the activator will not use the generic overload. But you should still achieve the same results.
If you absolutely require that the constructor be private you can try something like this: ``` public abstract class GenericFactory<T> where T : MyAbstractType { public static T GetInstance() { return (T)Activator.CreateInstance(typeof(T), true); } } ``` Otherwise you're best off adding the new constraint and going that route: ``` public abstract class GenericFactory<T> where T : MyAbstractType, new() { public static T GetInstance() { return new T; } } ``` You're trying to use GenericFactory as a base class for all of your factories rather than writing each from scratch right?
Activator.CreateInstance(string) and Activator.CreateInstance<T>() difference
[ "", "c#", "generics", "design-patterns", "" ]
Which compiles to faster code: "ans = n \* 3" or "ans = n+(n\*2)"? Assuming that n is either an int or a long, and it is is running on a modern Win32 Intel box. Would this be different if there was some dereferencing involved, that is, which of these would be faster? ``` long a; long *pn; long ans; ... *pn = some_number; ans = *pn * 3; ``` Or ``` ans = *pn+(*pn*2); ``` Or, is it something one need not worry about as optimizing compilers are likely to account for this in any case?
IMO such micro-optimization is not necessary unless you work with some exotic compiler. I would put readability on the first place.
It doesn't matter. Modern processors can execute an integer MUL instruction in one clock cycle or less, unlike older processers which needed to perform a series of shifts and adds internally in order to perform the MUL, thereby using multiple cycles. I would bet that ``` MUL EAX,3 ``` executes faster than ``` MOV EBX,EAX SHL EAX,1 ADD EAX,EBX ``` The last processor where this sort of optimization might have been useful was probably the 486. (yes, this is biased to intel processors, but is probably representative of other architectures as well). In any event, any reasonable compiler should be able to generate the smallest/fastest code. So always go with readability first.
Which compiles to faster code: "n * 3" or "n+(n*2)"?
[ "", "c++", "c", "optimization", "compiler-construction", "performance", "" ]
Are **CDATA** tags ever necessary in script tags and if so when? In other words, when and where is this: ``` <script type="text/javascript"> //<![CDATA[ ...code... //]]> </script> ``` preferable to this: ``` <script type="text/javascript"> ...code... </script> ```
A CDATA section is required if you need your document to parse as XML (e.g. when an XHTML page is interpreted as XML) *and you want to be able to write literal `i<10` and `a && b` instead of `i&lt;10` and `a &amp;&amp; b`*, as XHTML will parse the JavaScript code as parsed character data as opposed to character data by default. This is not an issue with scripts that are stored in external source files, but for any inline JavaScript in XHTML you will *probably* want to use a CDATA section. Note that many XHTML pages were never intended to be parsed as XML in which case this will not be an issue. For a good writeup on the subject, see <https://web.archive.org/web/20140304083226/http://javascript.about.com/library/blxhtml.htm>
When browsers treat the markup as XML: ``` <script> <![CDATA[ ...code... ]]> </script> ``` When browsers treat the markup as HTML: ``` <script> ...code... </script> ``` When browsers treat the markup as HTML and you want your XHTML 1.0 markup (for example) to validate. ``` <script> //<![CDATA[ ...code... //]]> </script> ```
When is a CDATA section necessary within a script tag?
[ "", "javascript", "html", "xhtml", "cdata", "" ]
I understand the overall meaning of pointers and references(or at least I think i do), I also understand that when I use **new** I am dynamically allocating memory. My question is the following: If i were to use `cout << &p`, it would display the "virtual memory location" of `p`. Is there a way in which I could manipulate this "virtual memory location?" For example, the following code shows an array of `int`s. If I wanted to show the value of `p[1]` and I knew the "virtual memory location" of `p`, could I somehow do "`&p + 1`" and obtain the value of `p[1]` with `cout << *p`, which will now point to the second element in the array? ``` int *p; p = new int[3]; p[0] = 13; p[1] = 54; p[2] = 42; ```
Sure, you can manipulate the pointer to access the different elements in the array, but you will need to manipulate the content of the pointer (i.e. the address of what p is pointing to), rather than the address of the pointer itself. ``` int *p = new int[3]; p[0] = 13; p[1] = 54; p[2] = 42; cout << *p << ' ' << *(p+1) << ' ' << *(p+2); ``` Each addition (or subtraction) mean the subsequent (prior) element in the array. If p points to a 4 byte variable (e.g. *int* on typical 32-bits PCs) at address say 12345, p+1 will point to 12349, and not 12346. Note you want to change the value of what p contains before dereferencing it to access what it points to.
Not quite. `&p` is the address *of the pointer `p`*. `&p+1` will refer to an address which is one `int*` further along. What you want to do is ``` p=p+1; /* or ++p or p++ */ ``` Now when you do ``` cout << *p; ``` You will get 54. The difference is, `p` contains the *address of the start of the array of ints*, while `&p` is the *address of p*. To move one item along, you need to point further into the *int array*, not further along your stack, which is where `p` lives. If you only had `&p` then you would need to do the following: ``` int **q = &p; /* q now points to p */ *q = *q+1; cout << *p; ``` That will also output 54 if I am not mistaken.
Change pointer to an array to get a specific array element
[ "", "c++", "pointers", "" ]
I have a `String` representation of a date that I need to create a `Date` or `Calendar` object from. I've looked through `Date` and `Calendar` APIs but haven't found anything that can do this other than creating my own ugly parse method. I know there must be a way, does anyone know of a solution?
In brief: ``` DateFormat formatter = new SimpleDateFormat("MM/dd/yy"); try { Date date = formatter.parse("01/29/02"); } catch (ParseException e) { e.printStackTrace(); } ``` See [`SimpleDateFormat` javadoc](http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html) for more. And to turn it into a `Calendar`, do: ``` Calendar calendar = Calendar.getInstance(); calendar.setTime(date); ```
# tl;dr ``` LocalDate.parse( "2015-01-02" ) ``` # java.time Java 8 and later has a new [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) framework that makes these other answers outmoded. This framework is inspired by [Joda-Time](http://www.joda.org/joda-time/), defined by [JSR 310](http://jcp.org/en/jsr/detail?id=310), and extended by the [ThreeTen-Extra](http://www.threeten.org/threeten-extra/) project. See the [Tutorial](http://docs.oracle.com/javase/tutorial/java/TOC.html). The old bundled classes, java.util.Date/.Calendar, are notoriously troublesome and confusing. Avoid them. # `LocalDate` Like Joda-Time, java.time has a class [`LocalDate`](http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html) to represent a date-only value without time-of-day and without time zone. # ISO 8601 If your input string is in the standard [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format of `yyyy-MM-dd`, you can ask that class to directly parse the string with no need to specify a formatter. The ISO 8601 formats are used by default in java.time, for both parsing and generating string representations of date-time values. ``` LocalDate localDate = LocalDate.parse( "2015-01-02" ); ``` # Formatter If you have a different format, specify a formatter from the [java.time.format](http://docs.oracle.com/javase/8/docs/api/java/time/format/package-summary.html) package. You can either specify your own formatting pattern or let java.time automatically localize as appropriate to a `Locale` specifying a human language for translation and cultural norms for deciding issues such as period versus comma. ## Formatting pattern Read the [`DateTimeFormatter`](http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) class doc for details on the codes used in the format pattern. They vary a bit from the old outmoded `java.text.SimpleDateFormat` class patterns. Note how the second argument to the `parse` method is a [method reference](http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html), syntax added to Java 8 and later. ``` String input = "January 2, 2015"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "MMMM d, yyyy" , Locale.US ); LocalDate localDate = LocalDate.parse ( input , formatter ); ``` Dump to console. ``` System.out.println ( "localDate: " + localDate ); ``` > localDate: 2015-01-02 ## Localize automatically Or rather than specify a formatting pattern, let java.time localize for you. Call `DateTimeFormatter.ofLocalizedDate`, and be sure to specify the desired/expected `Locale` rather than rely on the JVM’s current default which can change at any moment during runtime(!). ``` String input = "January 2, 2015"; DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG ); formatter = formatter.withLocale ( Locale.US ); LocalDate localDate = LocalDate.parse ( input , formatter ); ``` Dump to console. ``` System.out.println ( "input: " + input + " | localDate: " + localDate ); ``` > input: January 2, 2015 | localDate: 2015-01-02
How to convert a date String to a Date or Calendar object?
[ "", "java", "date", "calendar", "" ]
Suppose I have two applications written in C#. The first is a third party application that raises an event called "OnEmailSent". The second is a custom app that I've written that I would like to somehow subscribe to the "OnEmailSent" even of the first application. Is there any way that I could somehow attach the second application to an instance of the first application to listen for "OnEmailSent" event? --- So for further clarification, my specific scenario is that we have a custom third party application written in c# that raises an "OnEmailSent" event. We can see the event exists using reflector. What we want to do is have some other actions take place when this component sends an email. The most efficient way we can think of would be to be able to use some form of IPC as anders has suggested and listen for the OnEmailSent event being raised by the third party component. Because the component is written in C# we are toying with the idea of writing another C# application that can attach itself to the executing process and when it detect the OnEmailSent event has been raise it will execute it's own event handling code. --- I might be missing something, but from what I understand of how remoting works is that there would need to be a server defining some sort of contract that the client can subscribe to. I was more thinking about a scenario where someone has written a standalone application like outlook for example, that exposes events that I would like to subscribe to from another application. I guess the scenario I'm thinking of is the .net debugger and how it can attach to executing assemblies to inspect the code whilst it's running.
In order for two applications (separate processes) to exchange events, they must agree on how these events are communicated. There are many different ways of doing this, and exactly which method to use may depend on architecture and context. The general term for this kind of information exchange between processes is [Inter-process Communication (IPC)](http://en.wikipedia.org/wiki/Inter-process_communication). There exists many standard ways of doing IPC, the most common being files, pipes, (network) sockets, [remote procedure calls (RPC)](http://en.wikipedia.org/wiki/Remote_procedure_call) and shared memory. On Windows it's also common to use [window messages](http://msdn.microsoft.com/en-us/library/aa931932.aspx). I am not sure how this works for .NET/C# applications on Windows, but in native Win32 applications you can [hook on to the message loop of external processes and "spy" on the messages they are sending](http://msdn.microsoft.com/en-us/library/ms644990.aspx). If your program generates a message event when the desired function is called, this could be a way to detect it. If you are implementing both applications yourself you can chose to use any IPC method you prefer. Network sockets and higher-level socket-based protocols like HTTP, XML-RPC and SOAP are very popular these days, as they allow you do run the applications on different physical machines as well (given that they are connected via a network).
You can try [Managed Spy](http://msdn.microsoft.com/en-us/magazine/cc163617.aspx) and for programmatic access **ManagedSpyLib** > ManagedSpyLib introduces a class > called ControlProxy. A ControlProxy is > a representation of a > System.Windows.Forms.Control in > another process. ControlProxy allows > you to get or set properties and > subscribe to events as if you were > running inside the destination > process. Use ManagedSpyLib for > automation testing, event logging for > compatibility, cross process > communication, or whitebox testing. But this might not work for you, depends whether ControlProxy can somehow access the event you're after within your third-party application. You could also use [Reflexil](http://www.codeproject.com/KB/msil/reflexil.aspx) > Reflexil allows > IL modifications by using the powerful > Mono.Cecil library written by Jb > EVAIN. Reflexil runs as Reflector plug-in and > is directed especially towards IL code > handling. It accomplishes this by > proposing a complete instruction > editor and by allowing C#/VB.NET code > injection.
Listen for events in another application
[ "", "c#", "events", "delegates", "" ]
In VB.net I'm using the TcpClient to retrieve a string of data. I'm constantly checking the .Connected property to verify if the client is connected but even if the client disconnects this still returns true. What can I use as a workaround for this? This is a stripped down version of my current code: ``` Dim client as TcpClient = Nothing client = listener.AcceptTcpClient do while client.connected = true dim stream as networkStream = client.GetStream() dim bytes(1024) as byte dim numCharRead as integer = stream.Read(bytes,0,bytes.length) dim strRead as string = System.Text.Encoding.ASCII.GetString(bytes,0,i) loop ``` I would have figured at least the GetStream() call would throw an exception if the client was disconnected but I've closed the other app and it still doesn't... Thanks. **EDIT** Polling the Client.Available was suggested but that doesn't solve the issue. If the client is not 'acutally' connected available just returns 0. The key is that I'm trying to allow the connection to stay open and allow me to receive data multiple times over the same socket connection.
When NetworkStream.Read returns 0, then the connection has been closed. [Reference](http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.read(VS.71).aspx): > If no data is available for reading, the NetworkStream.Read method will block until data is available. To avoid blocking, you can use the DataAvailable property to determine if data is queued in the incoming network buffer for reading. If DataAvailable returns true, the Read operation will complete immediately. The Read operation will read as much data as is available, up to the number of bytes specified by the size parameter. **If the remote host shuts down the connection, and all available data has been received, the Read method will complete immediately and return zero bytes.**
Better answer: ``` if (client.Client.Poll(0, SelectMode.SelectRead)) { byte[] checkConn = new byte[1]; if (client.Client.Receive(checkConn, SocketFlags.Peek) == 0) throw new IOException(); } ```
TcpClient.Connected returns true yet client is not connected, what can I use instead?
[ "", "c#", ".net", "vb.net", "sockets", "" ]
I have two unrelated processes that use .NET assemblies as plugins. However, either process can be started/stopped at any time. I can't rely on a particular process being the server. In fact, there may be multiple copies running of one of the processes, but only one of the other. I initially implemented a solution based off of [this article](http://www.developer.com/net/net/article.php/3520891). However, this requires the one implementing the server to be running before the client. Whats the best way to implement some kind of notification to the server when the client(s) were running first?
Using shared memory is tougher because you'll have to manage the size of the shared memory buffer (or just pre-allocate enough). You'll also have to manually manage the data structures that you put in there. Once you have it tested and working though, it will be easier to use and test because of its simplicity. If you go the remoting route, you can use the IpcChannel instead of the TCP or HTTP channels for a single system communication using Named Pipes. <http://msdn.microsoft.com/en-us/library/4b3scst2.aspx>. The problem with this solution is that you'll need to come up with a registry type solution (either in shared memory or some other persistent store) that processes can register their endpoints with. That way, when you're looking for them, you can find a way to query for all the endpoints that are running on the system and you can find what you're looking for. The benefits of going with Remoting are that the serialization and method calling are all pretty straightforward. Also, if you decide to move to multiple machines on a network, you could just flip the switch to use the networking channels instead. The cons are that Remoting can get frustrating unless you clearly separate what are "Remote" calls from what are "Local" calls. I don't know much about WCF, but that also might be worth looking into. Spider sense says that it probably has a more elegant solution to this problem... maybe. Alternatively, you can create a "server" process that is separate from all the other processes and that gets launched (use a system Mutex to make sure more than one isn't launched) to act as a go-between and registration hub for all the other processes. One more thing to look into the Publish-Subscribe model for events (Pub/Sub). This technique helps when you have a listener that is launched before the event source is available, but you don't want to wait to register for the event. The "server" process will handle the event registry to link up the publishers and subscribers.
Why not host the server and the client on both sides, and whoever comes up first gets to be the server? And if the server drops out, the client that is still active switches roles.
.NET IPC without having a service mediator
[ "", "c#", ".net", "windows", "remoting", "ipc", "" ]
I need to send MMS thought a C# application. I have already found 2 interesting components: <http://www.winwap.com> <http://www.nowsms.com> Does anyone have experience with other third party components? Could someone explain what kind of server I need to send those MMS? Is it a classic SMTP Server?
Typically I have always done this using a 3rd party aggregator. The messages are compiled into SMIL, which is the description language for the MMS messages. These are then sent on to the aggregator who will then send them through the MMS gateway of the Network Operator. They are typically charged on a per message basis and the aggregators will buy the messages in a block from the operators. If you are trying to send an MMS message without getting charged then I am not sure how to do this, or if it is possible.
You could do it yourself. Some MMS companies just have a SOAP API that you can call. All you need to do is construct the XML and send it off via a URL. I have done this once before, but can't remember the name of the company I used.
How to send MMS with C#
[ "", "c#", "mms", "" ]
I'd like to use a different icon for the demo version of my game, and I'm building the demo with a different build config than I do for the full verison, using a preprocessor define to lockout some content, use different graphics, etc. Is there a way that I can make Visual Studio use a different icon for the app Icon in the demo config but continue to use the regular icon for the full version's config?
According to [this page](http://msdn.microsoft.com/en-us/library/aa381033(VS.85).aspx) you may use preprocessor directives in your \*.rc file. You should write something like this ``` #ifdef _DEMO_VERSION_ IDR_MAINFRAME ICON "demo.ico" #else IDR_MAINFRAME ICON "full.ico" #endif ```
What I would do is setup a pre-build event (Project properties -> Configuration Properties -> Build Events -> Pre-Build Event). The pre-build event is a command line. I would use this to copy the appropriate icon file to the build icon. For example, let's say your build icon is 'app.ico'. I would make my fullicon 'app\_full.ico' and my demo icon 'app\_demo.ico'. Then I would set my pre-build events as follows: Full mode pre-build event: ``` del app.ico | copy app_full.ico app.ico ``` Demo mode pre-build event: ``` del app.ico | copy app_demo.ico app.ico ``` I hope that helps!
Change app icon in Visual Studio 2005?
[ "", "c++", "visual-studio-2005", "icons", "visual-c++-2005", "" ]
Why isn't [Collection.remove(Object o)](http://java.sun.com/javase/6/docs/api/java/util/Collection.html#remove(java.lang.Object)) generic? Seems like `Collection<E>` could have `boolean remove(E o);` Then, when you accidentally try to remove (for example) `Set<String>` instead of each individual String from a `Collection<String>`, it would be a compile time error instead of a debugging problem later.
Josh Bloch and Bill Pugh refer to this issue in [*Java Puzzlers IV: The Phantom Reference Menace, Attack of the Clone, and Revenge of The Shift*](https://www.youtube.com/watch?v=wDN_EYUvUq0). Josh Bloch says (6:41) that they attempted to generify the get method of Map, remove method and some other, but "it simply didn't work". There are too many reasonable programs that could not be generified if you only allow the generic type of the collection as parameter type. The example given by him is an intersection of a `List` of `Number`s and a `List` of `Long`s.
`remove()` (in `Map` as well as in `Collection`) is not generic because you should be able to pass in any type of object to `remove()`. The object removed does not have to be the same type as the object that you pass in to `remove()`; it only requires that they be equal. From the specification of `remove()`, `remove(o)` removes the object `e` such that `(o==null ? e==null : o.equals(e))` is `true`. Note that there is nothing requiring `o` and `e` to be the same type. This follows from the fact that the `equals()` method takes in an `Object` as parameter, not just the same type as the object. Although, it may be commonly true that many classes have `equals()` defined so that its objects can only be equal to objects of its own class, that is certainly not always the case. For example, the specification for `List.equals()` says that two List objects are equal if they are both Lists and have the same contents, even if they are different implementations of `List`. So coming back to the example in this question, it is possible to have a `Map<ArrayList, Something>` and for me to call `remove()` with a `LinkedList` as argument, and it should remove the key which is a list with the same contents. This would not be possible if `remove()` were generic and restricted its argument type.
Why aren't Java Collections remove methods generic?
[ "", "java", "generics", "collections", "" ]
Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)? What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.
We've used IronPython to build our flagship spreadsheet application (40kloc production code - and it's Python, which IMO means loc per feature is low) at [Resolver Systems](http://www.resolversystems.com/), so I'd definitely say it's ready for production use of complex apps. There are two ways in which this might not be a useful answer to you :-) 1. We're using IronPython, not the more usual CPython. This gives us the huge advantage of being able to use .NET class libraries. I may be setting myself up for flaming here, but I would say that I've never really seen a CPython application that looked "professional" - so having access to the WinForms widget set was a huge win for us. IronPython also gives us the advantage of being able to easily drop into C# if we need a performance boost. (Though to be honest we have *never* needed to do that. All of our performance problems to date have been because we chose dumb algorithms rather than because the language was slow.) Using C# from IP is much easier than writing a C Extension for CPython. 2. We're an Extreme Programming shop, so we write tests before we write code. I would not write production code in a dynamic language without writing the tests first; the lack of a compile step needs to be covered by something, and as other people have pointed out, refactoring without it can be tough. (Greg Hewgill's answer suggests he's had the same problem. On the other hand, I don't think I would write - or especially refactor - production code in *any* language these days without writing the tests first - but YMMV.) Re: the IDE - we've been pretty much fine with each person using their favourite text editor; if you prefer something a bit more heavyweight then [WingIDE](http://www.wingware.com/products) is pretty well-regarded.
You'll find mostly two answers to that – the religous one (Yes! Of course! It's the best language ever!) and the other religious one (you gotta be kidding me! Python? No... it's not mature enough). I will maybe skip the last religion (Python?! Use Ruby!). The truth, as always, is far from obvious. **Pros**: it's easy, readable, batteries included, has lots of good libraries for pretty much everything. It's expressive and dynamic typing makes it more concise in many cases. **Cons**: as a dynamic language, has way worse IDE support (proper syntax completion **requires** static typing, whether explicit in Java or inferred in SML), its object system is far from perfect (interfaces, anyone?) and it is easy to end up with messy code that has methods returning either int or boolean or object or some sort under unknown circumstances. My take – I love Python for scripting, automation, tiny webapps and other simple well defined tasks. In my opinion it is by far **the best** dynamic language on the planet. That said, I would **never** use it **any** dynamically typed language to develop an application of substantial size. Say – it would be fine to use it for Stack Overflow, which has three developers and I guess no more than 30k lines of code. For bigger things – first your development would be super fast, and then once team and codebase grow things are slowing down more than they would with Java or C#. You need to offset lack of compilation time checks by writing more unittests, refactorings get harder cause you never know what your refacoring broke until you run all tests or even the whole big app, etc. Now – decide on how big your team is going to be and how big the app is supposed to be once it is done. If you have 5 or less people and the target size is roughly Stack Overflow, go ahead, write in Python. You will finish in no time and be happy with good codebase. But if you want to write second Google or Yahoo, you will be much better with C# or Java. Side-note on C/C++ you have mentioned: if you are not writing performance critical software (say massive parallel raytracer that will run for three months rendering a film) or a very mission critical system (say Mars lander that will fly three years straight and has only one chance to land right or you lose $400mln) do not use it. For web apps, most desktop apps, most apps in general it is not a good choice. You will die debugging pointers and memory allocation in complex business logic.
Is Python good for big software projects (not web based)?
[ "", "python", "ide", "" ]
This is a follow up question to [This Question](https://stackoverflow.com/questions/85815/how-to-tell-if-a-javascript-function-is-defined). I like (and understand) the solution there. However, in the code I am working in, another way to solve the same problem is used: ``` function exist(sFN) { if(self[sFN]) return true; return false; } ``` It seems to work fine, although I don't understand how. Does it work? How? What are minuses of this approach? Should I switch to solution from the other question?
Your condition is checking the existence of the "sFN" property in the "self" object. Anything that isn't null, undefined, 0, and "" will evaluate to true. As others have said, you can use typeof, or instanceof to see if it's actually a function. Looking at your linked example, you should read up on the difference between ==/!= and ===/!== in javascript. Short answer: ("" == null) is true, ("" === null) is false.
Try this: ``` function exist(sFN) { return (typeof sFN == 'function'); } ```
Tell if a Javascript function is defined by looking at self[name] - is this a good way?
[ "", "javascript", "" ]
Is there a difference between just saying `throw;` and `throw ex;` assuming `ex` is the exception you're catching?
`throw ex;` will erase your stacktrace. Don't do this unless you mean to clear the stacktrace. Just use `throw;`
Here is a simple code snippet that will help illustrate the difference. The difference being that throw ex will reset the stack trace as if the line "`throw ex;`" were the source of the exception. Code: ``` using System; namespace StackOverflowMess { class Program { static void TestMethod() { throw new NotImplementedException(); } static void Main(string[] args) { try { //example showing the output of throw ex try { TestMethod(); } catch (Exception ex) { throw ex; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.WriteLine(); Console.WriteLine(); try { //example showing the output of throw try { TestMethod(); } catch (Exception ex) { throw; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.ReadLine(); } } } ``` Output (notice the different stack trace): > `System.NotImplementedException: The method or operation is not implemented.` > `at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 23` > > `System.NotImplementedException: The method or operation is not implemented.` > `at StackOverflowMess.Program.TestMethod() in Program.cs:line 9` > `at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 43`
Throwing exceptions in ASP.NET C#
[ "", "c#", ".net", "exception", "" ]
We have a case where clients seem to be eternally caching versions of applets. We're making use of the `<param name="cache_version">` tag correctly within our `<object>` tag, or so we think. We went from a version string of `7.1.0.40` to `7.1.0.42` and this triggered a download for only about half of our clients. It doesn't seem to matter which version of the JRE the client is running. We've seen people have this problem on 1.4, 1.5 and 1.6. Does anybody have experience with explicit cache versions? Does it work more reliably (ignoring speed) to instead rely on the `cache_archive`'s "Last-Modified" and/or "Content-Length" values (as per [Sun's Site](http://java.sun.com/j2se/1.4.2/docs/guide/plugin/developer_guide/applet_caching.html))? FYI, object block looks like this: ``` <object> <param name="ARCHIVE" value="foo.jar"> <param name="CODE" value="com.foo.class"> <param name="CODEBASE" value="."> <param name="cache_archive" value="foo.jar"> <param name="cache_version" value="7.1.0.40"> <param name="NAME" value="FooApplet"> <param name="type" value="application/x-java-applet;jpi-version=1.4.2_13"> <param name="scriptable" value="true"> <param name="progressbar" value="true"/> <param name="boxmessage" value="Loading Web Worksheet Applet..."/> </object> ```
Unfortunately, different versions of the Java Plug-In have different caching behaviors. Setting your Cache-Control and Last-Modified HTTP headers is the ideal solution, but it only works under [the most recent versions](http://java.sun.com/javase/6/docs/technotes/guides/deployment/enhancements.html) of the JRE. The only solution GUARANTEED to work is to rename your application jars when their versions change (we've seen strange caching behavior when trying other tricks like adding query strings based on file dates). This isn't so difficult to do if you have a properly automated deployment system.
You can remove applet from Java cache using `Java Control Panel`. For example, on Win XP ``` Start -> Control Panel -> Java -> Temporary Internet Files[View] ```
Java applet cached forever, not downloading new version?
[ "", "java", "caching", "applet", "" ]
At home we have a proxy server. At work we don't. Firefox irritates in this regard: whenever I launch it, it defaults to the proxy server. If I do Tools>Options>Settings and select "No proxy", no problem. However, if I shutdown Firefox and restart it, I have to do the Tools>Options>Settings thing all over again because the "No proxy" setting doesn't "stick". How do I make it stick? Alternatively, can someone suggest a bit of javascript that I can assign to a button on my toolbar which will toggle between the two states?
Use [FoxyProxy](http://foxyproxy.mozdev.org/), much more flexible to configure
The problem was a recent windows-only regression in Firefox. It was hard to track down, basically I got lucky... Here's the meta bug: <https://bugzilla.mozilla.org/show_bug.cgi?id=448634> Here's where the fix was put in. <https://bugzilla.mozilla.org/show_bug.cgi?id=446536> I haven't had time to verify it, my windows system is dead right now, so I have to do it via bugmail.
Proxy settings in Firefox don't "stick"
[ "", "javascript", "firefox", "proxy", "" ]
I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ? ``` from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('YOUR.MAIL.SERVER', 26) smtp.login('USERNAME@DOMAIN', 'PASSWORD') from_addr = "John Doe <john@doe.net>" to_addr = "foo@bar.com" subj = "hello" date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) message_text = "Hello\nThis is a mail from your server\n\nBye\n" msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text ) smtp.sendmail(from_addr, to_addr, msg) smtp.quit() ```
The script I use is quite similar; I post it here as an example of how to use the email.\* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc. I rely on my ISP to add the date time header. My ISP requires me to use a secure smtp connection to send mail, I rely on the smtplib module (downloadable at <http://www1.cs.columbia.edu/~db2501/ssmtplib.py>) As in your script, the username and password, (given dummy values below), used to authenticate on the SMTP server, are in plain text in the source. This is a security weakness; but the best alternative depends on how careful you need (want?) to be about protecting these. ======================================= ``` #! /usr/local/bin/python SMTPserver = 'smtp.att.yahoo.com' sender = 'me@my_email_domain.net' destination = ['recipient@her_email_domain.com'] USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER" PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER" # typical values for text_subtype are plain, html, xml text_subtype = 'plain' content="""\ Test message """ subject="Sent from Python" import sys import os import re from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL) # from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption) # old version # from email.MIMEText import MIMEText from email.mime.text import MIMEText try: msg = MIMEText(content, text_subtype) msg['Subject']= subject msg['From'] = sender # some SMTP servers will do this automatically, not all conn = SMTP(SMTPserver) conn.set_debuglevel(False) conn.login(USERNAME, PASSWORD) try: conn.sendmail(sender, destination, msg.as_string()) finally: conn.quit() except: sys.exit( "mail failed; %s" % "CUSTOM_ERROR" ) # give an error message ```
The method I commonly use...not much different but a little bit ``` import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText msg = MIMEMultipart() msg['From'] = 'me@gmail.com' msg['To'] = 'you@gmail.com' msg['Subject'] = 'simple email in python' message = 'here is the email' msg.attach(MIMEText(message)) mailserver = smtplib.SMTP('smtp.gmail.com',587) # identify ourselves to smtp gmail client mailserver.ehlo() # secure our email with tls encryption mailserver.starttls() # re-identify ourselves as an encrypted connection mailserver.ehlo() mailserver.login('me@gmail.com', 'mypassword') mailserver.sendmail('me@gmail.com','you@gmail.com',msg.as_string()) mailserver.quit() ``` That's it
Sending mail from Python using SMTP
[ "", "python", "smtp", "" ]
Consider the Oracle `emp` table. I'd like to get the employees with the top salary with `department = 20` and `job = clerk`. Also assume that there is no "empno" column, and that the primary key involves a number of columns. You can do this with: ``` select * from scott.emp where deptno = 20 and job = 'CLERK' and sal = (select max(sal) from scott.emp where deptno = 20 and job = 'CLERK') ``` This works, but I have to duplicate the test deptno = 20 and job = 'CLERK', which I would like to avoid. Is there a more elegant way to write this, maybe using a `group by`? BTW, if this matters, I am using Oracle.
The following is slightly over-engineered, but is a good SQL pattern for "top x" queries. ``` SELECT * FROM scott.emp WHERE (deptno,job,sal) IN (SELECT deptno, job, max(sal) FROM scott.emp WHERE deptno = 20 and job = 'CLERK' GROUP BY deptno, job ) ``` Also note that this will work in Oracle and Postgress (i think) but not MS SQL. For something similar in MS SQL see question [SQL Query to get latest price](https://stackoverflow.com/questions/49404/sql-query-to-get-latest-price#49424)
If I was certain of the targeted database I'd go with Mark Nold's solution, but if you ever want some dialect agnostic SQL\*, try ``` SELECT * FROM scott.emp e WHERE e.deptno = 20 AND e.job = 'CLERK' AND e.sal = ( SELECT MAX(e2.sal) FROM scott.emp e2 WHERE e.deptno = e2.deptno AND e.job = e2.job ) ``` \*I believe this should work everywhere, but I don't have the environments to test it.
SQL: aggregate function and group by
[ "", "sql", "oracle", "aggregate", "" ]
I have a large GUI project that I'd like to port to Linux. What is the most recommended framework to utilize for GUI programming in Linux? Are Frameworks such as KDE / Gnome usable for this objective Or is better to use something more generic other than X? I feel like if I chose one of Gnome or KDE, I'm closing the market out for a chunk of the Linux market who have chosen one over the other. (Yes I know there is overlap) Is there a better way? Or would I have to create 2 complete GUI apps to have near 100% coverage? It's not necessary to have a cross-platform solution that will also work on Win32.
Your best bet may be to port it to a cross-platform widget library such as [wxWidgets](http://en.wikipedia.org/wiki/WxWidgets), which would give you portability to any platform wxWidgets supports. It's also important to make the distinction between Gnome libraries and GTK, and likewise KDE libraries and Qt. If you write the code to use GTK or Qt, it should work fine for users of any desktop environment, including less popular ones like XFCE. If you use other Gnome or KDE-specific libraries to do non-widget-related tasks, your app would be less portable between desktop environments.
I recommend [wxWidgets](http://www.wxwidgets.org/) or [Qt](http://www.trolltech.no/). They are both mature, well-structured and cross-platform, with decent documentation and sample source code.
Linux GUI development
[ "", "c++", "linux", "user-interface", "gnome", "kde-plasma", "" ]
I am wondering if it is possible to extract the index position in a given string where a Regex failed when trying to match it? For example, if my regex was "abc" and I tried to match that with "abd" the match would fail at index 2. Edit for clarification. The reason I need this is to allow me to simplify the parsing component of my application. The application is an Assmebly language teaching tool which allows students to write, compile, and execute assembly like programs. Currently I have a tokenizer class which converts input strings into Tokens using regex's. This works very well. For example: The tokenizer would produce the following tokens given the following input = "INP :x:" : ``` Token.OPCODE, Token.WHITESPACE, Token.LABEL, Token.EOL ``` These tokens are then analysed to ensure they conform to a syntax for a given statement. Currently this is done using IF statements and is proving cumbersome. The upside of this approach is that I can provide detailed error messages. I.E ``` if(token[2] != Token.LABEL) { throw new SyntaxError("Expected label");} ``` I want to use a regular expression to define a syntax instead of the annoying IF statements. But in doing so I lose the ability to return detailed error reports. I therefore would at least like to inform the user of WHERE the error occurred.
I agree with Colin Younger, I don't think it is possible with the existing Regex class. However, I think it is doable if you are willing to sweat a little: 1. Get the Regex class source code (e.g. <http://www.codeplex.com/NetMassDownloader> to download the .Net source). 2. Change the code to have a readonly property with the failure index. 3. Make sure your code uses that Regex rather than Microsoft's.
I guess such an index would only have meaning in some simple case, like in your example. If you'll take a regex like "ab\*c\*z" (where by \* I mean any character) and a string "abbbcbbcdd", what should be the index, you are talking about? It will depend on the algorithm used for mathcing... Could fail on "abbbc..." or on "abbbcbbc..."
Regex index in matching string where the match failed
[ "", "c#", "regex", "" ]
What I'm trying to do here is get the headers of a given URL so I can determine the MIME type. I want to be able to see if `http://somedomain/foo/` will return an HTML document or a JPEG image for example. Thus, I need to figure out how to send a HEAD request so that I can read the MIME type without having to download the content. Does anyone know of an easy way of doing this?
**edit**: This answer works, but nowadays you should just use the [requests](http://docs.python-requests.org/en/latest/index.html) library as mentioned by other answers below. --- Use [httplib](https://docs.python.org/2/library/httplib.html). ``` >>> import httplib >>> conn = httplib.HTTPConnection("www.google.com") >>> conn.request("HEAD", "/index.html") >>> res = conn.getresponse() >>> print res.status, res.reason 200 OK >>> print res.getheaders() [('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'Sat, 20 Sep 2008 06:43:36 GMT'), ('content-type', 'text/html; charset=ISO-8859-1')] ``` There's also a `getheader(name)` to get a specific header.
[urllib2](https://docs.python.org/2/library/urllib2.html) can be used to perform a HEAD request. This is a little nicer than using httplib since urllib2 parses the URL for you instead of requiring you to split the URL into host name and path. ``` >>> import urllib2 >>> class HeadRequest(urllib2.Request): ... def get_method(self): ... return "HEAD" ... >>> response = urllib2.urlopen(HeadRequest("http://google.com/index.html")) ``` Headers are available via response.info() as before. Interestingly, you can find the URL that you were redirected to: ``` >>> print response.geturl() http://www.google.com.au/index.html ```
How do you send a HEAD HTTP request in Python 2?
[ "", "python", "python-2.7", "http", "http-headers", "content-type", "" ]
I have the concept of `NodeType`s and `Node`s. A `NodeType` is a bunch of meta-data which you can create `Node` instances from (a lot like the whole Class / Object relationship). I have various `NodeType` implementations and various Node implementations. In my AbstractNodeType (top level for NodeTypes) I have ab abstract `createInstance()` method that will, once implemented by the subclass, creates the correct Node instance: ``` public abstract class AbstractNodeType { // .. public abstract <T extends AbstractNode> T createInstance(); } ``` In my `NodeType` implementations I implement the method like this: ``` public class ThingType { // .. public Thing createInstance() { return new Thing(/* .. */); } } // FYI public class Thing extends AbstractNode { /* .. */ } ``` This is all well and good, but `public Thing createInstance()` creates a warning about type safety. Specifically: > Type safety: The return type Thing for > createInstance() from the type > ThingType needs unchecked conversion > to conform to T from the type > AbstractNodeType **What am I doing wrong to cause such a warning?** **How can I re-factor my code to fix this?** *`@SuppressWarnings("unchecked")` is not good, I wish to fix this by coding it correctly, not ignoring the problem!*
You can just replace `<T extends AbstractNode> T` with `AbstractNode` thanks to the magic of [covariant returns](http://en.wikipedia.org/wiki/Covariant_return_type). `Java 5` added support, but it didn't receive the pub it deserved.
Two ways: (a) Don't use generics. It's probably not necessary in this case. (Although that depends on the code you havn't shown.) (b) Generify AbstractNodeType as follows: ``` public abstract class AbstractNodeType<T extends AbstractNode> { public abstract T createInstance(); } public class ThingType<Thing> { public Thing createInstance() { return new Thing(...); } } ```
Generic Method Type Safety
[ "", "java", "generics", "" ]
There have been some questions about whether or not JavaScript is an object-oriented language. Even a statement, "just because a language has objects doesn't make it OO." Is JavaScript an object-oriented language?
IMO (and it is only an opinion) **the** key characteristic of an object orientated language would be that it would support [*polymorphism*](http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming). Pretty much all dynamic languages do that. The next characteristic would be [*encapsulation*](http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29) and that is pretty easy to do in Javascript also. However in the minds of many it is [*inheritance*](http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29) (specifically implementation inheritance) which would tip the balance as to whether a language qualifies to be called object oriented. Javascript does provide a fairly easy means to inherit implementation via prototyping but this is at the expense of encapsulation. So if your criteria for object orientation is the classic threesome of polymorphism, encapsulation and inheritance then Javascript doesn't pass. **Edit**: The supplementary question is raised "how does prototypal inheritance sacrifice encapsulation?" Consider this example of a non-prototypal approach:- ``` function MyClass() { var _value = 1; this.getValue = function() { return _value; } } ``` The \_value attribute is encapsulated, it cannot be modified directly by external code. We might add a mutator to the class to modify it in a way entirely controlled by code that is part of the class. Now consider a prototypal approach to the same class:- ``` function MyClass() { var _value = 1; } MyClass.prototype.getValue = function() { return _value; } ``` Well this is broken. Since the function assigned to getValue is no longer in scope with \_value it can't access it. We would need to promote \_value to an attribute of `this` but that would make it accessable outside of the control of code written for the class, hence encapsulation is broken. Despite this my vote still remains that Javascript is object oriented. Why? Because given an [OOD](http://en.wikipedia.org/wiki/Object-oriented_design) I can implement it in Javascript.
The short answer is Yes. For more information: From [Wikipedia](http://en.wikipedia.org/wiki/Javascript): > JavaScript is heavily object-based. > Objects are associative arrays, > augmented with prototypes (see below). > Object property names are associative > array keys: obj.x = 10 and obj["x"] = > 10 are equivalent, the dot notation > being merely syntactic sugar. > Properties and their values can be > added, changed, or deleted at > run-time. The properties of an object > can also be enumerated via a for...in > loop. Also, see [this series of articles](http://www.sitepoint.com/article/oriented-programming-1/) about OOP with Javascript.
Is JavaScript object-oriented?
[ "", "javascript", "oop", "" ]
In a custom module for drupal 4.7 I hacked together a node object and passed it to node\_save($node) to create nodes. This hack appears to no longer work in drupal 6. While I'm sure this hack could be fixed I'm curious if there is a standard solution to create nodes without a form. In this case the data is pulled in from a custom feed on another website.
I don't know of a standard API for creating a node pragmatically. But this is what I've gleaned from building a module that does what you're trying to do. 1. Make sure the important fields are set: uid, name, type, language, title, body, filter (see `node_add()` and `node_form()`) 2. Pass the node through `node_object_prepare()` so other modules can add to the $node object.
The best practices method of making this happen is to utilize drupal\_execute. drupal\_execute will run standard validation and basic node operations so that things behave the way the system expects. drupal\_execute has its quirks and is slightly less intuitive than simply a node\_save, but, in Drupal 6, you can utilize drupal\_execute in the following fashion. ``` $form_id = 'xxxx_node_form'; // where xxxx is the node type $form_state = array(); $form_state['values']['type'] = 'xxxx'; // same as above $form_state['values']['title'] = 'My Node Title'; // ... repeat for all fields that you need to save // this is required to get node form submits to work correctly $form_state['submit_handlers'] = array('node_form_submit'); $node = new stdClass(); // I don't believe anything is required here, though // fields did seem to be required in D5 drupal_execute($form_id, $form_state, $node); ```
How do I create a node from a cron job in drupal?
[ "", "php", "drupal", "drupal-6", "" ]
I have been asked to lend a hand on a hobby project that a couple friends are working on, they are using SharpDevelop 3.0 (Beta 2 I think, but it might be Beta 1) is there any hassle for me to install and use this IDE given that I have Visual Studio 2008 installed?
I've had no problems at all, in fact some of the tools in sharpdevelop (like the vb.net -> c# converter) are very nice to have. In addition, there are some good libraries included with sharpdevelop that are also handy (like sharpziplib for zip files) I actually have VS2005, VS2008, SharpDevelop and VisualStudio 6 installed at the moment, and there's more compat problems with MS's tools than with #develop.
They behave very well together, I have had SharpDevelop installed with 2003, 2005 and 2008. No issues at all.
Any problems running SharpDevelop 3.0 and Visual Studio 2008 side by side?
[ "", "c#", "visual-studio", "sharpdevelop", "" ]
In C++, you can specify that a function may or may not throw an exception by using an exception specifier. For example: ``` void foo() throw(); // guaranteed not to throw an exception void bar() throw(int); // may throw an exception of type int void baz() throw(...); // may throw an exception of some unspecified type ``` I'm doubtful about actually using them because of the following: 1. The compiler doesn't really enforce exception specifiers in any rigorous way, so the benefits are not great. Ideally, you would like to get a compile error. 2. If a function violates an exception specifier, I think the standard behaviour is to terminate the program. 3. In VS.Net, it treats throw(X) as throw(...), so adherence to the standard is not strong. Do you think exception specifiers should be used? Please answer with "yes" or "no" and provide some reasons to justify your answer.
No. Here are several examples why: 1. Template code is impossible to write with exception specifications, ``` template<class T> void f( T k ) { T x( k ); x.x(); } ``` The copies might throw, the parameter passing might throw, and `x()` might throw some unknown exception. 2. Exception-specifications tend to prohibit extensibility. ``` virtual void open() throw( FileNotFound ); ``` might evolve into ``` virtual void open() throw( FileNotFound, SocketNotReady, InterprocessObjectNotImplemented, HardwareUnresponsive ); ``` You could really write that as ``` throw( ... ) ``` The first is not extensible, the second is overambitious and the third is really what you mean, when you write virtual functions. 3. Legacy code When you write code which relies on another library, you don't really know what it might do when something goes horribly wrong. ``` int lib_f(); void g() throw( k_too_small_exception ) { int k = lib_f(); if( k < 0 ) throw k_too_small_exception(); } ``` `g` will terminate, when `lib_f()` throws. This is (in most cases) not what you really want. `std::terminate()` should never be called. It is always better to let the application crash with an unhandled exception, from which you can retrieve a stack-trace, than to silently/violently die. 4. Write code that returns common errors and throws on exceptional occasions. ``` Error e = open( "bla.txt" ); if( e == FileNotFound ) MessageUser( "File bla.txt not found" ); if( e == AccessDenied ) MessageUser( "Failed to open bla.txt, because we don't have read rights ..." ); if( e != Success ) MessageUser( "Failed due to some other error, error code = " + itoa( e ) ); try { std::vector<TObj> k( 1000 ); // ... } catch( const bad_alloc& b ) { MessageUser( "out of memory, exiting process" ); throw; } ``` Nevertheless, when your library just throws your own exceptions, you can use exception specifications to state your intent.
Avoid exception specifications in C++. The reasons you give in your question are a pretty good start for why. See Herb Sutter's ["A Pragmatic Look at Exception Specifications"](http://www.gotw.ca/publications/mill22.htm).
Should I use an exception specifier in C++?
[ "", "c++", "function", "exception", "throw", "specifier", "" ]
I have a Google App Engine app - <http://mylovelyapp.appspot.com/> It has a page - mylovelypage For the moment, the page just does `self.response.out.write('OK')` If I run the following Python at my computer: ``` import urllib2 f = urllib2.urlopen("http://mylovelyapp.appspot.com/mylovelypage") s = f.read() print s f.close() ``` it prints "OK" the problem is if I add `login:required` to this page in the app's yaml then this prints out the HTML of the Google Accounts login page I've tried "normal" authentication approaches. e.g. ``` passman = urllib2.HTTPPasswordMgrWithDefaultRealm() auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(None, uri='http://mylovelyapp.appspot.com/mylovelypage', user='billy.bob@gmail.com', passwd='billybobspasswd') opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) ``` But it makes no difference - I still get the login page's HTML back. I've tried [Google's ClientLogin auth API](http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html), but I can't get it to work. ``` h = httplib2.Http() auth_uri = 'https://www.google.com/accounts/ClientLogin' headers = {'Content-Type': 'application/x-www-form-urlencoded'} myrequest = "Email=%s&Passwd=%s&service=ah&source=DALELANE-0.0" % ("billy.bob@gmail.com", "billybobspassword") response, content = h.request(auth_uri, 'POST', body=myrequest, headers=headers) if response['status'] == '200': authtok = re.search('Auth=(\S*)', content).group(1) headers = {} headers['Authorization'] = 'GoogleLogin auth=%s' % authtok.strip() headers['Content-Length'] = '0' response, content = h.request("http://mylovelyapp.appspot.com/mylovelypage", 'POST', body="", headers=headers) while response['status'] == "302": response, content = h.request(response['location'], 'POST', body="", headers=headers) print content ``` I do seem to be able to get some token correctly, but attempts to use it in the header when I call 'mylovelypage' still just return me the login page's HTML. :-( Can anyone help, please? Could I use the [GData client library](http://code.google.com/p/gdata-python-client/) to do this sort of thing? From what I've read, I think it should be able to access App Engine apps, but I haven't been any more successful at getting the authentication working for App Engine stuff there either Any pointers to samples, articles, or even just keywords I should be searching for to get me started, would be very much appreciated. Thanks!
appcfg.py, the tool that uploads data to App Engine has to do exactly this to authenticate itself with the App Engine server. The relevant functionality is abstracted into appengine\_rpc.py. In a nutshell, the solution is: 1. Use the [Google ClientLogin API](http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html) to obtain an authentication token. appengine\_rpc.py does this in [\_GetAuthToken](http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/appengine_rpc.py#180) 2. Send the auth token to a special URL on your App Engine app. That page then returns a cookie and a 302 redirect. Ignore the redirect and store the cookie. appcfg.py does this in [\_GetAuthCookie](http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/appengine_rpc.py#228) 3. Use the returned cookie in all future requests. You may also want to look at [\_Authenticate](http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/appengine_rpc.py#253), to see how appcfg handles the various return codes from ClientLogin, and [\_GetOpener](http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/appengine_rpc.py#397), to see how appcfg creates a urllib2 OpenerDirector that doesn't follow HTTP redirects. Or you could, in fact, just use the AbstractRpcServer and HttpRpcServer classes wholesale, since they do pretty much everything you need.
thanks to Arachnid for the answer - it worked as suggested here is a simplified copy of the code, in case it is helpful to the next person to try! ``` import os import urllib import urllib2 import cookielib users_email_address = "billy.bob@gmail.com" users_password = "billybobspassword" target_authenticated_google_app_engine_uri = 'http://mylovelyapp.appspot.com/mylovelypage' my_app_name = "yay-1.0" # we use a cookie to authenticate with Google App Engine # by registering a cookie handler here, this will automatically store the # cookie returned when we use urllib2 to open http://currentcost.appspot.com/_ah/login cookiejar = cookielib.LWPCookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)) urllib2.install_opener(opener) # # get an AuthToken from Google accounts # auth_uri = 'https://www.google.com/accounts/ClientLogin' authreq_data = urllib.urlencode({ "Email": users_email_address, "Passwd": users_password, "service": "ah", "source": my_app_name, "accountType": "HOSTED_OR_GOOGLE" }) auth_req = urllib2.Request(auth_uri, data=authreq_data) auth_resp = urllib2.urlopen(auth_req) auth_resp_body = auth_resp.read() # auth response includes several fields - we're interested in # the bit after Auth= auth_resp_dict = dict(x.split("=") for x in auth_resp_body.split("\n") if x) authtoken = auth_resp_dict["Auth"] # # get a cookie # # the call to request a cookie will also automatically redirect us to the page # that we want to go to # the cookie jar will automatically provide the cookie when we reach the # redirected location # this is where I actually want to go to serv_uri = target_authenticated_google_app_engine_uri serv_args = {} serv_args['continue'] = serv_uri serv_args['auth'] = authtoken full_serv_uri = "http://mylovelyapp.appspot.com/_ah/login?%s" % (urllib.urlencode(serv_args)) serv_req = urllib2.Request(full_serv_uri) serv_resp = urllib2.urlopen(serv_req) serv_resp_body = serv_resp.read() # serv_resp_body should contain the contents of the # target_authenticated_google_app_engine_uri page - as we will have been # redirected to that page automatically # # to prove this, I'm just gonna print it out print serv_resp_body ```
How do you access an authenticated Google App Engine service from a (non-web) python client?
[ "", "python", "web-services", "google-app-engine", "authentication", "" ]
Can you provide a good example of rule definition language written in C#. Java guys have [JESS](http://herzberg.ca.sandia.gov/), is there anything good for C#?
This page shows some examples of open-source rules engines in C#: <http://csharp-source.net/open-source/rule-engines>
You can use the forward chaining inference engine that is part of Windows Workflow Foundation (.NET 3.5 and higher) The best part is that this has a free runtime licensing. You can use the [Rule Manager](http://www.acumenbusiness.com/products.htm) from Acumen Business and install the Windows Workflow Foundation adapter. Once installed, export the rules as WFRules (\*.rules). A visual studio .NET solution will be generated that shows how the rule engine can be invoked standalone (no workflow is necessary) See also <http://bizknowledge.blogspot.com/search/label/Windows%20Workflow%20Foundation>
Example of c# based rule language?
[ "", "c#", "rule-engine", "" ]
I have a distributed Java application running on 5 application servers. The servers all use the same Oracle 9i database running on a 6th machine. The application need to prefetch a batch of 100 IDs from a sequence. It's relatively easy to do in a single-threaded, non-distributed environment, you can just issue these queries: ``` SELECT seq.nextval FROM dual; ALTER SEQUENCE seq INCREMENT BY 100; SELECT seq.nextval FROM dual; ``` The first select fetches the first sequence ID that the application can use, the second select returns the last one that can be used. Things get way more interesting in a multithreaded environment. You can't be sure that before the second select another thread doesn't increase the sequence by 100 again. This issue can be solved by synchronizing the access on the Java side - you only let one thread begin fetching the IDs at one time. The situation becomes really hard when you can't synchronize because parts of the application doesn't run on the same JVM, not even on the same physical machine. I found some references on forums that others have problems with solving this problem too, but none of the answers are really working not to mention being reasonable. Can the community provide a solution for this problem? Some more information: * I can't really play with the transaction isolation levels. I use JPA and the change would affect the entire application, not only the prefetching queries and that's not acceptable for me. * On PostgreSQL I could do the following: `SELECT setval('seq', NEXTVAL('seq') + n - 1)` * The solution by Matthew works when you can use a fixed increment value (which is perfectly acceptable in my case). However is there a solution when you don't want to fix the size of the increment, but want to adjust it dynamically?
Why not just have the sequence as increment by 100 all the time? each "nextval" gives you 100 sequence numbers to work with ``` SQL> create sequence so_test start with 100 increment by 100 nocache; Sequence created. SQL> select so_test.nextval - 99 as first_seq, so_test.currval as last_seq from dual; FIRST_SEQ LAST_SEQ ---------- ---------- 1 100 SQL> / FIRST_SEQ LAST_SEQ ---------- ---------- 101 200 SQL> / FIRST_SEQ LAST_SEQ ---------- ---------- 201 300 SQL> ``` A note on your example.. Watch out for DDL.. It will produce an implicit commit **Example of commit produced by DDL** ``` SQL> select * from xx; no rows selected SQL> insert into xx values ('x'); 1 row created. SQL> alter sequence so_test increment by 100; Sequence altered. SQL> rollback; Rollback complete. SQL> select * from xx; Y ----- x SQL> ```
Why do you need to fetch the sequence IDs in the first place? In most cases you would insert into a table and return the ID. ``` insert into t (my_pk, my_data) values (mysequence.nextval, :the_data) returning my_pk into :the_pk; ``` It sounds like you are trying to pre-optimize the processing. If you REALLY need to pre-fetch the IDs then just call the sequence 100 times. The entire point of a sequence is that it manages the numbering. You're not supposed to assume that you can get 100 consecutive numbers.
How to prefetch Oracle sequence ID-s in a distributed environment
[ "", "java", "oracle", "" ]
What is the best way to disable `Alt` + `F4` in a c# win form to prevent the user from closing the form? I am using a form as a popup dialog to display a progress bar and I do not want the user to be able to close it.
This does the job: ``` private void Form1_FormClosing(object sender, FormClosingEventArgs e) { e.Cancel = true; } ``` Edit: In response to pix0rs concern - yes you are correct that you will not be able to programatically close the app. However, you can simply remove the event handler for the form\_closing event before closing the form: ``` this.FormClosing -= new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing); this.Close(); ```
If you look at the [value](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.closereason?view=netframework-4.7.2) of `FormClosingEventArgs e.CloseReason`, it will tell you why the form is being closed. You can then decide what to do, the possible values are: **Member name** - Description --- **None** - The cause of the closure was not defined or could not be determined. **WindowsShutDown** - The operating system is closing all applications before shutting down. **MdiFormClosing** - The parent form of this multiple document interface (MDI) form is closing. **UserClosing** - The user is closing the form through the user interface (UI), for example by clicking the Close button on the form window, selecting Close from the window's control menu, or pressing `ALT`+`F4`. **TaskManagerClosing** - The Microsoft Windows Task Manager is closing the application. **FormOwnerClosing** - The owner form is closing. **ApplicationExitCall** - The Exit method of the Application class was invoked.
How to Disable Alt + F4 closing form?
[ "", "c#", ".net", "winforms", "" ]
I'm trying to do a basic "OR" on three fields using a hibernate criteria query. Example ``` class Whatever{ string name; string address; string phoneNumber; } ``` I'd like to build a criteria query where my search string could match "name" or "address" or "phoneNumber".
You want to use `Restrictions.disjuntion()`. Like so ``` session.createCriteria(Whatever.class) .add(Restrictions.disjunction() .add(Restrictions.eq("name", queryString)) .add(Restrictions.eq("address", queryString)) .add(Restrictions.eq("phoneNumber", queryString)) ); ``` See the Hibernate doc [here](http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html#querycriteria-narrowing).
Assuming you have a hibernate session to hand then something like the following should work: ``` Criteria c = session.createCriteria(Whatever.class); Disjunction or = Restrictions.disjunction(); or.add(Restrictions.eq("name",searchString)); or.add(Restrictions.eq("address",searchString)); or.add(Restrictions.eq("phoneNumber",searchString)); c.add(or); ```
How do you "OR" criteria together when using a criteria query with hibernate?
[ "", "java", "hibernate", "" ]
I would like to create an XML-based website. I want to use XML files as datasources since it is a kind of online directory site. Can someone please give me a starting point? Are there any good online resources that I can refer to? I am pretty comfortable with ASP and JavaScript.
If you cannot or don't wish to store your data in XHTML format, then XSLT is definitely the way you want to go. By its very definition, it is a transformation language designed to transform data from one format to another. Because this is it's focus, it provides power, speed and flexibility you won't find in many other solutions. It will also ensure you output standards compliant (X)HTML as it's impossible to do otherwise (well, not without deliberately going out of your way to botch it). MSXML allows you to do XSL transformations for use in Classic ASP - see [this page](http://www.inov8design.com.au/articles/xml_xslt_asp.asp) for an example. [ZVON.org](http://www.zvon.org/xxl/XSLTreference/Output/index.html) is also a great XSLT reference.
Hey, here's an idea - xhtml is xml, after all, so if you can define the format of the xml files, just create browser-friendly xhtml to begin with. Otherwise I'm sure there are XML parsing libraries for ASP and you can look into XSLT (which is cool to learn, but a bit more of a challenge).
XML based website - how to create?
[ "", "javascript", "xml", "asp-classic", "" ]
This is probably a really simple jQuery question, but I couldn't answer it after 10 minutes in the documentation so... I have a list of checkboxes, and I can get them with the selector `'input[type=checkbox]'`. I want the user to be able to shift-click and select a range of checkboxes. To accomplish this, I need to get the index of a checkbox in the list, so I can pass that index to `.slice(start, end)`. How do I get the index when the user clicks a box?
The following selector should also work in jQuery: `input:checkbox`. You can then string the `:gt(index)` and `:lt(index)` filters together, so if you want the 5th to 7th checkboxes, you'd use `input:checkbox:gt(4):lt(2)`. To get the index of the currently clicked checkbox, just use `$("input:checkbox").index($(this))`.
This is a quick solution, but I would give each checkbox a unique ID, perhaps with an index hint, like so: ``` <input id="checkbox-0" type="checkbox" /> <input id="checkbox-1" type="checkbox" /> <input id="checkbox-2" type="checkbox" /> <input id="checkbox-3" type="checkbox" /> <input id="checkbox-4" type="checkbox" /> ``` You can then easily obtain the index: ``` $(document).ready(function() { $("input:checkbox").click(function() { index = /checkbox-(\d+)/.exec(this.id)[1]; alert(index); }); }); ```
jQuery slicing and click events
[ "", "javascript", "jquery", "" ]
I have a winforms application that normally is at about 2-4% CPU. We are seeing some spikes up to 27% of CPU for limited number of times. What is the best profiling tool to determine what is actually causing this spike. We use dottrace but i dont see how to map that to exactly the CPU spikes? Appreciate the help
I've used 2 profiling tools before - RedGate's ANTS profiler, and the built in profiler found in Visual Studio Team System. It's been some time since I used RedGate's (<http://www.red-gate.com/products/ants_profiler/index.htm>) profiler, though I used the built in in Visual Studio 2008 fairly recently. That being said, I felt that the RedGate product felt more intuitive to use. One thing that frustrated me back when I used the RedGate product was that I couldn't instruct the profiler to only profile my code starting at a certain point - I had a performance hit that couldn't be reached until a fair amount of code had already executed and therefore polluted my results. They may have added that feature since then. The built in version for Visual Studio is only available in their very-high end versions of the product. Someone correct me if I am wrong, but I don't think even the "Professional" version has the profiler. I am currently using Team System Developer Edition, which *does* have the code analysis tools. One thing the VS version does do though, is enable you to pause the profiling, and even start your app with profiling paused, so you can really focus on the performance of something very specific. This can be exceedingly helpful when you are trying to understand the analysis results. EDIT: Both tools will show you memory usage, and the number of times a specific method was called, and how much time was spent in each method. What they do not do, to the best of my knowledge, is show you CPU usage at any given point in time. However, there are likely strong correlations between CPU usage and the amount of time spent in a given block of code. If you can duplicate the CPU spikes consistently by invoking certain actions in the APP, then what I would do is try and get my hands on the VS profiler, start the app with profiling pause, enable profiling right before you do whatever typically results in the spike, and examine those results. This assumes of course that you have some sort of deterministic behavior to recreate the spikes. If not ... you might considering threaded processes or garbage collection a candidate for your performance hit.
I’ve found DevPartner from Compuware <http://www.compuware.com/> to be an excellent profiling tool. Unfortunately it looks like at the present time they don’t support VS 2008.
Winform application profiling CPU usage / spikes .
[ "", "c#", "winforms", "performance", "optimization", "cpu", "" ]
I need to implement auto-capitalization inside of a Telerik RadEditor control on an ASPX page as a user types. This can be an IE specific solution (IE6+). I currently capture every keystroke (down/up) as the user types to support a separate feature called "macros" that are essentially short keywords that expand into formatted text. i.e. the macro "so" could auto expand upon hitting spacebar to "stackoverflow". That said, I have access to the keyCode information, as well I am using the TextRange methods to select a word ("so") and expanding it to "stackoverflow". Thus, I have some semblence of context. However, I need to check this context to know whether I should auto-capitalize. This also needs to work regardless of whether a macro is involved. Since I'm monitoring keystrokes for the macros, should I just monitor for punctuation (it's more than just periods that signal a capital letter) and auto-cap the next letter typed, or should I use TextRange and analyze context?
I'm not sure if this is what you're trying to do, but here is a function ([reference](http://individed.com/code/to-title-case/js/to-title-case.js)) to convert a given string to title case: ``` function toTitleCase(str) { return str.replace(/([\w&`'‘’"“.@:\/\{\(\[<>_]+-? *)/g, function(match, p1, index, title){ // ' fix syntax highlighting if (index > 0 && title.charAt(index - 2) != ":" && match.search(/^(a(nd?|s|t)?|b(ut|y)|en|for|i[fn]|o[fnr]|t(he|o)|vs?\.?|via)[ -]/i) > -1) return match.toLowerCase(); if (title.substring(index - 1, index + 1).search(/['"_{([]/) > -1) return match.charAt(0) + match.charAt(1).toUpperCase() + match.substr(2); if (match.substr(1).search(/[A-Z]+|&|[\w]+[._][\w]+/) > -1 || title.substring(index - 1, index + 1).search(/[\])}]/) > -1) return match; return match.charAt(0).toUpperCase() + match.substr(1); }); } ```
Have you tried to apply the [text-transform](http://www.w3.org/TR/CSS2/text.html#caps-prop) CSS style to your controls?
How would you implement auto-capitalization in JavaScript/HTML
[ "", "javascript", "formatting", "text-editor", "" ]
When we compile a dll using \_\_stdcall inside visual studio 2008 the compiled function names inside the dll are. FunctionName Though when we compile the same dll using GCC using wx-dev-cpp GCC appends the number of paramers the function has, so the name of the function using Dependency walker looks like. FunctionName@numberOfParameters or == FunctionName@8 How do you tell GCC compiler to remove @nn from exported symbols in the dll?
\_\_stdcall decorates the function name by adding an underscore to the start, and the number of bytes of parameters to the end (separated by @). So, a function: ``` void __stdcall Foo(int a, int b); ``` ...would become \_Foo@8. If you list the function name (undecorated) in the EXPORTS section of your .DEF file, it is exported undecorated. Perhaps this is the difference?
Just use `-Wl,--kill-at` on the gcc command line, which will pass `--kill-at` to the linker. References: * <http://sourceware.org/binutils/docs/ld/Options.html#Options> * <http://www.geocities.com/yongweiwu/stdcall.htm>
GCC compiling a dll with __stdcall
[ "", "c++", "gcc", "name-decoration", "" ]
My professor did an informal benchmark on a little program and the Java times were: 1.7 seconds for the first run, and 0.8 seconds for the runs thereafter. * Is this due entirely to the loading of the runtime environment into the operating environment ? OR * Is it influenced by Java's optimizing the code and storing the results of those optimizations (sorry, I don't know the technical term for that)?
I agree that the performance difference seen by the poster is most likely caused by disk latency bringing the JRE into memory. The Just In Time compiler (JIT) would not have an impact on performance of a little application. Java 1.6u10 (<http://download.java.net/jdk6/>) touches the runtime JARs in a background process (even if Java isn't running) to keep the data in the disk cache. This significantly decreases startup times (Which is a huge benefit to desktop apps, but probably of marginal value to server side apps). On large, long running applications, the JIT makes a big difference over time - but the amount of time required for the JIT to accumulate sufficient statistics to kick in and optimize (5-10 seconds) is very, very short compared to the overall life of the application (most run for months and months). While storing and restoring the JIT results is an interesting academic exercise, the practical improvement is not very large (Which is why the JIT team has been more focused on things like GC strategies for minimizing memory cache misses, etc...). The pre-compilation of the runtime classes does help desktop applications quite a bit (as does the aforementioned 6u10 disk cache pre-loading).
Okay, I found where I read that. This is all from "Learning Java" (O'Reilly 2005): > The problem with a traditional JIT compilation is that optimizing code takes time. So a JIT compiler can produce decent results but may suffer a significant latency when the application starts up. This is generally not a problem for long-running server-side applications but is a serious problem for client-side software and applications run on smaller devices with limited capabilities. To address this, Sun's compiler technology, called HotSpot, uses a trick called adaptive compilation. If you look at what programs actually spend their time doing, it turns out that they spend almost all their time executing a relatively small part of the code again and again. The chunk of code that is executed repeatedly may be only a small fraction of the total program, but its behavior determines the program's overall performance. Adaptive compilation also allows the Java runtime to take advantage of new kinds of optimizations that simply can't be done in a statically compiled language, hence the claim that Java code can run faster than C/C++ in some cases. > > To take advantage of this fact, HotSpot starts out as a normal Java bytecode interpreter, but with a difference: it measures (profiles) the code as it is executing to see what parts are being executed repeatedly. Once it knows which parts of the code are crucial to performance, HotSpot compiles those sections into optimal native machine code. Since it compiles only a small portion of the program into machine code, it can afford to take the time necessary to optimize those portions. The rest of the program may not need to be compiled at all—just interpreted—saving memory and time. In fact, Sun's default Java VM can run in one of two modes: client and server, which tell it whether to emphasize quick startup time and memory conservation or flat out performance. > > A natural question to ask at this point is, Why throw away all this good profiling information each time an application shuts down? Well, Sun has partially broached this topic with the release of Java 5.0 through the use of shared, read-only classes that are stored persistently in an optimized form. This significantly reduces both the startup time and overhead of running many Java applications on a given machine. The technology for doing this is complex, but the idea is simple: optimize the parts of the program that need to go fast, and don't worry about the rest. I'm kind of wondering how far Sun has gotten with it since Java 5.0.
Does Java save its runtime optimizations?
[ "", "java", "optimization", "caching", "" ]
I want a splash screen to show while the application is loading. I have a form with a system tray control tied to it. I want the splash screen to display while this form loads, which takes a bit of time since it's accessing a web service API to populate some drop-downs. I also want to do some basic testing for dependencies before loading (that is, the web service is available, the configuration file is readable). As each phase of the startup goes, I want to update the splash screen with progress. I have been reading a lot on threading, but I am getting lost on where this should be controlled from (the `main()` method?). I am also missing how `Application.Run()` works, is this where the threads for this should be created from? Now, if the form with the system tray control is the "living" form, should the splash come from there? Wouldn't it not load until the form is completed anyway? I'm not looking for a code handout, more of an algorithm/approach so I can figure this out once and for all :)
Well, for a ClickOnce app that I deployed in the past, we used the `Microsoft.VisualBasic` namespace to handle the splash screen threading. You can reference and use the `Microsoft.VisualBasic` assembly from C# in .NET 2.0 and it provides a lot of nice services. 1. Have the main form inherit from `Microsoft.VisualBasic.WindowsFormsApplicationBase` 2. Override the "OnCreateSplashScreen" method like so: ``` protected override void OnCreateSplashScreen() { this.SplashScreen = new SplashForm(); this.SplashScreen.TopMost = true; } ``` Very straightforward, it shows your SplashForm (which you need to create) while loading is going on, then closes it automatically once the main form has completed loading. This really makes things simple, and the `VisualBasic.WindowsFormsApplicationBase` is of course well tested by Microsoft and has a lot of functionality that can make your life a lot easier in Winforms, even in an application that is 100% C#. At the end of the day, it's all IL and `bytecode` anyway, so why not use it?
The trick is to to create separate thread responsible for splash screen showing. When you run you app .net creates main thread and loads specified (main) form. To conceal hard work you can hide main form until loading is done. Assuming that Form1 - is your main form and SplashForm is top level, borderles nice splash form: ``` private void Form1_Load(object sender, EventArgs e) { Hide(); bool done = false; ThreadPool.QueueUserWorkItem((x) => { using (var splashForm = new SplashForm()) { splashForm.Show(); while (!done) Application.DoEvents(); splashForm.Close(); } }); Thread.Sleep(3000); // Emulate hardwork done = true; Show(); } ```
Multi-threaded splash screen in C#?
[ "", "c#", ".net", "winforms", "multithreading", "splash-screen", "" ]
Is there a way to mock object construction using JMock in Java? For example, if I have a method as such: ``` public Object createObject(String objectType) { if(objectType.equals("Integer") { return new Integer(); } else if (objectType.equals("String") { return new String(); } } ``` ...is there a way to mock out the expectation of the object construction in a test method? I'd like to be able to place expectations that certain constructors are being called, rather than having an extra bit of code to check the type (as it won't always be as convoluted and simple as my example). So instead of: ``` assertTrue(a.createObject() instanceof Integer); ``` I could have an expectation of the certain constructor being called. Just to make it a bit cleaner, and express what is actually being tested in a more readable way. Please excuse the simple example, the actual problem I'm working on is a bit more complicated, but having the expectation would simplify it. --- For a bit more background: I have a simple factory method, which creates wrapper objects. The objects being wrapped can require parameters which are difficult to obtain in a test class (it's pre-existing code), so it is difficult to construct them. Perhaps closer to what I'm actually looking for is: is there a way to mock an entire class (using CGLib) in one fell swoop, without specifying every method to stub out? So the mock is being wrapped in a constructor, so obviously methods can be called on it, is JMock capable of dynamically mocking out each method? My guess is no, as that would be pretty complicated. But knowing I'm barking up the wrong tree is valuable too :-)
The only thing I can think of is to have the create method on at factory object, which you would than mock. But in terms of mocking a constructor call, no. Mock objects presuppose the existence of the object, whereas a constructor presuppose that the object doesn't exist. At least in java where allocation and initialization happen together.
jmockit can do this. See my answer in <https://stackoverflow.com/questions/22697#93675>
How to mock object construction?
[ "", "java", "tdd", "junit", "mocking", "" ]
This is probably a silly question, but curiosity has gotten the better of me. I've been seeing code lately that seems to "reverse" the order of expressions for relational operators e.g.: ``` if (0 == someVariable) ``` As opposed to what I normally see/write: ``` if (someVariable == 0) ``` To me, the second method seems more readable and intuitive, so I'm wondering if there's some reason I'm seeing the first method? Logically, both statements evaluate to the same result, so is it just a matter of personal preference how they're written?
I understand that this is personal preference. Although by putting the variable second you can ensure that you don't accidentally assign the constant to the variable which used to concearn c developers. This is probably why you are seeing it in c# as developers switch language.
Order does not matter, however, the former implies that it s the zero you're checking. Convention dictates the use of hte latter.
relational operator expression order
[ "", "c#", "operators", "logical-operators", "" ]
How do you unit test a large MFC UI application? We have a few large MFC applications that have been in development for many years, we use some standard automated QA tools to run basic scripts to check fundamentals, file open etc. These are run by the QA group post the daily build. But we would like to introduce procedures such that individual developers can build and run tests against dialogs, menus, and other visual elements of the application before submitting code to the daily build. I have heard of such techniques as hidden test buttons on dialogs that only appear in debug builds, are there any standard toolkits for this. Environment is C++/C/FORTRAN, MSVC 2005, Intel FORTRAN 9.1, Windows XP/Vista x86 & x64.
It depends on how the App is structured. If logic and GUI code is separated (MVC) then testing the logic is easy. Take a look at Michael Feathers ["Humble Dialog Box"](https://web.archive.org/web/20080509080327/http://www.objectmentor.com/resources/articles/TheHumbleDialogBox.pdf "Humble Dialog Box") (PDF). EDIT: If you think about it: You should very carefully refactor if the App is not structured that way. There is no other technique for testing the logic. Scripts which simulate clicks are just scratching the surface. It is actually pretty easy: Assume your control/window/whatever changes the contents of a listbox when the user clicks a button and you want to make sure the listbox contains the right stuff after the click. 1. Refactor so that there is a separate list with the items for the listbox to show. The items are stored in the list and are not extracted from whereever your data comes from. The code that makes the listbox list things knows only about the new list. 2. Then you create a new controller object which will contain the logic code. The method that handles the button click only calls mycontroller->ButtonWasClicked(). It does not know about the listbox or anythings else. 3. MyController::ButtonWasClicked() does whats need to be done for the intended logic, prepares the item list and tells the control to update. For that to work you need to decouple the controller and the control by creating a interface (pure virtual class) for the control. The controller knows only an object of that type, not the control. Thats it. The controller contains the logic code and knows the control only via the interface. Now you can write regular unit test for MyController::ButtonWasClicked() by mocking the control. If you have no idea what I am talking about, read Michaels article. Twice. And again after that. (Note to self: must learn not to blather that much)
Since you mentioned MFC, I assumed you have an application that would be hard to get under an automated test harness. You'll observe best benefits of unit testing frameworks when you build tests as you write the code.. But trying to add a new feature in a test-driven manner to an application which is not designed to be testable.. can be hard work and well frustrating. Now what I am going to propose is definitely **hard work**.. but with some discipline and perseverance you'll see the benefit soon enough. * First you'll need some management backing for new fixes to take a bit longer. Make sure everyone understands why. * Next buy a copy of the [WELC book](https://rads.stackoverflow.com/amzn/click/com/0131177052). Read it cover to cover if you have the time OR if you're hard pressed, scan the index to find the symptom your app is exhibiting. This book contains a lot of good advice and is just what you need when trying to get existing code testable. [![alt text](https://i.stack.imgur.com/cyn4R.jpg)](https://i.stack.imgur.com/cyn4R.jpg) * Then for every new fix/change, spend some time and understand the area you're going to work on. Write some tests in a xUnit variant of your choice (freely available) to exercise current behavior. * Make sure all tests pass. Write a new test which exercises needed behavior or the bug. * Write code to make this last test pass. * Refactor mercilessly within the area under tests to improve design. * Repeat for every new change that you have to make to the system from here on. No exceptions to this rule. * Now *the promised land*: Soon ever growing islands of well tested code will begin to surface. More and more code would fall under the automated test suite and changes will become progressively easier to make. And that is because slowly and surely the underlying design becomes more testable. The easy way out was my previous answer. This is the difficult but right way out.
Unit testing MFC UI applications?
[ "", "c++", "unit-testing", "user-interface", "mfc", "tdd", "" ]