Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'll phrase this in the form of an example to make it more clear. Say I have a vector of animals and I want to go through the array and see if the elements are either dogs or cats? ``` class Dog: public Animal{/*...*/}; class Cat: public Animal{/*...*/}; int main() { vector<Animal*> stuff; //cramming the dogs and cats in... for(/*all elements in stuff*/) //Something to the effect of: if(stuff[i].getClass()==Dog) {/*do something*/} } ``` I hope that's sort of clear. I know about typeid, but I don't really have any Dog object to compare it to and I would like to avoid creating a Dog object if I can. Is there a way to do this? Thanks in advance.
As others has noted, you should neither use the `typeid`, nor the `dynamic_cast` operator to get the dynamic type of what your pointer points to. virtual functions were created to avoid this kind of nastiness. Anyway here is what you do if you **really** want to do it (note that dereferencing an iterator will give you `Animal*` . So if you do `**it` you will get an `Animal&`): ``` for(std::vector<Animal*>::iterator it = v.begin(); it != v.end(); ++it) { if(typeid(**it) == typeid(Dog)) { // it's a dog } else if(typeid(**it) == typeid(Cat)) { // it's a cat } } ``` Note you can apply the `typeid` operator to types itself too, as shown above. You don't need to create an object for this. Also note the typeid way doesn't work if you pass it a pointer like `typeid(*it)` . Using it like that will give you just `typeid(Animal*)` which isn't useful. Similar, `dynamic_cast` can be used: ``` for(std::vector<Animal*>::iterator it = v.begin(); it != v.end(); ++it) { if(Dog * dog = dynamic_cast<Dog*>(*it)) { // it's a dog (or inherited from it). use the pointer } else if(Cat * cat = dynamic_cast<Cat*>(*it)) { // it's a cat (or inherited from it). use the pointer. } } ``` Note that in both cases, your Animal type should be polymorph. That means it must have or inherited at least one virtual function.
You can use `dynamic_cast`, as long as the vector contains Animal pointers. ``` vector <Animal *> stuff; for(int i=0;i<stuff.size();i++) { Dog *pDog = dynamic_cast <Dog *> (stuff[i]); if(pDog) { // do whatever with the dog } Cat *pCat = dynamic_cast <Cat *> (stuff[i]); if(pCat) { // and so on } } ``` but you should be aware that this is generally not the best practice. You should try to work with polymorphism, not against it. In other words, try to write a virtual `Animal` function that `Dog` and `Cat` override, and let the compiler automagically call the right one. (Also, `dynamic_cast` is relatively slow, so too many of them will hinder performance; whereas a virtual function call is general just a single instruction.)
C++ class identification question
[ "", "c++", "class", "identification", "" ]
In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (becoming more) a stylistic decision rather than a practical one? For a concrete example, how should one handle construction of flexible URIs: ``` DOMAIN = 'http://stackoverflow.com' QUESTIONS = '/questions' def so_question_uri_sub(q_num): return "%s%s/%d" % (DOMAIN, QUESTIONS, q_num) def so_question_uri_cat(q_num): return DOMAIN + QUESTIONS + '/' + str(q_num) ``` Edit: There have also been suggestions about joining a list of strings and for using named substitution. These are variants on the central theme, which is, which way is the Right Way to do it at which time? Thanks for the responses!
Concatenation is (significantly) faster according to my machine. But stylistically, I'm willing to pay the price of substitution if performance is not critical. Well, and if I need formatting, there's no need to even ask the question... there's no option but to use interpolation/templating. ``` >>> import timeit >>> def so_q_sub(n): ... return "%s%s/%d" % (DOMAIN, QUESTIONS, n) ... >>> so_q_sub(1000) 'http://stackoverflow.com/questions/1000' >>> def so_q_cat(n): ... return DOMAIN + QUESTIONS + '/' + str(n) ... >>> so_q_cat(1000) 'http://stackoverflow.com/questions/1000' >>> t1 = timeit.Timer('so_q_sub(1000)','from __main__ import so_q_sub') >>> t2 = timeit.Timer('so_q_cat(1000)','from __main__ import so_q_cat') >>> t1.timeit(number=10000000) 12.166618871951641 >>> t2.timeit(number=10000000) 5.7813972166853773 >>> t1.timeit(number=1) 1.103492206766532e-05 >>> t2.timeit(number=1) 8.5206360154188587e-06 >>> def so_q_tmp(n): ... return "{d}{q}/{n}".format(d=DOMAIN,q=QUESTIONS,n=n) ... >>> so_q_tmp(1000) 'http://stackoverflow.com/questions/1000' >>> t3= timeit.Timer('so_q_tmp(1000)','from __main__ import so_q_tmp') >>> t3.timeit(number=10000000) 14.564135316080637 >>> def so_q_join(n): ... return ''.join([DOMAIN,QUESTIONS,'/',str(n)]) ... >>> so_q_join(1000) 'http://stackoverflow.com/questions/1000' >>> t4= timeit.Timer('so_q_join(1000)','from __main__ import so_q_join') >>> t4.timeit(number=10000000) 9.4431309007150048 ```
Don't forget about named substitution: ``` def so_question_uri_namedsub(q_num): return "%(domain)s%(questions)s/%(q_num)d" % locals() ```
String concatenation vs. string substitution in Python
[ "", "python", "string", "string-concatenation", "" ]
I can split editor panes horizontally or vertically, but it does not seem possible to view code in two separate physical windows. I am aware that Idea can open multiple **projects** in separate windows, but I'd like to be able to do this for two files in a **single** project. One answer suggested unpinning the tab, but I haven't been able to make that work (I'm on Mac OSX if that matters.) This seems like a basic feature in today's world of multi-headed workstations. Before moving to an IDE I used to do this regularly with good old Emacs. Is there some trick I am not aware of to make this happen?
Unfortunately there is no way (as of IDEA 8.0.1) to do what you're asking for. As you pointed out, you can split the editor pane but there is always exactly one editor per IDEA project. UPDATE: As of IDEA 10 (currently the latest is 10.5), the answer is yes, you can :-)
This is now possible in IDEA X. Hopefully you're still an IDEA user and can take advantage of this :)
Can IntelliJ IDEA open more than one editor window for files from the same project?
[ "", "java", "ide", "intellij-idea", "" ]
In C# if I want to convert a double (1.71472) to an int then I get the answer 2. If I do this in Java using intValue() method, I get 1 as the answer. Does Java round down on conversions? Why do the Java API docs have such scant information about their classes i.e. > Returns the value of the specified > number as an int. This may involve > rounding or truncation. A bit more info about the rounding would have been helpful!
Java rounds toward zero when narrowing from a floating point to an integer type—and so does C#, when you use the casting conversion. It's `Convert.ToInt32` that rounds: ``` double d = 1.71472; int x = (int) d; // x = 1 int y = Convert.ToInt32(d); // y = 2 ``` Details can be found in the [Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/conversions.html). Note that while the documentation cited in `Number` leaves options open for subclasses, the documentation on the concrete boxing types, like [`Double`,](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Double.html) is explicit about the implementation: > Returns the value of this Double as an > int (by casting to type int). When using [`BigDecimal`](http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html), you can specify one of eight different rounding policies.
Java rounds toward zero when narrowing from a floating point to an integer type. There's more documentation about the general rules in the [Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/conversions.html). Note that while the documentation in `Number` leaves options open for subclasses, the documentation on the concrete boxing types is more explicit: > Returns the value of this Double as an > int (by casting to type int). When using [BigDecimal](http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html), you can specify one of eight different rounding policies.
Different answer when converting a Double to an Int - Java vs .Net
[ "", "java", ".net", "rounding", "" ]
I was reading the Math.random() javadoc and saw that random is only psuedorandom. Is there a library (specifically java) that generates random numbers according to random variables like environmental temperature, CPU temperature/voltage, or anything like that?
Check out <http://random.org/> RANDOM.ORG is a true random number service that generates randomness via atmospheric noise. The Java library for interfacing with it can be found here: <http://sourceforge.net/projects/trng-random-org/>
Your question is ambiguous, which is causing the answers to be all over the place. If you are looking for a Random implementation which relies on the system's source of randomness (as I'm guessing you are), then java.security.SecureRandom does that. The default configuration for the Sun security provider in your java.security file has the following: ``` # # Select the source of seed data for SecureRandom. By default an # attempt is made to use the entropy gathering device specified by # the securerandom.source property. If an exception occurs when # accessing the URL then the traditional system/thread activity # algorithm is used. # # On Solaris and Linux systems, if file:/dev/urandom is specified and it # exists, a special SecureRandom implementation is activated by default. # This "NativePRNG" reads random bytes directly from /dev/urandom. # # On Windows systems, the URLs file:/dev/random and file:/dev/urandom # enables use of the Microsoft CryptoAPI seed functionality. # securerandom.source=file:/dev/urandom ``` If you are really asking about overriding this with something even more truly random, it can be done either by changing this property, or by using another SecureRandom. For example, you could use a JCE provider backed by an HSM module such as [nCipher nShield](http://www.ncipher.com/%7E/link.aspx?_id=3F2B4E1B9AE84FD38B3548927B556C51&_z=z) which has its own PRNG, or other solutions mentioned in the thread.
True random generation in Java
[ "", "java", "random", "" ]
I am trying to respond back to a client with a PDF stored in a MSSQL varbinary(MAX) field. The response works on my localhost and a test server over http connection, but does not work on the production server over https connection. I am using just a simple BinaryWrite (code below). ``` byte[] displayFile = DatabaseFiles.getPdfById(id); Response.ContentType = "application/pdf"; Response.BinaryWrite(displayFile); ``` Nothing fancy here. Just grab the binary data, set the content type, and write back to client. Is there anything special that needs to be done in order to respond back over https in this way? **Edit:** By doesn't work, I mean that I get a blank document in the browser. Acrobat does not load in browser. **Edit:** I just noticed that this problem is only occurring in IE 7. The PDF loads correctly in Firefox 3. Our client uses IE 7 exclusively (better than IE 6 which I persuaded them upgrade from...lol). **Edit:** Tried to add the header "content-disposition" to make the file act as an attachment. Browser failed to loaded under SSL with the IE error "Internet Explorer cannot download displayFile.aspx from ProductionServer.net." (Code Below) ``` byte[] displayFile = DatabaseFiles.getPdfById(id); Response.Clear(); Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", fileName)); Response.ContentType = "application/pdf"; Response.BinaryWrite(displayFile); ``` **Edit:** If the file is viewed over http on the Production Server, the browser displays the code for the PDF like it was being viewed through NotePad. (e.g. %PDF-1.4 %âãÏÓ 6 0 obj <> endobj xref 6 33 ...etc)
I just managed to get around this by replacing ``` Response.Clear(); ``` with ``` Response.ClearContent(); Response.ClearHeaders(); ``` so the whole thing looks like: ``` byte[] downloadBytes = doc.GetData(); Response.ClearContent(); Response.ClearHeaders(); Response.Buffer = true; Response.ContentType = "application/pdf"; Response.AddHeader("Content-Length", downloadBytes.Length.ToString()); Response.AddHeader("Content-Disposition", "attachment; filename=myFile.pdf"); Response.BinaryWrite(downloadBytes); Response.Flush(); Response.End(); ```
IE 7 has/had a [mime type "issue"](http://support.microsoft.com/kb/945686) with PDF, related to the [convoluted mime type rules](http://msdn.microsoft.com/en-us/library/ms775147.aspx). You may want to verify if the client has that patch. There's also been sporadic complaints of IE 7 blank pages due to other reasons (script tags, response.flush, and keepalives among them) that, AFAIK, have not been reliably solved. Luckily, it sounds like this is happening every time - so you should be able to get to the bottom of it fairly quickly. You can try associating .pdf with ASP.NET, so that the url is picked up as a PDF file by IE. That should override the mime type issue. Redirects (HTTP Response.Redirect, Javascript based, and links) seem to help some other issues. Checking IIS keepalive settings on the production server, or watching with Fiddler, will show you if keepalives are an issue. *Maybe* adding a content-disposition header would help...That's off the top of my head, though. My guess is that the SSL relation is a red herring, so I'd check with non-SSL on the production server as well.
C# BinaryWrite over SSL
[ "", "c#", ".net", "file", "binary", "" ]
I know this specific question has been [asked before](https://stackoverflow.com/questions/185235/jquery-tabs-getting-newly-selected-index), but I am not getting any results using the `bind()` event on the `jQuery UI Tabs` plugin. I just need the `index` of the newly selected tab to perform an action when the tab is clicked. `bind()` allows me to hook into the select event, but my usual method of getting the currently selected tab does not work. It returns the previously selected tab index, not the new one: ``` var selectedTab = $("#TabList").tabs().data("selected.tabs"); ``` Here is the code I am attempting to use to get the currently selected tab: ``` $("#TabList").bind("tabsselect", function(event, ui) { }); ``` **When I use this code, the ui object comes back `undefined`**. From the documentation, this should be the object I'm using to hook into the newly selected index using ui.tab. I have tried this on the initial `tabs()` call and also on its own. Am I doing something wrong here?
**For JQuery UI versions before 1.9**: `ui.index` from the `event` is what you want. **For JQuery UI 1.9 or later**: see the [answer](https://stackoverflow.com/a/12973370/2333214) by Giorgio Luparia, below.
If you need to get the tab index from outside the context of a tabs event, use this: ``` function getSelectedTabIndex() { return $("#TabList").tabs('option', 'selected'); } ``` Update: From version 1.9 'selected' is changed to 'active' ``` $("#TabList").tabs('option', 'active') ```
jQuery UI Tabs - How to Get Currently Selected Tab Index
[ "", "javascript", "jquery", "jquery-ui", "tabs", "jquery-ui-tabs", "" ]
In a project we have text files looking like this: ``` mv A, R3 mv R2, B mv R1, R3 mv B, R4 add A, R1 add B, R1 add R1, R2 add R3, R3 add R21, X add R12, Y mv X, R2 ``` I need to replace the strings according to the following, but I am looking for a more general solution. ``` R1 => R2 R2 => R3 R3 => R1 R12 => R21 R21 => R12 ``` I know I could do it in Perl, the replace() function in the following code, but the real application is written in Java, so the solution needs to be in Java as well. ``` #!/usr/bin/perl use strict; use warnings; use File::Slurp qw(read_file write_file); my %map = ( R1 => 'R2', R2 => 'R3', R3 => 'R1', R12 => 'R21', R21 => 'R12', ); replace(\%map, \@ARGV); sub replace { my ($map, $files) = @_; # Create R12|R21|R1|R2|R3 # making sure R12 is before R1 my $regex = join "|", sort { length($b) <=> length($a) } keys %$map; my $ts = time; foreach my $file (@$files) { my $data = read_file($file); $data =~ s/\b($regex)\b/$map{$1}/g; rename $file, "$file.$ts"; # backup with current timestamp write_file( $file, $data); } } ``` Your help for the Java implementation would be appreciated.
I've actually had to use this sort of algorithm several times in the past two weeks. So here it is the world's second-most verbose language... ``` import java.util.HashMap; import java.util.regex.Pattern; import java.util.regex.Matcher; /* R1 => R2 R2 => R3 R3 => R1 R12 => R21 R21 => R12 */ String inputString = "mv A, R3\n" + "mv R2, B\n" + "mv R1, R3\n" + "mv B, R4\n" + "add A, R1\n" + "add B, R1\n" + "add R1, R2\n" + "add R3, R3\n" + "add R21, X\n" + "add R12, Y\n" + "mv X, R2" ; System.out.println( "inputString = \"" + inputString + "\"" ); HashMap h = new HashMap(); h.put( "R1", "R2" ); h.put( "R2", "R3" ); h.put( "R3", "R1" ); h.put( "R12", "R21" ); h.put( "R21", "R12" ); Pattern p = Pattern.compile( "\\b(R(?:12?|21?|3))\\b"); Matcher m = p.matcher( inputString ); StringBuffer sbuff = new StringBuffer(); int lastEnd = 0; while ( m.find()) { int mstart = m.start(); if ( lastEnd < mstart ) { sbuff.append( inputString.substring( lastEnd, mstart )); } String key = m.group( 1 ); String value = (String)h.get( key ); sbuff.append( value ); lastEnd = m.end(); } if ( lastEnd < inputString.length() ) { sbuff.append( inputString.substring( lastEnd )); } System.out.println( "sbuff = \"" + sbuff + "\"" ); ``` This can be Java-ified by these classes: ``` import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; interface StringReplacer { public CharSequence getReplacement( Matcher matcher ); } class Replacementifier { static Comparator keyComparator = new Comparator() { public int compare( Object o1, Object o2 ) { String s1 = (String)o1; String s2 = (String)o2; int diff = s1.length() - s2.length(); return diff != 0 ? diff : s1.compareTo( s2 ); } }; Map replaceMap = null; public Replacementifier( Map aMap ) { if ( aMap != null ) { setReplacements( aMap ); } } public setReplacements( Map aMap ) { replaceMap = aMap; } private static String createKeyExpression( Map m ) { Set set = new TreeSet( keyComparator ); set.addAll( m.keySet()); Iterator sit = set.iterator(); StringBuffer sb = new StringBuffer( "(" + sit.next()); while ( sit.hasNext()) { sb.append( "|" ).append( sit.next()); } sb.append( ")" ); return sb.toString(); } public String replace( Pattern pattern, CharSequence input, StringReplacer replaceFilter ) { StringBuffer output = new StringBuffer(); Matcher matcher = pattern.matcher( inputString ); int lastEnd = 0; while ( matcher.find()) { int mstart = matcher.start(); if ( lastEnd < mstart ) { output.append( inputString.substring( lastEnd, mstart )); } CharSequence cs = replaceFilter.getReplacement( matcher ); if ( cs != null ) { output.append( cs ); } lastEnd = matcher.end(); } if ( lastEnd < inputString.length() ) { sbuff.append( inputString.substring( lastEnd )); } } public String replace( Map rMap, CharSequence input ) { // pre-condition if ( rMap == null && replaceMap == null ) return input; Map repMap = rMap != null ? rMap : replaceMap; Pattern pattern = Pattern.compile( createKeyExpression( repMap )) ; StringReplacer replacer = new StringReplacer() { public CharSequence getReplacement( Matcher matcher ) { String key = matcher.group( 1 ); return (String)repMap.get( key ); } }; return replace( pattern, input, replacer ); } } ```
The perl solution has an advantage of replacing all strings in one shot, sort of "transactionally". If you don't have the same option in Java (and I can't think of a way make it happen), you need to be careful of replacing R1=>R2, then R2=>R3. In that case, both R1 and R2 end up being replaced with R3.
How can I replace strings in a text in Java?
[ "", "java", "regex", "perl", "" ]
I need a Java library to convert PDFs to TIFF images. The PDFs are faxes, and I will be converting to TIFF so that I can then do barcode recognition on the image. Can anyone recommend a good free open source library for conversion from PDF to TIFF?
Disclaimer: I work for Atalasoft [We have an SDK that can convert PDF to TIFF](http://www.atalasoft.com/products/dotimage/). The rendering is powered by Foxit software which makes a very powerful and efficient PDF renderer.
I can't recommend any code library, but it's easy to use GhostScript to convert PDF into bitmap formats. I've personally used the script below (which also uses the netpbm utilties) to convert the *first* page of a PDF into a JPEG thumbnail: ``` #!/bin/sh /opt/local/bin/gs -q -dLastPage=1 -dNOPAUSE -dBATCH -dSAFER -r300 \ -sDEVICE=pnmraw -sOutputFile=- $* | pnmcrop | pnmscale -width 240 | cjpeg ``` You can use `-sDEVICE=tiff...` to get direct TIFF output in various TIFF sub-formats from GhostScript.
A good library for converting PDF to TIFF?
[ "", "java", "pdf", "tiff", "" ]
I'm researching this for a project and I'm wondering what other people are doing to prevent stale CSS and JavaScript files from being served with each new release. I don't want to append a timestamp or something similar which may prevent caching on every request. I'm working with the Spring 2.5 MVC framework and I'm already using the google api's to serve prototype and scriptaculous. I'm also considering using Amazon S3 and the new Cloudfront offering to minimize network latency.
I add a parameter to the request with the revision number, something like: ``` <script type="text/javascript" src="/path/to/script.js?ver=456"></script> ``` The 'ver' parameter is updated automatically with each build (read from file, which the build updates). This makes sure the scripts are cached only for the current revision.
Like @eran-galperin, I use a parameter in the reference to the JS file, but I include a server-generated reference to the file's "last modified" date. @stein-g-strindhaug suggests this approach. It would look something like this: ``` <script type="text/javascript" src="/path/to/script.js?1347486578"></script> ``` The server ignores the parameter for the static file and the client may cache the script until the date code changes. If (and only if) you modify the JS file on the server, the date code will change automatically. For instance, in PHP, my script to create this code looks like this: ``` function cachePreventCode($filename) { if (!file_exists($filename)) return ""; $mtime = filemtime($filename); return $mtime; } ``` So then when your PHP file includes a reference to a CSS file, it might look like this: ``` <link rel="stylesheet" type="text/css" href="main.css?<?= cachePreventCode("main.css") ?>" /> ``` ... which will create ... ``` <link rel="stylesheet" type="text/css" href="main.css?1347489244" /> ```
What are best practices for preventing stale CSS and JavaScript
[ "", "javascript", "css", "spring-mvc", "amazon-s3", "" ]
Both of these appservers are at least in part OSGI based. One (Glassfish) is obviously Java EE while the other isn't. Now I'm at the stage of choosing a platform for a new project and the natural choice is Glassfish v3 Prelude. This does raise the issue of perhaps we should be using S2AP instead. The question then is this: does the springsource dm server offer any compelling reason to use it over Glassfish? And vice versa.
Java EE app servers have distributed transaction managers. If that is at all important, then may want to see if SpringSource dm includes such. It is possible to do XA TX with Spring-Framework, is just that you're left on your own to locate a suitable XA manager and integrate it. Course XA TX have very much fallen into disrepute. Most folks try to avoid them like the plague. Amazon.com, for instance, does not use them. We currently use Spring-Framework and Tomcat in combo. We do all our own integration. Lots of folks have made similar middle-tier stack choice. We do get tied to Spring-Framework APIs - just like Java EE folks get tied to Java EE/EJB. Don't let Spring rhetoric fool you about that one. However, it continues to remain open source accessible to community of users. Once you go Java EE, you get tied to a particular Java EE vendor as it's difficult to move between implementations. EJB3 supposedly will ease this, but would bet it will still be a major undertaking to switch Java EE app servers. Frankly Spring-Framework provides more useful APIs than the Java EE/EJB standard and it is innovating at a more rapid rate.
This is an old thread but I thought it would be useful for people coming across this (as I did) to share the recent GlassFish OSGi enhancements, mainly in the area of OSGi Enterprise RFC's : <http://wiki.glassfish.java.net/Wiki.jsp?page=OsgiDashboard> Of course there's also the @Resource-based injection of OSGi Declarative Services that's been there since v3 in December '09.
Advantages/disadvantages of Glassfish v3 Prelude vs Springsource dm server for Web applications?
[ "", "java", "spring", "jakarta-ee", "glassfish", "" ]
DataGridView.CellContentClick is not firing if I mouse click a DataGridViewCheckBoxCell very fast. How can I solve this? I need to know when CheckBox's check state changes
Try handling the `CellMouseUp` event. You can check which colum the `MouseUp` event occurred in to see if it is your checkbox column. You can also find out if it is in edit mode and end the edit mode programmatically, which in turn will fire the `CellValueChanged` event. In the example below, I have a DataGridView with two colums. The first is a `DataGridViewTextBoxColumn` and the second is a `DataGridViewCheckBoxColumn`. When the checkbox changes, the first column wil reflect its check state, without having to move from the row or cell. ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); dataGridView1.Rows.Add("False", false); dataGridView1.Rows.Add("True", true); } private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e) { if (e.ColumnIndex == 1 && e.RowIndex >-1 && dataGridView1.Rows[e.RowIndex].Cells[1].IsInEditMode) { dataGridView1.EndEdit(); } } private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex != -1) { dataGridView1.Rows[e.RowIndex].Cells[0].Value = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(); } } } ```
Regardless of how fast the user clicks in the checkbox cell, the value won't change from true to false or vise versa until they click out of that row, and the DataGridView goes out of edit mode. What I've done in the past, is set that column to ReadOnly = true. Then, in the CellContentClick event handler, if that column was clicked, I manually flipped the bool like this: ``` bool b = (bool)this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = !b; ``` Then, you can do your logic at this point that you would normally do for the CheckChanged.
DataGridView.CellContentClick
[ "", "c#", "winforms", "" ]
I am using VMware Workstation 6.5 on Windows Vista x64. I would like to automate some of the VM management tasks. I know that there is a COM API (<http://www.vmware.com/support/developer/vix-api/>) available which I could use directly. Is there a C# wrapper for this COM API? Thanks, Arnie
ArnieZ. Any COM DLL can be used from .NET. Adding it as reference in visual studio will generate a DLL called "YourDll.Interop.dll" This is a .NET -> COM marshaling library, and will do what you need. You can also generate this from the command line using tlbimp.exe Of course, you'll have to keep in mind that you are invoking COM components, and remember to use the .NET Marshaling API to decrease reference counts when you are done using them, otherwise you will cause memory leaks. I've wrapped the interop implementation in another library that implements IDisposable on its objects so that cleanup is handled automatically before, but if it is a large library, this might not be worth the effort.
There's now a nice library that wraps this up: <http://www.codeproject.com/KB/library/VMWareTasks.aspx>
Is there a C# wrapper for the VMware VIX API?
[ "", "c#", "api", "vmware", "wrapper", "vix", "" ]
I have a table that represents a series of matches between ids from another table as follows: ``` CREATE TABLE #matches ( asid1 int, asid2 int ) insert into #matches values (1,2) insert into #matches values (1,3) insert into #matches values (3,1) insert into #matches values (3,4) insert into #matches values (7,6) insert into #matches values (5,7) insert into #matches values (8,1) insert into #matches values (1,8) insert into #matches values (8,9) insert into #matches values (8,3) insert into #matches values (10,11) insert into #matches values (12,10) ``` and I want to find groups of matches that are linked directly or indirectly to one another. The output would look like this: ``` group asid 1 1 1 2 1 3 1 4 1 8 1 9 2 5 2 6 2 7 3 10 3 11 3 12 ``` if I were to add another row: ``` insert into #matches values (7,8) ``` then this would mean that 2 of the groups above would be linked, so I would require output: ``` group asid 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 10 2 11 2 12 ``` Any ideas? Edit: Further research leads me to believe that a recursive common table expression should do the trick... if I figure out something elegant I'll post it
It appears that a [Disjoint-set](http://en.wikipedia.org/wiki/Disjoint-set_data_structure) is what you need to solve this. Here is a [listing](http://www.emilstefanov.net/Programming/DisjointSets.aspx) of a C# and C++ implementation.
If this can be done at all within SQL, it's going to be insanely difficult. You should analyze that table in whatever programming language you're using.
linking groups of matches
[ "", "sql", "sql-server", "t-sql", "" ]
I see in a header that I didn't write myself the following: ``` class MonitorObjectString: public MonitorObject { // some other declarations friend inline bool operator==(MonitorObjectString& lhs, MonitorObjectString& rhs) { return(lhs.fVal==rhs.fVal); } ``` I can't understand why this method is declared as friend. I thought it would make sense if the function is defined in another place and needs to access the internal member of the class, but this is not the case here as it is inline and doesn't even need to have access to the members. What do you think? Is the "friend" useless?
``` friend inline bool operator==(MonitorObjectString& lhs, MonitorObjectString& rhs) { return(lhs.fVal==rhs.fVal); } ``` is sometimes called `friend definition`, because it is a friend declaration that also defines the function. It will define the function as a non-member function of the namespace surrounding the class it appears in. Actually, the inline there is redundant: It's implicitly declared inline if it's a friend definition. Some pros and cons of it: * It makes the operator not visible to normal lookup. The only way you can call it is using argument dependent look-up. This will keep the namespace free of lots of operator declarations visible normally. Note that this will also disable the ability of calling it using implicit conversions to MonitorObjectString (because if both argument types do not match at the time of looking for candidates to be called, argument dependent look-up won't find the function). * The lookup for names starts in the scope of the class the friend definition appears in. This means that no long type-names or other names need to be written out. Just refer them as you would in a normal member function of the class. * As it is a friend, the function sees the internals of `MonitorObjectString`. But that's neither good nor bad. It depends on the situation. For example if there are functions `getFVal()` making the function friend is pretty pointless. Could use `getFVal` as-well then. I used to like this friend definition style of operators, because they have direct access to class members, and appear within the class definition - so I could have "everything with one sight". Recently, however, I came to the conclusion that it's not always a good idea. If you can (and you should) implement the operator purely using public member functions of the class, you should make it a non-friend (and non-member) operator, defined in the same namespace of the class. It makes sure that if you change some implementation - but keep the interface of the class the same - the operator will still work and you have less cascading changes, because you know it can't access implementation details. *However*, I prefer this style over writing member operators, because operator functions at namespace scope have the added features of being symmetric with their arguments: They don't treat the left side special, because both sides are just normal arguments and not object arguments that are bound to `*this`. If either the left or the right side is of the type of your class, the other side can be implicitly converted - regardless of whether it's left or right. For functions that are also defined without the friend definition syntax (traditionally, at namespace scope), you will have the feature of selectively including headers that make those operators available or not.
Grammatically speaking... The `friend` keyword is still needed to tell the compiler that this function is not a member of a class, **EDIT:** but instead a non-member function that can see the private members of the class. --- However, this could have been implemented more cleanly like this: ``` /* friend */ inline bool operator ==(const MonitorObjectString& rhs) const { return fVal == rhs.fVal; } ``` (Of course, I'm assuming `fVal` is of a suitable type that can be compared without affecting its const-ness.)
friend AND inline method, what's the point ?
[ "", "c++", "methods", "inline", "friend", "" ]
I am trying to send some data from a LINQ query in C# to an Excel speed sheet using OLE I have a query like this: ``` Var data = from d in db.{MyTable} where d.Name = "Test" select d; ``` I have the Excel OLE object working fine, I just can't figure out how to populate the cells in Excel with the data from the LINQ query. PS: I am using Excel 2003 if that makes any difference. Can anyone help me with this?
Sending individual OLE commands for each Excel cell is very slow so the key is to create an object array like this: ``` int noOfRows = data.Count - 1; int noOfColumns = mydataclass.GetType().GetProperties().Count() - 1; Object[noOfRows, noOfColumns] myArray; ``` Sending an object array allows you to send a mixture of data types e.g. string, integer, date etc. However, if you know that the data is all text for example, you can just send a string array. The array needs to be populated from the query either by assigning each individual value or perhaps by using reflection to get the data object properties. Then you can send the array to Excel like this: ``` XLOLESheetobj.Range("A1","Z20").Value = myArray; ``` You can substitute Z20 with the number of columns -> Char + the number of rows -> string.
I assume you are not using OLE in a web scenario, because it will eventually fail. If you just need raw data, you can dump to a tab-delimited textfile: var lines = data.Select(d => d.Name + '\t' + d.AnotherProperty + ...);
Populate Excel with data from LINQ to SQL query
[ "", "c#", "winforms", "linq", "excel", "ole", "" ]
I usually do not have difficulty to read JavaScript code but for this one I can’t figure out the logic. The code is from an exploit that has been published 4 days ago. You can find it at [milw0rm](https://web.archive.org/web/20100412164007/http://www.milw0rm.com/exploits/7477). Here is the code: ``` <html> <div id="replace">x</div> <script> // windows/exec - 148 bytes // http://www.metasploit.com // Encoder: x86/shikata_ga_nai // EXITFUNC=process, CMD=calc.exe var shellcode = unescape("%uc92b%u1fb1%u0cbd%uc536%udb9b%ud9c5%u2474%u5af4%uea83%u31fc%u0b6a%u6a03%ud407%u6730%u5cff%u98bb%ud7ff%ua4fe%u9b74%uad05%u8b8b%u028d%ud893%ubccd%u35a2%u37b8%u4290%ua63a%u94e9%u9aa4%ud58d%ue5a3%u1f4c%ueb46%u4b8c%ud0ad%ua844%u524a%u3b81%ub80d%ud748%u4bd4%u6c46%u1392%u734a%u204f%uf86e%udc8e%ua207%u26b4%u04d4%ud084%uecba%u9782%u217c%ue8c0%uca8c%uf4a6%u4721%u0d2e%ua0b0%ucd2c%u00a8%ub05b%u43f4%u24e8%u7a9c%ubb85%u7dcb%ua07d%ued92%u09e1%u9631%u5580"); // ugly heap spray, the d0nkey way! // works most of the time var spray = unescape("%u0a0a%u0a0a"); do { spray += spray; } while(spray.length < 0xd0000); memory = new Array(); for(i = 0; i < 100; i++) memory[i] = spray + shellcode; xmlcode = "<XML ID=I><X><C><![CDATA[<image SRC=http://&#x0a0a;&#x0a0a;.example.com>]]></C></X></XML><SPAN DATASRC=#I DATAFLD=C DATAFORMATAS=HTML><XML ID=I></XML><SPAN DATASRC=#I DATAFLD=C DATAFORMATAS=HTML></SPAN></SPAN>"; tag = document.getElementById("replace"); tag.innerHTML = xmlcode; </script> </html> ``` Here is what I believe it does and I would like you to help me for the part that I misunderstand. The variable `shellcode` contains the code to open the `calc.exe`. I do not get how they have found that weird string. Any idea? The second thing is the variable `spray`. I do not understand this weird loop. The third thing is the variable `memory` that is never used anywhere. Why do they create it? Last thing: what does the XML tag do in the page? --- For the moment I have good answers but mostly very general ones. I would like more explanations of the value of the code. An example is `unescape("%u0a0a%u0a0a");`. What does it mean? Same thing for the loop: why did the developer write: `length < 0xd0000`? I would like a deeper understanding, not only the theory of this code.
The shellcode contains some x86 assembly instructions that will do the actual exploit. `spray` creates a long sequence of instructions that will be put in `memory`. Since we can't usually find out the exact location of our shellcode in memory, we put a lot of `nop` instructions before it and jump to somewhere there. The `memory` array will hold the actual x86 code along with the jumping mechanism. We'll feed the crafted XML to the library which has a bug. When it's being parsed, the bug will cause the instruction pointer register to be assigned to somewhere in our exploit, leading to arbitrary code execution. To understand more deeply, you should actually figure out what is in the x86 code. `unscape` will be used to put the sequence of bytes represented of the string in the `spray` variable. It's valid x86 code that fills a large chunk of the heap and jumps to the start of shellcode. The reason for the ending condition is string length limitations of the scripting engine. You can't have strings larger than a specific length. In x86 assembly, `0a0a` represents `or cl, [edx]`. This is effectively equivalent to `nop` instruction for the purposes of our exploit. Wherever we jump to in the `spray`, we'll get to the next instruction until we reach the shellcode which is the code we actually want to execute. If you look at the XML, you'll see `0x0a0a` is there too. Exactly describing what happens requires specific knowledge of the exploit (you have to know where the bug is and how it's exploited, which I don't know). However, it seems that we force Internet Explorer to trigger the buggy code by setting the `innerHtml` to that malicious XML string. Internet Explorer tries to parse it and the buggy code somehow gives control to a location of memory where the array exists (since it's a large chunk, the probability of jumping there is high). When we jump there the CPU will keep executing `or cl, [edx]` instructions until in reaches the beginning of shellcode that's put in memory. I've disassembled the shellcode: ``` 00000000 C9 leave 00000001 2B1F sub ebx,[edi] 00000003 B10C mov cl,0xc 00000005 BDC536DB9B mov ebp,0x9bdb36c5 0000000A D9C5 fld st5 0000000C 2474 and al,0x74 0000000E 5A pop edx 0000000F F4 hlt 00000010 EA8331FC0B6A6A jmp 0x6a6a:0xbfc3183 00000017 03D4 add edx,esp 00000019 07 pop es 0000001A 67305CFF xor [si-0x1],bl 0000001E 98 cwde 0000001F BBD7FFA4FE mov ebx,0xfea4ffd7 00000024 9B wait 00000025 74AD jz 0xffffffd4 00000027 058B8B028D add eax,0x8d028b8b 0000002C D893BCCD35A2 fcom dword [ebx+0xa235cdbc] 00000032 37 aaa 00000033 B84290A63A mov eax,0x3aa69042 00000038 94 xchg eax,esp 00000039 E99AA4D58D jmp 0x8dd5a4d8 0000003E E5A3 in eax,0xa3 00000040 1F pop ds 00000041 4C dec esp 00000042 EB46 jmp short 0x8a 00000044 4B dec ebx 00000045 8CD0 mov eax,ss 00000047 AD lodsd 00000048 A844 test al,0x44 0000004A 52 push edx 0000004B 4A dec edx 0000004C 3B81B80DD748 cmp eax,[ecx+0x48d70db8] 00000052 4B dec ebx 00000053 D46C aam 0x6c 00000055 46 inc esi 00000056 1392734A204F adc edx,[edx+0x4f204a73] 0000005C F8 clc 0000005D 6E outsb 0000005E DC8EA20726B4 fmul qword [esi+0xb42607a2] 00000064 04D4 add al,0xd4 00000066 D084ECBA978221 rol byte [esp+ebp*8+0x218297ba],1 0000006D 7CE8 jl 0x57 0000006F C0CA8C ror dl,0x8c 00000072 F4 hlt 00000073 A6 cmpsb 00000074 47 inc edi 00000075 210D2EA0B0CD and [0xcdb0a02e],ecx 0000007B 2CA8 sub al,0xa8 0000007D B05B mov al,0x5b 0000007F 43 inc ebx 00000080 F4 hlt 00000081 24E8 and al,0xe8 00000083 7A9C jpe 0x21 00000085 BB857DCBA0 mov ebx,0xa0cb7d85 0000008A 7DED jnl 0x79 0000008C 92 xchg eax,edx 0000008D 09E1 or ecx,esp 0000008F 96 xchg eax,esi 00000090 315580 xor [ebp-0x80],edx ``` Understanding this shellcode requires x86 assembly knowledge and the problem in the MS library itself (to know what the system state is when we reach here), not JavaScript! This code will in turn execute `calc.exe`.
This looks like an exploit of the [recent Internet Explorer bug](http://www.microsoft.com/technet/security/Bulletin/MS08-078.mspx) that Microsoft released the emergency patch for. It uses a flaw in the databinding feature of Microsoft's XML handler, that causes heap memory to be deallocated incorrectly. Shellcode is machine code that will run when the bug occurs. Spray and memory are just some space allocated on the heap to help the exploitable condition occur.
How does this milw0rm heap spraying exploit work?
[ "", "javascript", "x86", "exploit", "assembly", "" ]
This is also a question that I asked in a comment in one of Miško Hevery's [google talks](http://misko.hevery.com/2008/11/11/clean-code-talks-dependency-injection/) that was dealing with dependency injection but it got buried in the comments. I wonder how can the factory / builder step of wiring the dependencies together can work in C++. I.e. we have a class A that depends on B. The builder will allocate B in the heap, pass a pointer to B in A's constructor while also allocating in the heap and return a pointer to A. Who cleans up afterwards? Is it good to let the builder clean up after it's done? It seems to be the correct method since in the talk it says that the builder should setup objects that are expected to have the same lifetime or at least the dependencies have longer lifetime (I also have a question on that). What I mean in code: ``` class builder { public: builder() : m_ClassA(NULL),m_ClassB(NULL) { } ~builder() { if (m_ClassB) { delete m_ClassB; } if (m_ClassA) { delete m_ClassA; } } ClassA *build() { m_ClassB = new class B; m_ClassA = new class A(m_ClassB); return m_ClassA; } }; ``` Now if there is a dependency that is expected to last longer than the lifetime of the object we are injecting it into (say ClassC is that dependency) I understand that we should change the build method to something like: ``` ClassA *builder::build(ClassC *classC) { m_ClassB = new class B; m_ClassA = new class A(m_ClassB, classC); return m_ClassA; } ``` What is your preferred approach?
This talk is about Java and dependency injection. In C++ we try **NOT** to pass RAW pointers around. This is because a RAW pointer have no ownership semantics associated with it. If you have no ownership then we don't know who is responsible for cleaning up the object. I find that most of the time dependency injection is done via references in C++. In the rare cases where you must use pointers, wrap them in [std::unique\_ptr<>](http://www.cplusplus.com/reference/memory/auto_ptr/) or [std::shared\_ptr<>](http://www.cplusplus.com/reference/memory/shared_ptr/) depending on how you want to manage ownership. In case you cannot use C++11 features, use std::auto\_ptr<> or boost::shared\_ptr<>. I would also point out that C++ and Java styles of programming are now so divergent that applying the style of one language to the other will inevitably lead to disaster.
This is interesting, DI in C++ using templates: <http://adam.younglogic.com/?p=146> I think the author is making the right moves as to not translate Java DI into C++ too literally. Worth the read.
Dependency injection in C++
[ "", "c++", "unit-testing", "dependency-injection", "" ]
Does anyone know a way to find out programatically which physical disk holds a given partition? Manually, I can find this info using Start->Run->diskmgmt.msc , where I can see that (on my computer) that partitions C: and D: are on disk 1, E: & F: on disk 0. This is for optimizing some file crunching operations by doing them in parallel if the files are on different physical disks.
You can obtain this information using WMI from System.Management namespace by quering [Win32\_DiskDrive](http://msdn.microsoft.com/en-us/library/aa394132(VS.85).aspx) class. [Here's](http://msdn.microsoft.com/en-us/library/ms257340(VS.80).aspx) basic info about WMI in .NET.
In addition to Arul's answer, here's a link that shows how to geth the disk<->partition association using WMI from a VBS script: [WMI Tasks: Disks and File Systems](http://msdn.microsoft.com/en-us/library/aa394592.aspx) -> see the last example on the page. Edit: Even better, [here's a good article](http://www.c-sharpcorner.com/UploadFile/klaus_salchner@hotmail.com/WMIPart211162005021718AM/WMIPart2.aspx) on WMI using C#, which just happens to also describe the exact relationships between the WMI classes needed to get the disk drive (e.g. `\\\\.\\PHYSICALDRIVE0` ) that holds a logical disk (e.g. `C:`)
How to find the disk that holds a given partition in C#?
[ "", "c#", "filesystems", "disk", "" ]
Assuming a class called `Bar` in a namespace called `foo`, which syntax do you prefer for your source (.cpp/.cc) file? ``` namespace foo { ... void Bar::SomeMethod() { ... } } // foo ``` or ``` void foo::Bar::SomeMethod() { ... } ``` I use namespaces heavily and prefer the first syntax, but when adding code using the Visual Studio Class Wizard (WM\_COMMAND handlers, etc.) the auto-generated code uses the second. Are there any advantages of one syntax over the other?
I would decline the first (*edit* : question changed, the first is what i prefer too now). Since it is not clear where Bar refers to from only looking at the function definition. Also, with your first method, slippy errors could show up: ``` namespace bar { struct foo { void f(); }; } namespace baz { struct foo { void f(); }; } using namespace bar; using namespace baz; void foo::f() { // which foo?? } ``` Because it looks in the current scope (there it is the global scope), it finds two foo's, and tells you the reference to it is ambiguous. Personally i would do it like this: ``` namespace foo { void Bar::SomeMethod() { // something in here } } ``` It's also not clear from only looking at the definition of SomeMethod to which namespace it belongs, but you have a namespace scope around it and you can easily look it up. Additionally, it is clear now that Bar refers to namespace foo. The second way you show would be too much typing for me actually. In addition, the second way can cause confusion among new readers of your code: Is foo the class, and Bar a nested class of it? Or is foo a namespace and Bar the class?
I prefer an option not listed: ``` namespace foo { void Bar::SomeMethod() { ... } } // foo namespace ``` Unlike option one, this makes it obvious your code belongs in the foo namespace, not merely uses it. Unlike option two, it saves lots of typing. Win-win.
Preferred namespace syntax for source files
[ "", "c++", "namespaces", "" ]
Is there a problem with using `IEnumerable<T>` as a return type? FxCop complains about returning `List<T>` (it advises returning `Collection<T>` instead). Well, I've always been guided by a rule "accept the least you can, but return the maximum." From this point of view, returning `IEnumerable<T>` is a bad thing, but what should I do when I want to use "lazy retrieval"? Also, the `yield` keyword is such a goodie.
This is really a two part question. 1) Is there inherently anything wrong with returning an IEnumerable<T> No nothing at all. In fact if you are using C# iterators this is the expected behavior. Converting it to a List<T> or another collection class pre-emptively is not a good idea. Doing so is making an assumption on the usage pattern by your caller. I find it's not a good idea to assume anything about the caller. They may have good reasons why they want an IEnumerable<T>. Perhaps they want to convert it to a completely different collection hierarchy (in which case a conversion to List is wasted). 2) Are there any circumstances where it may be preferable to return something other than IEnumerable<T>? Yes. While it's not a great idea to assume much about your callers, it's perfectly okay to make decisions based on your own behavior. Imagine a scenario where you had a multi-threaded object which was queueing up requests into an object that was constantly being updated. In this case returning a raw IEnumerable<T> is irresponsible. As soon as the collection is modified the enumerable is invalidated and will cause an execption to occur. Instead you could take a snapshot of the structure and return that value. Say in a List<T> form. In this case I would just return the object as the direct structure (or interface). This is certainly the rarer case though.
No, `IEnumerable<T>` is a *good* thing to return here, since all you are promising is "a sequence of (typed) values". Ideal for LINQ etc, and perfectly usable. The caller can easily put this data into a list (or whatever) - especially with LINQ (`ToList`, `ToArray`, etc). This approach allows you to lazily spool back values, rather than having to buffer all the data. Definitely a goodie. I wrote-up [another useful `IEnumerable<T>` trick](http://marcgravell.blogspot.com/2008/12/brute-force-but-lazily.html) the other day, too.
IEnumerable<T> as return type
[ "", "c#", "collections", "ienumerable", "enumeration", "" ]
Do T-SQL queries in SQL Server support short-circuiting? For instance, I have a situation where I have two database and I'm comparing data between the two tables to match and copy some info across. In one table, the "ID" field will always have leading zeros (such as "000000001234"), and in the other table, the ID field may or may not have leading zeros (might be "000000001234" or "1234"). So my query to match the two is something like: select \* from table1 where table1.ID LIKE '%1234' To speed things up, I'm thinking of adding an OR before the like that just says: table1.ID = table2.ID to handle the case where both ID's have the padded zeros and are equal. Will doing so speed up the query by matching items on the "=" and not evaluating the LIKE for every single row (will it short circuit and skip the LIKE)?
SQL Server does **NOT** short circuit where conditions. it can't since it's a cost based system: [How SQL Server short-circuits WHERE condition evaluation](http://weblogs.sqlteam.com/mladenp/archive/2008/02/25/How-SQL-Server-short-circuits-WHERE-condition-evaluation.aspx) .
You could add a computed column to the table. Then, index the computed column and use that column in the join. Ex: ``` Alter Table Table1 Add PaddedId As Right('000000000000' + Id, 12) Create Index idx_WhateverIndexNameYouWant On Table1(PaddedId) ``` Then your query would be... ``` select * from table1 where table1.PaddedID ='000000001234' ``` This will use the index you just created to quickly return the row.
SQL Server - Query Short-Circuiting?
[ "", "sql", "sql-server", "" ]
I have been up and down this site and found a lot of info on the Screen class and how to count the number of monitors and such but how do I determine which montitor a form is currently in?
A simpler method than using the bounds is to use the Screen.FromControl() method. This is the same functionality that Windows uses. ``` Screen.FromControl(this) ``` will return the screen object for the screen that contains most of the form that you call it from.
This should do the trick for you: ``` private Screen FindCurrentMonitor(Form form) { return Windows.Forms.Screen.FromRectangle(new Rectangle( _ form.Location, form.Size)); } ``` It will return the screen that has the majority of the form in it. Alternativley, you can use ``` return Windows.Forms.Screen.FromPoint(Form.Location); ``` to return the screen that has the top left corner of the form in it.
How do I determine which monitor my winform is in?
[ "", "c#", ".net", "winforms", ".net-3.5", ".net-2.0", "" ]
Is there a reasonable way to access FoxPro databases using LINQ?
One the blessing/curses of .NET is that the answer is rarely "no" to any .NET programming question. For example, this guy (thanks Sergey and Larry) shows a way to access FoxPro-type DBs with LINQ: <http://blogs.msdn.com/calvin_hsia/archive/2007/11/30/6620133.aspx> A better question is probably, not can you, but should you!? If you insist on such an option, the Entity Framework is probably a better place to look: <http://msdn.microsoft.com/en-us/library/aa697427(VS.80).aspx>
I just finished working on implementation. <http://linqtovfp.codeplex.com/>
LINQ with FoxPro?
[ "", "c#", ".net", "linq", "foxpro", "" ]
I am inside the IDE and I can run all the unit tests in a file but is there any way to run all test in a project or solution at once?
Right click on the project or solution in the VS solution-explorer and choose 'Run Unit Tests' Or go to the Resharper menu, choose Unit-Testing and choose one of the options from there.
If you learn executing menu commands with Alt-Letters, you can execute many commands fast even if they don't have direct shortcuts. Especially, if shortcuts are two-key combos. As for **run**ning all tests in solution the command is Alt-**RUN**, i.e. Alt-R for ReSharper menu, U for Unit Testing, and N for all tests in solution.
ReSharper run all unit tests in a project or solution at once
[ "", "c#", "resharper", "" ]
Is the following possible in SQL Server 2000? ``` CREATE FUNCTION getItemType (@code varchar(18)) RETURNS int AS BEGIN Declare @Type tinyint Select @Type = case len(@code) WHEN 12,14,17 THEN 1 WHEN 13,15,18 THEN 2 WHEN 8,10 THEN 3 ELSE 0 END RETURN (@Type) END ``` Thanks.
try this: ``` Select @Type = (select case WHEN len(@code) IN (12,14,17) THEN 1 WHEN len(@code) IN (13,15,18) THEN 2 WHEN len(@code) IN (8,10) THEN 3 ELSE 0 END) ```
This should do it: ``` CREATE FUNCTION getItemType(@code VARCHAR(18)) RETURNS INT AS BEGIN RETURN CASE WHEN LEN(@code) IN (12,14,17) THEN 1 WHEN LEN(@code) IN (13,15,18) THEN 2 WHEN LEN(@code) IN (8,100) THEN 3 ELSE 0 END END ```
SQL CASE Statement
[ "", "sql", "sql-server", "sql-server-2000", "case-statement", "" ]
I have around 8-9 parameters to pass in a function which returns an array. I would like to know that its better to pass those parameters directly in the function or pass an array instead? Which will be a better way and why?
If I would do anything, then it would be to create an structure that holds all parameters to get nice intellisence and strong names. ``` public struct user { public string FirstName; public string LastName; public string zilionotherproperties; public bool SearchByLastNameOnly; } public user[] GetUserData(user usr) { //search for users using passed data and return an array of users. } ```
Pass them individually, because: * that is the type-safe way. * IntelliSense will pick it up in Visual Studio and when you write your calling functions, you will know what's what. * It is faster to execute that way. If the parameter really IS the array, though, then pass the array. Example: For functions which look like this, use this notation: ``` Array FireEmployee(string first, string middle, string last, int id) {...} ``` For functions that look like this, use the array: ``` Array FireEmployees(Employee[] unionWorkers) {...} ```
Regarding Passing Many Parameters
[ "", "c#", ".net", "asp.net", ".net-2.0", "" ]
I was thinking about how to create a program that would only be valid for X period of time, (within a C# app). What I was thinking was that you would have the current date as a constant inside the program and it would check to see if it is X days older than that. Naturally I do not want to store the date, or the X outside of the program as it can be tampered with. What I also do not want to manually change this regularly and recompile and deploy it. So is there a way to set a variable to be the current date when it is compiled? I could have a batch file that would compile it and deploy the new exe to the distribution server. Thanks
Precompilation directives are your key here. You could create a constant in your application and have it set when you compile. Make sure you obfuscate your code, however. Someone could disassemble it easily and tamper with the constant. Another solution is to have your software "phone home" to register itself. That way, the registration info is stored on your server and not their machine. There are also third party packages that perform the same security as you're looking for, but they are **expensive**!
Check out AssemblyInfo.cs file in the Properties folder in your project: ``` // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ``` Change this to: ``` [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")] ``` Then, elsewhere in the assembly, use this: ``` System.Version MyVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; // MyVersion.Build = days after 2000-01-01 // MyVersion.Revision*2 = seconds after 0-hour (NEVER daylight saving time) DateTime MyTime = new DateTime(2000, 1, 1).AddDays(MyVersion.Build).AddSeconds(MyVersion.Revision * 2); return string.Format("Version:{0} Compiled:{1:s}", MyVersion, MyTime); ```
C# put date into program when compiled
[ "", "c#", "" ]
I don't want to discuss the merits of this approach, just if it is possible. I believe the answer to be "no". But maybe someone will surprise me! Imagine you have a core widget class. It has a method `calculateHeight()`, that returns a height. The height is too big - this result in buttons (say) that are too big. You can extend DefaultWidget to create your own NiceWidget, and implement your own `calculateHeight()` to return a nicer size. Now a library class WindowDisplayFactory, instantiates DefaultWidget in a fairly complex method. You would like it to use your NiceWidget. The factory class's method looks something like this: ``` public IWidget createView(Component parent) { DefaultWidget widget = new DefaultWidget(CONSTS.BLUE, CONSTS.SIZE_STUPIDLY); // bunch of ifs ... SomeOtherWidget bla = new SomeOtherWidget(widget); SomeResultWidget result = new SomeResultWidget(parent); SomeListener listener = new SomeListener(parent, widget, flags); // more widget creation and voodoo here return result; } ``` That's the deal. The result has the DefaultWidget deep within a hierarchy of other objects. The question - how to get this factory method to use my own NiceWidget? Or at least get my own `calculateHeight()` in there. Ideally, I'd like to be able to monkey patch the DefaultWidget so that its calculateHeight did the right thing... ``` public class MyWindowDisplayFactory { public IWidget createView(Component parent) { DefaultWidget.class.setMethod("calculateHeight", myCalculateHeight); return super.createView(parent); } } ``` Which is what I could do in Python, Ruby, etc. I've invented the name `setMethod()` though. The other options open to me are: * Copying and pasting the code of the `createView()` method into my own class that inherits from the factory class * Living with widgets that are too big The factory class can't be changed - it is part of a core platform API. I tried reflection on the returned result to get to the widget that (eventually) got added, but it is several widget-layers down and somewhere it gets used to initialize other stuff, causing odd side effects. Any ideas? My solution so far is the copy-paste job, but that's a cop out that requires tracking the changes in the parent factory class when upgrading to newer versions of the platform, and I'd be interested to hear other options.
Perhaps you could use Aspect Oriented Programming to trap calls to that function and return your own version instead? Spring offers some AOP functionality but there are other libraries that do it as well.
One ugly solution would be to put your own implementation of DefaultWidget (with same FQCN) earlier on the Classpath than the normal implementation. It's a terrible hack, but every other approach that I can think of is even worse.
Is it possible to monkey patch in Java?
[ "", "java", "reflection", "monkeypatching", "" ]
I have been working on this for the greater part of the day and I cant seem to make this part of my code work. The intent of the code is to allow the user to input a set of values in order to calculate the missing value. As an additional feature I placed a CheckBox on the form to allow the user to do further calculation. That is where my problem lies. I know the code works because if I change the formula the value that appears in tb3\_aic.Text changes per the formula. However, when I use the below the answer does not change like it should. Please reference the attached code. If a jpg image is needed of the formula I can e-mail it. ``` void Calc3Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(tb3_skv.Text) | String.IsNullOrEmpty(tb3_kva.Text) | String.IsNullOrEmpty(tb3_z.Text)) { MessageBox.Show("Enter all required values", "Missing Data", MessageBoxButtons.OK); } //If user does not enter all the values required for the calculation show error message box else { if (!String.IsNullOrEmpty(tb3_skv.Text) & !String.IsNullOrEmpty(tb3_kva.Text) & !String.IsNullOrEmpty(tb3_z.Text)) { //If motor load check box is not checked and required values are entered calculate AIC based on formula. int y; decimal x, z, a; x = decimal.Parse(tb3_skv.Text); y = int.Parse(tb3_kva.Text); a = decimal.Parse(tb3_z.Text); z = (y * 1000) / (x * 1.732050808m) / (a / 100); //the m at the end of the decimal allows for the multiplication of decimals tb3_aic.Text = z.ToString(); tb3_aic.Text = Math.Round(z,0).ToString(); } if (cb3_ml.Checked==true) {//If Motor Load CB is checked calculate the following int y, b; decimal x, z, a; x = decimal.Parse(tb3_skv.Text); y = int.Parse(tb3_kva.Text); a = decimal.Parse(tb3_z.Text); b = int.Parse(tb3_ml.Text); z = ((y * 1000) / (x * 1.732050808m) / (a / 100))+((b / 100)*(6*y)/(x*1.732050808m)*1000); tb3_aic.Text = z.ToString(); tb3_aic.Text = Math.Round(z,5).ToString(); } } ``` I am grateful for any help that can be provided. Thank you, Greg Rutledge
Without really knowing what the problem is, a few things look a bit odd: * Also, mixing decimal and int in a calculation can lead to unexpected results unless you really know what you are doing. I suggest using only decimals (or doubles, which are way faster and usually have enough precision for engineering computations). * You also set tb3\_aic.Text twice, I assume you decided on rounding later and forgot to remove the first one. **Edit: This is apparently wrong in C#:** * You use bit-wise AND (&) in the if-clause where you probably mean logical AND (&&). The only difference between them when used with boolean operands are that && short circuits (doesn't evaluate the right operand if the left is false). I learned something, thank you people commenting. :)
Change this: ``` int y, b; ``` To this: ``` int y; decimal b; ``` and it works, according to this test: ``` public void Test2() { int y; decimal b; decimal x, z, a; decimal z1, z2; x = 480m; y = 2500; a = 5.75m; b = 10; z1 = ((y * 1000) / (x * 1.732050808m) / (a / 100)); z2 = ((b / 100) * (6 * y) / (x * 1.732050808m) * 1000); z = z1 + z2; Console.WriteLine("{0}, {1}", z1, z2); Console.WriteLine(Math.Round(z, 0).ToString()); } ``` The reason is that integer 10 divided by integer 100 is integer 0, which zero's the whole z2.
C# Math Problem
[ "", "c#", "math", "" ]
Ok here's what I'm trying to do I want to write a class that inherits everything from the class ListItem ``` class RealListItem : ListItem { public string anExtraStringINeed; } ``` For some reason or another .net is treating all the members like they are private when I try to do this so my class is worthless. I tried to do a work around and do it like this: ``` class RealListItem : ListItem { public string anExtraStringINeed; public ListItem list; } ``` but it still doesn't work because I need to use it in a function that uses the accepts type ListItem and RealListItem isn't playing nice like it should. I can do aRealListItem.list but that only passes the list from RealListItem I need the whole object to be passed along. Whats with this am I doing something wrong or will microsoft just not let you inherit .net classes?
The System.Web.UI.Controls.ListItem class is "sealed"... That means you cannot inherit from it...
As Charles states, ListItem is sealed which means you can't inherit from it. In the framework, some classes are marked as sealed and others are not. (The ones that aren't sealed you can inherit.) You could create your own ListItem that contains a System.Web.UI.WebControls.ListItem, but I don't think this will actually provide you much benefit. What is it that you are trying to accomplish? You may need to find an alternate way to do things.
Inheriting a .net class
[ "", "c#", ".net", "asp.net", "" ]
I was just browsing a forum and someone asked about a PHP file they had found on the web. It has several spots like this in the code: `if ($REMOTE_ADDR == "") $ip = "no ip"; else $ip = getHostByAddr($REMOTE_ADDR);` I have always thought brackets are needed to enclose what you want to do if the condition is true. Is there some other alternative, such as if it is on the same line you don't? There is also another line like this: `if ($action != ""): mail("$adminaddress","Visitor Comment from YOUR SITE",` My instinct is to say this wouldn't work, but I also don't know if it is an outdated PHP file and it used to work?
you can do if else statements like this: ``` <?php if ($something) { echo 'one conditional line of code'; echo 'another conditional line of code'; } if ($something) echo 'one conditional line of code'; if ($something) echo 'one conditional line of code'; echo 'a NON-conditional line of code'; // this line gets executed regardless of the value of $something ?> ``` and then you can also write if - else in an alternate syntax: ``` <?php if ($something): echo 'one conditional line of code'; echo 'another conditional line of code'; elseif ($somethingElse): echo 'one conditional line of code'; echo 'another conditional line of code'; else: echo 'one conditional line of code'; echo 'another conditional line of code'; endif; ?> ``` with the alternate syntax you can also fall out of parsing mode like this: ``` <?php if ($something): ?> one conditional line of code<br /> another conditional line of code <?php else: echo "it's value was: $value<br />\n"; ?> another conditional line of code <?php endif; ?> ``` But this gets really messy really fast and I won't recommend it's use (except maybe for template-logic). and to make it complete: ``` <?php $result = $something ? 'something was true' : 'something was false'; echo $result; ?> equals <?php if ($something) { $result = 'something was true'; } else { $result = 'something was false'; } echo $result; ?> ```
To go into a little more detail, the reason that the braces are optional is that the syntax looks like: ``` if(CONDITION) BLOCK [elseif(CONDITION) BLOCK] [else BLOCK] ``` BLOCK can be a single statement: ``` foo(); ``` or it can be a brace-enclosed group of statements: ``` { foo(); bar(); } ```
PHP conditionals, brackets needed?
[ "", "php", "brackets", "conditional-statements", "" ]
Since PHP is a dynamic language what's the best way of checking to see if a provided field is empty? I want to ensure that: 1. null is considered an empty string 2. a white space only string is considered empty 3. that "0" is not considered empty This is what I've got so far: ``` $question = trim($_POST['question']); if ("" === "$question") { // Handle error here } ``` There must be a simpler way of doing this?
A literal answer to the question from the post title is quite obvious and straightforward: ``` function IsNullOrEmptyString($str){ return ($str === null || trim($str) === ''); } ``` But for *input variables,* which you're actually asking about, it would be both superfluous and insufficient. A `$_POST` array element cannot be null, hence checking for null would be superfluous. At the same time, any outside variable can be absent, which will raise an error and you probably want to avoid it. Therefore, given you need a `$question` variable, the code would be ``` $question = trim($_POST['question'] ?? ''); if ("" === $question) { // Handle error here } ```
Old post but someone might need it as I did ;) ``` if (strlen($str) == 0){ do what ever } ``` replace `$str` with your variable. `NULL` and `""` both return 0 when using `strlen`.
Better way to check variable for null or empty string?
[ "", "php", "validation", "" ]
Simple question; what's better and why? ``` out.resize( in.size() ); T1::iterator outit = out.begin(); for( inIt = in.begin() to end, ++inIt, ++outIt ) *outit = *inIt OR out.erase(); for( inIt = in.begin() to end, ++inIt ) out.push_back( inIt ); ``` I'm assuming the memory assignment implicit in push\_back is worth avoiding but want to make sure. Thanks EDIT: Thanks for the out = in suggestions guys ;). The actual code I'm playing with is: ``` template//can't stop the browser ignoring th class T1, class T2 in angle brackets bool asciihex( T1& out, const T2& in ) { //out.erase(); out.resize( in.size() / 2 ); if( std::distance( in.begin(), in.end() ) % 2 )//use distance rather than size to minimise the requirements on T2? return false; for( T2::const_iterator it = in.begin(); it != in.end(); it += 2 ) { out.push_back(((( (*it > '9' ? *it - 0x07 : *it) - 0x30) '9' ? *(it+1) - 0x07 : *(it+1)) - 0x30) & 0x000f)); } return true; } template bool asciihex( T1& out, const T2& in ) { size_t size = in.size(); if( size % 2 )//use distance rather than size to minimise the requirements on T2? return false; out.resize( size / 2 ); T1::iterator outit = out.begin(); for( T2::const_iterator it = in.begin(); it != in.end(); it += 2, ++outit ) { *outit = ((( (*it > '9' ? *it - 0x07 : *it) - 0x30) '9' ? *(it+1) - 0x07 : *(it+1)) - 0x30) & 0x000f); } return true; } ``` Edit: I've marked push\_back as the answer as it seems to be the consensus and, therefore, more useful to anyone else with the same problem. However I have ended up using the iterator method as one of the container classes I'm interested in doesn't support push\_back... mileage varies.
The second, and if you're concerned about multiple extensions use out.reserve(). The right answer to adding to a vector is almost always push\_back or back\_inserter, which avoid some possible problems (exception guarantees, constructors, writing past the end, for example) that you'd have to pay attention to with other methods.
The second one, as long as you reserve the right capacity first. One problem I see (apart from style) is that in the first one, if your copy assignment throws, you have taken an operation that should give you the strong guarantee, and used it to give no guarantee.
Looped push_back against resize() + iterator
[ "", "c++", "stl", "" ]
If you started a new Java EE project today which is to be finished in about a year, which application server would you choose and why? Part of your answer should include your arguments for your decision. And also how much experience you have with the Java EE server you choose and with the other available servers on the market. These are interesting as we all get a sense of the investigation and thought that was put into your answer.
I have used WebLogic, WebSphere, JBoss, GlassFish, Resin, Jetty, Tomcat, and a few others over the last 10+ years. So, if I were considering a new project, I would ask myself a few questions first. One thing that I would not question anymore is that I would flat refuse to use JSPs unless I was tortured until I cried for my mommy. Do I have to be compatible/deploy to a specific product because of someone's mandate? Is there no way to ignore them or convince them otherwise? If so, there's your answer. Do I have to use EJBs? Really? Avoid them if at all possible--they are really only needed for very large, enterprise-class systems. Remember that they are merely tools, and big ones at that (can anyone say "Golden Sledgehammer"?). They are heavily overused, so really, really question whether you need them. If you do need them, then that removes several of your options including my favorite, Jetty. Do you have to use any of the other major J2EE technologies like JMS, ESB, etc? If so, and you really can't do without, then you are again constrained to a full-blown J2EE container. Carefully think and investigate before you commit to BPM, for example, and avoid AquaLogic BPM at (almost) all costs--it is ugly in the extreme. If you really must use a full-blown J2EE container, consider open-source first because it is more robust, better supported, and more cost-effective. They have larger customer bases and more open support interaction, so they tend to get better fixes faster. However, Resin is immature and I would avoid it relative to GlassFish or JBoss--I found it problematic to deploy and support. I would prefer JBoss because of its wider customer base, maturity, etc. GlassFish is harder to incorporate into an automated build/deployment process, but it might be nicer for some of its specific features (if you need them). Do I have a special reason to need Apache? Then lean towards Tomcat, perhaps plus something. Can I make do with just servlets? Then I would use Jetty--it is the lightest, fastest, easiest, most flexible solution. If I am leaning against being able to use Jetty, I would question all my assumptions of why. YAGNI applies. Best is to use StringTemplate/WebStringTemplate on Jetty: a clean, robust, fast, maintainable solution with no licensing fees, solid reputation and support, etc. That is where I start nowadays. Most applications/systems choose lots of fancy J2EE features when all they really need is servlets and JDBC with some decent architecture/design. Question why you think you need more. Of the full-blown containers, I would avoid WebLogic and WebSphere unless you are supporting a MAJOR public website (my current employer's website is deployed on WebLogic and it gets eleven+ million hits per month, others have been comparable). WebLogic's real claim-to-fame is their relatively easy clustering, but avoid their proprietary vendor-lock-in features at (almost) all cost. WebSphere is simply a nightmare that I would avoid literally at all cost--I refuse to do projects involving WebSphere after having done a couple in the past. Neither product is worth the massive licensing fees, unless you truly have a special need that drives the use of a proprietary feature. In a decade as a senior architect/engineer for lots of Fortune 500 companies, I have yet to see such a need. On the other hand, I have seen LOTS of pain due to picking such proprietary products. Even for the really large, high traffic, public websites, the proprietary products are still questionable. I would rather spend that multi-million dollars per year of licensing fees on some good hardware and some quality time from a handful of really good consultants to address a simple scalability solution. The extra millions per year could then be used to produce something worthy of selling on that nice website... *EDIT: another piece to consider...* I have recently encountered [Terracotta](http://www.terracotta.org/). I am rethinking everything, and looking to deploy it in a significant system soon. In particular, Terracotta does clustering better than anything else, so I would NO LONGER recommend WebLogic for its clustering.
The term "application server" is ambiguous. With GlassFish v3, you can start small with, say, a traditional web container and evolve (using OSGi and simple "add container" functionality) to add anything you'd like : JPA, JAX-RS, EJB's, JTA, JMS, ESB, etc... Yet it's the same product, same admin interface, etc. Does this qualify as an application server to you? -Alexis (Sun)
Would you, at present date, use JBoss or Glassfish (or another) as Java EE server for a new project?
[ "", "java", "jboss", "jakarta-ee", "glassfish", "" ]
Is there a simple way to **set the focus** (input cursor) of a web page **on the first input element** (textbox, dropdownlist, ...) on loading the page without having to know the id of the element? I would like to implement it as a common script for all my pages/forms of my web application.
You can also try jQuery based method: ``` $(document).ready(function() { $('form:first *:input[type!=hidden]:first').focus(); }); ```
Although this doesn't answer the question (requiring a common script), I though it might be useful for others to know that HTML5 introduces the 'autofocus' attribute: ``` <form> <input type="text" name="username" autofocus> <input type="password" name="password"> <input type="submit" value="Login"> </form> ``` [Dive in to HTML5](http://fortuito.us/diveintohtml5/forms.html#autofocus) has more information.
How do I set the focus to the first input element in an HTML form independent from the id?
[ "", "javascript", "html", "forms", "focus", "" ]
I have at my SQL Server 2000 Database a column with type **Image**. How can I map it into NHibernate?
We used BinaryBlob on the mapping config file, and byte[] on the property.
Below is the sample code that i have used to map an image field. Where BlogImage was a column of Image Datatype mapped to byte type property BlogImage. length="2147483647" was used to ensure copy of full image in to database as nhibernate some times limit the max size of data that is going to be inserted. ``` <?xml version="1.0" encoding="utf-8" standalone="yes"?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true"> <class name="EAS.MINDSPACE.Infrastructure.Business.Entities.BlogMaster,EAS.MINDSPACE.Infrastructure.Business.Entities" lazy="false" table="BlogMaster" schema="dbo" > <id name="BlogId" column="BlogId"> <generator class="native" /> </id> <property name="BlogData" column="BlogData" /> <property name="BlogImage" column="BlogImage" length="2147483647" /> <property name="UserId" column="UserId" /> <property name="CreatedByName" column="CreatedBy" /> <property name="CreatedOn" column="CreatedOn" /> <property name="ReplyCount" column="ReplyCount" /> </class> </hibernate-mapping> ```
How to map Image type in NHibernate?
[ "", "c#", "sql-server", "nhibernate", "" ]
I'm looking for a good plugin for doing web front end work in Eclipse. I don't want something that completely takes over eclipse, or something that has masses of dependencies that need to be updated all the time, or something that is geared towards a particular server-side platform, or something that costs a heap. Is there something light-weight out there that hits the sweet spot? I tried aptana - found it took over my whole eclipse environment and put news feeds and other rubbish all over the place. I then tried installing a subset of the aptana jar's and ended up pretty happy with the result. Here's what I have in my plugins directory: > com.aptana.ide.core\_1.2.0.018852.jar > com.aptana.ide.snippets\_1.2.0.018852.jar > com.aptana.ide.core.ui\_1.2.0.018852.jar > com.aptana.ide.debug.core\_1.2.0.018852.jar > com.aptana.ide.editor.css\_1.2.0.018852.jar > com.aptana.ide.editor.html\_1.2.0.018852.jar > com.aptana.ide.editor.js\_1.2.0.018852.jar > com.aptana.ide.editors\_1.2.0.018852.jar > com.aptana.ide.editors.codeassist\_1.2.0.018852.jar > com.aptana.ide.epl\_1.2.0.018852.jar > com.aptana.ide.io.file\_1.2.0.018852.jar > com.aptana.ide.jface.text.source\_1.2.0.018852.jar > com.aptana.ide.lexer\_1.1.0.018852.jar > com.aptana.ide.libraries\_1.2.0.18696 > com.aptana.ide.libraries.jetty\_1.2.0.018852 > com.aptana.ide.logging\_1.2.0.018852.jar > com.aptana.ide.parsing\_1.2.0.018852.jar > com.aptana.ide.search.epl\_1.2.0.018852.jar > com.aptana.ide.server\_1.2.0.018852.jar > com.aptana.ide.server.core\_1.2.0.018852.jar > com.aptana.ide.server.jetty\_1.2.0.018852.jar > com.aptana.ide.server.ui\_1.2.0.018852.jar ..and in the features: > com.aptana.ide.feature.editor.css\_1.2.0.018852 > com.aptana.ide.feature.editors\_1.2.0.018852 > com.aptana.ide.feature.editor.html\_1.2.0.018852 > com.aptana.ide.feature.editor.js\_1.2.0.018852
Personally, I use the standalone community version of Aptana for that sort of thing, as I don't really use Eclipse for anything much else these days. There is an Eclipse plugin version of Aptana, info available here: <http://www.aptana.com/docs/index.php/Plugging_Aptana_into_an_existing_Eclipse_configuration> Update: New link to get this plugin: <http://aptana.org/products/studio3/download>
This is a very old initial question but since it's still very visible in Google I thought I'd update the answer for 2018 for anyone who happens to be wondering the same. Right now, the best editor for all the web languages is [CodeMix](https://www.genuitec.com/products/codemix/codemix-journey/). You can read about it at the link provided or install it from the [Eclipse Marketplace](https://marketplace.eclipse.org/content/codemix).
What CSS/JS/HTML/XML plugin(s) do you use in Eclipse?
[ "", "javascript", "html", "css", "eclipse", "" ]
**Is there a tool that will take you java beans (pojos) and automatically make them a form for a webpage?** To be more clear I have a bunch of Jaxb objects that I want to be able to display in a form without having to code a bunch of html. Is there a tool that will read the jaxb objects and generate the editable form for me? Also, this needs to run on a glassfish server...
Have a look at [Grails](http://grails.org), in particular [Scaffolding](http://grails.org/Scaffolding). It's a Groovy framework, but your POJOs will plug straight in.
If I interpret your question quite literally, then you should take a look at the ROMA framework: <http://www.romaframework.org/>. It tries to take POJOs (beans) which are annotated and automatically generate user interfaces.
Is there a tool to generate web pages based on Java beans?
[ "", "java", "web-applications", "javabeans", "pojo", "" ]
The log file from a JVM crash contains all sorts of useful information for debugging, such as shared libraries loaded and the complete environment. Can I force the JVM to generate one of these programmatically; either by executing code that crashes it or some other way? Or alternatively access the same information another way?
You can try throwing an OutOfMemoryError and adding the -XX:+HeapDumpOnOutOfMemoryError jvm argument. This is new as of 1.6 as are the other tools suggested by McDowell. <http://blogs.oracle.com/watt/resource/jvm-options-list.html>
Have a look at the [JDK Development Tools](http://java.sun.com/javase/6/docs/technotes/tools/), in particular the [Troubleshooting Tools](http://java.sun.com/javase/6/docs/technotes/tools/#troubleshoot) for dumping the heap, printing config info, etcetera.
Can I force generation of a JVM crash log file?
[ "", "java", "jvm", "crash", "" ]
When I try to create a Excel or Word workbook project in VS, I get the message: > A compatible version of Microsoft > Office is not installed on this > computer. You must install the > version of Office that is compatible > with your project. In addition, > repair the version of the Visual > Studio Tools for Office runtime that > is appropriate for your project by > running the installation program and > selecting the Repair option. The > runtime is available at the Microsoft > Download Center. I have VS 2008 and Office 2003 Professional SP 3 installed. I did a full install of Office, and it looks like the Interop DLLs are in the GAC. I am creating an Office 2003 project. I tried the steps from [VSTO problem - cannot create visual studio excel workbook project](https://stackoverflow.com/questions/274653/vsto-problem-cannot-create-visual-studio-excel-workbook-project). I repaired VS 2008 from the disk after installing Office 2003 Pro. I had Office 2003 Standard installed earlier, but I removed it before installing Office 2003 Pro. I am able to create add-ins. Any ideas?
The following steps worked: 1) Unistall Office Pro, reboot and reinstall. 2) Repair VS 2008 from disk.
Office 2k3 Standard is not compatible with VSTO; upgrading from 2k3 standard has likely left something in your registry. [This thread](http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/3f12200d-f685-4bc9-bff0-d380067f515a) suggests that even moving to 2k7 doesn't give compatibility in this case! How about creating a new user profile?
VSTO: Can't create workbooks
[ "", "c#", ".net", "visual-studio", "vsto", "" ]
I [this post](https://stackoverflow.com/questions/381164), I've seen this: ``` class MonitorObjectString: public MonitorObject { // some other declarations friend inline bool operator==(/*const*/ MonitorObjectString& lhs, /*const*/ MonitorObjectString& rhs) { return lhs.fVal==rhs.fVal; } } ``` --- Before we can continue, **THIS IS VERY IMPORTANT:** * I am **not questioning** anyone's ability to code. * I am **just wondering** why someone would need non-const references in a comparison. * The poster of [that question](https://stackoverflow.com/questions/381164) **did not** write that code. This was just in case. This is important too: * I added both `/*const*/`s and reformatted the code. --- Now, we get back to the topic: I can't think of a sane use of the equality operator that lets you modify its by-ref arguments. Do you?
Perhaps the classes use a form of lazy initialization. When the data is accessed, proper initialization must occur, and the data must be fetched. This may change class members. However, lazy initialization can be formed so that modification to the class isn't necessary. This can be accomplished by using the [Pimpl idiom](http://en.wikipedia.org/wiki/Pimpl) (by a pointer to a private class) or by using the [mutable keyword](https://stackoverflow.com/questions/105014/c-mutable-keyword) (not recommended!).
Most likely they forgot the `const`. Operator overloads *should* behave consistently and not perform 'out of character' actions. As a general rule, an equality operator should never modify any of the objects it is comparing. Declaring `const` enforces this at the compiler level. However, it is often left out. "Const correctness" is very often overlooked in C++.
An operator == whose parameters are non-const references
[ "", "c++", "operators", "constants", "equals-operator", "" ]
Is there an openID implementation in Java? I would like to use this in a tomcat application.
The [openid4java](https://github.com/jbufu/openid4java) library seems to be the most popular.
The only one I have looked into is [OpenID4Java](http://code.sxip.com/openid4java/) by there is are more options listed on at <http://wiki.openid.net/Libraries>. I recommend looking at [Using OpenID](http://www.theserverside.com/tt/articles/article.tss?l=OpenID) on [TheServerSide.COM](http://www.theserverside.com) for a good introduction with some valuable code snippets. At the moment I am leaning towards implementing the authentication and authorization in the web tier using [mod\_auth\_openid](http://trac.butterfat.net/public/mod_auth_openid). But still make my application an authentication provider for people who don't want to know they are using OpenID.
Is there an openID implementation in Java?
[ "", "java", "jsp", "tomcat", "openid", "" ]
I'm so sick of the pass-callback-data-as-void\*-struct anti-pattern. Boost bind solves it nicely, but is an unacceptable dependency. What's a lightweight alternative? How would I write it myself as simply as possible?
I'm not familiar with boost:bind, but is it something like this? ``` #include <iostream> void foo (int const& x) { std::cout << "x = " << x << std::endl; } void bar (std::string const& s) { std::cout << "s = " << s << std::endl; } template<class T> void relay (void (*f)(T const&), T const& a) { f(a); } int main (int argc, char *argv[]) { std::string msg("Hello World!"); relay (foo, 1138); relay (bar, msg); } ``` Output -- ``` x = 1138 s = Hello World! ```
First, I question your assertion that it's far too heavy for you to use. Second, roll your own template, if you need to control the behavior. Third, if you're afraid of rolling your own template, I question your ability to judge that `boost::bind` is too heavy for you to use.
lightweight boost::bind
[ "", "c++", "function", "boost", "binders", "" ]
I've used the [`setargv.obj` linking for expanding wildcard arguments](http://msdn.microsoft.com/en-us/library/8bch7bkk.aspx) in the past for a number of C and C++ applications, but I can't find any similar mention for .NET applications. Is there a standard way to have your application's command line parameters automatically wildcard expanded? (i.e., expand `*.doc` from one entry in the `args` parameter to all that match that wildcard). P.S.: I've hacked something together with `Directory.GetFiles()` for my current little project, but it does not cover wildcards with paths (yet), and it would be nice to do it without custom code. Here is my rough hack, for illustration. It needs to split the parameters for the path and name for the `GetFiles()`, but this is a general idea. Linking `setargv.obj` into a C or C++ application would basically do all the wildcard expansion, leaving the user to only iterate over the *argv* array. ``` public static void Main(string[] args) { foreach (string argString in args) { // Split into path and wildcard int lastBackslashPos = argString.LastIndexOf('\\') + 1; path = argString.Substring(0, lastBackslashPos); filenameOnly = argString.Substring(lastBackslashPos, argString.Length - lastBackslashPos); string[] fileList = System.IO.Directory.GetFiles(path, filenameOnly); foreach (string fileName in fileList) { // Do things for each file } } } ```
Your code looks like exactly how you're supposed to do it.
Here is my rough hack. I'd love for it to be recursive. And having experienced the shortcoming of Windows wildcards, I might decide to use regular expressions rather than letting GetFiles() do it for me. ``` using System.IO; public static string[] ExpandFilePaths(string[] args) { var fileList = new List<string>(); foreach (var arg in args) { var substitutedArg = System.Environment.ExpandEnvironmentVariables(arg); var dirPart = Path.GetDirectoryName(substitutedArg); if (dirPart.Length == 0) dirPart = "."; var filePart = Path.GetFileName(substitutedArg); foreach (var filepath in Directory.GetFiles(dirPart, filePart)) fileList.Add(filepath); } return fileList.ToArray(); } ```
Is there a wildcard expansion option for .NET applications?
[ "", "c#", ".net", "vb.net", "wildcard", "" ]
I have a sqlite (v3) table with this column definition: ``` "timestamp" DATETIME DEFAULT CURRENT_TIMESTAMP ``` The server that this database lives on is in the CST time zone. When I insert into my table without including the timestamp column, sqlite automatically populates that field with the current timestamp in GMT, not CST. Is there a way to modify my insert statement to force the stored timestamp to be in CST? On the other hand, it is probably better to store it in GMT (in case the database gets moved to a different timezone, for example), so is there a way I can modify my select SQL to convert the stored timestamp to CST when I extract it from the table?
I found on the sqlite documentation (<https://www.sqlite.org/lang_datefunc.html>) this text: > Compute the date and time given a unix > timestamp 1092941466, and compensate > for your local timezone. ``` SELECT datetime(1092941466, 'unixepoch', 'localtime'); ``` That didn't look like it fit my needs, so I tried changing the "datetime" function around a bit, and wound up with this: ``` select datetime(timestamp, 'localtime') ``` That seems to work - is that the correct way to convert for your timezone, or is there a better way to do this?
simply use local time as the default: ``` CREATE TABLE whatever( .... timestamp DATE DEFAULT (datetime('now','localtime')), ... ); ```
Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine
[ "", "sql", "sqlite", "timezone", "timestamp", "" ]
I have a webservice in java that receives a list of information to be inserted or updated in a database. I don't know which one is to insert or update. Which one is the best approach to abtain better performance results: 1. Iterate over the list(a object list, with the table pk on it), try to insert the entry on Database. If the insert failed, run a update 2. Try to load the entry from database. if the results retrieved update, if not insert the entry. 3. another option? tell me about it :) In first calls, i believe that most of the entries will be new bd entries, but there will be a saturation point that most of the entries will be to update. I'm talking about a DB table that could reach over 100 million entries in a mature form. What will be your approach? Performance is my most important goal.
If your database supports MERGE, I would have thought that was most efficient (and treats all the data as a single set). See: <http://www.oracle.com/technology/products/oracle9i/daily/Aug24.html> <https://web.archive.org/web/1/http://blogs.techrepublic%2ecom%2ecom/datacenter/?p=194>
If performance is your goal then first get rid of the word iterate from your vocabulary! learn to do things in sets. If you need to update or insert, always do the update first. Otherwise it is easy to find yourself updating the record you just inserted by accident. If you are doing this it helps to have an identifier you can look at to see if the record exists. If the identifier exists, then do the update otherwise do the insert.
Insert fail then update OR Load and then decide if insert or update
[ "", "java", "database", "performance", "" ]
I'm currently building a Spring MVC application. I was looking to use JSP pages with tag libraries for handling the view layer and formatting of the HTML, but I've come across another group in my company that uses Velocity templates for the same purpose. From what I can see, it seems to me as if there are a lot of similarities between the two approaches: 1. Both have easy-to-understand syntax. Makes it easy for non-developers to understand and use, allowing the designers to focus on the HTML/CSS and only having to use directives/tag libraries in the few cases where they need conditionals/dynamic content without having to have a full understanding of Java. 2. Simple to see which part of the content is HTML vs which are directives/logic. 3. Both are heavily used and well supported. 4. Simple to integrate with Spring MVC. But in comparing the two technologies, I can't see any specific reasons to use one versus the other. I'm having trouble thinking of any cons specific to either Velocity or JSTL. So my question is, what are the pros and cons of each in your opinion? If you have built a (Spring) MVC app using one or the other, what made you decide on the view layer technology you are using and what (if anything) made you decide against the other? **Update**: I've found a similar discussion of this same topic archived on the Spring Framework forum's [here](http://forum.springframework.org/archive/index.php/t-10443.html), which might be of some interest to anyone making the same decision between JSTL and Velocity as I am.
I would prefer to use Velocity just because using JSP+JSTL can allow lazy/sloppy developers to get into trouble by adding scriptlets. There should be no reason to have java code in your view tier. It doesn't take much to understand Velocity and as a matter of fact I just picked it up in about two weeks. While I don't like the formatting of the output, for the most part it works pretty well. We're actually not using it in the app's view tier but rather for generating HTML for use by other browsers. We save the output from Velocity as files which is then deployed to a different server for consumption by other web clients.
I actually slightly prefer Freemarker to Velocity, just in case you're open to exploring other options. Comparison here: <http://freemarker.org/fmVsVel.html> I agree with Ben's statements about enforcing a simple view by avoiding JSP and the possibility of scriptlets. I also like the ability to render a Freemarker or Velocity template in any kind of execution environment (JUnit, main() method) without requiring a Servlet/JSP container as JSP would.
Benefits of using JSTL vs Velocity for view layer in MVC app?
[ "", "java", "spring", "jsp", "spring-mvc", "velocity", "" ]
**UPDATE** I have combined various answers from here into a 'definitive' answer on a [new question](https://stackoverflow.com/questions/1747235/weak-event-handler-model-for-use-with-lambdas/1747236#1747236). **Original question** In my code I have an event publisher, which exists for the whole lifetime of the application (here reduced to bare essentials): ``` public class Publisher { //ValueEventArgs<T> inherits from EventArgs public event EventHandler<ValueEventArgs<bool>> EnabledChanged; } ``` Because this publisher can be used all over the place, I was quite pleased with myself for creating this little helper class to avoid re-writing the handling code in all subscribers: ``` public static class Linker { public static void Link(Publisher publisher, Control subscriber) { publisher.EnabledChanged += (s, e) => subscriber.Enabled = e.Value; } //(Non-lambda version, if you're not comfortable with lambdas) public static void Link(Publisher publisher, Control subscriber) { publisher.EnabledChanged += delegate(object sender, ValueEventArgs<bool> e) { subscriber.Enabled = e.Value; }; } } ``` It worked fine, until we started using it on smaller machines, when I started getting the occasional: ``` System.ComponentModel.Win32Exception Not enough storage is available to process this command ``` As it turns out, there is one place in the code where subscribers controls are being dynamically created, added and removed from a form. Given my advanced understanding of garbage collection etc (i.e. none, until yesterday), I never thought to clear up behind me, as in the vast majority of cases, the subscribers also live for the lifetime of the application. I've fiddled around a while with [Dustin Campbell's WeakEventHandler](http://diditwith.net/CommentView,guid,aacdb8ae-7baa-4423-a953-c18c1c7940ab.aspx#commentstart), but it *doesn't work with anonymous delegates* (not for me anyway). Is there anyway out of this problem? I really would like to avoid having to copy-paste boiler-plate code all over the shop. (Oh, and don't bother with asking me WHY we are creating and destroying controls all the time, it wasn't my design decision...) (PS: It's a winforms application, but we've upgraded to VS2008 and .Net 3.5, should I consider using the [Weak Event pattern](http://msdn.microsoft.com/en-us/library/aa970850.aspx)?) (PPS: Good [answer from Rory](http://#371150), but if anyone can come up with an equivalent to the WeakEventHandler which avoids me having to remember to explicitly UnLink/Dispose, that would be cool...) **EDIT** I must admit that I worked around this problem by "recycling" the controls in question. However the workaround has come back to haunt me as the 'key' I was using is apparently non-unique (sob). I've just discovered other links [here](http://danylaporte.blogspot.com/2008/09/weakeventhandler.html) (tried this - seems to be a bit *too* weak - GC clears delegates even if target is still alive, same problem with [s,oɔɯǝɹ answer](https://stackoverflow.com/questions/371109/garbage-collection-when-using-anonymous-delegates-for-event-handling/955928#955928) below), [here](http://code.logos.com/blog/2008/08/event_subscription_using_weak_references.html) (forces you to modify publisher, and doesn't really work with anonymous delegates) and [here](http://joshsmithonwpf.wordpress.com/2009/04/06/a-mediator-prototype-for-wpf-apps/) (cited-as-incomplete by Dustin Campbell). It occurs to me that what I'm looking for may be semantically impossible - closures are designed to 'hang around even after I'm gone'. I've found another workaround, so I'll stick with that, pending a [voice from the gods](http://blogs.msdn.com/ericlippert/).
I know that this question is ancient, but hell - I found it, and I figure that others might as well. I'm trying to resolve a related issue, and might have some insight. You mentioned Dustin Campbell's WeakEventHandler - it indeed cannot work with anonymous methods by design. I was trying to fiddle something together that would, when I realized that a) in 99% of cases I'd need something like this his original solution would be safer, and b) in those few cases where I have to (note: have to, not "want to because lambdas are so much prettier and concise") it's possible to make it work if you get a little clever. Your example seems like exactly the kind of one-off case where getting a little tricky can result in a fairly concise solution. ``` public static class Linker { public static void Link(Publisher publisher, Control subscriber) { // anonymous method references the subscriber only through weak // references,so its existance doesn't interfere with garbage collection var subscriber_weak_ref = new WeakReference(subscriber); // this instance variable will stay in memory as long as the anonymous // method holds a reference to it we declare and initialize it to // reserve the memory (also, compiler complains about uninitialized // variable otherwise) EventHandler<ValueEventArgs<bool>> handler = null; // when the handler is created it will grab references to the local // variables used within, keeping them in memory after the function // scope ends handler = delegate(object sender, ValueEventArgs<bool> e) { var subscriber_strong_ref = subscriber_weak_ref.Target as Control; if (subscriber_strong_ref != null) subscriber_strong_ref.Enabled = e.Value; else { // unsubscribing the delegate from within itself is risky, but // because only one instance exists and nobody else has a // reference to it we can do this ((Publisher)sender).EnabledChanged -= handler; // by assigning the original instance variable pointer to null // we make sure that nothing else references the anonymous // method and it can be collected. After this, the weak // reference and the handler pointer itselfwill be eligible for // collection as well. handler = null; } }; publisher.EnabledChanged += handler; } } ``` The WPF Weak Event pattern is rumored to come with a lot of overhead, so in this particular situation I wouldn't use it. Furthermore, referencing the core WPF library in a WinForm app seems a little heavy as well.
If you retain a reference to the anonymous delegate and then remove it when the controls are removed from the form that should allow both the controls and the anonymous delegates to be garbage collected. So something like this: ``` public static class Linker { //(Non-lambda version, I'm not comfortable with lambdas:) public static EventHandler<ValueEventArgs<bool>> Link(Publisher publisher, Control subscriber) { EventHandler<ValueEventArgs<bool>> handler = delegate(object sender, ValueEventArgs<bool> e) { subscriber.Enabled = e.Value; }; publisher.EnabledChanged += handler; return handler; } public static void UnLink(Publisher publisher, EventHandler<ValueEventArgs<bool>> handler) { publisher.EnabledChanged -= handler; } } ``` See [Unsubscribe anonymous method in C#](https://stackoverflow.com/questions/183367/unsubscribe-anonymous-method-in-c) for an example of removing delegates.
Garbage collection when using anonymous delegates for event handling
[ "", "c#", "event-handling", "garbage-collection", "" ]
C#: How do you tell which item index is selected in ListView?
``` ListView mylistv = new ListView(); var index = mylistv.SelectedIndices(); ``` That should do it.
Have you tried SelectedIndices? ``` myListView.SelectedIndices ```
C#: How do you tell which item index is selected in ListView?
[ "", "c#", "" ]
I'm looking for something like `alert()`, but that doesn't "pause" the script. I want to display an alert and allow the next command, a form `submit()`, to continue. So the page will be changing after the alert is displayed, but it won't wait till the user has clicked OK. Is there something like this or is it just one of those impossible things?
You could do the alert in a setTimeout (which a very short timeout) as setTimeout is asynchronous: ``` setTimeout("alert('hello world');", 1); ``` Or to do it properly you really show use a method rather than a string into your setTimeout: ``` setTimeout(function() { alert('hello world'); }, 1); ``` Otherwise you open yourself up to JavaScript injection attacks. When you pass a string it is run through the JavaScript `eval` function.
If already using JQuery <http://docs.jquery.com/UI/Dialog> is simple to use and styles nicely.
Is there a JavaScript alert that doesn't pause the script?
[ "", "javascript", "" ]
I'm working on a legacy application that has a C++ extended stored procedure. This xsproc uses ODBC to connect to the database, which means it requires a DSN to be configured. I'm updating the installer (created using Visual Studio 2008 setup project), and want to have a custom action that can create the ODBC DSN entry, but am struggling to find useful information on Google. Can anyone help?
I actually solved this myself in the end by manipulating the registry. I've created a class to contain the functionality, the contents of which I've included here: ``` ///<summary> /// Class to assist with creation and removal of ODBC DSN entries ///</summary> public static class ODBCManager { private const string ODBC_INI_REG_PATH = "SOFTWARE\\ODBC\\ODBC.INI\\"; private const string ODBCINST_INI_REG_PATH = "SOFTWARE\\ODBC\\ODBCINST.INI\\"; /// <summary> /// Creates a new DSN entry with the specified values. If the DSN exists, the values are updated. /// </summary> /// <param name="dsnName">Name of the DSN for use by client applications</param> /// <param name="description">Description of the DSN that appears in the ODBC control panel applet</param> /// <param name="server">Network name or IP address of database server</param> /// <param name="driverName">Name of the driver to use</param> /// <param name="trustedConnection">True to use NT authentication, false to require applications to supply username/password in the connection string</param> /// <param name="database">Name of the datbase to connect to</param> public static void CreateDSN(string dsnName, string description, string server, string driverName, bool trustedConnection, string database) { // Lookup driver path from driver name var driverKey = Registry.LocalMachine.CreateSubKey(ODBCINST_INI_REG_PATH + driverName); if (driverKey == null) throw new Exception(string.Format("ODBC Registry key for driver '{0}' does not exist", driverName)); string driverPath = driverKey.GetValue("Driver").ToString(); // Add value to odbc data sources var datasourcesKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + "ODBC Data Sources"); if (datasourcesKey == null) throw new Exception("ODBC Registry key for datasources does not exist"); datasourcesKey.SetValue(dsnName, driverName); // Create new key in odbc.ini with dsn name and add values var dsnKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + dsnName); if (dsnKey == null) throw new Exception("ODBC Registry key for DSN was not created"); dsnKey.SetValue("Database", database); dsnKey.SetValue("Description", description); dsnKey.SetValue("Driver", driverPath); dsnKey.SetValue("LastUser", Environment.UserName); dsnKey.SetValue("Server", server); dsnKey.SetValue("Database", database); dsnKey.SetValue("Trusted_Connection", trustedConnection ? "Yes" : "No"); } /// <summary> /// Removes a DSN entry /// </summary> /// <param name="dsnName">Name of the DSN to remove.</param> public static void RemoveDSN(string dsnName) { // Remove DSN key Registry.LocalMachine.DeleteSubKeyTree(ODBC_INI_REG_PATH + dsnName); // Remove DSN name from values list in ODBC Data Sources key var datasourcesKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + "ODBC Data Sources"); if (datasourcesKey == null) throw new Exception("ODBC Registry key for datasources does not exist"); datasourcesKey.DeleteValue(dsnName); } ///<summary> /// Checks the registry to see if a DSN exists with the specified name ///</summary> ///<param name="dsnName"></param> ///<returns></returns> public static bool DSNExists(string dsnName) { var driversKey = Registry.LocalMachine.CreateSubKey(ODBCINST_INI_REG_PATH + "ODBC Drivers"); if (driversKey == null) throw new Exception("ODBC Registry key for drivers does not exist"); return driversKey.GetValue(dsnName) != null; } ///<summary> /// Returns an array of driver names installed on the system ///</summary> ///<returns></returns> public static string[] GetInstalledDrivers() { var driversKey = Registry.LocalMachine.CreateSubKey(ODBCINST_INI_REG_PATH + "ODBC Drivers"); if (driversKey == null) throw new Exception("ODBC Registry key for drivers does not exist"); var driverNames = driversKey.GetValueNames(); var ret = new List<string>(); foreach (var driverName in driverNames) { if (driverName != "(Default)") { ret.Add(driverName); } } return ret.ToArray(); } } ```
Further to [chrfalch's post](https://stackoverflow.com/questions/334939/how-do-i-create-an-odbc-dsn-entry-using-c/2336287#2336287), here is some sample code for updating a DSN (I know the OP is asking for creation, however this code is easily translatable to whatever you need to do) using the API call rather than via the registry direct (using the information from the [pinvoke.net page](http://www.pinvoke.net/default.aspx/odbccp32.sqlconfigdatasource)):- ``` [DllImport("ODBCCP32.DLL", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool SQLConfigDataSourceW(UInt32 hwndParent, RequestFlags fRequest, string lpszDriver, string lpszAttributes); enum RequestFlags : int { ODBC_ADD_DSN = 1, ODBC_CONFIG_DSN = 2, ODBC_REMOVE_DSN = 3, ODBC_ADD_SYS_DSN = 4, ODBC_CONFIG_SYS_DSN = 5, ODBC_REMOVE_SYS_DSN = 6, ODBC_REMOVE_DEFAULT_DSN = 7 } bool UpdateDsnServer(string name, string server) { var flag = RequestFlags.ODBC_CONFIG_SYS_DSN; string dsnNameLine = "DSN=" + name; string serverLine = "Server=" + server; string configString = new[] { dsnNameLine, serverLine }.Aggregate("", (str, line) => str + line + "\0"); return SQLConfigDataSourceW(0, flag, "SQL Server", configString); } ```
How do I create an ODBC DSN entry using C#?
[ "", "c#", "odbc", "" ]
By default C# compares DateTime objects to the 100ns tick. However, my database returns DateTime values to the nearest millisecond. What's the best way to compare two DateTime objects in C# using a specified tolerance? Edit: I'm dealing with a truncation issue, not a rounding issue. As Joe points out below, a rounding issue would introduce new questions. The solution that works for me is a combination of those below. ``` (dateTime1 - dateTime2).Duration() < TimeSpan.FromMilliseconds(1) ``` This returns true if the difference is less than one millisecond. The call to Duration() is important in order to get the absolute value of the difference between the two dates.
I usally use the TimeSpan.FromXXX methods to do something like this: ``` if((myDate - myOtherDate) > TimeSpan.FromSeconds(10)) { //Do something here } ```
How about an extension method for DateTime to make a bit of a fluent interface (those are all the rage right?) ``` public static class DateTimeTolerance { private static TimeSpan _defaultTolerance = TimeSpan.FromSeconds(10); public static void SetDefault(TimeSpan tolerance) { _defaultTolerance = tolerance; } public static DateTimeWithin Within(this DateTime dateTime, TimeSpan tolerance) { return new DateTimeWithin(dateTime, tolerance); } public static DateTimeWithin Within(this DateTime dateTime) { return new DateTimeWithin(dateTime, _defaultTolerance); } } ``` This relies on a class to store the state and define a couple operator overloads for == and != : ``` public class DateTimeWithin { public DateTimeWithin(DateTime dateTime, TimeSpan tolerance) { DateTime = dateTime; Tolerance = tolerance; } public TimeSpan Tolerance { get; private set; } public DateTime DateTime { get; private set; } public static bool operator ==(DateTime lhs, DateTimeWithin rhs) { return (lhs - rhs.DateTime).Duration() <= rhs.Tolerance; } public static bool operator !=(DateTime lhs, DateTimeWithin rhs) { return (lhs - rhs.DateTime).Duration() > rhs.Tolerance; } public static bool operator ==(DateTimeWithin lhs, DateTime rhs) { return rhs == lhs; } public static bool operator !=(DateTimeWithin lhs, DateTime rhs) { return rhs != lhs; } } ``` Then in your code you can do: ``` DateTime d1 = DateTime.Now; DateTime d2 = d1 + TimeSpan.FromSeconds(20); if(d1 == d2.Within(TimeSpan.FromMinutes(1))) { // TRUE! Do whatever } ``` The extension class also houses a default static tolerance so that you can set a tolerance for your whole project and use the Within method with no parameters: ``` DateTimeTolerance.SetDefault(TimeSpan.FromMinutes(1)); if(d1 == d2.Within()) { // Uses default tolerance // TRUE! Do whatever } ``` I have a few unit tests but that'd be a bit too much code for pasting here.
How do you compare DateTime objects using a specified tolerance in C#?
[ "", "c#", "datetime", "comparison", "resolution", "" ]
I am using C# .Net 2.0 to write a webservices client. The server's soap implementation is tested and is pretty solid. gSoap/C++ applications had no problem reading the responses. However the .Net implementation complains "There is an error in XML document" while calling one of the methods. Similar responses recieved from the server were happily processed by the xml parser. Looks like to me the MSXML parser (I hope thats the one .Net is been using) is a very unforgiving parser. I have no control over the server. Some how I have to work around this problem. So, I was thinking of writing a SoapExtension as describe [here](https://stackoverflow.com/questions/256234/how-do-i-get-access-to-soap-response) So my question is, can I hook a parser before Deserialize stage and completely bypass the Deserialize stage. And above all, how do i instruct the SOAP stub to use my extended class ?
First of all I'd grab a snapshot of the failing XML in the Deserialise stage to try and diagnose the problem. You can hook your soap extension into your client app without recompiling. Just add: ``` <webServices> <soapExtensionTypes> <add type="DebugTools.SOAP.SOAPTrace.SoapTraceExtension, DebugTools.SOAP" priority="0" group="High"/> </soapExtensionTypes> </webServices> ``` *DebugTools.SOAP.SOAPTrace* is the namespace of the SoapTraceExtension *DebugTools.SOAP* is the name of the assembly containing the soap trace code. to your app.config or web.config file. It would be handy if you could paste in the complete exception with stack trace. There may be something really obvious. Also, if possible the WSDL for the web service, that would be **very** useful.
If you would like to step through the serialise/deserialise code, you can use a tool called SGen. This comes with VS in the SDK, and is used as follows: 1. Compile the app using the normal VS-generated (or wsdl.exe generated) proxy classes (These are usually hidden and are in a file called Reference.cs 2. Drop to the Visual Studio cmd prompt, and open the Debug/Release folder (i.e. the folder the exe has been compiled to) 3. Type the following at the cmd prompt (replacing TheApplicationName with yor app's name): SGEN /keep TheApplicationName.exe You will now see a number of files have been created. Delete all the generated files except for the .cs file (including the dll it creates) Move the .cs file to the source folder, and include it in your project. Add the following attribute to your Reference.cs : ``` [XmlSerializerAssembly()] ``` You can now step through the actual serialising and deserialising code to find the actual problem (and if there's no other way to fix the problem, you can alter this generated code as required)
XML Parse error while processing the SOAP response
[ "", "c#", "vb.net", "web-services", "" ]
We have a lot of unit tests but they aren't run every night. I have setup some batch files that compile all the code from the SVN repository and I would like to run NUnit. This is not a big problem because I can call it from the batch file after the compilation BUT the output is stored in the network drive and I need to open it every morning to check if errors happen. This is where the problem is. Do you have a better way to do the same thing that will take the code from the repository, execute test and tell me in a "more fast convenient way" if errors appears? **Update** I have installed Team City 4.0 and it work like a charm. Maybe Cruise Control .Net could have been done the same, but Team City website/documentation/features looked better.
We have recently started using TeamCity with our projects, and so far it seems great. We are using it with Subversion and NUnit, aswell as running an external program which makes the final install file of the application. The projects and build configurations are really easy to set up.
Sounds like you need a build server. See [Cruise Control .Net](http://sourceforge.net/projects/ccnet/)
NUnit with night build, how to get errors easily?
[ "", "c#", ".net", "unit-testing", "automation", "" ]
I have some Python code that works correctly when I use python.exe to run it, but fails if I use pythonw.exe. ``` def runStuff(commandLine): outputFileName = 'somefile.txt' outputFile = open(outputFileName, "w") try: result = subprocess.call(commandLine, shell=True, stdout=outputFile) except: print 'Exception thrown:', str(sys.exc_info()[1]) myThread = threading.Thread(None, target=runStuff, commandLine=['whatever...']) myThread.start() ``` The message I get is: ``` Exception thrown: [Error 6] The handle is invalid ``` However, if I don't specify the 'stdout' parameter, subprocess.call() starts okay. I can see that pythonw.exe might be redirecting output itself, but I can't see why I'm blocked from specifying stdout for a new thread.
`sys.stdin` and `sys.stdout` handles are invalid because pythonw does not provide console support as it runs as a deamon, so default arguments of `subprocess.call()` are failing. Deamon programs close stdin/stdout/stderr purposedly and use logging instead, so that you have to manage this yourself: I would suggest to use subprocess.PIPE. If you *really* don't care about what the sub process says for errors and all, you could use `os.devnull` (I'm not really sure how portable it is?) but I wouldn't recommend that.
For the record, my code now looks like this: ``` def runStuff(commandLine): outputFileName = 'somefile.txt' outputFile = open(outputFileName, "w") if guiMode: result = subprocess.call(commandLine, shell=True, stdout=outputFile, stderr=subprocess.STDOUT) else: proc = subprocess.Popen(commandLine, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE) proc.stdin.close() proc.wait() result = proc.returncode outputFile.write(proc.stdout.read()) ``` Note that, due to an apparent bug in the subprocess module, the call to Popen() has to specify a pipe for stdin as well, which we close immediately afterwards.
Python subprocess.call() fails when using pythonw.exe
[ "", "python", "multithreading", "subprocess", "" ]
Using instance methods as callbacks for event handlers changes the scope of `this` from *"My instance"* to *"Whatever just called the callback"*. So my code looks like this ``` function MyObject() { this.doSomething = function() { ... } var self = this $('#foobar').bind('click', function(){ self.doSomethng() // this.doSomething() would not work here }) } ``` It works, but is that the best way to do it? It looks strange to me.
This question is not specific to jQuery, but specific to JavaScript in general. The core problem is how to "channel" a variable in embedded functions. This is the example: ``` var abc = 1; // we want to use this variable in embedded functions function xyz(){ console.log(abc); // it is available here! function qwe(){ console.log(abc); // it is available here too! } ... }; ``` This technique relies on using a closure. But it doesn't work with `this` because `this` is a pseudo variable that may change from scope to scope dynamically: ``` // we want to use "this" variable in embedded functions function xyz(){ // "this" is different here! console.log(this); // not what we wanted! function qwe(){ // "this" is different here too! console.log(this); // not what we wanted! } ... }; ``` What can we do? Assign it to some variable and use it through the alias: ``` var abc = this; // we want to use this variable in embedded functions function xyz(){ // "this" is different here! --- but we don't care! console.log(abc); // now it is the right object! function qwe(){ // "this" is different here too! --- but we don't care! console.log(abc); // it is the right object here too! } ... }; ``` `this` is not unique in this respect: `arguments` is the other pseudo variable that should be treated the same way — by aliasing.
Yeah, this appears to be a common standard. Some coders use self, others use me. It's used as a reference back to the "real" object as opposed to the event. It's something that took me a little while to really get, it does look odd at first. I usually do this right at the top of my object (excuse my demo code - it's more conceptual than anything else and isn't a lesson on excellent coding technique): ``` function MyObject(){ var me = this; //Events Click = onClick; //Allows user to override onClick event with their own //Event Handlers onClick = function(args){ me.MyProperty = args; //Reference me, referencing this refers to onClick ... //Do other stuff } } ```
var self = this?
[ "", "javascript", "jquery", "scope", "closures", "" ]
I'm just wondering if there is a quick way to echo undefined variables without getting a warning? (I can change error reporting level but I don't want to.) The smallest I have so far is: `isset($variable)?$variable:''` I dislike this for a few reasons: * It's a bit "wordy" and complex * `$variable` is repeated * The echoing of a blank string always kind of annoys me. * My variable names will probably be longer, eg `$arrayvar['parameter']`
you could use the ifsetor() example taken from [here](http://wiki.php.net/rfc/ifsetor): ``` function ifsetor(&$variable, $default = null) { if (isset($variable)) { $tmp = $variable; } else { $tmp = $default; } return $tmp; } ``` for example: ``` echo ifsetor($variable); echo ifsetor($variable, 'default'); ``` This does not generate a notice because the variable is passed by reference.
You can run it with the [error suppression operator](http://www.php.net/operators.errorcontrol) @. ``` echo @$variable; ``` However, it's best not to ignore unset variables. Unset variables could indicate a logical error on the script, and it's best to ensure all variables are set before use.
PHP: printing undefined variables without warning
[ "", "php", "variables", "warnings", "undefined", "" ]
I`m developing an application using Spring WebFlow 2, Facelets and JSF. One of my flows does have a page that must trigger a form submit at certain events. For each different action, a different view must be presented. So, I'm trying to activate the following javascript code to perform the submission: ``` function myFormSubmit( eventId ) { var formAction = document.myForm.action; document.myForm.action = formAction + '&_eventId=' + eventId; document.myForm.submit(); } ``` Unfortunatelly, this doesn't triggers the requested transition in my flow. The page doesn't change. Does anyone knows how to deal with this? Thanks, Alexandre
I've got the solution in the Spring WebFlow forum. According to Jeremy Grelle, the submission of "\_eventId" parameter does not trigger transitions when integrating Spring WebFlow to JSF. The solution he gave was to create a JSF PhaseListener that creates a JSF action when an "\_eventId" parameter is sent. The phaseListener code can be seen at <http://forum.springsource.org/showthread.php?p=219358#post219358>.
Don't know anything about SringFaceletsSF, but I think that event handler should probably return `true`. Otherwise your browser will not submit the form. so: ``` function myFormSubmit( eventId ) { var formAction = document.myForm.action; document.myForm.action = formAction + '&_eventId=' + eventId; document.myForm.submit(); return true; } ```
Javascript form submission to activate Spring Web Flow transitions with JSF integration
[ "", "javascript", "jsf", "facelets", "spring-webflow", "" ]
I'm just playing around and I'm trying to grab information from websites. Unfortunately, with the following code: ``` import sys import socket import re from urlparse import urlsplit url = urlsplit(sys.argv[1]) sock = socket.socket() sock.connect((url[0] + '://' + url[1],80)) path = url[2] if not path: path = '/' print path sock.send('GET ' + path + ' HTTP/1.1\r\n' + 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.3.154.9 Safari/525.19\r\n' + 'Accept: */*\r\n' + 'Accept-Language: en-US,en\r\n' + 'Accept-Charset: ISO-8859-1,*,utf-8\r\n' + 'Host: 68.33.143.182\r\n' + 'Connection: Keep-alive\r\n' + '\r\n') ``` I get the following error: > Traceback (most recent call last): > File > "D:\Development\Python\PyCrawler\PyCrawler.py", > line 10, in > sock.connect((url[0] + '://' + url[1],80)) File "", line 1, > in connect socket.gaierror: (11001, > 'getaddrinfo failed') The only time I do not get an error is if the url passed is <http://www.reddit.com>. Every other url I have tried comes up with the socket.gaierror. Can anyone explain this? And possibly give a solution?
Please please please please please please please don't do this. urllib and urllib2 are your friends. Read [the "missing" urllib2 manual](http://www.voidspace.org.uk/python/articles/urllib2.shtml) if you are having trouble with it.
> ``` > sock.connect((url[0] + '://' + url[1],80)) > ``` Do not do that, instead do this: ``` sock.connect((url[1], 80)) ``` `connect` expects a hostname, not a URL. Actually, you should probably use something higher-level than sockets to do HTTP. Maybe [httplib](http://docs.python.org/library/httplib.html).
(Python) socket.gaierror on every addres...except http://www.reddit.com?
[ "", "python", "http", "sockets", "" ]
I love to Extend my Assert.AreEqual to many different classes, the known one is the CollectionAssert of course, but I can think of some more such as: [ImageAssert](http://www.human-debugger.net/blog/2008/12/21/TddExtendingAssertToSupportImages.aspx), XmlAssert etc.. Did you Create your own Assert classes? and what kind of new would you like to create?
I've just added an implementation to [ImageAssert](https://web.archive.org/web/20131031051646/http://human-debugger.net/wp-blog/2008/12/21/tdd-extending-assert-to-support-images/) as I wrote above (in my question) I would be glad to hear more of that kind of samples ``` [TestMethod] public void CompareImagesSize() { Image expected = Bitmap.FromFile(@"C:\ShaniData\Projects2008\TddSamples\Output\ExpectedImage.png"); Image actual = Bitmap.FromFile(@"C:\ShaniData\Projects2008\TddSamples\Output\RhinoDiagram.png"); Bitmap expectedBitmap = new Bitmap(expected); Bitmap actualBitmap = new Bitmap(actual); ImageAssert.HasTheSameSize(expectedBitmap, actualBitmap); } [TestMethod] public void CompareTwoSameImagesButWithDifferenExtension() { Image expected = Bitmap.FromFile(@"C:\ShaniData\Projects2008\TddSamples\Output\Image2.png"); Image actual = Bitmap.FromFile(@"C:\ShaniData\Projects2008\TddSamples\Output\Image1.jpg"); Bitmap expectedBitmap = new Bitmap(expected); Bitmap actualBitmap = new Bitmap(actual); ImageAssert.AreEqual(expectedBitmap, actualBitmap); } public class ImageAssert { //public static void MoreMethods(Bitmap expected, Bitmap actual) //{ // //Compare image extensions // //Compare Thumbnail... //} public static void HasTheSameSize(Bitmap expected, Bitmap actual) { if ((expected.Height != actual.Height) || (expected.Width != actual.Width)) HandleFail("ImageAssert.HasTheSameSize", String.Empty); } public static void AreEqual(Bitmap expected, Bitmap actual) { for (int i = 0; i < expected.Width; i++) { for (int j = 0; j < expected.Height; j++) { Color expectedBit = expected.GetPixel(i, j); Color actualBit = actual.GetPixel(i, j); if (!expectedBit.Equals(actualBit)) { HandleFail("ImageAssert.AreEqual", String.Empty, i, j); return; } } } } internal static void HandleFail(string assertionName, string message, params object[] parameters) { throw new AssertFailedException(String.Format(assertionName)); } } ```
That's my solution: ``` using MyStuff; using A = Microsoft.VisualStudio.TestTools.UnitTesting.Assert; namespace Mytestproj.Tests { public static class Assert { public static void AreEqual(object expected, object actual) { A.AreEqual(expected, actual); } // my extension public static void AreEqual(MyEnum expected, int actual) { A.AreEqual((int)expected, actual); } public static void IsTrue(bool o) { A.IsTrue(o); } public static void IsFalse(bool o) { A.IsFalse(o); } public static void AreNotEqual(object notExpected, object actual) { A.AreNotEqual(notExpected, actual); } public static void IsNotNull(object o) { A.IsNotNull(o); } public static void IsNull(object o) { A.IsNull(o); } } } ```
How did you extend your Assert class
[ "", "c#", "unit-testing", "tdd", "assertions", "" ]
I'm just wondering how other developers tackle this issue of getting 2 or 3 answers from a method. 1) return a object[] 2) return a custom class 3) use an out or ref keyword on multiple variables 4) write or borrow (F#) a simple Tuple<> generic class <http://slideguitarist.blogspot.com/2008/02/whats-f-tuple.html> I'm working on some code now that does data refreshes. From the method that does the refresh I would like to pass back (1) Refresh Start Time and (2) Refresh End Time. At a later date I may want to pass back a third value. Thoughts? Any good practices from open source .NET projects on this topic?
Your question points to the possibility that you'll be returning more data in the future, so I would recommend implementing your own class to contain the data. What this means is that your method signature will remain the same even if the inner representation of the object you're passing around changes to accommodate more data. It's also good practice for readability and encapsulation reasons.
It entirely depends on what the results are. If they are related to one another, I'd usually create a custom class. If they're not really related, I'd either use an out parameter or split the method up. If a method wants to return three unrelated items, it's probably doing too much. The exception to this is when you're talking across a web-service boundary or something else where a "purer" API may be too chatty.
C# Syntax - Your preferred practice for getting 2 or 3 answers from a method
[ "", "c#", ".net", "syntax", "parameters", "tuples", "" ]
I'm not really sure how to title this question but basically I have an interface like this: ``` public interface IFoo { string ToCMD(); } ``` a couple of absract classes which implement IFoo like: ``` public abstract class Foo : IFoo { public abstract string ToCMD(); } public abstract class Bar : IFoo { public abstract string ToCMD(); } ``` then classes which inherit Foo and Bar: ``` public class FooClass1 : Foo { public override string ToCMD() {return "Test";} } ///there are about 10 foo classes. public class BarClass : Bar { public override string ToCMD() {return "BarClass";} } ///about the same for bar classes. ``` I am doing this so that when I have my custom list like: ``` public class Store<T> : List<T> where T : IFoo {} ``` I then can restrict the types that go in it but by having the interface it will still take any type of IFoo. Something like: ``` Store<Foo> store = new Store<Foo>(); //Only Foo types will work. store.Add(new FooClass1()); //Will compile. Store<IFoo> store = new Store<IFoo>(); //All IFoo types will work. store.Add(new FooClass1()); //Will compile. store.Add(new BarClass()); //Will compile. ``` My question is: Is this an ok way of going about this? or is there a better way? EDIT: Picture-> ![alt text](https://i.stack.imgur.com/RqPPj.jpg)
The need for an inheritance chain is questionable, in general. However the specific scenario of combining an abstract base class with an interface.. I see it this way: If you have an abstract base class like this, you should also have a corresponding interface. If you have an interface, then use the abstract base class only where the inheritance chain is sensible. That said, if I'm writing a library and this is part of my API/Framework, I will generally include a "default implementation" that can be used as a base class. It will implement the interface methods in a naive, general way, where possible, and leave the rest for inheritors to implement/override as needed. This is just a convenience feature of the library though, to assist people who want to implement the interface by providing a functional example that may cover most of what they need to implement already. In short, the interface is more valuable than the base class, but a base class might save a lot of time and reduce buggy interface implementations.
you need the interface; you may or may not need the abstract class. in general, if you can provide some useful behavior in a base class, then provide a base class; if the base class is not complete by itself then make it abstract (MustInherit in VB parlance) otherwise, the interface is sufficient
Inheritance design using Interface + abstract class. Good practice?
[ "", "c#", "oop", "inheritance", "" ]
Working to get DateTimes for any time zone. I'm using DateTimeOffset, and a string, and an XmlElement attribute. When I do, I get the following error: > [InvalidOperationException: 'dateTime' > is an invalid value for the > XmlElementAttribute.DataType property. > dateTime cannot be converted to > System.String.] > System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel > model, String ns, ImportContext > context, String dataType, > XmlAttributes a, Boolean repeats, > Boolean openModel, RecursionLimiter > limiter) +450 > > [InvalidOperationException: There was > an error reflecting type > 'System.String'.] > System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel > model, String ns, ImportContext > context, String dataType, > XmlAttributes a, Boolean repeats, > Boolean openModel, RecursionLimiter > limiter) +1621 > System.Xml.Serialization.XmlReflectionImporter.ImportAccessorMapping(MemberMapping > accessor, FieldModel model, > XmlAttributes a, String ns, Type > choiceIdentifierType, Boolean rpc, > Boolean openModel, RecursionLimiter > limiter) +8750 > System.Xml.Serialization.XmlReflectionImporter.ImportFieldMapping(StructModel > parent, FieldModel model, > XmlAttributes a, String ns, > RecursionLimiter limiter) +139 > System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping > mapping, StructModel model, Boolean > openModel, String typeName, > RecursionLimiter limiter) +1273 > > [InvalidOperationException: There was > an error reflecting property > 'creationTimeX'.] ... Code: ``` [System.Xml.Serialization.XmlElement(ElementName = "creationTime", DataType="dateTime")] public string creationTimeX { get { return this.creationTimeField.ToString("yyyy-MM-ddTHH:mm:sszzz"); } set { DateTimeOffset.TryParse(value, out this.creationTimeField); } } [System.Xml.Serialization.XmlIgnoreAttribute()] public System.DateTimeOffset creationTime { get { return this.creationTimeField; } set { this.creationTimeField = value; } } ```
Take a look at this StackOverflow question about serializing dates and UTC: [Best practices for DateTime serialization in .Net framework 3.5/SQL Server 2008](https://stackoverflow.com/questions/65164/best-practices-for-datetime-serialization-in-net-framework-35sql-server-2008) No need to create a special property just to accomplish the serialization.
This is what worked for me ``` private const string DateTimeOffsetFormatString = "yyyy-MM-ddTHH:mm:sszzz"; private DateTimeOffset eventTimeField; [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)] public string eventTime { get { return eventTimeField.ToString(DateTimeOffsetFormatString); } set { eventTimeField = DateTimeOffset.Parse(value); } } ```
How to serialize to dateTime
[ "", "c#", "datetime", ".net-2.0", "xml-serialization", "" ]
In PHP, is there an easy way to convert a number to a word? For instance, *27* to *twenty-seven*.
I [found](http://bloople.net/num2text/cnumlib.txt) some (2007/2008) source-code online and as it is copyright but I can use it freely and modify it however I want, so I place it here and re-license under CC-Wiki: ``` <?php /** * English Number Converter - Collection of PHP functions to convert a number * into English text. * * This exact code is licensed under CC-Wiki on Stackoverflow. * http://creativecommons.org/licenses/by-sa/3.0/ * * @link http://stackoverflow.com/q/277569/367456 * @question Is there an easy way to convert a number to a word in PHP? * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2007-2008 Brenton Fletcher. http://bloople.net/num2text * You can use this freely and modify it however you want. */ function convertNumber($number) { list($integer, $fraction) = explode(".", (string) $number); $output = ""; if ($integer{0} == "-") { $output = "negative "; $integer = ltrim($integer, "-"); } else if ($integer{0} == "+") { $output = "positive "; $integer = ltrim($integer, "+"); } if ($integer{0} == "0") { $output .= "zero"; } else { $integer = str_pad($integer, 36, "0", STR_PAD_LEFT); $group = rtrim(chunk_split($integer, 3, " "), " "); $groups = explode(" ", $group); $groups2 = array(); foreach ($groups as $g) { $groups2[] = convertThreeDigit($g{0}, $g{1}, $g{2}); } for ($z = 0; $z < count($groups2); $z++) { if ($groups2[$z] != "") { $output .= $groups2[$z] . convertGroup(11 - $z) . ( $z < 11 && !array_search('', array_slice($groups2, $z + 1, -1)) && $groups2[11] != '' && $groups[11]{0} == '0' ? " and " : ", " ); } } $output = rtrim($output, ", "); } if ($fraction > 0) { $output .= " point"; for ($i = 0; $i < strlen($fraction); $i++) { $output .= " " . convertDigit($fraction{$i}); } } return $output; } function convertGroup($index) { switch ($index) { case 11: return " decillion"; case 10: return " nonillion"; case 9: return " octillion"; case 8: return " septillion"; case 7: return " sextillion"; case 6: return " quintrillion"; case 5: return " quadrillion"; case 4: return " trillion"; case 3: return " billion"; case 2: return " million"; case 1: return " thousand"; case 0: return ""; } } function convertThreeDigit($digit1, $digit2, $digit3) { $buffer = ""; if ($digit1 == "0" && $digit2 == "0" && $digit3 == "0") { return ""; } if ($digit1 != "0") { $buffer .= convertDigit($digit1) . " hundred"; if ($digit2 != "0" || $digit3 != "0") { $buffer .= " and "; } } if ($digit2 != "0") { $buffer .= convertTwoDigit($digit2, $digit3); } else if ($digit3 != "0") { $buffer .= convertDigit($digit3); } return $buffer; } function convertTwoDigit($digit1, $digit2) { if ($digit2 == "0") { switch ($digit1) { case "1": return "ten"; case "2": return "twenty"; case "3": return "thirty"; case "4": return "forty"; case "5": return "fifty"; case "6": return "sixty"; case "7": return "seventy"; case "8": return "eighty"; case "9": return "ninety"; } } else if ($digit1 == "1") { switch ($digit2) { case "1": return "eleven"; case "2": return "twelve"; case "3": return "thirteen"; case "4": return "fourteen"; case "5": return "fifteen"; case "6": return "sixteen"; case "7": return "seventeen"; case "8": return "eighteen"; case "9": return "nineteen"; } } else { $temp = convertDigit($digit2); switch ($digit1) { case "2": return "twenty-$temp"; case "3": return "thirty-$temp"; case "4": return "forty-$temp"; case "5": return "fifty-$temp"; case "6": return "sixty-$temp"; case "7": return "seventy-$temp"; case "8": return "eighty-$temp"; case "9": return "ninety-$temp"; } } } function convertDigit($digit) { switch ($digit) { case "0": return "zero"; case "1": return "one"; case "2": return "two"; case "3": return "three"; case "4": return "four"; case "5": return "five"; case "6": return "six"; case "7": return "seven"; case "8": return "eight"; case "9": return "nine"; } } ```
Alternatively, you can use the NumberFormatter class from [`intl`](http://www.php.net/manual/en/intl.setup.php) package in PHP . Here's a sample code to get you started (for commandline): ``` <?php if ($argc < 3) { echo "usage: php {$argv[0]} lang-tag number ...\n"; exit; } array_shift($argv); $lang_tag = array_shift($argv); $nf1 = new NumberFormatter($lang_tag, NumberFormatter::DECIMAL); $nf2 = new NumberFormatter($lang_tag, NumberFormatter::SPELLOUT); foreach ($argv as $num) { echo $nf1->format($num).' is '.$nf2->format($num)."\n"; } ```
Is there an easy way to convert a number to a word in PHP?
[ "", "php", "numbers", "" ]
I'm writing a unit test for a method that packs boolean values into a byte. The various bit locations are determined by the value of an enum, which only has 5 values right now, but it's conceivable (though extremely unlikely) that this number could go to 9. I'd like a simple test along the lines of: private byte m\_myNum; enum MyEnum {...} assert(sizeof(m\_myNum) <= MyEnum.values().length); I'm under the impression that there's not a sizeof function in Java. What's the most elegant workaround? ---EDIT I don't think I was clear. I'm not concerned about normal runtime. My issue is that I can write this code now with a byte that stores all the information, but as the Enum grows in an unrelated part of code, I could reach a point where my bitmasking code breaks. Rather than having this in a deployed application, I'd like to have a unit test that fails when the number of states in the enum exceeds the number of bits in the storage variable, so when a programmer adds that ninth enum, they can adjust the type of the variable to something with more than eight bits.
I think this test does what you want. It is probably a waste of your time to get more generic than this. ``` public void testEnumSizeLessThanOneByte() throws Exception { assertTrue("MyEnum must have 8 or less values.", MyEnum.values().length <= 8); } ```
if this is a real concern and performance isn't that important you could always use a [bitset](http://java.sun.com/j2se/1.4.2/docs/api/java/util/BitSet.html)
Programatically calculate the size of a value type
[ "", "java", "unit-testing", "sizeof", "bitmask", "memory-size", "" ]
I have a class that inherits QTreeWidget. How can I find the currently selected row? Usually I connect signals to slots this way: ``` connect(myButton, SIGNAL(triggered(bool)), this, SLOT(myClick())); ``` However, I can't find anything similar for `QTreeWidget->QTreeWidgetItem`. The only way I found is to redefine the mousePressEvent of the QTreeWidget class like this: ``` void MyQTreeWidget::mousePressEvent(QMouseEvent *e){ QTreeView::mousePressEvent(e); const QModelIndex index = indexAt(e->pos()); if (!index.isValid()) { const Qt::KeyboardModifiers modifiers = QApplication::keyboardModifiers(); if (!(modifiers & Qt::ShiftModifier) && !(modifiers & Qt::ControlModifier)) clearSelection(); } } ``` I didn't try it yet. Is the only solution or is there any easier way?
Using the itemClicked() signal will miss any selection changes made using the keyboard. I'm assuming that's a bad thing in your case.
Dusty is almost correct. But the itemSelectionChanged signal will not tell you which item is selected. ``` QList<QTreeWidgetItem *> QTreeWidget::selectedItems() const ``` will give you the selected item(s). So, connect a slot to the itemSelectionChanged signal, then call selectedItems() on the tree widget to get the selected item(s).
How can I find the selected item in a QTreeWidget?
[ "", "c++", "qt", "events", "kde-plasma", "treewidget", "" ]
Having fallen behind in the world of ORM and modern data access, I'm looking to move away from DataSets (*shudder*) and into a proper mapping framework. I've just about got my head around Linq to SQL, an I'm now looking into NHibernate with the view to using it in our next project. With old school sql and data sets, your sql queries obviously only return the data you want. I also understand that L2S is also clever enough to evaluate its where clauses so that it only ever returns the objects you requested. Is NHibernate the same? And is it the same with Ayende's Linq to NHibernate? By this i mean, if i do the equivalent of: ``` Select * from customers where name = "fred" ``` will it fetch every customer into memory, and then filter out the non-freds, or is it clever enough to only get what it needs in the first place? If it is intelligent, what are the caveats? Are there certains types of query which cannot be evaluated in this way? What performance issues do i need to be aware of? Thanks Andrew
A quick answer is that the ORM will check the property name and will transform it to a SQL query that will do you name = .... So it won't load all the customers into the memory to search for the name.
Nhibernate comes with a couple of different ways to query the database. Hibernate uses a Sql like syntax called HQL, which is SQL on objects. Also it can do a search by example, where you create an object and fill in the critea you want, then hibernate will pull the object out of the DB which have the same property values. have a look here it will get you up to speed [summer of Nhibernate](http://www.summerofnhibernate.com/) lession 2 and 2a will answer in more depth HTH bones
NHibernate efficiency
[ "", "c#", "performance", "nhibernate", "" ]
Hello all you helpful folks @ stackoverflow! Best resources for Java GUI's? Looking at the Java Documentation, it is pretty easy to figure out the basics of JButtons, JFrames, etc but grasping the concepts of accessing JComponents from a frame, what creating a different panel does, etc is not very easy to understand. Is there some tutorial that teaches the basics about Java GUI like swing and real-life examples? Book suggestions are always welcome.
Hmm... Have you seen the [The Swing tutorial](http://java.sun.com/docs/books/tutorial/uiswing/index.html)?
Once you've finished the [Swing Tutorial](http://java.sun.com/docs/books/tutorial/uiswing/index.html), you should have a look at [Java Swing](http://books.google.com/books?id=cPxGfk-FZNUC&dq=java+swing&pg=PP1&ots=gFtz5Zntal&source=bn&sig=hKGpY7QtUTZrNjav41bPRuN4VcI&hl=en&sa=X&oi=book_result&resnum=4&ct=result). It's a fairly comprehensive book.
Java GUI - General
[ "", "java", "user-interface", "jbutton", "" ]
I am having a problem setting the Authorize attribute Role value from a variable. The error message says it requires a const variable. When I create a const type variable it works fine but I am trying to load the value from the Web.Config file or anything else that will allow the end user to set this. I'm using integrated Windows authentication since this is an intranet only application. Is there a way to check the users role from a controller? I will use this in an if statement to authenticate instead of an attribute. ``` [Authorize(Roles = Config.GMPUser)] public ActionResult Index() { return View(); } ```
You can use `User.InRole( "RoleName" )` within a controller. **EDIT: The code below will not work since GetCustomAttributes() apparently returns a copy of each attribute instead of a reference to the actual attribute. Left as answer to provide context for other answers.** As far as setting it in the authorize attribute, the only idea that I have is to set it to the empty string in the attribute definition, then use reflection on the controller's type to get and modify the CustomAttribute property corresponding to the AuthorizeAttribute (i.e., the one whose type is AuthorizeAttribute) for each method you care about. You should be able to set the Roles property to your configuration item that way. ``` var attributes = typeof(MyController).GetMethod("Index") .GetCustomAttributes(typeof(AuthorizeAttribute), false) as AuthorizeAttribute; attributes[0].Roles = Config.GMPUser; ``` I suppose that you would do this in your Global.asax file on application start so that it only needs to be done once.
I have a class called StringResources that provides access to static string values. I ran into the same snag and solved the problem in the following manner. I inherited from the AuthorizeAttribute class and added a method override for the AuthorizeCore method. The functionality of the method had a call to IsInRole() and passes in the static string property. That did the trick. The only problem is having to create separate classes for each role (or for combinations of roles in whatever manner your business logic dictates). ``` public class SystemAdministratorAuthorizationRequiredAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(System.Security.Principal.IPrincipal user) { return user.IsInRole( StringResources.AdministrationViewsStrings.SystemAdministratorRoleName ); } } ```
ASP.NET MVC: Problem setting the Authorize attribute Role from a variable, requires const
[ "", "c#", "asp.net-mvc", "authorization", "" ]
I discovered to have some problem to fully understand callbacks scoping when trying to learn Jquery. I would add that i have little experience with the Javascript language The code: ``` var globDom; // placeholder for DOM fragment // Getting xml file; jquery parses the file and give me back a DOM fragment // saveXML is the callback $.get(requestTarget, {}, saveXML); // the globDom here is UNDEFINED ! alert(globDom); // the callback function saveXML(xmlDom) { globDom = xmlDom; } ``` I am sure that here there is a BIG misunderstanding by me ... Have any suggestion? Thanks Daniel --- Ah-Ah. Very clear, I understand perfectly the error in my assumption: i forgot to take in account the time lag between the access time to the data (previous!) and the time at which content becomes available. A quite serious flaw - batch programming biased :-( The problem is clear and I can now address it properly. Many, many thanks for responding!
What Herms said. your (simplified) timeline looks like ``` 0.001 globdom = undefined; 0.002 $.get(somerequest, callback) 0.003 alert(globdom) .. 50 milliseconds later .. 0.053 saveXml(xmlDom) ```
I haven't used jquery myself, but my understanding is that a lot of the stuff it does is asynchronous. That get method probably doesn't call your callback immediately. You'll need to wait until after the callback has been run before you try accessing globDom. Try putting an alert within your callback method. Does that one happen before or after the alert your put after get()?
Callback and scope
[ "", "javascript", "jquery", "" ]
I need to sanitize HTML submitted by the user by closing any open tags with correct nesting order. I have been looking for an algorithm or Python code to do this but haven't found anything except some half-baked implementations in PHP, etc. For example, something like ``` <p> <ul> <li>Foo ``` becomes ``` <p> <ul> <li>Foo</li> </ul> </p> ``` Any help would be appreciated :)
using BeautifulSoup: ``` from BeautifulSoup import BeautifulSoup html = "<p><ul><li>Foo" soup = BeautifulSoup(html) print soup.prettify() ``` gets you ``` <p> <ul> <li> Foo </li> </ul> </p> ``` As far as I know, you can't control putting the <li></li> tags on separate lines from Foo. using Tidy: ``` import tidy html = "<p><ul><li>Foo" print tidy.parseString(html, show_body_only=True) ``` gets you ``` <ul> <li>Foo</li> </ul> ``` Unfortunately, I know of no way to keep the <p> tag in the example. Tidy interprets it as an empty paragraph rather than an unclosed one, so doing ``` print tidy.parseString(html, show_body_only=True, drop_empty_paras=False) ``` comes out as ``` <p></p> <ul> <li>Foo</li> </ul> ``` Ultimately, of course, the <p> tag in your example is redundant, so you might be fine with losing it. Finally, Tidy can also do indenting: ``` print tidy.parseString(html, show_body_only=True, indent=True) ``` becomes ``` <ul> <li>Foo </li> </ul> ``` All of these have their ups and downs, but hopefully one of them is close enough.
Run it through [Tidy](http://tidy.sourceforge.net/) or one of its ported [libraries](http://utidylib.berlios.de/). Try to code it by hand and you *will* want to gouge your eyes out.
How do I fix wrongly nested / unclosed HTML tags?
[ "", "python", "html", "algorithm", "xhtml", "" ]
I'm writing small and very [DRY](http://en.wikipedia.org/wiki/DRY) framework, which heavily relies on metadata. I'd like to know if there is a way to obtain method parameter names, i.e. given some method ``` public void a(int myIntParam, String theString) { ... } ``` get the strings `"myIntParam"` and `"theString"`. I know I could annotate parameters, but that wouldn't be nice... ``` public void a( @Param("myIntParam") int myIntParam, @Param("theString") String theString ) { ... } ```
We created a custom annotation for the method that holds a String[] of parameter names. This approach felt a little easier to manage than having to annotate each individual parameter. We plan to add build-time checking that the number of annotated parameter names matches the number of arguments, since that it what we require.
Here is a dirty solution that needs some tweaking. Maybe someone can make it better. ### Cons: * Requires that you know the location of compiled class file. * It has to be compiled with the -g flag. ### Code: ``` import com.sun.org.apache.bcel.internal.classfile.ClassParser; import com.sun.org.apache.bcel.internal.classfile.JavaClass; import com.sun.org.apache.bcel.internal.classfile.LocalVariable; import com.sun.org.apache.bcel.internal.classfile.Method; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { ClassParser parser = new ClassParser("Main.class"); JavaClass clazz = parser.parse(); for (Method m : clazz.getMethods()) { System.out.println("Method: " + m.getName()); int size = m.getArgumentTypes().length; if (!m.isStatic()) { size++; } for (int i = 0; i < size; i++) { LocalVariable variable = m.getLocalVariableTable().getLocalVariable(i); System.out.println(" - Param: " + variable.getName()); } } } public void a(int myIntParam, String theString) { } } ``` ### Output: `$ javac -g Main.java` `$ java Main` `Method: <init>` `- Param: this` `Method: main - Param: args Method: a - Param: this - Param: myIntParam - Param: theString`
Is there a way to obtain names of method parameters in Java?
[ "", "java", "reflection", "" ]
I'm trying to write out a `Byte[]` array representing a complete file to a file. The original file from the client is sent via TCP and then received by a server. The received stream is read to a byte array and then sent to be processed by this class. This is mainly to ensure that the receiving `TCPClient` is ready for the next stream and separate the receiving end from the processing end. The `FileStream` class does not take a byte array as an argument or another Stream object ( which does allow you to write bytes to it). I'm aiming to get the processing done by a different thread from the original ( the one with the TCPClient). I don't know how to implement this, what should I try?
Based on the first sentence of the question: *"I'm trying to write out a Byte[] array **representing a complete file** to a file."* The path of least resistance would be: ``` File.WriteAllBytes(string path, byte[] bytes) ``` Documented here: > [`System.IO.File.WriteAllBytes` - MSDN](http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx)
You can use a `BinaryWriter` object. ``` protected bool SaveData(string FileName, byte[] Data) { BinaryWriter Writer = null; string Name = @"C:\temp\yourfile.name"; try { // Create a new stream to write to the file Writer = new BinaryWriter(File.OpenWrite(Name)); // Writer raw data Writer.Write(Data); Writer.Flush(); Writer.Close(); } catch { //... return false; } return true; } ``` **Edit:** Oops, forgot the `finally` part... lets say it is left as an exercise for the reader ;-)
Can a Byte[] Array be written to a file in C#?
[ "", "c#", ".net", "" ]
In the footer of my page, I would like to add something like "last updated the xx/xx/200x" with this date being the last time a certain mySQL table has been updated. What is the best way to do that? Is there a function to retrieve the last updated date? Should I access to the database every time I need this value?
In later versions of MySQL you can use the `information_schema` database to tell you when another table was updated: ``` SELECT UPDATE_TIME FROM information_schema.tables WHERE TABLE_SCHEMA = 'dbname' AND TABLE_NAME = 'tabname' ``` This does of course mean opening a connection to the database. --- An alternative option would be to "touch" a particular file whenever the MySQL table is updated: On database updates: * Open your timestamp file in `O_RDRW` mode * `close` it again or alternatively * use [`touch()`](https://www.php.net/manual/en/function.touch.php), the PHP equivalent of the `utimes()` function, to change the file timestamp. On page display: * use `stat()` to read back the file modification time.
I don't have information\_schema database, using mysql version 4.1.16, so in this case you can query this: ``` SHOW TABLE STATUS FROM your_database LIKE 'your_table'; ``` It will return these columns: ``` | Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment | ``` As you can see there is a column called: "**Update\_time**" that shows you the last update time for **your\_table**.
How can I tell when a MySQL table was last updated?
[ "", "mysql", "sql", "" ]
I have a .NET webform that has a file upload control that is tied to a regular expression validator. This validator needs to validate that only certain filetypes should be allowed for upload (jpg,gif,doc,pdf) The current regular expression that does this is: ``` ^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.gif|.GIF|.doc|.DOC|.pdf|.PDF)$ ``` However this does not seem to be working... can anyone give me a little reg ex help?
Your regex seems a bit too complex in my opinion. Also, remember that the dot is a special character meaning "any character". The following regex should work (note the escaped dots): ``` ^.*\.(jpg|JPG|gif|GIF|doc|DOC|pdf|PDF)$ ``` You can use a tool like [Expresso](http://www.ultrapico.com/Expresso.htm) to test your regular expressions.
``` ^.+\.(?:(?:[dD][oO][cC][xX]?)|(?:[pP][dD][fF]))$ ``` Will accept .doc, .docx, .pdf files having a filename of at least one character: ``` ^ = beginning of string .+ = at least one character (any character) \. = dot ('.') (?:pattern) = match the pattern without storing the match) [dD] = any character in the set ('d' or 'D') [xX]? = any character in the set or none ('x' may be missing so 'doc' or 'docx' are both accepted) | = either the previous or the next pattern $ = end of matched string ``` Warning! Without enclosing the whole chain of extensions in (?:), an extension like .docpdf would pass. You can test regular expressions at [http://www.regextester.com/](http://www.regextester.com/ "regextester")
Validating file types by regular expression
[ "", "c#", "asp.net", ".net", "regex", "" ]
I was writing some code, and I notice a pattern in the exception handling that got me thinking: ``` try{ // do stuff... throws JMS, Create and NamingException } catch (NamingException e) { log1(e); rollback(); doSomething(e) } catch (CreateException e) { log1(e); rollback(); doSomething(e) } ``` Where JMSException would be handle some where up in the stack. Would it be to just write: ``` try{ // do stuff... throws JMS, Create and NamingException } catch Exception[NamingException, CreateException] e) { log1(e); rollback(); doSomething(e) } ``` instead of putting it in tu a helper method: ``` try{ // do stuff... throws JMS, Create and NamingException } catch (NamingException e) { helper_handleError1(e) } catch (CreateException e) { helper_handleError1(e) } ``` Notice that I want to propagate stacktrace of the original JMSException, and I don't "feel like" creating an new JMSException with a third catch clause :) Any toughs? Is this an extreme situation that would only pollute the syntax of Java, or just a cool thing to add?
They are considering an extension of this type for Java 7. See: <http://tech.puredanger.com/java7#catch>
As long as we're making up syntaxes, here's how I'd like to see it: ``` try { // do stuff ... } catch (NamingException e) catch (CreateException e) { log1(e); rollback(); doSoemthing(e); } ``` Similar to the the fallthrough of a switch statement or C# `using` block. Of course, there's a problem here with the variable e declared twice, but I think something could be worked out.
Cool or Stupid? Catch(Exception[NamingException, CreateException] e)
[ "", "java", "programming-languages", "exception", "" ]
As input I get an int (well, actually a string I should convert to an int). This int should be converted to bits. For each bit position that has a 1, I should get the position. In my database, I want all records that have an int value field that has this position as value. I currently have the following naive code that should ask my entity(holding the databaseValue) if it matches the position, but obviously doesn't work correctly: ``` Byte[] bits = BitConverter.GetBytes(theDatabaseValue); return bits[position].equals(1); ``` Firstly, I have an array of byte because there apparantly is no bit type. Should I use Boolean[] ? Then, how can I fill this array? Lastly, if previous statements are solved, I should just return bits[position] I feel like this should somehow be solved with bitmasks, but I don't know where to start.. Any help would be appreciated
Your feeling is correct. This should be solved with bitmasks. BitConverter does not return bits (and how could it? "bits" isn't an actual data type), it converts raw bytes to CLR data types. Whenever you want to extract the bits out of something, you should think bitmasks. If you want to check if a bit at a certain position is set, use the & operator. Bitwise & is only true if both bits are set. For example if you had two bytes 109 and 33, the result of & would be ``` 0110 1101 & 0010 0001 ----------- 0010 0001 ``` If you just want to see if a bit is set in an int, you & it with a number that has only the bit you're checking set (ie 1, 2, 4, 8, 16, 32 and so forth) and check if the result is not zero. ``` List<int> BitPositions(uint input) { List<int> result = new List<int>(); uint mask = 1; int position = 0; do { if (input & mask != 0) { result.Add(position); } mask <<= 1; position++; } while (mask != 0); return result; } ```
I suspect [BitArray](http://msdn.microsoft.com/en-us/library/system.collections.bitarray.aspx) is what you're after. Alternatively, using bitmasks yourself isn't hard: ``` for (int i=0; i < 32; i++) { if ((value & (1 << i)) != 0) { Console.WriteLine("Bit {0} was set!", i); } } ```
Why does the BitConverter return Bytes and how can I get the bits then?
[ "", "c#", "bit-manipulation", "bit-masks", "" ]
I can remember *Convert* class in .net which is named not in accordance with the guide lines. Any more examples?
In Java, `java.lang.System.arraycopy` - note the lowercase second c. Also `NullPointerException` in Java is better as `NullReferenceException` in .NET. `AppDomain` violates the convention of *normally* not using abbreviations. `Control.ID` violates the explicit convention of Pascal-casing ID to "Id" and Camel-casing it to "id". EDIT: Due to popular demand, a couple more... although they're more just badly named than convention-defying. `SortedList` in .NET - that explains what the *implementation* is, but doesn't give the correct impression about what the *API* is - that of a dictionary. `Type.MakeGenericType` - it makes a *constructed* type. Ditto `MethodInfo.MakeGenericMethod`.
* [IPEndPoint](http://msdn.microsoft.com/en-us/library/system.net.ipendpoint.aspx) breaks the [compound word capitalization](http://msdn.microsoft.com/en-us/library/ms229043.aspx) guideline (which, oddly enough, specifically calls out endpoint as an example). * All the Interop references are verboten, because they are an abbreviation for Interoperability. Thankfully, they left them as Interop though. I swear there's an attribute or something that's completely misspelled, but I can't recall it off the top of my head. But, there is the always amusing case of [HTTP\_REFERER](http://en.wikipedia.org/wiki/Referer).
Which are the examples for contra guideline implementations/misnomers in .net/java framework?
[ "", "java", ".net", "" ]
I'd like to write a simple detail formatter that displays `byte[]` data in the form of a `String` (using `String.<init>([B)` to do the dirty work). However, I'm not sure how to find the class name for `[B` to use when creating the formatter. Is this even possible? Or, alternatively, is there another way to view byte arrays as strings in the debugger?
I don't know how to get eclipse's detail formatter to automagically display byte arrays as Strings, but you can display a particular byte array by adding `new String(byteArray)` as a watch expression.
If your question is how would I get a string representation of a byte array of [0,1,2] to be "[0,1,2]", I would suggest you take a look at Arrays.toString(byte[]) <http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#toString(byte[])>
How can I display a byte array as a String in java's debug detail formatter?
[ "", "java", "eclipse", "debugging", "" ]
Is it possible to reflectively instantiate a generic type in Java? Using the technique described [here](http://www.velocityreviews.com/forums/t149816-generics-and-forname.html) I get an error because class tokens cannot be generic. Take the example below. I want to instantiate some subclass of Creator that implements Creator. The actual class name is passed in as a command line argument. The idea is to be able to specify an implementation of Creator at runtime. Is there another way to accomplish what I'm trying to do here? ``` public interface Creator<T> { T create(); } public class StringCreator implements Creator<String> { public String create() { return new String(); } } public class FancyStringCreator implements Creator<String> { public String create() { return new StringBuffer().toString(); } } public static void main(String[] args) throws Exception { Class<?> someClass = Class.forName(args[0]); /*ERROR*/Class<? extends Creator<String>> creatorClass = someClass.asSubclass(Creator.class); Constructor<? extends Creator<String>> creatorCtor = creatorClass.getConstructor((Class<?>[]) null); Creator<String> creator = creatorCtor.newInstance((Object[]) null); } ``` Edit: I like Marcus' approach as being the most simple and pragmatic without circumventing the whole generics thing. I can use it in my situation because I can specify that the class passed must be a subclass of StringCreator. But as Ericson pointed out the generic information is still there at the type level, just not at the runtime level so it is still possible to reflectively examine whether a given class implements the correct generic type.
The generic information is lost in runtime. There is no runtime equivalent of a Creator<String>.class. You could create a type between Creator and StringCreator which fixes the generic type: ``` public interface Creator<T> { T create(); } public interface StringCreator extends Creator<String> { } public class StringCreatorImpl implements StringCreator { public String create() { return new String(); } } public class FancyStringCreator implements StringCreator { public String create() { return new StringBuffer().toString(); } } public static void main(String[] args) throws Exception { Class<?> someClass = Class.forName(args[0]); Class<? extends StringCreator> creatorClass = someClass.asSubclass(StringCreator.class); Constructor<? extends StringCreator> creatorCtor = creatorClass.getConstructor((Class<?>[]) null); Creator<String> creator = creatorCtor.newInstance((Object[]) null); } ``` But of course you lose a bit of flexibility, because you cannot use the following creator class: ``` public class AnotherCreator implements Creator<String> { public String create() { return ""; } } ```
This will do what you are trying to do while providing type safety. There's no way to avoid an unchecked warning, but the type checking done here justifies its suppression. ``` public static void main(String[] args) throws Exception { Class<? extends Creator<String>> clz = load(argv[0], String.class); Constructor<? extends Creator<String>> ctor = clz.getConstructor(); Creator<String> creator = ctor.newInstance(); System.out.println(creator.create()); } public static <T> Class<? extends Creator<T>> load(String fqcn, Class<T> type) throws ClassNotFoundException { Class<?> any = Class.forName(fqcn); for (Class<?> clz = any; clz != null; clz = clz.getSuperclass()) { for (Object ifc : clz.getGenericInterfaces()) { if (ifc instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) ifc; if (Creator.class.equals(pType.getRawType())) { if (!pType.getActualTypeArguments()[0].equals(type)) throw new ClassCastException("Class implements " + pType); /* We've done the necessary checks to show that this is safe. */ @SuppressWarnings("unchecked") Class<? extends Creator<T>> creator = (Class<? extends Creator<T>>) any; return creator; } } } } throw new ClassCastException(fqcn + " does not implement Creator<String>"); } ``` The main restriction you have to adhere to is that a class in the hierarchy must specify the type parameter. For example `class MyCreator implements Creator<String>`. You can't use it with `class GenericCreator<T> implements Creator<T>`. It doesn't currently handle the valid case where you create a new interface `interface StringCreatorIfc extends Creator<String>`, and have a class implement that. It could be enhanced to do that, but I'll leave that as an exercise for those inclined.
can I reflectively instantiate a generic type in java?
[ "", "java", "generics", "reflection", "" ]
From time to time my applications GUI stops redrawing. There a lot of threads that are firing all kinds of events (like timers or network data ready etc.). Also there are a lot of controls that are subscribing these events. Because of that, all the event handlers play the InvokeRequired/Invoke game. Now I figured out that when the GUI freezes a lot of threads are waiting for Invoke() to return. Looks like the message pump stopped pumping. The handlers look like this: ``` private void MyEventHandler( object sender, EventArgs e ) { if ( InvokeRequired ) { Invoke( new EventHandler( MyEventHandler ), sender, e ); return; } SetSomeStateVariable(); Invalidate(); } ``` Any ideas? Solution: BeginInvoke(). Looks like you should always use BeginInvoke() if you have lots of CrossThread-Events... Thanks. Thanks everybody. **EDIT:** Looks like `BeginInvoke()` really solved it. No freezing until now.
Invoke waits until the event is handled in the GUI thread. If you want it to be asynchronous use BeginInvoke()
Deadlock perhaps? Do you make sure that the events are never fired while holding a lock? Are you able to see this with a debugger attached? If so, make it freeze and then hit the "pause" button - and see what the UI thread is doing. Note that if you are able to get away with BeginInvoke instead of Invoke, life is a bit easier as it won't block. Also note that you don't need the "new EventHandler" bit - just ``` Invoke((EventHandler) MyEventHandler, sender, e); ``` should be fine.
Invoke() is blocking
[ "", "c#", ".net", "winforms", ".net-2.0", "" ]
I need to connect to an Exchange mailbox in a Python script, without using any profile setup on the local machine (including using Outlook). If I use win32com to create a MAPI.Session I could logon (with the Logon() method) with an existing profile, but I want to just provide a username & password. Is this possible? If so, could someone provide example code? I would prefer if it only used the standard library and the pywin32 package. Unfortunately, enabling IMAP access for the Exchange server (and then using imaplib) is not possible. In case it is necessary: all the script will be doing is connecting to the mailbox, and running through the messages in the Inbox, retrieving the contents. I can handle writing the code for that, if I can get a connection in the first place! To clarify regarding Outlook: Outlook will be installed on the local machine, but it does not have any accounts setup (i.e. all the appropriate libraries will be available, but I need to operate independently from anything setup inside of Outlook).
I'm pretty sure this is going to be impossible without using Outlook and a MAPI profile. If you can sweet talk your mail admin into enabling IMAP on the Exchange server it would make your life a lot easier.
I know this is an old thread, but... If you're using Exchange 2007 or newer, or Office365, take a look at Exchange Web Services. It's a pretty comprehensive SOAP-based interface for Exchange, and you can do pretty much anything Outlook is able to do, including delegate or impersonation access to other user accounts. <https://learn.microsoft.com/en-us/exchange/client-developer/web-service-reference/ews-reference-for-exchange> UPDATE: I have released a [Python EWS client](https://pypi.python.org/pypi/exchangelib/) on PyPI that supports autodiscover, calendars, inbox, tasks, contacts, and more: ``` from exchangelib import DELEGATE, Account, Credentials credentials = Credentials( username='MYDOMAIN\\myusername', # Or me@example.com for O365 password='topsecret' ) a = Account( primary_smtp_address='john@example.com', credentials=credentials, autodiscover=True, access_type=DELEGATE ) # Print first 100 inbox messages in reverse order for item in a.inbox.all().only('subject').order_by('-datetime_received')[:100]: print(item.subject) ```
Connect to Exchange mailbox with Python
[ "", "python", "email", "connection", "exchange-server", "pywin32", "" ]
Yesterday, I found myself writing code like this: ``` SomeStruct getSomeStruct() { SomeStruct input; cin >> input.x; cin >> input.y; } ``` Of course forgetting to actually return the struct I just created. Oddly enough, the values in the struct that *was* returned by this function got initialized to zero (when compiled using g++ that is). Is this just a coincidence or did another SomeStruct get created and initialized somewhere implicitly?
> Did another SomeStruct get created and initialized somewhere implicitly? Think about how the struct is returned. If both `x` and `y` are 32 bits, it is too big to fit in a register on a 32-bit architecture, and the same applies to 64-bit values on a 64-bit architecture (@Denton Gentry's answer mentions how simpler values are returned), so it has to be allocated somewhere. It would be wasteful to use the heap for this, so it has to be allocated on the stack. But it cannot be on the stack frame of your `getSomeStruct` function, since that is not valid anymore after the function returns. The compiler instead has the caller tells the called function where to put the result (which is probably somewhere on the stack of the caller), by passing the called function a hidden pointer to the space allocated to it. So, the place where it is being set to zero is on the *caller*, not on your `getSomeStruct` function. There are also optimizations like the "named value return optimization" where extra copies can be elided. So, had you used the missing `return`, the result would be created directly on the space allocated by the caller, instead of creating a temporary and copying it. To know more about what is happening, you have to look at the caller function. Is it initializing (to zero) an "empty" `SomeStruct` to which you later assign the return value of your `getSomeStruct` function? Or is it doing something else?
Falling off the end of a function that is declared to return a value (without explicitly returning a value) leads to undefined consequences. For gcc, you should start with the `-Wall` command line switch that turns on most useful warnings. The specific gcc warning that controls the warning you want is `-Wreturn-type` (which is included in `-Wall`, I just mention this for completeness). Once you have warnings turned on, you should also use `-Werror` to treat warnings as errors and make the build stop at the point it detects an error.
What happens if you don't return a value in C++?
[ "", "c++", "g++", "return-value", "" ]
In my javascript I have this ``` loopDeLoop: while (foo !== bar) { switch (fubar) { case reallyFubar: if (anotherFoo == anotherBar) { break loopDeLoop; } break; default: break; } } ``` But JSLint says... lint warning: use of label Here's the notes from [JSLint](http://www.jslint.com/lint.html) > Labels > JavaScript allows any statement to have a label, and labels have a separate name space. JSLint is more strict. > > JSLint expects labels only on statements that interact with break: switch, while, do, and for. JSLint expects that labels will be distinct from vars and parameters. How do I construct the above to get rid of the warning? Thanks, Greg
You are using the label correctly. JSLint is throwing a warning because labels in Javascript are horribly bad style, and JSLint wants you to know that. To reiterate, if you use labels at all, even correctly, JSLint will give that warning. Edit: Looks like you might be able to disable the label warning with a `-use_of_label` configuration directive.
You could set a flag that determines whether or not you are done working in the loop. ``` var done = false; while (foo !== bar && !done) { switch (fubar) { case reallyFubar: if (anotherFoo == anotherBar) { done = true; } break; default: break; } if(!done) { //If you have more logic inside the loop, put it here } } ```
Getting a JSLint warning concerning labels in Javascript
[ "", "javascript", "jslint", "" ]
I have a generic method with this (dummy) code (yes I'm aware IList has predicates, but my code is not using IList but some other collection, anyway this is irrelevant for the question...) ``` static T FindThing<T>(IList collection, int id) where T : IThing, new() { foreach (T thing in collection) { if (thing.Id == id) return thing; } return null; // ERROR: Cannot convert null to type parameter 'T' because it could be a value type. Consider using 'default(T)' instead. } ``` This gives me a build error > "Cannot convert null to type parameter > 'T' because it could be a value type. > Consider using 'default(T)' instead." Can I avoid this error?
Three options: * Return `default` (or `default(T)` for older versions of C#) which means you'll return `null` if `T` is a reference type (or a nullable value type), `0` for `int`, `'\0'` for `char`, etc. ([Default values table (C# Reference)](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/default-values-table)) * If you're happy to restrict `T` to be a reference type with the `where T : class` constraint and then return `null` as normal * If you're happy to restrict `T` to be a non-nullable value type with the `where T : struct` constraint, then again you can return `null` as normal from a method with a return value of `T?` - note that this is *not* returning a null reference, but the null value of the nullable value type.
``` return default(T); ```
How can I return NULL from a generic method in C#?
[ "", "c#", "generics", "" ]
In our C++ course they suggest not to use C++ arrays on new projects anymore. As far as I know [Stroustrup](https://en.wikipedia.org/wiki/Bjarne_Stroustrup) himself suggests not to use arrays. But are there significant performance differences?
Using C++ arrays with `new` (that is, using dynamic arrays) should be avoided. There is the problem that you have to keep track of the size, and you need to delete them manually and do all sorts of housekeeping. Using arrays on the stack is also discouraged because you don't have range checking, and passing the array around will lose any information about its size (array to pointer conversion). You should use `std::array` in that case, which wraps a C++ array in a small class and provides a `size` function and iterators to iterate over it. Now, **std::vector vs. native C++ arrays** (taken from the internet): ``` // Comparison of assembly code generated for basic indexing, dereferencing, // and increment operations on vectors and arrays/pointers. // Assembly code was generated by gcc 4.1.0 invoked with g++ -O3 -S on a // x86_64-suse-linux machine. #include <vector> struct S { int padding; std::vector<int> v; int * p; std::vector<int>::iterator i; }; int pointer_index (S & s) { return s.p[3]; } // movq 32(%rdi), %rax // movl 12(%rax), %eax // ret int vector_index (S & s) { return s.v[3]; } // movq 8(%rdi), %rax // movl 12(%rax), %eax // ret // Conclusion: Indexing a vector is the same damn thing as indexing a pointer. int pointer_deref (S & s) { return *s.p; } // movq 32(%rdi), %rax // movl (%rax), %eax // ret int iterator_deref (S & s) { return *s.i; } // movq 40(%rdi), %rax // movl (%rax), %eax // ret // Conclusion: Dereferencing a vector iterator is the same damn thing // as dereferencing a pointer. void pointer_increment (S & s) { ++s.p; } // addq $4, 32(%rdi) // ret void iterator_increment (S & s) { ++s.i; } // addq $4, 40(%rdi) // ret // Conclusion: Incrementing a vector iterator is the same damn thing as // incrementing a pointer. ``` Note: If you allocate arrays with `new` and allocate non-class objects (like plain `int`) or classes without a user defined constructor *and* you don't want to have your elements initialized initially, using `new`-allocated arrays can have performance advantages because `std::vector` initializes all elements to default values (0 for int, for example) on construction (credits to @bernie for reminding me).
## Preamble for micro-optimizer people Remember: > "Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: **premature optimization is the root of all evil.** Yet we should not pass up our opportunities in that critical 3%". (Thanks to [metamorphosis](https://stackoverflow.com/users/3454889/metamorphosis) for the full quote) Don't use a C array instead of a vector (or whatever) just because you believe it's faster as it is supposed to be lower-level. You would be wrong. Use by default vector (or the safe container adapted to your need), and then if your profiler says it is a problem, see if you can optimize it, either by using a better algorithm, or changing container. This said, we can go back to the original question. ## Static/Dynamic Array? The C++ array classes are better behaved than the low-level C array because they know a lot about themselves, and can answer questions C arrays can't. They are able to clean after themselves. And more importantly, they are usually written using templates and/or inlining, which means that what appears to a lot of code in debug resolves to little or no code produced in release build, meaning no difference with their built-in less safe competition. All in all, it falls on two categories: ### Dynamic arrays Using a pointer to a malloc-ed/new-ed array will be at best as fast as the std::vector version, and a lot less safe (see [litb's post](https://stackoverflow.com/questions/381621/using-arrays-or-stdvectors-in-c-whats-the-performance-gap#381656)). So use a std::vector. ### Static arrays Using a static array will be at best: * as fast as the [std::array](http://en.cppreference.com/w/cpp/container/array) version * and a lot less safe. So use a [std::array](http://en.cppreference.com/w/cpp/container/array). ### Uninitialized memory Sometimes, using a `vector` instead of a raw buffer incurs a visible cost because the `vector` will initialize the buffer at construction, while the code it replaces didn't, as remarked [bernie](https://stackoverflow.com/users/1030527/bernie) by in his [answer](https://stackoverflow.com/a/43955169/14089). If this is the case, then you can handle it by using a `unique_ptr` instead of a `vector` or, if the case is not exceptional in your codeline, actually write a class `buffer_owner` that will own that memory, and give you easy and safe access to it, including bonuses like resizing it (using `realloc`?), or whatever you need.
Using arrays or std::vectors in C++, what's the performance gap?
[ "", "c++", "arrays", "vector", "" ]
I have a result from an SQL query that I would like to sort alphabetical, but there are a couple of commonly used results that I would like to float to the top. Is there a simple way I can achieve this either by doing clever SQL or by sorting the (asp.net) datatable once I have it filled? I know the database ID of the things that I want to keep at the top ahead of time if that makes a difference.
The easiest way to do this is to sort by something that sets those fields aside from the others... Under the assumption you have access to modify the structure of the table (which you may not), then add a "sticky" field which allows you to mark items as sticky and attach an order to the sticky items if you like. Sort by this field before the regular sort. As for a trick to do this without that field defined - you would need to sort by some data that you can find in these fields or maintain the ids in a separate table - or a list in your query... not the most ideal way, but it will work.
You could define a custom column that sets a "special flag" that you can sort by. Then, sort by the alphabetical column. ``` SELECT ... IsSpecial = CASE WHEN RowID IN (100,534,203) THEN 1 ELSE 0 END FROM ... ORDER BY IsSpecial DESC, RowID ASC, Name ASC ```
How can I sort an SQL result but keep some results as special?
[ "", ".net", "sql", "sorting", "" ]
We want to build a library of c# *snips* for .NET. We are looking around to see if there is something similar out there. The library will be open source and free to use and distribute. I see there is a similar question here, but is more theoretical than practical, I want to have [Good Source of .NET Dsg Patterns](https://stackoverflow.com/questions/324824/good-source-of-net-design-patterns). Any help will be greatly appreciated.
Doodads has a lot of C# examples in their website [Here is a list of GOF Pattern implementation in C#](http://dofactory.com/Patterns/Patterns.aspx) They also have a 'Design Pattern Framework' for GOF patterns, it is commercial. I purchased it long time back, was good for reference. <http://dofactory.com/Framework/Framework.aspx>
If there would be a library, why would we even bother with the pattern? We'd just use the lib and fall into the pit of success. The idea of the pattern is to not make the same mistake as the other thousand developers. The pattern is something of "if you need to architect something that way, this way works best" .. And everybody knows what I'm talking about when saying "strategy, or factory etc" Correct me if i'm wrong...
Is there any good framework or library for c# snips of design-patterns?
[ "", "c#", "design-patterns", "" ]
A common argument against using .NET for high volume, transactional enterprise systems is that IIS does not compare to the likes of Weblogic and websphere for java. Is this true? Unfortunately for .NET web apps IIS is the only option as an application server. Does anyone have any arguments against this? I would like to promote .NET more in the enterprise and need some help putting my case forward. Thanks
I've been coding ASP.NET for 6 years now and prior to getting into the field I was a network engineer. IMO, ASP.NET on IIS is faster out of the box than most of those other platforms. However, it's easy to screw up performance with mediocre programming skills, and it is possible that a highly tuned platform could beat a standard IIS configuration. Honestly, I don't put much stock in the whole debate about which platform has the higher potential performance, because I've never had to address the issue, and I've developed sites which received upwards of 2-3 million hits an hour without hiccups.
If you are asking if IIS & .Net can do high performance web sites, the answer is yes. You are unlikely to get to the kind of scale where either of the web servers you have mentioned starts being the problem. You are more likely to have issues with back end databases first. If you are asking how to convince management then I would try some MS case studies which can all be found at the [Microsoft Case Study site](http://www.microsoft.com/casestudies/default.aspx). You will probably want to find a case study that is relevant to your field of business, but here are some that I have used in the past: 1. [GoDaddy.com: World’s Largest Domain Registrar Moves 3.5 Million Domains from Linux to Windows](http://www.microsoft.com/casestudies/casestudy.aspx?casestudyid=1000003748) 2. [London Stock Exchange Cuts Information Dissemination Time from 30 to 2 Milliseconds](http://www.microsoft.com/casestudies/casestudy.aspx?casestudyid=200042) 3. [Virgin Group: Web Site Traffic Increases by Almost 50 Per Cent with Microsoft .NET](http://www.microsoft.com/casestudies/casestudy.aspx?casestudyid=51584) 4. [Break.com: Popular Entertainment Site Handles Up to 35 Million Daily Page Views on Two Web Servers](http://www.microsoft.com/casestudies/casestudy.aspx?casestudyid=4000002034)
How does IIS compare in terms of performance and scalability to weblogic and websphere for enterprise web applications?
[ "", "java", ".net", "iis", "websphere", "weblogic", "" ]
The Zend Framework based site I have been working on is now being migrated to its production server. This server turns out to be nginx (surprise!). Naturally the site does not work correctly as it was developed on Apache and relies on an htaccess file. My question is... anyone have any experience with this? Any ideas on how to translate what the htaccess file does to an nginx.conf file? I'm researching this but am hoping someone already has experience with this. Thanks! EDIT: This is the current htaccess: ``` RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ /index.php [NC,L] ```
I know it's a pretty old thread but it might help some people anyway. Basically it redirects any 404 error to index.php, but if the file exists (type file) it will set the right root. I did it from the top of my head. It might not be working right away, and you have to put the right path and fastcgi config. I also put everything back to index.php as it should work like that with Zend\_Framework ``` error_page 404 = /index.php; location / { if (-f $request_filename) { root /var/www; } } location ~ \.php$ { fastcgi_pass unix:/tmp/php.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /var/www/index.php; include /etc/nginx/fastcgi_params; } ```
``` server { listen 80; ## listen for ipv4 listen [::]:80 default ipv6only=on; ## listen for ipv6 server_name localhost; access_log /var/log/nginx/localhost.access.log; error_log /var/log/nginx/localhost.error.log; root /var/www/localhost/public; try_files $uri @php_index; # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location @php_index { fastcgi_pass 127.0.0.1:9000; fastcgi_param SCRIPT_FILENAME /var/www/localhost/index.php; include fastcgi_params; } } ``` It's recommended to use try\_files when ever possible.
Zend Framework on nginx
[ "", "php", "zend-framework", "mod-rewrite", "nginx", "" ]
I've got a table, called faq\_questions with the following structure: ``` id int not_null auto_increment, question varchar(255), sort_order int ``` I'm attempting to build a query that given a sort order, selects the row with the next highest sort order. Example: ``` id question sort_order 1 'This is question 1' 10 2 'This is question 2' 9 3 'This is another' 8 4 'This is another one' 5 5 'This is yet another' 4 ``` Ok, so imagine I pass in 5 for my known sort order (id 4), I need it to return the row with id 3. Since there's no guarantee that sort\_order will be contiguous I can't just select known\_sort\_order + 1. Thanks!
It seems too simple, but it looks like what you need: ``` SELECT id,question FROM `questions` WHERE `sort_order` > sort_order_variable ORDER BY sort_order ASC LIMIT 1 ```
``` SELECT * FROM table_name WHERE sort_order > 5 ORDER BY sort_order ASC LIMIT 1 ```
MySql Query, Select greater than
[ "", "sql", "mysql", "" ]
I'm using VS 2008 to create a C++ DLL (not managed) project and I need convert a char\* to a long long type. Is there an easy way to do it? Thanks in advance :)
Try `_atoi64.` This takes `char*` and returns `__int64`.
The easiest way is to use the std::stringstream (it's also the most typesafe...) ``` std::stringstream sstr(mystr); __int64 val; sstr >> val; ``` You may need to target a 64-bit application for this to work. [C++ FAQ](http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.2)
convert string to long long
[ "", "c++", "string", "visual-studio-2008", "" ]
I'm writing a small and inadequate linear algebra library in C++ for a project (I'm sorry). I'm implementing matrices and operations using double precision numbers. I'm doing right? Should I implement a template class instead? Is there a more precise type around?
I've written a C++ linear algebra library using templates. My thought was that we might want to use complex numbers or extended precision numbers some day. That was maybe seven years ago, and we haven't done it yet. We almost always use doubles as the template type, and we have typedefs to make that easy. A few times we've gone the other way, using types *smaller* than a double. For example, we've used float rather than double in a memory-bound application described [here](http://www.codeproject.com/KB/recipes/TailKeeper.aspx). But 99.9 percent of the time we use doubles. If you do use a template argument, watch out for using an integer type but implicitly requiring a floating point type. For example, say you have a matrix whose entries are all integers and so you use a matrix<int> class. But then you pass that to a linear solver. Now your arithmetic is done using *integer* division, and your results are wrong. (I've done that!)
I would implement the class/struct using a template. In the beginning, you will most likely be satisfied with just `double`, but I have found that in every project where I **didn't** implement matrices as templates, I later regretted it. Also, it gives you an opportunity to use more interesting element-algebras - interval arithmetic, probability distributions, complex math, fixed-point match, sub-matrices, simple math :-), etc.
Best base type to deal with linear algebra
[ "", "c++", "linear-algebra", "double-precision", "" ]
I have a little project with some jsp deployed on an Tomcat 5.5. Recently the Servlets which are also deployed with the jsp files (one war archive) stopped working. I also checked out a previous version from my svn which should work. What I noticed that the `displayname` (I use a german version of Tomcat , so I guess that is how I would translate it, the name in the second column in the Tomcat manager) disappeared. I use Eclipse Ganymede on vista. Tomcat is running on Debian. A local Tomcat shows the same behavior. Hope someone have an idea. Thanks.
Is the `<display-name>` element in the web.xml file? Is the `web.xml` file in the WAR and at `/WEB-INF/web.xml`? Does it validate (eclipse can do that, or try [w3c.org's validation service](http://validator.w3.org/))?
You are looking for ``` <web-app blahblah> <display-name>**This**</display-name> <servlet> <servlet-name>Not this</servlet-name> </servlet> </web-app> ```
tomcat application missing displayname
[ "", "java", "eclipse", "tomcat", "servlets", "" ]
I have 2 tables, an active table and an inactive table. I want to *move* rows from the active to the inactive table. My first thought was ``` insert into inactive select * from active where ... delete from active active where ... ``` However about .42 seconds later I noticed this will drop/duplicate rows if updates alter what the where clause selects. In this case, I can easily prevent that but what should I do in cases where I can't? edit: From the answers it look like there isn't an easy/trivial way to do this. I'm really surprised by this. I would think that there would be some substantial benefits to having it.
Status flags are your friend. ``` UPDATE old_data SET move="MARKED"; INSERT INTO somewhere... SELECT where move="MARKED"; DELETE FROM old_data WHERE move="MARKED"; ``` If you do this with Autocommit off, it will seize locks all over the place. You can COMMIT after each step, if you want to do a little less locking.
Does your database support the OUTPUT Clause? Then this could be a perfect and easy to follow solution for you, couldn't it? <http://msdn.microsoft.com/en-us/library/ms177564.aspx> ``` delete active with (readpast) output DELETED.* into inactive where ... ```
Move rows between tables in SQL
[ "", "sql", "partitioning", "" ]
I need to grab the height of the window and the scrolling offset in jQuery, but I haven't had any luck finding this in the jQuery docs or Google. I'm 90% certain there's a way to access height and scrollTop for an element (presumably including the window), but I just can't find the specific reference.
From jQuery Docs: ``` const height = $(window).height(); const scrollTop = $(window).scrollTop(); ``` <http://api.jquery.com/scrollTop/> <http://api.jquery.com/height/>
from <http://api.jquery.com/height/> (Note: The difference between the use for the window and the document object) ``` $(window).height(); // returns height of browser viewport $(document).height(); // returns height of HTML document ``` from <http://api.jquery.com/scrollTop/> ``` $(window).scrollTop() // return the number of pixels scrolled vertically ```
How do I determine height and scrolling position of window in jQuery?
[ "", "javascript", "jquery", "" ]
Which is more efficient? ``` SELECT theField FROM theTable GROUP BY theField ``` or ``` SELECT DISTINCT theField FROM theTable ```
In your example, both queries will generate the same execution plan so their performance will be the same. However, they both have their own purpose. To make your code easier to understand, you should use distinct to **eliminate duplicate rows** and group by to **apply aggregate operators** (sum, count, max, ...).
Doesn't matter, it results in the same execution plan. (at least for these queries). These kind of questions are easy to solve, by enabling query analyzer or SSMS to show the execution plan and perhaps the server trace statistics after running the query.
Which is better: Distinct or Group By
[ "", "sql", "sql-server", "" ]
Goal: Create [Photomosaics](http://en.wikipedia.org/wiki/Photographic_mosaic) programmatically using .NET and C#. Main reason I'd like to do this programatically is to be able to record which image and where it goes myself, so I can create an animated effect of the images coming together to create the photomosaic. It would be great to just find something existing already that I could use to accomplish this almost right out of the box. Any ideas?
[Photomosaic-generator](http://www.atalasoft.com/cs/blogs/31appsin31days/archive/2008/05/18/photomosaic-generator.aspx) There's source code available
I think you can borrow ideas from color quantization. For each photograph, calculate it's average color. Since it's small, that's how it will look when viewed from a distance. Then split your target image in photograph-sized rectangles and calculate their average colors. Or, for better results, properly downsize it so, that every photograph corresponds to one pixel in the target picture. Then, for every pixel of the target picture, choose the photograph which has the color value closest to the pixels color. (Closest - as in closest in the 3D RGB cube). You can also apply some dithering for it to look better (Floyd-Steinberg's algorithm is one of the best algorithms out there).
Programmatically create Photomosaic
[ "", "c#", ".net", "graphics", "" ]
How do I check if a variable, specifically a pointer, is defined in C++? Suppose I have a class: ``` class MyClass { public: MyClass(); ~MyClass() { delete pointer; // if defined! } initializePointer() { pointer = new OtherClass(); } private: OtherClass* pointer; }; ```
Why worry about checking for the pointers value? Just initialize it to a null pointer value and then just call delete on it. delete on a null pointer does nothing (the standard guarantees it). ``` class MyClass { public: MyClass():pointer(0) { } ~MyClass() { delete pointer; pointer = 0; } initializePointer() { pointer = new OtherClass(); } private: OtherClass* pointer; }; ``` And everytime you call delete on it, you should set the pointer to a null pointer value. Then you are all fine.
I tend to initialize my pointer values to NULL on object construction. This allows a check against NULL to see if the pointer variable is defined.
Check for pointer definedness in C++
[ "", "c++", "pointers", "" ]