Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm looking for (arguably) the correct way to return data from a `XmlHttpRequest`. Options I see are: * **Plain HTML**. Let the request format the data and return it in a usable format. *Advantage*: easy to consume by the calling page. *Disadvantage*: Very rigid, stuck with a fixed layout. * **XML**. Let the r...
If you're looking for a quick solution that should work with most available frameworks, I'd go for JSON. It's easy to start with and works. If you're trying to build a larger application that you're going to extend (in terms of size or maybe your own API for 3rd party extensions) I'd go for XML. You could write a prox...
I'd agree with John Topley - it depends on the application. There's a good article on quirksmode that discusses the advantages and disadvantages of each format that you might want to read: <http://www.quirksmode.org/blog/archives/2005/12/the_ajax_respon.html>
XmlHttpRequest return values
[ "", "javascript", "ajax", "" ]
I know you can look at the row.count or tables.count, but are there other ways to tell if a dataset is empty?
I would suggest something like:- ``` bool nonEmptyDataSet = dataSet != null && (from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any(); ``` **Edits:** I have significantly cleaned up the code after due consideration, I think this is much cleaner. Many thanks to Keith for the inspiration rega...
What's wrong with (aDataSet.Tables.Count == 0) ?
In C#, what is the best way to test if a dataset is empty?
[ "", "c#", ".net", "" ]
I need to enable/disable completely network interfaces from a script in Windows XP. I'm looking for a python solution, but any general way (eg WMI, some command-line à la netsh, some windows call) is welcome and will be adjusted. Thanks.
Using the netsh interface Usage set interface [name = ] IfName [ [admin = ] ENABLED|DISABLED [connect = ] CONNECTED|DISCONNECTED [newname = ] NewName ] Try including everything inside the outer brackets: netsh interface set interface name="thename" admin=disabled connect=DISCONNECTED newname="thename" See also this M...
So far I've found the following Python solution: ``` >>> import wmi; c=wmi.WMI() >>> o=c.query("select * from Win32_NetworkAdapter where NetConnectionID='wifi'")[0] >>> o.EnableDevice(1) (-2147217407,) ``` which is translated, AFAIU, to the generic WMI error 0x80041001. Could be permissions.
How to programmatically enable/disable network interfaces? (Windows XP)
[ "", "python", "networking", "windows-xp", "" ]
I want to apply an XSLT Stylesheet to an XML Document using C# and write the output to a File.
I found a possible answer here: <http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63> From the article: ``` XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ; XslTransform myXslTrans = new XslTransform() ; myXslTrans.Load(myStyleSheet); XmlTextWriter myW...
Based on Daren's excellent answer, note that this code can be shortened significantly by using the appropriate [XslCompiledTransform.Transform overload](http://msdn.microsoft.com/en-us/library/ms163431.aspx): ``` var myXslTrans = new XslCompiledTransform(); myXslTrans.Load("stylesheet.xsl"); myXslTrans.Transform("so...
How to apply an XSLT Stylesheet in C#
[ "", "c#", "xml", "xslt", "" ]
How do you tell if a function in JavaScript is defined? I want to do something like this ``` function something_cool(text, callback) { alert(text); if( callback != null ) callback(); } ``` But it gets me a > callback is not a function error when callback is not defined.
``` typeof callback === "function" ```
All of the current answers use a literal string, which I prefer to not have in my code if possible - this does not (and provides valuable semantic meaning, to boot): ``` function isFunction(possibleFunction) { return typeof(possibleFunction) === typeof(Function); } ``` Personally, I try to reduce the number of stri...
How to tell if a JavaScript function is defined
[ "", "javascript", "reflection", "" ]
Does anyone have, or know of, a binary patch generation algorithm implementation in C#? Basically, compare two files (designated *old* and *new*), and produce a patch file that can be used to upgrade the *old* file to have the same contents as the *new* file. The implementation would have to be relatively fast, and w...
Sorry I couldn't be more help. I would definately keep looking at xdelta because I have used it a number of times to produce quality diffs on 600MB+ ISO files we have generated for distributing our products and it performs very well.
[bsdiff](http://www.daemonology.net/bsdiff/) was designed to create very small patches for binary files. As stated on its page, it requires `max(17*n,9*n+m)+O(1)` bytes of memory and runs in `O((n+m) log n)` time (where `n` is the size of the old file and `m` is the size of the new file). The original implementation i...
Binary patch-generation in C#
[ "", "c#", "file", "patch", "" ]
I'm writing C# code that uses the windows IP Helper API. One of the functions I'm trying to call is "[GetBestInterface](http://msdn.microsoft.com/en-us/library/aa365920(VS.85).aspx)" that takes a 'uint' representation of an IP. What I need is to parse a textual representation of the IP to create the 'uint' representati...
MSDN [says](http://msdn.microsoft.com/en-us/library/system.net.ipaddress.getaddressbytes.aspx) that IPAddress.Address property (which returns numeric representation of IP address) is obsolete and you should use [GetAddressBytes](http://msdn.microsoft.com/en-us/library/system.net.ipaddress.getaddressbytes.aspx) method. ...
Shouldn't it be: ``` var ipAddress = IPAddress.Parse("some.ip.address"); var ipBytes = ipAddress.GetAddressBytes(); var ip = (uint)ipBytes [0] << 24; ip += (uint)ipBytes [1] << 16; ip += (uint)ipBytes [2] <<8; ip += (uint)ipBytes [3]; ``` ?
How do you parse an IP address string to a uint value in C#?
[ "", "c#", ".net", "winapi", "networking", "iphelper", "" ]
Is it possible to use gcov for coverage testing of multi-threaded applications? I've set some trivial tests of our code-base up, but it would be nice to have some idea of the coverage we're achieving. If gcov isn't appropriate can anyone recommend an alternative tool (possible oprofile), ideally with some good documen...
We've certainly used gcov to get coverage information on our multi-threaded application. You want to compile with gcc 4.3 which can do coverage on dynamic code. You compile with the `-fprofile-arcs -ftest-coverage` options, and the code will generate .gcda files which gcov can then process. We do a separate build of...
Gcov works fine for multi-threaded apps. The instrumentation architecture is properly serialized so you will get coverage data of good fidelity. I would suggest using gcov in conjunction with [lcov](http://ltp.sourceforge.net/coverage/lcov.php). This will give you great reports scoped from full project down to individ...
GCOV for multi-threaded apps
[ "", "c++", "testing", "code-coverage", "" ]
In Python you can use [StringIO](https://docs.python.org/library/struct.html) for a file-like buffer for character data. [Memory-mapped file](https://docs.python.org/library/mmap.html) basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is ...
You are probably looking for [io.BytesIO](http://docs.python.org/release/3.1.3/library/io.html#binary-i-o) class. It works exactly like StringIO except that it supports binary data: ``` from io import BytesIO bio = BytesIO(b"some initial binary data: \x00\x01") ``` StringIO will throw TypeError: ``` from io import S...
As long as you don't try to put any unicode data into your `StringIO` and you are careful NOT to use `cStringIO` you should be fine. According to the [StringIO](https://docs.python.org/library/stringio.html) documentation, as long as you keep to either unicode or 8-bits everything works as expected. Presumably, `Strin...
Binary buffer in Python
[ "", "python", "binary", "io", "buffer", "" ]
Is it possible to create images with PHP (as opposed to simply linking to them via HTML) and if so, where should I go first to learn about such a thing?
I prefer the [GD library](http://www.php.net/gd) - check out [the Examples](http://www.php.net/manual/en/image.examples.php), and this example: ``` <?php header ("Content-type: image/png"); $im = @imagecreatetruecolor(120, 20) or die("Cannot Initialize new GD image stream"); $text_color = imagecolorallocate($im,...
Yes this is possible. I believe there are multiple libraries to accomplish this. The most widely used is probably [ImageMagick](http://www.imagemagick.org/script/index.php) which is actually not PHP specific but comes with appropriate bindings. See also in the [PHP documentation](http://php.net/imagick).
How to create images in PHP
[ "", "php", "image", "" ]
I did a lot of PHP programming in the last years and one thing that keeps annoying me is the weak support for Unicode and multibyte strings (to be sure, natively there is none). For example, "htmlentities" seems to be a much used function in the PHP world and I found it to be absolutely annoying when you've put an effo...
Named entities in "real" XHTML (i.e. with `application/xhtml+xml`, rather than the more frequently-used `text/html` compatibility mode) are discouraged. Aside from the five defined in XML itself (`&lt;`, `&gt;`, `&amp;`, `&quot;`, `&apos;`), they'd all have to be defined in the DTD of the particular DocType you're usin...
If using XHTML, it's actually recommended not to use named entities ([citation needed]). Some browsers (Firefox …), when parsing this as XML (which they normally don't), don't read the DTD files and thus are unable to handle the entities. As it's best practice anyway to use UTF-8 as encoding if there are no compelling...
Are named entities in HTML still necessary in the age of Unicode aware browsers?
[ "", "php", "html", "unicode", "internationalization", "" ]
I have a solution with many projects. One project contain few custom components. One of these components is used to display a title on an image. We can change the color of the background and many other things. The problem is IF I decide to change the default color of the background of the component or change the posit...
This is most likely due to **[references](http://msdn.microsoft.com/en-us/library/z6609kte.aspx)**. Your other projects probably **[copy in a reference](http://msdn.microsoft.com/en-us/library/ms169644.aspx)** to your component project. You'll have to rebuild these other projects for them to re-copy in the referenced ...
My guess is that the designer is smart and remembers the settings for the component as you have it in the designer and thus sees it as the default.
C# component do not refresh when source code updated
[ "", "c#", ".net", "custom-component", "" ]
I have two arrays of animals (for example). ``` $array = array( array( 'id' => 1, 'name' => 'Cat', ), array( 'id' => 2, 'name' => 'Mouse', ) ); $array2 = array( array( 'id' => 2, 'age' => 321, ), array( 'id' => 1, 'age' => 123...
This does what Erik suggested (id no. as array key) and merges vlaues in `$array2` to `$results`. ``` $results = array(); foreach($array as $subarray) { $results[$subarray['id']] = array('name' => $subarray['name']); } foreach($array2 as $subarray) { if(array_key_exists($subarray['id'], $results)) { ...
@Andy > <http://se.php.net/array_merge> That was my first thought but it doesn't quite work - however [array\_merge\_recursive](http://www.php.net/manual/en/function.array-merge-recursive.php) might work - too lazy to check right now.
How can I merge PHP arrays?
[ "", "php", "arrays", "" ]
I'm rewriting an old application and use this as a good opportunity to try out C# and .NET development (I usually do a lot of plug-in stuff in C). The application is basically a timer collecting data. It has a start view with a button to start the measurement. During the measurement the app has five different views de...
Creating a bunch of overlaid panels is a design-time nightmare. I would suggest using a tab control with each "view" on a separate tab, and then picking the correct tab at runtime. You can avoid showing the tab headers by putting something like this in your form's Load event: ``` tabControl1.Top = tabControl1.Top - t...
What I do is to have a Panel where your different views will sit on the main form. then create user controls for your different views. Then when I want to switch between a'view' you dock it to Panel on the main form.. code looks a little like this. i preffer this because you can then reuse your views, like if you wan...
Building C# .NET windows application with multiple views
[ "", "c#", ".net", "windows", "" ]
I have an image and on it are logos (it's a map), I want to have a little box popup with information about that logo's location when the user moves their mouse over said logo. Can I do this without using a javascript framework and if so, are there any small libraries/scripts that will let me do such a thing?
Yes, you can do this without Javascript. Use an HTML image map, with title attributes, like this: ``` <img usemap="#logo" src="http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png"> <map name="logo"> <area shape="rect" href="" coords="52,42,121,65" title="Stack"> <area shape="rect" href="" coords="122,42,24...
The [`title`](http://www.w3.org/TR/html4/struct/global.html#h-7.4.3) attribute is the simplest solution and guaranteed to work, *and* degrade gracefully for useragents that don't support it correctly.
Tooltips on an image
[ "", "javascript", "html", "" ]
There are similar question, but not regarding C# libraries I can use in my source code. Thank you all for your help. I've already saw lucene, but I need something more easy to search for similar strings and without the overhead of the indexing part. The answer I marked has got two very easy algorithms, and one uses ...
Levenshtein distance implementation: * [Using LINQ](http://www.dotnetperls.com/levenshtein) (not really, see comments) * [Not using LINQ](http://web.archive.org/web/20110720094521/http://www.merriampark.com/ldcsharp.htm) I have a .NET 1.1 project in which I use the latter. It's simplistic, but works perfectly for wha...
you can also look at the very impressive library titled Sam's String Metrics <https://github.com/StefH/SimMetrics.Net> . this includes a host of algorithms. * Hamming distance * Levenshtein distance * Needleman-Wunch distance or Sellers Algorithm * Smith-Waterman distance * Gotoh Distance or Smith-Waterman-Gotoh dista...
Are there any Fuzzy Search or String Similarity Functions libraries written for C#?
[ "", "c#", ".net", "string", "comparison", "" ]
I've been doing some HTML scraping in PHP using regular expressions. This works, but the result is finicky and fragile. Has anyone used any packages that provide a more robust solution? A config driven solution would be ideal, but I'm not picky.
I would recomend [PHP Simple HTML DOM Parser](https://sourceforge.net/projects/simplehtmldom/) after you have scraped the HTML from the page. It supports invalid HTML, and provides a very easy way to handle HTML elements.
If the page you're scraping is valid X(HT)ML, then any of [PHP's built-in XML parsers](http://www.php.net/manual/en/refs.xml.php) will do. I haven't had much success with PHP libraries for scraping. If you're adventurous though, you can try [simplehtmldom](https://sourceforge.net/projects/simplehtmldom/). I'd recommen...
HTML Scraping in Php
[ "", "php", "html", "screen-scraping", "" ]
It seems to me that it would work perfectly well to do tail-recursion optimization in both C and C++, yet while debugging I never seem to see a frame stack that indicates this optimization. That is kind of good, because the stack tells me how deep the recursion is. However, the optimization would be kind of nice as wel...
**All current mainstream compilers perform tail call optimisation** fairly well (and have done for more than a decade), [even for mutually recursive calls](https://godbolt.org/g/TjqTHV) such as: ``` int bar(int, int); int foo(int n, int acc) { return (n == 0) ? acc : bar(n - 1, acc + 2); } int bar(int n, int acc...
As well as the obvious (compilers don't do this sort of optimization unless you ask for it), there is a complexity about tail-call optimization in C++: destructors. Given something like: ``` int fn(int j, int i) { if (i <= 0) return j; Funky cls(j,i); return fn(j, i-1); } ``` The compiler ...
Which, if any, C++ compilers do tail-recursion optimization?
[ "", "c++", "optimization", "tail-recursion", "" ]
I see 2 main ways to set events in JavaScript: 1. Add an event directly inside the tag like this: `<a href="" onclick="doFoo()">do foo</a>` 2. Set them by JavaScript like this: `<a id="bar" href="">do bar</a>` and add an event in a `<script>` section inside the `<head>` section or in an external JavaScript fi...
In my experience, there are two major points to this: 1) The most important thing is to be consistent. I don't think either of the two methods is necessarily easier to read, as long as you stick to it. I only get confused when both methods are used in a project (or even worse on the same page) because then I have to s...
> I think the first method is easier to read and maintain I've found the opposite to be true. Bear in mind that sometimes more than one event handler will be bound to a given control. Declaring all events in one central place helps to organize the actions taking place on the site. If you need to change something you ...
What is the best way to add an event in JavaScript?
[ "", "javascript", "html", "events", "event-binding", "" ]
I would like to extract the date a jpg file was created. Java has the lastModified method for the File object, but appears to provide no support for extracting the created date from the file. I believe the information is stored within the file as the date I see when I hover the mouse pointer over the file in Win XP is ...
The information is stored within the image in a format called [EXIF](http://en.wikipedia.org/wiki/Exchangeable_image_file_format) or [link text](http://www.exif.org). There several libraries out there capable of reading this format, like [this one](http://www.drewnoakes.com/code/exif/)
The date is stored in the [EXIF](http://en.wikipedia.org/wiki/Exif) data in the jpeg. There's a [java library](http://www.drewnoakes.com/code/exif/) and a [viewer in java](http://sourceforge.net/projects/jexifviewer/) that might be helpful.
How to get date picture created in java
[ "", "java", "date", "" ]
My team is currently trying to automate the deployment of our .Net and PHP web applications. We want to streamline deployments, and to avoid the hassle and many of the headaches caused by doing it manually. We require a solution that will enable us to: ``` - Compile the application - Version the application with ...
Thank you all for your kind suggestions. We checked them all out, but after careful consideration we decided to roll our own with a combination of CruiseControl, NAnt, MSBuild and MSDeploy. This article has some great information: [Integrating MSBuild with CruiseControl.NET](http://dougrohm.com/blog/post/2006/01/29/In...
I have used [Visual Build Pro](http://www.kinook.com/VisBuildPro/) for years, It's quite slick and easy to use and has many standard operations (like the ones you mentioned) built in.
Automate Deployment for Web Applications?
[ "", ".net", "php", "deployment", "web-applications", "" ]
What is the proper way for an MFC application to cleanly close itself?
Programatically Terminate an MFC Application ``` void ExitMFCApp() { // same as double-clicking on main window close box ASSERT(AfxGetMainWnd() != NULL); AfxGetMainWnd()->SendMessage(WM_CLOSE); } ``` <http://support.microsoft.com/kb/117320>
``` AfxGetMainWnd()->PostMessage(WM_CLOSE); ```
How can an MFC application terminate itself?
[ "", "c++", "visual-c++", "mfc", "" ]
I've made many different seperate parts of a GUI system for the Nintendo DS, like buttons and textboxes and select boxes, but I need a way of containing these classes in one Gui class, so that I can draw everything to the screen all at once, and check all the buttons at once to check if any are being pressed. My questi...
This question is very similar to one I was going to post, only mine is for Sony PSP programming. I've been toying with something for a while, I've consulted some books and [VTMs](http://www.3dbuzz.com/xcart/product.php?productid=30&cat=12&page=1), and so far this is a rough idea of a simple ui systems. ``` class uiEl...
For anyone who's interested, here's my open source, BSD-licenced GUI toolkit for the DS: <http://www.sourceforge.net/projects/woopsi> thing2k's answer is pretty good, but I'd seriously recommend having code to contain child UI elements in the base uiElement class. This is the pattern I've followed in Woopsi. If you ...
How do I make a GUI?
[ "", "c++", "user-interface", "" ]
I'm downloading a web page (tag soup HTML) with XMLHttpRequest and I want to take the output and turn it into a DOM object that I can then run XPATH queries on. How do I convert from a string into DOM object? It appears that the general solution is to create a hidden iframe and throw the contents of the string into th...
Ajaxian actually had a [post on inserting / retrieving html from an iframe](http://ajaxian.com/archives/introducing-html-into-an-iframe-and-getting-it-back) today. You can probably use the js snippet they have posted there. As for handling closing of a browser / tab, you can attach to the onbeforeunload (<http://msdn....
**Try this:** ``` var request = new XMLHttpRequest(); request.overrideMimeType( 'text/xml' ); request.onreadystatechange = process; request.open ( 'GET', url ); request.send( null ); function process() { if ( request.readyState == 4 && request.status == 200 ) { var xml = request.responseXML; } } ```...
How can I turn a string of HTML into a DOM object in a Firefox extension?
[ "", "javascript", "firefox", "dom", "" ]
Is Boost the only way for VS2005 users experience TR2? Also is there a idiot proof way of downloading only the TR2 related packages? I was looking at the boost installer provided by BoostPro Consulting. If I select the options for all the threading options with all the packages for MSVC8 it requires 1.1GB. While I am ...
I believe you're actually referring to [TR1](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1745.pdf), rather than TR2. The call for proposals for TR2 is open, but don't expect to see much movement until the new C++ standard is out. Also, although boost is a provider of an implementation of TR1, dinkumware an...
Part of the beauty of Boost is that all code is in header files. They have to for template reasons. So probably downloading the code and including it in your project will work. There are some libraries in Boost that do need compiling, but as long as you don't need those...
C++ std::tr2 for VS2005
[ "", "c++", "boost", "visual-studio-2005", "c++-tr2", "" ]
For example, in Java there is [Functional Java](http://functionaljava.org/) and [Higher-Order Java](http://www.cs.chalmers.se/~bringert/hoj/). Both essentially give a small API for manipulating higher-order, curried functions, and perhaps a few new data types (tuples, immutable lists).
have you looked into [F#](https://www.microsoft.com/en-us/research/project/f-at-microsoft-research/?from=http://research.microsoft.com/fsharp/fsharp.aspx)? Also a neat blog post would be [here](https://web.archive.org/web/20210121191830/http://geekswithblogs.net/akraus1/articles/79880.aspx) that talks about how to use...
LanguageExt looks **very** promising for making functional style programming in C# easier. <https://github.com/louthy/language-ext>
Is there a Functional Programming library for .NET?
[ "", "c#", ".net", "functional-programming", "" ]
My company is currently using Sage MAS as their ERP system. While integrating our shopping cart is not going to be impossible, it uses COM and has it's own challenges. I was wondering if there was a more developer friendly ERP out there. I have looked into Microsoft Dynamics but getting information on ERP systems that...
MS Dyanamics is very cool app. V3 was fully Web Serviced V4 i assume even more- all actions are exposed as webservices, there is a big license hit on MS CRM due to "internet" licensing. We use CRMv3 in a totally .NET SOA here and its great. You should have no problems doing the integration - security aside =>
When you talk about Microsoft Dynamics, it sounds a bit like you are talking about a specific product. However there are close to 10 different systems in the Dynamics line-up from Microsoft and at least 6 of them are different ERP system, all with different functionalities and extendabilities. The new verions of Micros...
Developer Friendly ERP
[ "", "c#", "erp", "" ]
Below is an example class hierarchy and code. What I'm looking for is a way to determine if 'ChildClass1' or 'ChildClass2' had the static method whoAmI() called on it without re-implementing it in each child class. ``` <?php abstract class ParentClass { public static function whoAmI () { // NOT correct,...
Now that PHP 5.3 is widely available in the wild, I wanted to put together a summary answer to this question to reflect newly available techniques. As mentioned in the other answers, PHP 5.3 has introduced [Late Static Binding](http://php.benscom.com/manual/en/language.oop5.late-static-bindings.php) via a new [`static...
I believe what you're referring to is a known php bug. Php 5.3 is aiming to address this issue with a new Late Static Binding feature. <http://www.colder.ch/news/08-24-2007/28/late-static-bindings-expl.html>
Is there any way to detect the target class in static methods?
[ "", "php", "oop", "php-5.3", "php-5.2", "" ]
I've used the PHP MVC framework Symfony to build an on-demand web app. It has an annoying bug - the session expires after about 15-30 minutes of inactivity. There is a config directive to prevent session expiration but it does not work. Even workarounds such as [this one](http://robrosenbaum.com/php/howto-disable-sess...
I looked into it, and my coworker agrees that a heartbeat page call should work, you just have to make sure that the action invoked does reset the session timer (things like ajax field completion don't do this on their own).
The company I work for has been using Symfony and the workaround that we've used is to trigger a warning with javascript before the user gets logged out. I suspect that there is a a way to make 'heartbeat' ajax calls to the server to trigger the timer to reset, but that may be a lot of trouble. I think that there may n...
How to prevent session timeout in Symfony 1.0?
[ "", "php", "symfony1", "" ]
For a given table 'foo', I need a query to generate a set of tables that have foreign keys that point to foo. I'm using Oracle 10G.
This should work (or something close): ``` select table_name from all_constraints where constraint_type='R' and r_constraint_name in (select constraint_name from all_constraints where constraint_type in ('P','U') and table_name='<your table here>'); ```
The following statement should give the children and all of their descendents. I have tested it on an Oracle 10 database. ``` SELECT level, main.table_name parent, link.table_name child FROM user_constraints main, user_constraints link WHERE main.constraint_type IN ('P', 'U') AND link.r_constraint_na...
Query a Table's Foreign Key relationships
[ "", "sql", "database", "oracle", "oracle10g", "" ]
What would be the best way to implement a simple crash / error reporting mechanism? Details: my app is **cross-platform (mac/windows/linux) and written in Python**, so I just need something that will send me a small amount of text, e.g. just a timestamp and a traceback (which I already generate and show in my error di...
The web service is the best way, but there are some caveats: 1. You should always ask the user if it is ok to send error feedback information. 2. You should be prepared to fail gracefully if there are network errors. Don't let a failure to report a crash impede recovery! 3. You should avoid including user identifying ...
> I can't think of a way to do this without including a username and password for the smtp server in the application... You only need a username and password for authenticating yourself to a smarthost. You don't need it to send mail directly, you need it to send mail through a relay, e.g. your ISP's mail server. It's ...
How to best implement simple crash / error reporting?
[ "", "python", "cross-platform", "error-reporting", "" ]
I'm writing a program that sends an email out at a client's specific local time. I have a .NET method that takes a timezone & time and destination timezone and returns the time in that timezone. So my method is to select every distinct timezone in the database, check if it is the correct time using the method, then sel...
# Hey! These queries are not equivalent. Results will be same only if assuming that one email belongs only to the one time zone. Of course it does however SQL engine doesn't know that and tries to remove duplicities. So the first query should be faster. Always use UNION ALL, unless you know why you want to use UNION....
For most database related performance questions, the real answer is to run it and analyze what the DB does for your dataset. Run an explain plan or trace to see if your query is hitting the proper indexes or create indexes if necessary. I would likely go with the first using the IN clause since that carries the most s...
What's optimal? UNION vs WHERE IN (str1, str2, str3)
[ "", "sql", "optimization", "" ]
Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.) Antiword seems like it might be a reasonable option, but it seems like it might be abandoned. A Python so...
I use catdoc or antiword for this, whatever gives the result that is the easiest to parse. I have embedded this in python functions, so it is easy to use from the parsing system (which is written in python). ``` import os def doc_to_text_catdoc(filename): (fi, fo, fe) = os.popen3('catdoc -w "%s"' % filename) ...
(Same answer as [extracting text from MS word files in python](https://stackoverflow.com/questions/125222/extracting-text-from-ms-word-files-in-python)) Use the native Python docx module which I made this week. Here's how to extract all the text from a doc: ``` document = opendocx('Hello world.docx') # This location...
Best way to extract text from a Word doc without using COM/automation?
[ "", "python", "ms-word", "" ]
I've got a new varchar(10) field in a database with 1000+ records. I'd like to update the table so I can have random data in the field. I'm looking for a SQL solution. I know I can use a cursor, but that seems inelegant. MS-SQL 2000,BTW
``` update MyTable Set RandomFld = CONVERT(varchar(10), NEWID()) ```
You might be able to adapt something [like this](http://www.mitchelsellers.com/blogs/articletype/articleview/articleid/249/creating-random-sql-server-test-data.aspx) to load a test dataset of values, depending on what you are looking for
How to update a field with random data?
[ "", "sql", "sql-server", "" ]
We have several jobs that run concurrently that have to use the same config info for log4j. They are all dumping the logs into one file using the same appender. Is there a way to have each job dynamically name its log file so they stay seperate? Thanks Tom
Can you pass a Java system property for each job? If so, you can parameterize like this: ``` java -Dmy_var=somevalue my.job.Classname ``` And then in your log4j.properties: ``` log4j.appender.A.File=${my_var}/A.log ``` You could populate the Java system property with a value from the host's environment (for example...
If the job names are known ahead of time, you could include the job name when you do the getLogger() call. You then can bind different appenders to different loggers, with separate file names (or other destinations). If you cannot know the job name ahead of time, you could configure the logger at runtime instead of us...
log4j log file names?
[ "", "java", "logging", "log4j", "" ]
How can I go about generating a Friendly URL in C#? Currently I simple replace spaces with an underscore, but how would I go about generating URL's like Stack Overflow? For example how can I convert: > How do I generate a Friendly URL in C#? Into > how-do-i-generate-a-friendly-url-in-C
There are several things that could be improved in Jeff's solution, though. ``` if (String.IsNullOrEmpty(title)) return ""; ``` IMHO, not the place to test this. If the function gets passed an empty string, something went seriously wrong anyway. Throw an error or don't react at all. ``` // remove any leading or trai...
Here's how we do it. Note that there are probably more edge conditions than you realize at first glance.. ``` if (String.IsNullOrEmpty(title)) return ""; // remove entities title = Regex.Replace(title, @"&\w+;", ""); // remove anything that is not letters, numbers, dash, or space title = Regex.Replace(title, @"[^A-Za...
How do I generate a Friendly URL in C#?
[ "", "c#", "friendly-url", "" ]
Is there any way to force a listview control to treat all clicks as though they were done through the Control key? I need to replicate the functionality of using the control key (selecting an item sets and unsets its selection status) in order to allow the user to easily select multiple items at the same time. Thank ...
It's not the standard behaviour of the ListView control, even when MultiSelect is set to true. If you wanted to create your own custom control you would need to do the following: 1. Derive a control from ListView 2. add a handler to the "Selected" event. 3. In the "OnSelected", maintain your own list of selected item...
Here is the complete solution that I used to solve this problem using WndProc. Basically, it does a hit test when the mouse is clicked.. then if MutliSelect is on, it will automatically toggle the item on/off [.Selected] and not worry about maintaining any other lists or messing with the ListView functionality. I have...
Listview Multiple Selection
[ "", "c#", "winforms", "" ]
Can you please point to alternative data storage tools and give good reasons to use them instead of good-old relational databases? In my opinion, most applications rarely use the full power of SQL--it would be interesting to see how to build an SQL-free application.
Plain text files in a filesystem * Very simple to create and edit * Easy for users to manipulate with simple tools (i.e. text editors, grep etc) * Efficient storage of binary documents --- XML or JSON files on disk * As above, but with a bit more ability to validate the structure. --- Spreadsheet / CSV file * Ve...
Matt Sheppard's answer is great (mod up), but I would take account these factors when thinking about a spindle: 1. Structure : does it obviously break into pieces, or are you making tradeoffs? 2. Usage : how will the data be analyzed/retrieved/grokked? 3. Lifetime : how long is the data useful? 4. Size : how much data...
Good reasons NOT to use a relational database?
[ "", "sql", "database", "nosql", "" ]
How do I enumerate the properties of a JavaScript object? I actually want to list all the defined variables and their values, but I've learned that defining a variable actually creates a property of the window object.
Simple enough: ``` for(var propertyName in myObject) { // propertyName is what you want // you can get the value like this: myObject[propertyName] } ``` Now, you will not get private variables this way because they are not available. --- EDIT: [@bitwiseplatypus](https://stackoverflow.com/questions/85992/how-d...
Use a `for..in` loop to enumerate an object's properties, but be careful. The enumeration will return properties not just of the object being enumerated, but also from the prototypes of any parent objects. ``` var myObject = {foo: 'bar'}; for (var name in myObject) { alert(name); } // results in a single alert of ...
How do I enumerate the properties of a JavaScript object?
[ "", "javascript", "properties", "" ]
I know what `yield` does, and I've seen a few examples, but I can't think of real life applications, have you used it to solve some specific problem? (Ideally some problem that cannot be solved some other way)
I realise this is an old question (pre Jon Skeet?) but I have been considering this question myself just lately. Unfortunately the current answers here (in my opinion) don't mention the most obvious advantage of the yield statement. The biggest benefit of the yield statement is that it allows you to iterate over very ...
actually I use it in a non traditional way on my site [IdeaPipe](http://www.ideapipe.com) ``` public override IEnumerator<T> GetEnumerator() { // goes through the collection and only returns the ones that are visible for the current user // this is done at this level instead of the display level so that ideas ...
What are real life applications of yield?
[ "", "c#", ".net", "yield", "" ]
How do i measure how long a client has to wait for a request. On the server side it is easy, through a filter for example. But if we want to take into accout the total time including latency and data transfer, it gets diffcult. is it possible to access the underlying socket to see when the request is finished? or is ...
There's no way you can know how long the client had to wait purely from the server side. You'll need some JavaScript. You don't want to synchronize the client and server clocks, that's overkill. Just measure the time between when the client makes the request, and when it finishes displaying its response. If the clien...
You could wrap the HttpServletResponse object and the OutputStream returned by the HttpServletResponse. When output starts writing you could set a startDate, and when it stops (or when it's flushed etc) you can set a stopDate. This can be used to calculate the length of time it took to stream all the data back to the ...
Measure Total Network Transfer Time from Servlets
[ "", "java", "tomcat", "servlets", "time", "sockets", "" ]
``` foreach ($_GET as $field => $label) { $datarray[]=$_GET[$field]; echo "$_GET[$field]"; echo "<br>"; } print_r($datarray); ``` --- This is the output I am getting. I see the data is there in datarray but when I `echo $_GET[$field]` I only get "Array" But `print_r($datarray)` prints all the data. Any ide...
EDIT: When I completed your test, here was the final URL: <http://hofstrateach.org/Roberto/process.php?keys=Grade1&keys=Nathan&keys=North%20America&keys=5&keys=3&keys=no&keys=foo&keys=blat&keys=0%3A0%3A24> This is probably a malformed URL. When you pass duplicate keys in a query, PHP makes them an array. The above UR...
Use `var_export($_GET)` to more easily see what kind of array you are getting. From the output of your script I can see that you have multiple nested arrays. It seems to be something like: ``` $_GET = array( array( array("Grade1", "ln", "North America", "yuiyyu", "iuy", "uiyui", "yui","uiy","0:0:5"))) ``` so to get ...
Php $_GET issue
[ "", "php", "arrays", "printing", "foreach", "get", "" ]
I'm trying to the the flv Flash player [from here](http://www.jeroenwijering.com/?item=JW_FLV_Player) in a windows forms application. I currently have it playing 1 .flv file with no problems but I really need to be able to play multiple files. Has anyone had experienace of using the playlists that this control offers o...
Can you get the control to run the way you want it in a webpage/browser? If yes (and the problem is with winforms, I'd just embed it in a browser control. If no, I'd as the creators directly.
I would be very hesitant to place the WebBrowser control between your software and the flv, because you will lose all control of the flv and will not get any meaningful notifications about its status. The lack of tight integration will lead to a very poor user experience. The blog post [here](http://weblogs.asp.net/twa...
Embedding flv (flash) player in windows forms
[ "", "c#", "winforms", "flash", "flv", "embedded-flashplayer", "" ]
Using C# 2.0 what is the best way to implement dynamic form controls? I need to provide a set of controls per data object, so should i just do it manually and lay them out while increment the top value or is there a better way?
You can use panels with automatic layout such as [FlowLayoutPanel](http://msdn.microsoft.com/en-us/library/system.windows.forms.flowlayoutpanel.asp) and [TableLayoutPanel](http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.aspx). Unfortunately there are only 2 panels with automatic layout ou...
@Sam I know this question was about Windows Forms, but you should definitely start looking at WPF. This sort of scenario is *really* easy in WPF with DataTemplates and TemplateSelectors.
Dynamic Form Controls
[ "", "c#", ".net", "winforms", "" ]
We are trying to create a web-service that we plan to pass a variable amount of variables to it. Can this be done? Basically instead of pass all possible parameters we wish to pass only the set values and use the defaults set in the web-service. Here is an example of the XML we are looking to send, we would sent an ...
I would pass in an xml document instead of doing concreate functions for this. The webservice in your example is leaky - the consumer needs to know too much about this interface and the implementation of the webservice internally. XML Document and then tie that with an XSD. That way you can prevalidte the input to th...
You can simply pass a variable-length array as a parameter.
How to you pass a variable amount of parmeters to web-service
[ "", "c#", "web-services", "soap", "" ]
example: ``` a_list = [1, 2, 3] a_list.len() # doesn't work len(a_list) # works ``` Python being (very) object oriented, I don't understand why the 'len' function isn't inherited by the object. Plus I keep trying the wrong solution since it appears as the logical one to me
Guido's explanation is [here](http://mail.python.org/pipermail/python-3000/2006-November/004643.html): > First of all, I chose len(x) over x.len() for HCI reasons (def \_\_len\_\_() came much later). There are two intertwined reasons actually, both HCI: > > (a) For some operations, prefix notation just reads better th...
The short answer: 1) backwards compatibility and 2) there's not enough of a difference for it to really matter. For a more detailed explanation, read on. The idiomatic Python approach to such operations is special methods which aren't intended to be called directly. For example, to make `x + y` work for your own class...
Why isn't the 'len' function inherited by dictionaries and lists in Python
[ "", "python", "" ]
It's common to want browsers to cache resources - JavaScript, CSS, images, etc. until there is a new version available, and then ensure that the browser fetches and caches the new version instead. One solution is to embed a version number in the resource's filename, but will placing the resources to be managed in this...
Yes, any change in *any part* of the URL (excluding HTTP and HTTPS protocols changes) is interpreted as a different resource by the browser (and any intermediary proxies), and will thus result in a separate entity in the browser-cache. **Update:** The claim in [this ThinkVitamin article](http://www.thinkvitamin.com/f...
Browser cache key is a combination of the request method and resource URI. URI consists of scheme, authority, path, query, and fragment. Relevant excerpt from [HTTP 1.1 specification](https://www.rfc-editor.org/rfc/rfc7234#section-2): > The primary cache key consists of the request method and target URI. > However, s...
Is it the filename or the whole URL used as a key in browser caches?
[ "", "javascript", "url", "browser", "caching", "filenames", "" ]
I would like to know which dependency described in my pom.xml brings a transitive dependency in my target directory. To be more precise, I have the library "poi-2.5.1-final-20040804.jar" in my WEB-INF/lib directory and I would like to know which dependency in my pom.xml brings that.
To add to @David Crow, here's [a dependency:tree example](http://maven.apache.org/plugins/maven-dependency-plugin/examples/filtering-the-dependency-tree.html) from the Maven site: ``` mvn dependency:tree -Dincludes=velocity:velocity ``` might output ``` [INFO] [dependency:tree] [INFO] org.apache.maven.plugins:maven-...
Using the [Maven Dependency Plugin](http://maven.apache.org/plugins/maven-dependency-plugin/): ``` mvn dependency:tree ```
In Maven 2, how do I know from which dependency comes a transitive dependency?
[ "", "java", "maven-2", "build-process", "" ]
I'm wondering the *best* way to start a pthread that is a member of a C++ class? My own approach follows as an answer...
I usually use a static member function of the class, and use a pointer to the class as the void \* parameter. That function can then either perform thread processing, or call another non-static member function with the class reference. That function can then reference all class members without awkward syntax.
This can be simply done by using the boost library, like this: ``` #include <boost/thread.hpp> // define class to model or control a particular kind of widget class cWidget { public: void Run(); } // construct an instance of the widget modeller or controller cWidget theWidget; // start new thread by invoking method...
Best way to start a thread as a member of a C++ class?
[ "", "c++", "pthreads", "" ]
I have **1 red polygon** say and **50 randomly placed blue polygons** - they are situated in geographical **2D space**. What is the quickest/speediest algorithim to find the the shortest distance between a red polygon and its nearest blue polygon? Bear in mind that it is not a simple case of taking the points that mak...
I doubt there is better solution than calculating the distance between the red one and every blue one and sorting these by length. Regarding sorting, usually QuickSort is hard to beat in performance (an optimized one, that cuts off recursion if size goes below 7 items and switches to something like InsertionSort, mayb...
You might be able to reduce the problem, and then do an intensive search on a small set. Process each polygon first by finding: * Center of polygon * Maximum radius of polygon (i.e., point on edge/surface/vertex of the polygon furthest from the defined center) Now you can collect, say, the 5-10 closest polygons to t...
What is the quickest way to find the shortest cartesian distance between two polygons
[ "", "c#", "algorithm", "gis", "polygon", "distance", "" ]
My web application has a login page that submits authentication credentials via an AJAX call. If the user enters the correct username and password, everything is fine, but if not, the following happens: 1. The web server determines that although the request included a well-formed Authorization header, the credentials ...
I don't think this is possible -- if you use the browser's HTTP client implementation, it will always pop up that dialog. Two hacks come to mind: 1. Maybe Flash handles this differently (I haven't tried yet), so having a flash movie make the request might help. 2. You can set up a 'proxie' for the service that you're ...
I encountered the same issue here, and the backend engineer at my company implemented a behavior that is apparently considered a good practice : when a call to a URL returns a 401, if the client has set the header `X-Requested-With: XMLHttpRequest`, the server drops the `www-authenticate` header in its response. The s...
How can I suppress the browser's authentication dialog?
[ "", "javascript", "ajax", "http-authentication", "" ]
I have a simple setter method for a property and `null` is not appropriate for this particular property. I have always been torn in this situation: should I throw an [`IllegalArgumentException`](http://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html), or a [`NullPointerException`](http://docs....
It seems like an `IllegalArgumentException` is called for if you don't want `null` to be an allowed value, and the `NullPointerException` would be thrown if you were trying to *use* a variable that turns out to be `null`.
You should be using `IllegalArgumentException` (IAE), not `NullPointerException` (NPE) for the following reasons: First, the [NPE JavaDoc](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/NullPointerException.html) explicitly lists the cases where NPE is appropriate. Notice that all of them are thrown *by the ru...
IllegalArgumentException or NullPointerException for a null parameter?
[ "", "java", "exception", "null", "nullpointerexception", "illegalargumentexception", "" ]
I'm trying to find a way to validate a large XML file against an XSD. I saw the question [...best way to validate an XML...](https://stackoverflow.com/questions/15732/whats-the-best-way-to-validate-an-xml-file-against-an-xsd-file) but the answers all pointed to using the Xerces library for validation. The only problem ...
Instead of using a DOMParser, use a SAXParser. This reads from an input stream or reader so you can keep the XML on disk instead of loading it all into memory. ``` SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true); factory.setNamespaceAware(true); SAXParser parser = factory.newSAX...
Use [libxml](http://xmlsoft.org/), which performs validation *and* has a streaming mode.
Validating a HUGE XML file
[ "", "java", "xml", "validation", "xsd", "" ]
I'm maintaining some code that uses a \*= operator in a query to a Sybase database and I can't find documentation on it. Does anyone know what \*= does? I assume that it is some sort of a join. ``` select * from a, b where a.id *= b.id ``` I can't figure out how this is different from: ``` select * from a, b where a...
From <http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.dc34982_1500/html/mig_gde/mig_gde160.htm>: Inner and outer tables The terms outer table and inner table describe the placement of the tables in an outer join: * In a left join, the outer table and inner table are the left and right tables respective...
It means outer join, a simple = means inner join. ``` *= is LEFT JOIN and =* is RIGHT JOIN. ``` (or vice versa, I keep forgetting since I'm not using it any more, and Google isn't helpful when searching for \*=)
*= in Sybase SQL
[ "", "sql", "t-sql", "join", "sybase", "" ]
I'm looking for a Java library for SWIFT messages. I want to * parse SWIFT messages into an object model * validate SWIFT messages (including SWIFT network validation rules) * build / change SWIFT messages by using an object model Theoretically, I need to support all SWIFT message types. But at the moment I need MT10...
SWIFT is releasing a "Standards Developer Kit" which includes an "MT/XML Schema Library". From the doc: "The MT/XML Schema Library is a complete set of XML schema definitions for MT messages, and software which shows how to convert messages from an MT format to an MT XML representation and back. This approach allows X...
Have you looked at [WIFE](http://wife.sourceforge.net/)? We use that in our application which translates SWIFT messages to an internal XML format and back again. We haven't had any problems with it. Also, it's licensed under the LGPL, so you can hack it up if you need to. Check it out.
Java SWIFT Library
[ "", "java", "swift-mt", "" ]
I'm trying to use `strtotime()` to respond to a button click to advance -1 and +1 days (two buttons) relative to the day advanced to on the previous click. **Example:** * It's the 10th of the month, I click "-1 day" button, and now the date reads as the 9th. * I click the "-1 day" button again and now the readout sta...
Working from previous calls to the same script isn't really a good idea for this type of thing. What you want to do is always pass two values to your script, the date, and the movement. (the below example is simplified so that you only pass the date, and it will always add one day to it) Example <http://www.site.com...
Kevin, you work off a solid absolute base (i.e. a date / time), not a relative time period. You then convert to the relative time periods. So, for example, by default, if you were showing a calendar, you'd work from todays date. ``` int strtotime ( string $time [, int $now ] ) ``` You can see in the function defin...
Advancing through relative dates using strtotime()
[ "", "php", "date", "strtotime", "" ]
The Gang of Four's [Design Patterns](http://en.wikipedia.org/wiki/Design_Patterns) uses a word processor as an example for at least a few of their patterns, particularly Composite and Flyweight. Other than by using C or C++, could you really use those patterns and the object-oriented overhead they entail to write a hi...
Flyweight really is just a way of conserving resources in situations where there are thousands of objects with intrinsic shared state, so it could be useful in higher level languages than C/C++. Maybe the GoF's example using glyphs in a document was not the best choice to illustrate this pattern. I think there's a lot...
Well, [flyweight](http://en.wikipedia.org/wiki/Flyweight_pattern) is a ridiculous pattern to use in a word processor. IIRC, they had each character being referenced as a object [note: it was for each *glyph*, which is still crazy because your OS will happily draw that for you]. With a pointer being wider than a charact...
Can you really build a fast word processor with GoF Design Patterns?
[ "", "java", "performance", "design-patterns", "ide", "text-processing", "" ]
I don't like the AutoSize property of the Label control. I have a custom Label that draws a fancy rounded border among other things. I'm placing a `AutoSize = false` in my constructor, however, when I place it in design mode, the property always is True. I have overridden other properties with success but this one is ...
I've seen similar behaviour when setting certain properties of controls in the constructor of the form itself. They seem to revert back to their design-time defaults. I notice you're already overriding the OnLoad method. Have you tried setting AutoSize = false there? Or are you mainly concerned with providing a *defau...
I spent a lot of time with it and this finally works! (my code is vb.net but is simple to convert it) ``` Private _Autosize As Boolean Public Sub New() _Autosize=False End Sub Public Overrides Property AutoSize() As Boolean Get Return MyBase.AutoSize End Get Set(ByVal Value As Boolean) ...
C#.NET Winforms: Is it possible to override Label.Autosize?
[ "", "c#", "winforms", "" ]
I'd be interested in some before-and-after c# examples, some non-idiomatic vs idiomatic examples. Non-c# examples would be fine as well if they get the idea across. Thanks.
Idiomatic means following the conventions of the language. You want to find the easiest and most common ways of accomplishing a task rather than porting your knowledge from a different language. non-idiomatic python using a loop with append: ``` mylist = [1, 2, 3, 4] newlist = [] for i in mylist: newlist.append(i...
Some examples: **Resource management**, non idiomatic: ``` string content; StreamReader sr = null; try { File.OpenText(path); content = sr.ReadToEnd(); } finally { if (sr != null) { sr.Close(); } } ``` Idiomatic: ``` string content; using (StreamReader sr = File.OpenText(path)) { content...
What is idiomatic code?
[ "", "c#", "idioms", "" ]
I know that IList is the interface and List is the concrete type but I still don't know when to use each one. What I'm doing now is if I don't need the Sort or FindAll methods I use the interface. Am I right? Is there a better way to decide when to use the interface or the concrete type?
There are two rules I follow: * Accept the most basic type that will work * Return the richest type your user will need So when writing a function or method that takes a collection, write it not to take a List, but an IList<T>, an ICollection<T>, or IEnumerable<T>. The generic interfaces will still work even for hete...
Microsoft guidelines as checked by FxCop discourage use of List<T> in public APIs - prefer IList<T>. Incidentally, I now almost always declare one-dimensional arrays as IList<T>, which means I can consistently use the IList<T>.Count property rather than Array.Length. For example: ``` public interface IMyApi { ILi...
When to use IList and when to use List
[ "", "c#", ".net", "" ]
I've been writing PHP for about six years now and have got to a point where I feel I should be doing more to write better code. I know that Object Oriented code is the way to go but I can't get my head around the concept. Can anyone explain in terms that any idiot can understand, OO and how it works in PHP or point me...
I have been in your shoes, but I saw the light after I read this book (a few times!) <http://www.apress.com/book/view/9781590599099> After I read this, I really "got" it and I haven't looked back. You'll get it on Amazon. I hope you persist, get it, and love it. When it comes together, it will make you smile. Composi...
Think of a thingy. Any thingy, a thingy you want to do stuff to. Say, a breakfast. (All code is pseudocode, any resemblance to any language living, dead, or being clinically abused in the banking industry is entirely coincidental and nothing to do with your post being tagged PHP) So you define a template for how you'...
OO and how it works in PHP
[ "", "php", "oop", "" ]
Is it possible for UDP data to come to you corrupted? I know it is possible for it to be lost.
UDP packets use a 16 bit checksum. It is not impossible for UDP packets to have corruption, but it's pretty unlikely. In any case it is not more susceptible to corruption than TCP.
First of all, the "IP checksum" referenced above is only an IP header checksum. It does not protect the payload. See RFC 791 Secondly, UDP allows transport with NO checksum, which means that the 16-bit checksum is set to 0 (ie, none). See RFC 768. (An all zero transmitted checksum value means that the transmitter gene...
Can UDP data be delivered corrupted?
[ "", "c++", "networking", "udp", "" ]
What is a good way to render data produced by a Java process in the browser? I've made extensive use of JSP and the various associated frameworks ([JSTL](http://java.sun.com/products/jsp/jstl/), [Struts](http://struts.apache.org/), [Tapestry](http://tapestry.apache.org/), etc), as well as more comprehensive frameworks...
I personally use [Tapestry 5](http://tapestry.apache.org/tapestry5/) for creating webpages with Java, but I agree that it can sometimes be a bit overkill. I would look into using JAX-RS ([java.net project](https://jsr311.dev.java.net/), [jsr311](http://jcp.org/en/jsr/detail?id=311)) it is pretty simple to use, it suppo...
We're using [Stripes](http://www.stripesframework.org/). It gives you more structure than straight servlets, but it lets you control your urls through a @UrlBinding annotation. We use it to stream xml and json back to the browser for ajax stuff. You could easily consume it with another technology if you wanted to go t...
Web Scripting for Java
[ "", "java", "jsp", "scripting", "" ]
I have a control that, upon postback, saves form results back to the database. It populates the values to be saved by iterating through the querystring. So, for the following SQL statement (vastly simplified for the sake of discussion)... ``` UPDATE MyTable SET MyVal1 = @val1, MyVal2 = @val2 WHERE @id = @id ``` ....
After struggling to find a simpler solution, I gave up and wrote a routine to parse my SQL query for variable names: ``` Dim FieldRegEx As New Regex("@([A-Z_]+)", RegexOptions.IgnoreCase) Dim Fields As Match = FieldRegEx.Match(Query) Dim Processed As New ArrayList While Fields.Success Dim Key As String = Fields.G...
First of all, I would suggest against adding all entries on the querystring as parameter names, I'm not sure this is unsafe, but I wouldn't take that chance. The problem is you're calling ``` Command.Parameters.AddWithValue("@val2", null) ``` Instead of this you should be calling: ``` If MyValue Is Nothing Then ...
Handling empty values with ADO.NET and AddWithValue()
[ "", "sql", "vb.net", "ado.net", "" ]
I'm working on a game (C#) that uses a [Robocode-like](http://robocode.sourceforge.net/) programming model: participants inherit a base Class and add strategic behaviors. The game then loads instances of participants' Classes and the competition begins. Unfortunately, participants can "cheat" by sharing static variable...
Load each competitor into a different AppDomain.
static variables are per-AppDomain, so you could look into using different AppDomains, but I totally don't know what other consequences that may have. Otherwise you could check the classes beforehand using reflection, and reject any classes that have static members.
How do I prevent static variable sharing in the .NET runtime?
[ "", "c#", ".net", "multithreading", "" ]
Since the WMI class Win32\_OperatingSystem only includes OSArchitecture in Windows Vista, I quickly wrote up a method using the registry to try and determine whether or not the current system is a 32 or 64bit system. ``` private Boolean is64BitOperatingSystem() { RegistryKey localEnvironment = Registry.LocalMachin...
Take a look at Raymond Chens solution: [How to detect programmatically whether you are running on 64-bit Windows](http://blogs.msdn.com/oldnewthing/archive/2005/02/01/364563.aspx) and here's the PINVOKE for .NET: [IsWow64Process (kernel32)](http://www.pinvoke.net/default.aspx/kernel32/IsWow64Process.html?diff=y) **...
> The easiest way to test for 64-bit under .NET is to check the value of IntPtr.Size. I believe the value of IntPtr.Size is 4 for a 32bit app that's running under WOW, isn't it? **Edit**: @Edit: Yeah. :)
Is this a good way to determine OS Architecture?
[ "", "c#", "windows", "registry", "" ]
I'm designing this collection of classes and abstract (MustInherit) classes… ![class diagram](https://web.archive.org/web/20120911004421/http://img396.imageshack.us/img396/1711/nodeclassinheritanceej0.gif) This is the database table where I'm going to store all this… ![database table](https://web.archive.org/web/201...
Use CHECK constraints on the table. These allow you to use any kind of boolean logic (including on other values in the table) to allow/reject the data. From the [Books Online](http://msdn.microsoft.com/en-us/library/ms188258.aspx) site: > You can create a CHECK constraint with > any logical (Boolean) expression that ...
Have a unique table for each type of node. Why not just make the class you're building enforce the data integrity for its own type? --- **EDIT** In that case, you can either a) use logical constraints (see below) or b) stored procedures to do inserts/edits (a good idea regardless) or c) again, just make the class e...
How do I enforce data integrity rules in my database?
[ "", "sql", "sql-server", "database", "database-design", "" ]
I have a dataset that I have modified into an xml document and then used a xsl sheet to transform into an Excel xml format in order to allow the data to be opened programatically from my application. I have run into two problems with this: 1. Excel is not the default Windows application to open Excel files, therefore ...
``` Process.Start(@"C:\Program Files\Microsoft Office\Officexx\excel.exe", "yourfile.xml"); ``` That being said, you will still get the message box. I suppose that you could use the Interop, but I am not sure how well it will work for you.
If you insert the following into the 2nd line of your XML it directs Windows to open with Excel ``` <?mso-application progid="Excel.Sheet"?> ```
XML to Excel (2007) Ideas using Windows XP, and C#.Net
[ "", "c#", ".net", "xml", "excel", "" ]
In a C# windows forms application. I have a splash screen with some multi-threaded processes happening in the background. What I would like to do is when I display the splash screen initially, I would like to have it appear to "fade in". And then, once all the processes finish, I would like it to appear as though the s...
You could use a timer to modify the [Form.Opacity level](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.opacity(VS.80).aspx).
When using Opacity property have to remember that its of type double, where 1.0 is complete opacity, and 0.0 is completely transparency. ``` private void fadeTimer_Tick(object sender, EventArgs e) { this.Opacity -= 0.01; if (this.Opacity <= 0) { this.Close(); } ...
Fade splash screen in and out
[ "", "c#", "winforms", ".net-2.0", "splash-screen", "" ]
For a C# UserControl on Windows Mobile (though please answer if you know it for full Windows...it might work) how do you change what shows up in the Designer Properties window for one of the Control's public Properties. For example: ``` private Color blah = Color.Black; public Color Blah { get { return this.blah;...
Is this of use to you? I am not into CF development, but it looks like you need to add some XML metadata to enable it: <http://blogs.msdn.com/bluecollar/archive/2007/02/08/adding-compact-framework-design-time-attributes-or-more-fun-with-textboxes.aspx> Interesting read.. Looks like a lot of design time support was st...
`DesignerCategory` is used to say if the class is a form, component etc. For full windows the attribute you want is: ``` [System.ComponentModel.Category("Custom")] ``` and for the description you can use `[System.ComponentModel.Description("This is the description")]` To use both together: ``` [System.ComponentMod...
User Control Property Designer Properties
[ "", "c#", "user-controls", "windows-mobile", "" ]
I need to be able to get at the full URL of the page I am on from a user control. Is it just a matter of concatenating a bunch of Request variables together? If so which ones? Or is there a more simpiler way?
I usually use `Request.Url.ToString()` to get the full url (including querystring), no concatenation required.
Here is a list I normally refer to for this type of information: ``` Request.ApplicationPath : /virtual_dir Request.CurrentExecutionFilePath : /virtual_dir/webapp/page.aspx Request.FilePath : /virtual_dir/webapp/page.aspx Request.Path : /virtual_dir/webapp/page.aspx Request.PhysicalApplicationPath : d:\Inetpub\...
How do I get the full url of the page I am on in C#
[ "", "c#", "asp.net", "user-controls", "" ]
I've tried to do this several times with no luck. After reading [this post](https://stackoverflow.com/questions/1451/what-is-the-best-way-to-handle-multiple-permission-types#1477), it made me interested in doing this again. So can anyone tell me why the following doesn't work? ``` <?php $guest = 1; $editor = 2; $admi...
Use the bitwise OR operator (|) to set bits, use the AND operator (&) to check bits. Your code should look like this: ``` <?php $guest = 1; $editor = 2; $admin = 4; $user = $editor; if( $user & ($editor | $admin) ) { echo "Test"; } ?> ``` If you don't understand binary and exac...
In the interest of not reinventing the wheel, why not take a look at ACL/Authentication systems like [Zend ACL](http://framework.zend.com/manual/en/zend.acl.html) and [Zend Auth](http://framework.zend.com/manual/en/zend.auth.html)? Both can be used independently from the Zend Framework as a whole. Access Control is a t...
Implementing permissions in PHP
[ "", "php", "permissions", "" ]
Does anyone know if it is possible to detect whether the browser has closed the connection during the execution of a long `PHP` script, when using `apache` and `mod_php`? For example, in `Java`, the `HttpOutputStream` will throw an `exception` if one attempts to write to it after the browser has closed it -- Or will r...
Use [connection\_aborted()](https://www.php.net/manual/en/function.connection-aborted.php)
In at least PHP4, connection\_aborted and connection\_status only worked after the script sent any output to the browser (using: flush() | ob\_flush()). Also don't expect accurately timed results. It's mostly useful to check if there is still someone waiting on the other side.
Detect browser connection closed in PHP
[ "", "php", "apache", "http", "mod-php", "" ]
My application dynamically loads assemblies at runtime from specific subfolders. These assemblies are compiled with dependencies to other assemblies. The runtime trys to load these from the application directory. But I want to put them into the modules directory. Is there a way to tell the runtime that the dlls are in...
One nice approach I've used lately is to add an event handler for the AppDomain's AssemblyResolve event. ``` AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler); ``` Then in the event handler method you can load the assembly that was attem...
You can use the `<probing>` element in a manifest file to tell the Runtime to look in different directories for its assembly files. <http://msdn.microsoft.com/en-us/library/823z9h8w.aspx> e.g.: ``` <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <probing privatePath="bin;...
Loading assemblies and its dependencies
[ "", "c#", ".net", "" ]
How do I turn the following 2 queries into 1 query ``` $sql = "SELECT level FROM skills WHERE id = $id LIMIT 1;"; $result = $db->sql_query($sql); $level = (int) $db->sql_fetchfield('level'); $db->sql_freeresult($result); ++$level; $sql = "UPDATE skills SET level = $level WHERE id = $id;"; $result = $db->sql_q...
I get downmodded for this? ``` $sql = "UPDATE skills SET level = level+1 WHERE id = $id"; $result = $db->sql_query($sql); $db->sql_freeresult($result); ``` In Teifion's specific case, the phpBB DDL lists that particular field as NOT NULL, so there's no danger of incrementing NULL. In the general case, you should not...
This way: ``` UPDATE skills SET level = level + 1 WHERE id = $id ```
Add 1 to a field
[ "", "php", "mysql", "" ]
I know almost nothing about linq. I'm doing this: ``` var apps = from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero select app; ``` Which gets me all the running processes which match that criteria. But I don't know how to get the first on...
@FryHard FirstOrDefault will work but remember that it returns null if none are found. This code isn't tested but should be close to what you want: ``` var app = Process.GetProcesses().FirstOrDefault(p => p.ProcessName.Contains("MyAppName") && p.MainWindowHandle != IntPtr.Zero); if (app == null) return; SetForeg...
Do *not* use `Count()` like ICR says. `Count()` will iterate through the `IEnumerable` to figure out how many items it has. In this case the performance penalty may be negligible since there aren't many processes, but it's a bad habit to get into. Only use `Count()` when your query is only interested in the *number of ...
Linq to objects - select first object
[ "", "c#", "linq", "linq-to-objects", "" ]
Does [Facelets](https://facelets.dev.java.net/) have any features for neater or more readable internationalised user interface text labels that what you can otherwise do using JSF? For example, with plain JSF, using h:outputFormat is a very verbose way to interpolate variables in messages. *Clarification:* I know tha...
You could create your own faces tag library to make it less verbose, something like: ``` <ph:i18n key="label.widget.count" p0="#{widgetCount}"/> ``` Then create the taglib in your view dir: /components/ph.taglib.xml ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE facelet-taglib PUBLIC "-//Sun Microsystems, Inc....
Since you're using Seam, [you can use EL](http://docs.jboss.com/seam/2.1.0.BETA1/reference/en-US/html_single/#d0e13037) in the messages file. Property: ``` label.widget.count = You have a total of #{widgetCount} widgets. ``` XHTML: ``` <h:outputFormat value="#{messages['label.widget.count']}" /> ``` This still use...
Internationalised labels in JSF/Facelets
[ "", "java", "jsf", "internationalization", "facelets", "" ]
Using a configuration file I want to enable myself to turn on and off things like (third party) logging and using a cache in a C# website. The solution should not be restricted to logging and caching in particular but more general, so I can use it for other things as well. I have a configuration xml file in which I ca...
I'm curious what kind of logging/caching statements you have? If you have some class that is doing WriteLog or StoreCahce or whatever... why not just put the if(logging) in the WriteLog method. It seems like if you put all of your logging caching related methods into once class and that class knew whether logging/cachi...
Why not just use the web.config and the System.Configuration functionality that already exists? Your web app is going to parse web.config on every page load anyway, so the overhead involved in having yet another XML config file seems overkill when you can just define your own section on the existing configuration.
How to conditionally enable actions in C# ASP.NET website
[ "", "c#", "" ]
Does anyone know of any 'standard' way to interface with a telephony system (think Cisco CCM) from a C/C++ app in \*nix? I have used MS TAPI in the past but this is Windows only and don't want to go the jTAPI (Java) route, which seems to be the only option on the face of it. I want to monitor the phone system for logg...
I have experience with two telephony standards TAPI, and CSTA, as far as I know there is no such agreement between vendors (e.g. Cisco, Nortel, NEC) regarding THE standard API. I would recommend looking at the availability of [SMDR](http://en.wikipedia.org/wiki/Call_detail_record) (Station Messaging Detail Recording) ...
Here's another vote for SMDR. The telephony systems I've seen all offer the option of SMDR logging through a serial port on the phone box. Just capture the text from the serial port and parse it as needed. I wrote a server process that captures the SMDR output, parses it and saves the result in a database that our oth...
Interfacing with telephony systems from *nix
[ "", "c++", "unix", "cisco", "tapi", "" ]
I'm regularly running into similar situations : I have a bunch of COM .DLLs (no IDL files) which I need to use and invoke to be able to access some foreign (non-open, non-documented) data format. Microsoft's Visual Studio platform has very nice capabilities to import such COM DLLs and use them in my project (Visual C+...
Answering myself but I managed to find the **perfect** library for OLE/COM calling in non-Microsoft compilers : [disphelper](http://disphelper.sourceforge.net/). (it's available from [sourceforge.net](http://sourceforge.net/projects/disphelper/) under a permissive BSD license). It works both in C and C++ (and thus an...
The problem with the Ole/Com Object Viewer packaged with Visual Studio and Windows SDKs is that it produces a broken .IDL out of the .DLL, which can't further be compiled by MIDL into a .H/.CPP pair. Wine's own reimplementation of OleViewer is currently unstable and crashes when trying to use those libraries.
Using Component Object Model (COM) on non-Microsoft platforms
[ "", "c++", "com", "cygwin", "mingw", "wine", "" ]
* Do you need to use some kind of provider? * Can you setup your own SMS server? * Does any open source solutions exist? I am an SMS newbie so any insight on how this is accomplished would be great. I am partial to Java but any language is fine.
This is easy. Yes, you need a "sms gateway" provider. There are a lot out there. These companies provide APIs for you to send/receive SMS. e.g. the German company [Mobilant](http://mobilant.de/) provides an easy API. If you want to receive a SMS just program a simple PHP / JSP / s.th.else dynamic web page and let Mobi...
I used kannel on a linux box with an old mobile phone connected via a serial cable to the box. Got a pre-paid card in the phone as I was using it for private use only. Worked like a charm!
What can you use to get an application to be able to receive SMS message?
[ "", "java", "sms", "" ]
How to restrict the maximum number of characters that can be entered into an HTML `<textarea>`? I'm looking for a cross-browser solution.
The `TEXTAREA` tag does not have a `MAXLENGTH` attribute the way that an `INPUT` tag does, at least not in most standard browsers. A very simple and effective way to limit the number of characters that can be *typed* into a `TEXTAREA` tag is: ``` <textarea onKeyPress="return ( this.value.length < 50 );"></textarea> ``...
HTML5 now allows [`maxlength` attribute on `<textarea>`](https://developer.mozilla.org/en/docs/Web/HTML/Element/textarea#attr-maxlength). It is supported by all browsers except IE <= 9 and iOS Safari 8.4. See [support table on caniuse.com](http://caniuse.com/#feat=maxlength).
Max length for HTML <textarea>
[ "", "javascript", "html", "cross-browser", "textarea", "" ]
I'm trying to run a batch file, as another user, from my web app. For some reason, the batch file hangs! I can see "cmd.exe" running in the task manager, but it just sits there forever, unable to be killed, and the batch file is not running. Here's my code: ``` SecureString password = new SecureString(); foreach (char...
I believe I've found the answer. It seems that Microsoft, in all their infinite wisdom, has blocked batch files from being executed by IIS in Windows Server 2003. Brenden Tompkins has a work-around here: <http://codebetter.com/blogs/brendan.tompkins/archive/2004/05/13/13484.aspx> That won't work for me, because my ba...
Why not just do all the work in C# instead of using batch files? I was bored so i wrote this real quick, it's just an outline of how I would do it since I don't know what the command line switches do or the file paths. ``` using System; using System.IO; using System.Text; using System.Security; using System.Diagnosti...
C#.Net: Why is my Process.Start() hanging?
[ "", "c#", ".net", "" ]
Either I had a bad dream recently or I am just too stupid to google, but I remember that someone somewhere wrote that ASP.net has a Function which allows "merging" multiple JavaScript files automatically and only delivering one file to the client, thus reducing the number of HTTP Requests. Server Side, you still kept ...
It's called [Script Combining](http://msdn.microsoft.com/en-us/library/cc837190.aspx). There is a video example from asp.net explaining it [here](http://www.asp.net/Learn/3.5-SP1/video-296.aspx).
you can find [here](http://www.codeproject.com/KB/aspnet/HttpCombine.aspx) an usefull article for it
Combining and Caching multiple JavaScript files in ASP.net
[ "", "asp.net", "javascript", "" ]
I want to limit my users to a directory and its sub directories but the "Parent Directory" button allows them to browse to an arbitrary directory. How should I go about doing that?
You can probably do this by setting your own [FileSystemView](https://docs.oracle.com/javase/8/docs/api/javax/swing/filechooser/FileSystemView.html).
Incase anyone else needs this in the future: ``` class DirectoryRestrictedFileSystemView extends FileSystemView { private final File[] rootDirectories; DirectoryRestrictedFileSystemView(File rootDirectory) { this.rootDirectories = new File[] {rootDirectory}; } DirectoryRestrictedFileSyste...
How do I restrict JFileChooser to a directory?
[ "", "java", "swing", "jfilechooser", "" ]
When designing LINQ classes using the LINQ to SQL designer I've sometimes needed to reorder the classes for the purposes of having the resultant columns in a DataGridView appear in a different order. Unfortunately this seems to be exceedingly difficult; you need to cut and paste properties about, or delete them and re-...
Using Linq-to-Sql, you can have columns in the DataGridView appear different than in the original table by: 1. In your Linq query, extract the columns that you want, in the order than you want, and store them in a var. Then the autogenerate columns should show them in that order in the DataGridView 2. Use Template col...
Open the [DataClasses].dbml file in your favorite XML editor, and reorder the [Column] elements for the table. Save, and reopen (or reload) the designer in Visual studio. The order of the columns displayed in the designer will be fixed.
How can you easily reorder columns in LINQ to SQL designer?
[ "", "c#", "linq", "linq-to-sql", "" ]
Is there a simple way to drop a group of interrelated tables in SQL Server? Ideally I'd like to avoid having to worry about what order they're being dropped in since I know the entire group will be gone by the end of the process.
At the risk of sounding stupid, I don't believe SQL Server supports the delete / cascade syntax. I think you can configure a delete rule to do cascading deletes (<http://msdn.microsoft.com/en-us/library/ms152507.aspx>), but as far as I know the trick with SQL Server is to just to run your drop query once for each table...
A diferent approach could be: first get rid of the constraints, then drop the tables in a single shot. In other words, a DROP CONSTRAINT for every constraint, then a DROP TABLE for each table; at this point the order of execution shouldn't be an issue.
Dropping a group of tables in SQL Server
[ "", "sql", "sql-server", "database", "" ]
How is your javaScript code organized? Does it follow patterns like MVC, or something else? I've been working on a side project for some time now, and the further I get, the more my webpage has turned into a full-featured application. Right now, I'm sticking with [jQuery](http://jquery.com), however, the logic on the ...
..but Javascript has many facets that **are** OO. Consider this: ``` var Vehicle = jQuery.Class.create({ init: function(name) { this.name = name; } }); var Car = Vehicle.extend({ fillGas: function(){ this.gas = 100; } }); ``` I've used this technique to create page-level javascript classes that...
JavaScriptMVC is a great choice for organizing and developing a large scale JS application. The architecture design very well thought out. There are 4 things you will ever do with JavaScript: 1. Respond to an event 2. Request Data / Manipulate Services (Ajax) 3. Add domain specific information to the ajax response. 4...
Alternative "architectural" approaches to javaScript client code?
[ "", "javascript", "model-view-controller", "architecture", "client", "ria", "" ]
Anybody have a good example how to deep clone a WPF object, preserving databindings? --- The marked answer is the first part. The second part is that you have to create an ExpressionConverter and inject it into the serialization process. Details for this are here: <http://www.codeproject.com/KB/WPF/xamlwriterandbi...
The simplest way that I've done it is to use a XamlWriter to save the WPF object as a string. The Save method will serialize the object and all of its children in the logical tree. Now you can create a new object and load it with a XamlReader. ex: Write the object to xaml (let's say the object was a Grid control): ``...
In .NET 4.0, the new xaml serialization stack makes this MUCH easier. ``` var sb = new StringBuilder(); var writer = XmlWriter.Create(sb, new XmlWriterSettings { Indent = true, ConformanceLevel = ConformanceLevel.Fragment, OmitXmlDeclaration = true, NamespaceHandling = NamespaceHandling.OmitDuplicates,...
How can you clone a WPF object?
[ "", "c#", "wpf", "binding", "clone", "" ]
So, I am seeing a curious problem. If I have a function ``` // counter wraps around to beginning eventually, omitted for clarity. var counter; cycleCharts(chartId) { // chartId should be undefined when called from setInterval console.log('chartId: ' + chartId); if(typeof chartId == 'undefined' || chartId ...
setInterval is feeding cycleCharts actual timing data ( so one can work out the actual time it ran and use to produce a less stilted response, mostly practical in animation ) you want ``` var cycleId = setInterval(function(){ cycleCharts(); }, 10000); ``` ( this behavior may not be standardized, so don't rely on it...
It tells you how many milliseconds late the callback is called.
Why is setInterval calling a function with random arguments?
[ "", "javascript", "firefox", "" ]
I'm working on some code to colorize an image in Java. Basically what I'd like to do is something along the lines of GIMP's colorize command, so that if I have a BufferedImage and a Color, I can colorize the Image with the given color. Anyone got any ideas? My current best guess at doing something like this is to get t...
I have never used GIMP's colorize command. However, if your getting the RGB value of each pixel and adding RGB value to it you should really use a **[LookupOp](http://docs.oracle.com/javase/7/docs/api/java/awt/image/LookupOp.html).** Here is some code that I wrote to apply a BufferedImageOp to a BufferedImage. Using N...
Let `Y = 0.3*R + 0.59*G + 0.11*B` for each pixel in the image, then set them to be `((R1+Y)/2,(G1+Y)/2,(B1+Y)/2)` if `(R1,G1,B1)` is what you are colorizing with.
Colorizing images in Java
[ "", "java", "colors", "bufferedimage", "colorize", "" ]
I would much prefer to do this without catching an exception in `LoadXml()` and using this results as part of my logic. Any ideas for a solution that doesn't involve manually parsing the xml myself? I think VB has a return value of false for this function instead of throwing an XmlException. Xml input is provided from ...
Just catch the exception. The small overhead from catching an exception drowns compared to parsing the XML. If you want the function (for stylistic reasons, not for performance), implement it yourself: ``` public class MyXmlDocument: XmlDocument { bool TryParseXml(string xml){ try{ ParseXml(xml); re...
Using a XmlValidatingReader will prevent the exceptions, if you provide your own ValidationEventHandler.
How to check for valid xml in string input before calling .LoadXml()
[ "", "c#", ".net", "xml", "exception", "" ]
What is the best way to find something in a list? I know LINQ has some nice tricks, but let's also get suggestions for C# 2.0. Lets get the best refactorings for this common code pattern. Currently I use code like this: ``` // mObjList is a List<MyObject> MyObject match = null; foreach (MyObject mo in mObjList) { ...
> @ Konrad: So how do you use it? Let's say I want to match mo.ID to magicNumber. In C# 2.0 you'd write: ``` result = mObjList.Find(delegate(int x) { return x.ID == magicNumber; }); ``` 3.0 knows lambdas: ``` result = mObjList.Find(x => x.ID == magicNumber); ```
Using a Lambda expression: ``` List<MyObject> list = new List<MyObject>(); // populate the list with objects.. return list.Find(o => o.Id == myCriteria); ```
Cleanest Way to Find a Match In a List
[ "", "c#", "refactoring", "" ]
The problem: Loading an excel spreadsheet template. Using the Save command with a different filename and then quitting the interop object. This ends up saving the original template file. Not the result that is liked. ``` public void saveAndExit(string filename) { excelApplication.Save(filename); excelA...
Excel interop is pretty painful. I dug up an old project I had, did a little fiddling, and I think this is what you're looking for. The other commenters are right, but, at least in my experience, there's a lot more to calling SaveAs() than you'd expect if you've used the same objects (without the interop wrapper) in VB...
Rather than using an ExcelApplication, you can use the Workbook object and call the SaveAs() method. You can pass the updated file name in there.
Using Interop with C#, Excel Save changing original. How to negate this?
[ "", "c#", "excel", "" ]
So, I need some help. I am working on a project in C++. However, I think I have somehow managed to corrupt my heap. This is based on the fact that I added an `std::string` to a class and assigning it a value from another `std::string`: ``` std::string hello = "Hello, world.\n"; /* exampleString = "Hello, world.\n" wou...
These are relatively cheap mechanisms for possibly solving the problem: 1. Keep an eye on my [heap corruption question](https://stackoverflow.com/questions/1069/heap-corruption-under-win32-how-to-locate) - I'm updating with the answers as they shake out. The first was balancing `new[]` and `delete[]`, but you're alrea...
We once had a bug which eluded all of the regular techniques, valgrind, purify etc. The crash only ever happened on machines with lots of memory and only on large input data sets. Eventually we tracked it down using debugger watch points. I'll try to describe the procedure here: 1) Find the cause of the failure. It l...
Of Memory Management, Heap Corruption, and C++
[ "", "c++", "memory", "stack", "heap-memory", "" ]
What profilers have you used when working with .net programs, and which would you particularly recommend?
I have used [JetBrains dotTrace](http://www.jetbrains.com/profiler/) and [Redgate ANTS](http://www.red-gate.com/products/ants_performance_profiler/) extensively. They are fairly similar in features and price. They both offer useful performance profiling and quite basic memory profiling. dotTrace integrates with Reshar...
Others have covered performance profiling, but **with regards to memory profiling** I'm currently evaluating both the Scitech .NET Memory Profiler 3.1 and ANTS Memory Profiler 5.1 (current versions as of September 2009). I tried the JetBrains one a year or two ago and it wasn't as good as ANTS (for memory profiling) so...
What Are Some Good .NET Profilers?
[ "", "c#", ".net", "profiling", "profiler", "" ]
In the code below I am using a recursive CTE(Common Table Expression) in SQL Server 2005 to try and find the top level parent of a basic hierarchical structure. The rule of this hierarchy is that every CustID has a ParentID and if the CustID has no parent then the ParentID = CustID and it is the highest level. ``` DEC...
If you just want want the highest recursion depth couldn't you do something like this?Then, when you actually query the CTE just look for the row with max(Depth)? Like so: ``` DECLARE @LookupID int --Our test value SET @LookupID = 1; WITH cteLevelOne (ParentID, CustID, Depth) AS ( SELECT a.ParentID, a.Cust...
I'm not certain I fully understand the problem, but just to hack & slash at it you could try: ``` SELECT TOP 1 FROM cteLevelOne ORDER BY CustID DESC ``` That assumes that the CustID is also in order as in the example, and not something like a GUID.
How do you get the last record generated in a recursive CTE?
[ "", "sql", "sql-server", "recursion", "common-table-expression", "" ]
What are the differences between delegates and an events? Don't both hold references to functions that can be executed?
An **Event** declaration adds a layer of abstraction and protection on the **delegate** instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list.
To understand the differences you can look at this 2 examples Example with Delegates (in this case, an Action - that is a kind of delegate that doesn't return a value) ``` public class Animal { public Action Run {get; set;} public void RaiseEvent() { if (Run != null) { Run(); ...
What are the differences between delegates and events?
[ "", "c#", "events", "delegates", "glossary", "" ]
I am using StretchImage because the box is resizable with splitters. It looks like the default is some kind of smooth bilinear filtering, causing my image to be blurry and have moire patterns.
I needed this functionality also. I made a class that inherits PictureBox, overrides `OnPaint` and adds a property to allow the interpolation mode to be set: ``` using System.Drawing.Drawing2D; using System.Windows.Forms; /// <summary> /// Inherits from PictureBox; adds Interpolation Mode Setting /// </summary> publi...
I suspect you're going to have to do the resizing manually thru the Image class and DrawImage function and respond to the resize events on the PictureBox.
How do I make a PictureBox use Nearest Neighbor resampling?
[ "", "c#", ".net", "winforms", "gdi+", "picturebox", "" ]
Recently I tried understanding the use of **java.math.MathContext** but failed to understand properly. Is it used for rounding in `java.math.BigDecimal`. If yes why does not it round the decimal digits but even mantissa part. From API docs, I came to know that it follows the standard specified in `ANSI X3.274-1996` an...
@jatan > Thanks for you answer. It makes sense. Can you please explain me MathContext in the context of BigDecimal#round method. There's nothing special about `BigDecimal.round()` *vs.* any other `BigDecimal` method. In all cases, the `MathContext` specifies the number of significant digits and the rounding technique...
For rounding just the fractional part of a BigDecimal, check out the `BigDecimal.setScale(int newScale, int roundingMode)` method. E.g. to change a number with three digits after the decimal point to one with two digits, and rounding up: ``` BigDecimal original = new BigDecimal("1.235"); BigDecimal scaled = original....
Use of java.math.MathContext
[ "", "java", "math", "bigdecimal", "mathcontext", "" ]