Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have the following code (cut down for readability): **Main Class:** ``` public StartProcess() { Thinker th = new Thinker(); th.DoneThinking += new Thinker.ProcessingFinished(ThinkerFinished); th.StartThinking(); } void ThinkerFinished() { Console.WriteLine("Thinker finished"); } ``` **Thinker Class:** ``` public class Thinker { private System.Timers.Timer t; public delegate void ProcessingFinished(); public event ProcessingFinished DoneThinking; BackgroundWorker backgroundThread; public Thinker() { } public StartThinking() { t = new System.Timers.Timer(5000); // 5 second timer t.AutoReset = false; t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed); t.Start(); // start a background thread to do the thinking backgroundThread = new BackgroundWorker(); backgroundThread.DoWork += new DoWorkEventHandler(BgThread_DoWork); backgroundThread.RunWorkerAsync(); } void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { DoneThinking(); } BgThread_DoWork(object sender, DoWorkEventArgs e) { // work in here should go for much less than 5 seconds // it will die if it doesn't t.Stop(); DoneThinking(); } } ``` What I originally expected to happen was that the event handler in the main class would prevent the Thinker from being garbage collected. [Apparently this isn't the case](https://stackoverflow.com/questions/298261/do-event-handlers-stop-garbage-collection-from-occuring). I'm now wondering whether garbage collection will occur regardless of whether this thread is "busy" or not. In other words, is there a chance it will be garbage collected before the 5 second timeout has expired? To put it another way, is it possible for the garbage collector to collect my Thinker before it's finished processing?
No, a thread is considered live as long as it is referenced, and any thread that is running is considered to be referenced (IIRC a running thread registers its stack as a GC root, and that stack will reference the thread). That said i'm looking at your example and i don't understand where you believe a thread is being spawned?
No, a running thread's stack acts as a root for GC purposes. That stack will live as long as the Thread is running, so the Thread itself won't be collected as long its running. Here's an [article](http://msdn.microsoft.com/en-us/magazine/bb985010.aspx) that mentions (among other things) what the roots are for GC purposes. To save some time, GC roots are global objects, static objects, all reference on all thread stacks, and all CPU registers containing references.
Will .Net Garbage Collect an object that's not referenced, but has a thread that's doing work?
[ "", "c#", ".net", "multithreading", "garbage-collection", "" ]
**ORIGINAL Q:** I'm wondering if anyone has had experience of migrating a large Cobol/PL1 codebase to Java? How automated was the process and how maintainable was the output? How did the move from transactional to OO work out? Any lessons learned along the way or resources/white papers that may be of benefit would be appreciated. --- **EDIT 7/7:** Certainly the NACA approach is interesting, the ability to continue making your BAU changes to the COBOL code right up to the point of releasing the JAVA version has merit for any organization. The argument for procedural Java in the same layout as the COBOL to give the coders a sense of comfort while familiarizing with the Java language is a valid argument for a large organisation with a large code base. As @Didier points out the $3mil annual saving gives scope for generous padding on any BAU changes going forward to refactor the code on an ongoing basis. As he puts it if you care about your people you find a way to keep them happy while gradually challenging them. The problem as I see it with the suggestion from @duffymo to > Best to try and really understand the > problem at its roots and re-express it > as an object-oriented system is that if you have any BAU changes ongoing then during the LONG project lifetime of coding your new OO system you end up coding & testing changes on the double. That is a major benefit of the NACA approach. I've had some experience of migrating Client-Server applications to a web implementation and this was one of the major issues we encountered, constantly shifting requirements due to BAU changes. It made PM & scheduling a real challenge. Thanks to @hhafez who's experience is nicely put as *"similar but slightly different"* and has had a reasonably satisfactory experience of an automatic code migration from Ada to Java. Thanks @Didier for contributing, I'm still studying your approach and if I have any Q's I'll drop you a line.
**Update 6/25:** A friend just ran across the [NACA](http://media-tech.blogspot.com/2009/06/naca-presented-jazoon-2009.html) Cobol to Java converter. Looks quite interesting, it was used to translate 4m lines of Cobol with 100% accuracy. Here's the [NACA open source project page](http://code.google.com/p/naca/). The other converters I've seen were proprietary, and the materials were conspicuously lacking success stories and detailed example code. NACA is worth a long look. **Update 7/4:** @Ira Baxter reports that the Java output looks very Cobol-esque, which it absolutely does. To me, this is the natural result of automatic translation. I doubt we'll ever find a much better translator. This perhaps argues for a gradual re-write approach. **Update 2/7/11:** @spgennard points out that there are some Cobol compilers on the JVM, for example Veryant's [isCobol Evolve](http://www.veryant.com/products/). These could be used to help gradually transition the code base, though I think the OP was more interested in automated source conversion. --- I'd be very cautious about this. (I used to work for a company that automatically *corrected* Cobol and PL/I programs for Y2K, and did the front end compiler that converted many dialects of Cobol into our intermediate analytic form, and also a code generator.) My sense is that you'd wind up with a Java code base that still would be inelegant and unsatisfying to work with. You may wind up with performance problems, dependencies on vendor-supplied libraries, generated code that's buggy, and so on. You'll certainly incur a huge testing bill. Starting from scratch with a new object-oriented design can be the right approach, but you also have to carefully consider the decades of stored knowledge represented by the code base. Often there are many subtleties that your new code may miss. On the other hand, if you're having a hard time finding staff to maintain the legacy system, you may not have a choice. One gradual approach would be to first upgrade to Cobol 97. This adds object-orientation, so you can rewrite and refactor subsystems individually when you add new functionality. Or you could replace individual subsystems with freshly-written Java. Sometimes you'll be able to replace components with off-the-shelf software: we helped one very large insurance company that still had 2m lines of code in a legacy language it created in the 1950s. We converted half of it to Y2K compliant legacy language, and they replaced the other half with a modern payroll system they bought from an outside vendor.
It was clearly our intent to obtain initial java code that was very close to the original cobol in order to facilitate the migration of people: they find the good old app they wrote in cobol in exact same structure. one of our most important goals was to keep initial developers on board: that's the way we found to achieve it. When application migrated to Java, those people can start make it more OO as they further develop / refactor it. If you don't care about migrating people, you can use other strategy. This 1-to-1 conversion also made 100% automated conversion simpler & faster: the good consequence is that we made our recurring savings (3 millions euros / year) much faster: we estimate 12-18 months. Those early savings can clearly be reinvested in OO refactoring feel free to contact me: didier.durand@publicitas.com or mediaandtech@gmail.com didier
Experience migrating legacy Cobol/PL1 to Java
[ "", "java", "migration", "cobol", "code-migration", "" ]
Okay lets say I have a list, and I want to check if that list exists within another list. I can do that doing this: ``` all(value in some_map for value in required_values) ``` Which works fine, but lets say I want to the raise an exception when a required value is missing, with the value that it is missing. How can I do that using list comprehension? I'm more or less curious, all signs seem to point to no. *EDIT* Argh I meant this: ``` for value in required_values: if value not in some_map: raise somecustomException(value) ``` Looking at those I cant see how I can find the value where the error occurred
> lets say i want to the raise an exception when a required value is missing, with the value that it is missing. How can i do that using list comprehension? List comprehensions are a syntactically concise way to create a list based on some existing list—they're *not* a general-purpose way of writing any `for`-loop in a single line. In this example, you're not actually creating a list, so it doesn't make any sense to use a list comprehension.
If you don't want to consider duplicates and the values are hashable, use sets. They're easier, faster, and can extract "all" elements missing in a single operation: ``` required_values = set('abc') # store this as a set from the beginning values = set('ab') missing = required_values - values if missing: raise SomeException('The values %r are not in %r' % (missing, required_values)) ```
Using list comprehensions and exceptions?
[ "", "python", "list", "list-comprehension", "" ]
I've been developing in PHP for a while now, and I still have not had a task where I've had to use variable variables. Can anyone give me examples where using them is a good idea ? Or were they included in the language just for fun ?
One situation where I've had to use them is URI processing, although this technique might be dated, and I admittedly haven't used it in a long time. Let's say we want to pull the URI from the script in the format `domain.tld/controller/action/parameter/s`. We could remove the script name using the following: ``` $uri_string = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['REQUEST_URI']); ``` To extract the controller, action, and parameter values from this we're going to have to explode the string using the path delimiter '/'. However, if we have leading or trailing delimiters, we'll have empty array values upon explosion, so we should trim those from the beginning and end of the string: ``` $uri_string = trim($uri_string, '/'); ``` We can now explode the path into an array: ``` $uri_data = explode('/', $uri_string); ``` `$uri_data[0]` now contains our controller name, `$uri_data[1]` contains the action name, and values in the array beyond that are parameters that should be passed to the action method. ``` $controller_name = $uri_data[0]; $action_name = $uri_data[1]; ``` So, now that we have these names, we can use them for a number of things. If you keep your controllers in a very specific directory relative to the site root, you can use this information to `require_once` the controller class. At that point, you can instantiate it and call it using variable variables: ``` $controller = new $controller_name(); $controller->{$action_name}(); // Or pass parameters if they exist ``` There are a lot of security gotchas to look out for in this approach, but this is one way I've seen to make use of variable variables. **DISCLAIMER**: I'm not suggesting your actually use this code.
I generally find them in places where the code smells bad. Maybe references a static configuration variable etc... But why wouldn't the usual associative array have been a better solution. Seems like a security hole waiting to happen. I suppose you might be able to use them in templates effectively.
When to use a variable variable in PHP?
[ "", "php", "variable-variables", "" ]
Could anyone please clarify the defination of attribute? for example, in the following code, what is an attribute: ``` request.setAttribute("ja",new foo.Employee()); ``` Is the attribute in the above code an object of type foo.Employee(), or it is key/value pair, or it is actually "ja"?
Request attributes are values indexed by a key (in your case "ja") which are shared in the life of the request object. In Java **filter, servlet, jsp, include and forward** use same request object so for example you can *push* an object in a servlet and *pull* it in a JSP. The same approach is for session and application scopes
Request attributes are (or at least act like) a map of objects, in this case the key is "ja" and the value is a new foo.Employee. The session, page, and application have the same data structure.
What are attributes?
[ "", "java", "jsp", "servlets", "" ]
I'm building a client-server (c#) application that uses a web services to synchronize the data. Basically I am passing the XML of a DataSet back and forth. But depending on various parameters the dataset can actually be quite large. I'm compressing the XML using Gzip and want to pass that to the web server and the get the resulting compressed XML back. What is the best way to pass potentially large chunks of data back and forth? Clarification: I guess I'm asking what format is the best to pass the data. JSON, SOAP, ordinary POST (I'm not very familiar with Web Services so I'm sure there's more that I'm not thinking of).
Best probably depends on a lot of factors. If by best you mean most performant, here are some points to consider: * XML is not the best way at all * Binary serialization is far more efficient. * You may not have this option, however, if you need to concern yourself with interoperability. In that case, you may want to consider using a flat file or delimited format. * If neither of those are doable, then you might consider just sending what has changed instead of all of the data. * If that isn't an option, then compressing the XML is an... ok solution. I'd use XML as a last resort, since there's a lot of unnecessary metadata that is included in XML that will easily increase the size of your payload by more than 5X.
What you probably want to investigate is using [MTOM](http://en.wikipedia.org/wiki/MTOM). This allows you to send binary SOAP in a chunked manner. This is cool because chunking the data, coupled with an AJAX UI, will allow you to present a progress bar to the user that is uploading it. [Here](http://www.codeproject.com/KB/XML/MTOMWebServices.aspx) is an example of using MTOM to send/receive data in a chunked manner. I hope this helps.
How to pass large quantity of data to web service
[ "", "c#", "asp.net", "web-services", "client-server", "" ]
I'm trying to convert the data from a simple object graph into a dictionary. I don't need type information or methods and I don't need to be able to convert it back to an object again. I found [this question about creating a dictionary from an object's fields](https://stackoverflow.com/questions/61517/python-dictionary-from-an-objects-fields), but it doesn't do it recursively. Being relatively new to python, I'm concerned that my solution may be ugly, or unpythonic, or broken in some obscure way, or just plain old NIH. My first attempt appeared to work until I tried it with lists and dictionaries, and it seemed easier just to check if the object passed had an internal dictionary, and if not, to just treat it as a value (rather than doing all that isinstance checking). My previous attempts also didn't recurse into lists of objects: ``` def todict(obj): if hasattr(obj, "__iter__"): return [todict(v) for v in obj] elif hasattr(obj, "__dict__"): return dict([(key, todict(value)) for key, value in obj.__dict__.iteritems() if not callable(value) and not key.startswith('_')]) else: return obj ``` This seems to work better and doesn't require exceptions, but again I'm still not sure if there are cases here I'm not aware of where it falls down. Any suggestions would be much appreciated.
An amalgamation of my own attempt and clues derived from Anurag Uniyal and Lennart Regebro's answers works best for me: ``` def todict(obj, classkey=None): if isinstance(obj, dict): data = {} for (k, v) in obj.items(): data[k] = todict(v, classkey) return data elif hasattr(obj, "_ast"): return todict(obj._ast()) elif hasattr(obj, "__iter__") and not isinstance(obj, str): return [todict(v, classkey) for v in obj] elif hasattr(obj, "__dict__"): data = dict([(key, todict(value, classkey)) for key, value in obj.__dict__.items() if not callable(value) and not key.startswith('_')]) if classkey is not None and hasattr(obj, "__class__"): data[classkey] = obj.__class__.__name__ return data else: return obj ```
One line of code to convert an object to JSON recursively. ``` import json def get_json(obj): return json.loads( json.dumps(obj, default=lambda o: getattr(o, '__dict__', str(o))) ) obj = SomeClass() print("Json = ", get_json(obj)) ```
Recursively convert python object graph to dictionary
[ "", "python", "python-2.6", "" ]
I am a PHP/MySQL developer, slowly venturing into the realm of C#/SQL Server and I am having a problem in C# when it comes to reading an SQL Server query that joins two tables. Given the two tables: TableA: ``` int:id VARCHAR(50):name int:b_id ``` TableB: ``` int:id VARCHAR(50):name ``` And given the query ``` SELECT * FROM TableA,TableB WHERE TableA.b_id = TableB.id; ``` Now in C# I normally read query data in the following fashion: ``` SqlDataReader data_reader= sql_command.ExecuteReader(); data_reader["Field"]; ``` Except in this case I need to differentiate from TableA's name column, and TableB's name column. In PHP I would simply ask for the field "TableA.name" or "TableB.name" accordingly but when I try something like ``` data_reader["TableB.name"]; ``` in C#, my code errors out. How can fix this? And how can I read a query on multiple tables in C#?
The result set only sees the returned data/column names, not the underlying table. Change your query to something like ``` SELECT TableA.Name as Name_TA, TableB.Name as Name_TB from ... ``` Then you can refer to the fields like this: ``` data_reader["Name_TA"]; ```
To those posting that it is wrong to use "SELECT \*", I strongly disagree with you. There are many real world cases where a SELECT \* is necessary. Your absolute statements about its "wrong" use may be leading someone astray from what is a legitimate solution. The problem here does not lie with the use of SELECT \*, but with a constraint in [ADO.NET](https://en.wikipedia.org/wiki/ADO.NET). As the OP points out, in PHP you can index a data row via the "TABLE.COLUMN" syntax, which is also how raw SQL handles column name conflicts: > SELECT table1.ID, table2.ID FROM table1, table; Why DataReader is not implemented this way I do not know... That said, a solution to be used could build your SQL statement dynamically by: * querying the schema of the tables you're selecting from * build your SELECT clause by iterating through the column names in the schema In this way you could build a query like the following without having to know what columns currently exist in the schema for the tables you're selecting from > SELECT TableA.Name as Name\_TA, TableB.Name as Name\_TB from ...
How to read the result of SELECT * from joined tables with duplicate column names in .NET
[ "", "c#", "join", "" ]
I am writing an application that I would like to release binaries for on Mac, Windows, and Linux. I have code that compiles under Mac and Linux, but under Windows, it does not. This is because of Windows lack of a strcasecmp. I've read a little bit about how I can create some sort of header to wrap my code, but I don't really understand this concept too well. I've worked on the code on my Mac with just vim and make, but now I'm trying to switch it all over to Visual Studio. Is there some way I can set my project up to include Windows wrapper headers when I'm building on Windows, but omit them when I'm building on my Mac or Linux box? This problem is really giving me a headache and I'd appreciate any suggestions!
You could do ``` #ifdef WIN32 #include <windows_specific_header.h> #else #include <other_header.h> ``` There is also an MS Visual Studio-specific macro: \_MSC\_VER, so ``` #ifdef _MSC_VER ``` would also work here. There is also WINVER define in windows.h.
> configure my project to generate platform independent code That is a bit of an odd phase, so I'm not sure that I'm aswering the right question, but here goes: You have to write platform independent code. Do one of these: * Write to a cross-platform framework (i.e. QT) * Only use library functions that are available on all your targets or * provide wrappers to fill up any gaps in the library for on (or more) targets
How can I configure my project to generate platform independent code?
[ "", "c++", "cross-platform", "" ]
I have an excel sheet with some cells having some background color. I need this color in html code and hence I want to convert Excel.Range.Interior.Color to RGB format or System.Drawing.Color. After doing that i would be using System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color) to get color to be used in html tags. I tried doing following: ``` Excel.Range r = (Excel.Range)m_objRange[2, 2]; System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(r.Interior.Color); MessageBox.Show(""+converter.ConvertTo(r.Interior.Color,typeof(System.Drawing.Color))); ``` But i get an error that i cannot convert System.Double to System.Drawing.Color
The value returned by Excel.Range.Interior.Color is a long integer value of a color. **Examples**: '#000000 is equal to 0 '#FFFFFF is equal to 16777215 You need to convert the decimal value into Hexadecimal. From there, it is easy to convert to RGB. (Group into 2 octets, and convert back to decimal) :)
It's much easier to let ColorTranslator do the work for you: ``` System.Drawing.Color col = System.Drawing.ColorTranslator.FromOle((int) r.Interior.Color); ``` And when you are writing an Excel project inside Visual Studio with the automatically generated proxy objects (instead of the regular Interop project) you need to cast r.Interior.Color to a double, and then back to an int: ``` System.Drawing.Color col = System.Drawing.ColorTranslator.FromOle((int)((double) r.Interior.Color)); ```
How to convert Excel.Range.Interior.Color to System.Drawing.Color in C#?
[ "", "c#", "excel", "" ]
Hey, **I'm trying to figure out what the [B@ prefix means in java.** They come out when I attempt to print byte arrays. However, byte arrays of size 32 and size 4 are identical in length. Always "[@B1234567". What is this? Also, they have the property of only printing hex values. I know it can't just be a binary print because random extended ascii chars would appear. Here is an example of a byte[] to byte[] hashtable mapping print, where mappings are separated by a colon, and these are byte arrays of 4-byte keys and 32-byte elements. ``` [B@1ef9157:[B@1f82982 [B@181ed9e:[B@16d2633 [B@27e353:[B@e70e30 [B@cb6009:[B@154864a [B@18aaa1e:[B@3c9217 [B@20be79:[B@9b42e6 [B@16925b0:[B@14520eb [B@8ee016:[B@1742700 [B@1bfc93a:[B@acb158 [B@107ebe1:[B@1af33d6 [B@156b6b9:[B@17431b9 [B@139b78e:[B@16c79d7 [B@2e7820:[B@b33d0a [B@82701e:[B@16c9867 [B@1f14ceb:[B@89cc5e [B@da4b71:[B@c837cd [B@ab853b:[B@c79809 [B@765a16:[B@1ce784b [B@1319c:[B@3bc473 ```
You're looking at the object ID, not a dump of the contents. * The **[** means array. * The **B** means byte. * The **@** separates the type from the ID. * The **hex digits** are an object ID or hashcode. If the intent is to print the contents of the array, there are many ways. For example: ``` byte[] in = new byte[] { 1, 2, 3, -1, -2, -3 }; System.out.println(byteArrayToString(in)); String byteArrayToString(byte[] in) { char out[] = new char[in.length * 2]; for (int i = 0; i < in.length; i++) { out[i * 2] = "0123456789ABCDEF".charAt((in[i] >> 4) & 15); out[i * 2 + 1] = "0123456789ABCDEF".charAt(in[i] & 15); } return new String(out); } ``` A [complete list](http://download.oracle.com/javase/6/docs/technotes/guides/jni/spec/types.html#wp16432) of the type nomenclature can be found in the [JNI documentation](http://download.oracle.com/javase/6/docs/technotes/guides/jni/spec/types.html#wp16432). Here is the entire list: * **B** - byte * **C** - char * **D** - double * **F** - float * **I** - int * **J** - long * **L\*\*\*fully-qualified-class\***;\*\* - between an `L` and a `;` is the full class name, using `/` as the delimiter between packages (for example, `Ljava/lang/String;`) * **S** - short * **Z** - boolean * **[** - one `[` for every dimension of the array * **(\*\*\*argument types\***)\*\*\*return-type\* - method signature, such as `(I)V`, with the additional pseudo-type of `V` for void method
[B@ means "byte array". Other primitive array types have different prefixes: ``` class Test { public static void main(String [] args) { byte[] b = new byte[0]; int[] i = new int[0]; char[] c = new char[0]; long[] l = new long[0]; double[] d = new double[0]; float[] f = new float[0]; short[] s = new short[0]; System.out.println(b); System.out.println(i); System.out.println(c.toString()); System.out.println(l); System.out.println(d); System.out.println(f); System.out.println(s); } } ``` Prints: ``` [B@3e25a5 [I@19821f [C@addbf1 [J@42e816 [D@9304b1 [F@190d11 [S@a90653 ``` Non-primitive types include the type name after `[L` for instance: ``` [Ljava.lang.String;@a90653 [Ljava.lang.Object;@de6ced ``` If you want to print the contents of a byte array as hex, here's some code to help you: ``` class Test { public static void main(String [] args) { byte[] b = new byte[] { (byte) 0xf3, (byte) 0xf1, (byte) 0x7f }; System.out.println(toHex(b)); } private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray(); public static String toHex(byte[] bytes) { char[] c = new char[bytes.length*2]; int index = 0; for (byte b : bytes) { c[index++] = HEX_DIGITS[(b >> 4) & 0xf]; c[index++] = HEX_DIGITS[b & 0xf]; } return new String(c); } } ```
Java: Syntax and meaning behind "[B@1ef9157"? Binary/Address?
[ "", "java", "syntax", "binary", "hex", "" ]
I am attempting to create a linked server from a 2005 to 2008 Microsoft SQL Server. I do this regularly for 2005 instances, but this is the first step of my long journey into SQL 2008. I am able to create the linked server as any other linked server, I receive no errors, however any time I try to use the linked server for anything (a simple "SELECT \*" statement, for example) I get this error in SSMS: "OLE DB provider "SQLNCLI" for linked server {linked server name} returned message "Invalid character value for cast specification"." What do I need to know about creating a linked server to a 2008 instance in a 2005 instance?
Turns out the tables I kept choosing to test, the most business important tables on the 2008 server, each had fields of the "geography" data type, which is new to 2008. When testing queries on one of the other tables without this datatype the query works correctly. So...you know... it was...an "Invalid character value for cast specification" after all.
It's either collation (my first guess), or Unicode conversions (VARCHAR vs NVARCHAR). I'd upvote John, but I don't have enough reputation.
"Invalid character value for cast specification" for linked 2008 SQL server in 2005 instance
[ "", "sql", "sql-server", "sql-server-2005", "sql-server-2008", "linked-server", "" ]
I think the subject pretty much covers it. I'm not a web programmer (I am a programmer), I'd like to write some play web apps, I don't really have a lot of spare time. So what's the quickest way to get up and running to play around with GWT?
I would say Google's [GWT Quick Start](http://code.google.com/webtoolkit/gettingstarted.html). That said, learning some Java skills would be a good idea if you're not already familiar with the language.
The [StockWatcher application](http://code.google.com/webtoolkit/tutorials/1.6/gettingstarted.html) tutorial covers pretty much step by step all you need to play around and get an idea of GWT as a beginner (provided you know a bit of JAVA). This is part of the [GWT Quick Start](http://code.google.com/webtoolkit/gettingstarted.html) documentation (as mentioned also by someone else) where you can find loads of other examples and resources.
What's the quickest way to play with GWT for someone with almost no spare time?
[ "", "java", "gwt", "frameworks", "" ]
I am pretty new to OOP with PHP. OK first of all this produces an error: ``` $mail->addBody(new MailWishListInquiry()->getBody(348)); ``` but this doesn't: ``` $wishListInquiry = new MailWishListInquiry(); $mail->addBody($wishListInquiry->getBody(348)); ``` I do not understand why? Also the method getBody() is not returning anything..but no error either..here is a snippet of it: ``` function getBody($pid) { $qry = 'SELECT * FROM cart_product WHERE product_id = '.$pid; $result = mysql_query($qry); $row = mysql_fetch_assoc($result); $item_name = $row['product_name']; $item_url = 'product.php?pid='.$pid; $item_image_url = 'product_images/'.$pid.'_sm_'.$row['product_image_sm']; return ?> <div style="width:600px; font-family:Arial, Helvetica, sans-serif; color:#333333;"> ... </div> <?php } ``` Does anyone know why? Thanks!! **Edit:** You guys have done a good job explaining that dereferencing doesnt work in PHP. But I still need help figuring out why getBody() is not returning a string. Is it because I am breaking out of the php so I don't have to quote it? Even if I pass nothing it should still return the html string right? Why is it not? Thanks!
What others have said that you "cannot directly dereference return values from methods" is not quite correct. You actually 'just' cannot directly dereference newly created instances of a class, which is what you are trying to do. But it is of course possible to do somthing like this: ``` class Test { public function a() { echo "a"; return $this; } public function b() { echo "b"; return $this; } public function c() { echo "c"; return $this; } } $test = new Test(); $test->a()->b()->c(); ``` So you cannot directly do something with a newly created object, but you can do something with return values of methods. Your other problem, that getBody does not return anything is because you are trying to return a block of HTML defined outside of the PHP block. You might think that PHP just takes everything you wrote between the ?> and <?php tags and return it as a string. But instead it will just write it to the standard output (usually your browser) and return from the method with no value (void). To return a string of HTML, you can use normal string delimiters like this: ``` function getBody() { return '<p style="color: red;">Hello</p> <p>World</p>'; } ```
> I do not understand why? Because PHP syntax arbitrarily says so: you cannot directly dereference (either as an object or as an array) return values from methods. You first need to assign them to variables. Threre really is no meaningful semantical explanation behind this behaviour. As far as I know, this is furthermore subject to change in a future version of PHP.
PHP: OOP issues
[ "", "php", "oop", "" ]
I'm stopping a service in my application wanted to know what is the usage of ExitProcess and if I should use it
You should never need to use `ExitProcess()` to stop a service. In fact, you should never need to use `ExitProcess()` at all. Services are deeply intertwined with the SCM, and if a service that it thinks should be running just vanishes it will take some action to repair it. In extreme cases, it will force the system to reboot. The correct way to stop a service is to use the documented API to ask the SCM to ask the service to stop. It often takes several seconds for this process to complete as the service itself usually needs to a clean shutdown after asking its worker threads to finish up and halt. The privileges required to interact with the SCM are less dangerous than that required to end an arbitrary process, but neither is usually granted outside of the Administrators group. **Edit:** A comment asked about stopping a service from inside itself. That can be a tough call, especially if the service is in some kind of unfortunate state. The service and the SCM absolutely have to agree that the service is stopping, or the SCM will take the recovery action that was configured for the service. I do have a complete implementation of a service that might serve as an alternative point of view for how to handle some of these things. It is [LuaService](http://luaforge.net/projects/luaservice/) and is a framework that allows a (single worker thread) service to be implemented in pure [Lua](http://www.lua.org/) aside from the LuaService executable itself. Its [reference manual](http://luaforge.net/docman/view.php/326/1640/LuaService.pdf) attempts to fully document the internals, as well as document some of the details of a service's lifetime that are otherwise documented through the interaction of various articles on MSDN.
Look into the *[OpenSCManager()](http://msdn.microsoft.com/en-us/library/ms684323(VS.85).aspx)*, *[OpenService()](http://msdn.microsoft.com/en-us/library/ms684330(VS.85).aspx)* and *[ControlService()](http://msdn.microsoft.com/en-us/library/ms684330(VS.85).aspx)* Windows API calls. Note that your program may not have the necessary permissions to call these, so elevation may be necessary - see [Service Security and Access Rights](http://msdn.microsoft.com/en-us/library/ms685981(VS.85).aspx) for further information. There is also an example [how to stop a service](http://msdn.microsoft.com/en-us/library/ms686335(VS.85).aspx).
Stopping a service in c++ when do I use the ExitProcess() func
[ "", "c++", "service", "" ]
What is the **easiest** way to generate a random hash (MD5) in Python?
A md5-hash is just a 128-bit value, so if you want a random one: ``` import random hash = random.getrandbits(128) print("hash value: %032x" % hash) ``` I don't really see the point, though. Maybe you should elaborate why you need this...
I think what you are looking for is a universal unique identifier.Then the module UUID in python is what you are looking for. ``` import uuid uuid.uuid4().hex ``` UUID4 gives you a random unique identifier that has the same length as a md5 sum. Hex will represent is as an hex string instead of returning a uuid object. <http://docs.python.org/2/library/uuid.html> <https://docs.python.org/3/library/uuid.html>
Random hash in Python
[ "", "python", "hash", "md5", "" ]
`enter code here`I have a table on SQL server 2005 with bigint primary key and MS Access 2003 front end (linked tables). I want to update the record for the table that has bigint as primarykey. I use ``` CurentDb.execute _ "Update myTable SET Field1 =1 , Field2 = 'test' WHERE bigintKey = " & myVar ``` I get **Data mismatch in criteria expression.** How I can update a record on MS SQL database that has bigint field from MS Access? EDIT: It doesn't give me an error when I do ``` CurentDb.execute _ "Update myTable SET Field1 =1 , Field2 = 'test' WHERE bigintKey = '" & _ myVar & "'" ``` but it doesn't update the record...
There not a whole lot of reason to use a Primary key value that has a range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. You best just change that primary key to a int column on the sql side. If you make this change, things will then work just fine. I recommend doing this. Rememeber, in sql server a int = long in ms-access. Try opening up the linked table in the tables view in access. I find that sql 2005 table with bigint as the PK will not even display correctly (you will see deleted in every column). I find the link DOES work ok if you remove the PK setting on sql server side. In other words you can have a unique index and also set it up to increment (identity), but do NOT set it as a PK. This not ideal from a documentation point of view, and if there is other tables in enforced relations, then I don’t recommend removing the PK setting (in fact you can't do this). So, as it stands now I am unable to successfully link to a SQL server table if the PK is bigint. Note that other columns work fine as a bigint. They are simply linked as a text data type for ms-access. I see your code samples correctly assume this is going to be a text column (that is correct on your part). It is ONLY when the bigInt is a PK column does this mess up. I would change the bigint on the sql side to int (I just can't see the need for such a MASSIVE sized pk). If you must keep the column as bigInt, then simply remove the PK setting on the sql side (if that is possible). So you can have that bigInt column as an unique index, and it can continue to be a auto increment identity column. However, it CAN NOT be a BigInt PK, that just don’t work.
**Data mismatch in criteria expression** usually means that you SQL Syntax is wrong. Try copying the resulting SQL into a new Query in MS Access and running directly from Access. What is myVar in your example? What is the resulting SQL?
Update SQL table with bigint field from VBA (MS Access)
[ "", "sql", "sql-server", "vba", "ms-access", "" ]
I am trying to learn Java, I was reading a tutorial that said something like this: ``` while (N <= 0) { TextIO.put("The starting point must be positive. Please try again: "); N = TextIO.getlnInt(); } ``` It seems like when you ask the user for input it suspends until the response is recieved? I am used to these things happening asynchronously. Is this normal for Java? or can you do both? Thanks.
I'm not familiar with that `TextIO` library, but when calling [InputStream.read()](http://java.sun.com/j2se/1.5.0/docs/api/java/io/InputStream.html#read()), i.e. when using `System.in.read()`, it will block until input data is available. This makes it synchronous. You can avoid this (i.e. make it asynchronous) by using another thread to capture input.
For asynchronous I/O, there is java.nio. But yes, synchronous I/O is typical of Java.
Does Java not do things asynchronously?
[ "", "java", "asynchronous", "" ]
I have a ListBox with many objects displayed, each of which can be a variable height, based on the number of values each object has. [See my previous question that was answered here.](https://stackoverflow.com/questions/957771/displaying-a-data-bound-stackpanel-inside-a-datatemplate) Many objects are 5-lines high, while others are 1. The scroll bar in the ListBox does not appear to like this, probably due to the virtualization. While you scroll through, **the thumb on the scroll bar will change its size**, based on how many items are actually fitting into the box at that current moment. This makes the thumb very big at times, and very small at other times. Since this ListBox is also contained within a TabControl, when you switch from one tab to another, the ListBox will often scroll to a different section when you return to it. Any ideas how to resolve an issue like this? **Additional Info:** Disabling virtualization does fix the scrolling problem, although at the cost of a slower initial display. However, resizing the ListBox with the content inside causes some heavy lag when resizing horizontally (vertical is fine), which I'm assuming is due to my template's width changing and requiring a redraw on every element: ``` <DataTemplate DataType="{x:Type xmlset:Variable}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="170"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Border BorderThickness="1,0,0,1" BorderBrush="Black"> <TextBlock Margin="2,2,0,2" Text="{Binding Path=Identifier.Name, Mode=OneWay}"/> </Border> <ItemsControl IsTabStop="False" Grid.Column="1" ItemsSource="{Binding Path=Values, Mode=OneWay}"> <ItemsControl.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="120"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Border Grid.Column="0" BorderThickness="1,0,0,1" BorderBrush="Black"> <TextBlock Margin="2,2,0,2" Text="{Binding Path=Optimization, Mode=OneWay}"/> </Border> <Border Grid.Column="1" Width="Auto" BorderThickness="1,0,1,1" BorderBrush="Black"> <TextBox Margin="0,2,0,2" BorderThickness="0" Text="{Binding Path=Value}" TextChanged="TextBox_TextChanged"/> </Border> </Grid> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Grid> </DataTemplate> ``` This is drawing borders around the edges of the fields to make a visual grouping, where val will stretch to the content size. The listbox also has HorizontalContentAlignmment = Stretch to ensure this looks correct. ``` ------------------- - var - opt - val - - ------------- - - opt - val - - ------------- - - opt - val - ------------------- ``` *note: if this needs to be asked in a different question, tell me and i'll seperate the questions*
Why not switch off any size restrictions on the ListBox itself, let it size to contents and wrap it into a ScrollViewer, setting a proper size for the latter? The markup should look like the following: ``` <ScrollViewer Width="640px" Height="480px"> <ListBox> <ListBox.ItemTemplate> <DataTemplate> <!--Visualization of a list item--> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </ScrollViewer> ``` I saw no thumb size changings during scrolling if it was implemented this way.
Set `ScrollViewer.CanContentScroll="False"` on the ListBox, this will disable what's called "logical scrolling", which does scrolling based on item count instead of height ("physical scrolling").
Listbox scrollbar thumb changes size when content is variable height
[ "", "c#", "wpf", "listbox", "itemscontrol", "" ]
Why does the derived class have to declare its methods as virtual for dynamic binding to work even though the methods of the base class are declared virtual?
It doesn't have to. If a method is declared virtual in a base class, overriding it in a derived class makes the overriding function virtual as well, even if the `virtual` keyword is not used.
It doesn't. ``` class Base { virtual void foo() {} }; class Derived : public Base { void foo() {} } ``` in this code `foo()` is still virtual in the `Derived` class even though it isn't declared as such.
Dynamic Binding in C++
[ "", "c++", "inheritance", "dynamic", "binding", "" ]
I would like to open my html page in fullscreen mode. I tried to execute this javascript in body's onload event handler. ``` window.fullScreen = true; ``` But unfortunately that doesn't seem to be working. Is there any other way with which we can achieve the same.
I dont think you can set the windows properties by using the onload event. Try setting the properties as you open the window. This should work... ``` <div onclick="window.open('http://stackoverflow.com', 'Stackoverflow' , 'type=fullWindow, fullscreen, scrollbars=yes');"> Hello Stackoverflow! </div> ```
This is unadvisable as it results in unexpected browser behviour for the user. For this reason, many browsers no longer let unprivileged scripts modify this setting. For example, from Mozilla Developer Center > With chrome privileges, the property is read-write, otherwise it is read-only. See <https://developer.mozilla.org/En/DOM/Window.fullScreen>
window.fullScreen=true is not working
[ "", "javascript", "html", "fullscreen", "" ]
I have this XML file, and I want to deserialize it to an object. But I don't want to type its class definition. There is any tool that can create the C# code of the class for me, inferring the data types from sample data?
Yes. Out of the box, you can use xsd.exe to generate XSD files from XML. You can also use this tool to generate classes from XSD files. The code it produces is limited, which is why there are some third party tools that have stepped in. Two of those tools include LiquidXML (costs money) and CodeXS (free). We use CodeXS, because it is free and extensible. We have extended it quite a bit. **EDIT:** CodeXS has an [online tool](http://www.bware.biz/default.htm?http%3A//www.bware.biz/DotNet/Tools/CodeXS/WebClient/GenerateInput.aspx). Just give it an XSD. It produces your classes for you. They also have a [command-line tool](http://www.bware.biz/default.htm?http%3A//www.bware.biz/DotNet/Tools/CodeXS/WebClient/GenerateInput.aspx) (source code) which is extensible and doesn't require you to send the XSD to their web service. We use it as a pre-build step.
Liquid Technologies has a good tool for this purpose (Data binding) <http://www.liquid-technologies.com/>. You'll really need to define a schema though instead of letting such a tool "infer" it from sample data. One of the benefits of Liquid that we've found is that it can also generate code for Java, C++, C#, VBA etc. All very consistent.
There is any tool that creates a class from a XML for deserialization?
[ "", "c#", ".net", "xml", "xml-serialization", "" ]
I have a TCL script running on windows. I need to communicate to a old vc++ 6 app running in a different process. I need to have 2 way communication. In Linux I would use dbus, but what IPC strategy should I use for windows?
Tcl on windows has dde support built-in (see docs for the dde command) which could help if the other application supports this. Another option is the TWAPI (Tcl Windows API) extension, which has facilities for sending keyboard and mouse input to another application, see <http://twapi.magicsplat.com/input.html> .
[Boost.interprocess](http://www.boost.org/doc/libs/1_39_0/doc/html/interprocess.html) has various ways such as shared-memory and message passing for C++. You could always start there and see what is compatible with your script.
Interprocess communication on windows
[ "", "c++", "windows", "ipc", "tcl", "" ]
I have an xml document that I am creating using the loop below and the XML writer from C#. It currently works fine, but I wanted to implement a solution where every time the XML is written it automatically sorts it ascending using the driveStart field. I know people say you should do this in XSLT but I am having a hard time finding a good example to follow. Anyone have any experience in this that I can use? Any help is greatly appreciative. ``` XmlDocument doc = new XmlDocument(); XmlElement rn = doc.CreateElement("DriveLayout"); XmlElement dn = null; XmlAttribute xa, xa1, xa2, xa3, xa4, xa5, xa6; doc.AppendChild(rn); foreach (GridItem item in this.fileSystemGrid.Items) { dn = doc.CreateElement("Drive"); xa = doc.CreateAttribute("driveTime"); xa.Value = item["DriveTime"].ToString(); xa1 = doc.CreateAttribute("driveStart"); xa1.Value = item["DriveStart"].ToString(); xa2 = doc.CreateAttribute("driveEnd"); xa2.Value = item["DriveEnd"].ToString(); } dn.SetAttributeNode(xa); dn.SetAttributeNode(xa1); dn.SetAttributeNode(xa2); rn.AppendChild(dn); return doc.InnerXml; ```
Sort your collection by their DriveStart before using the xml writer.
I wonder why you don't *build* your XML in a sorted fashion from the start. This would be easier and more efficient, especially since you seem to be new to XSL. Anyway, for the fun of it — assuming your XML looks like this: ``` <DriveLayout> <Drive driveTime="somevalue" driveStart="somevalue" driveEnd="somevalue" /> <Drive driveTime="somevalue" driveStart="somevalue" driveEnd="somevalue" /> <Drive driveTime="somevalue" driveStart="somevalue" driveEnd="somevalue" /> </DriveLayout> ``` Then sorting would take this XSLT 1.0 stylesheet: ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="DriveLayout"> <xsl:copy> <xsl:apply-templates select="Drive"> <xsl:sort select="@driveTime" /> </xsl:apply-templates> </xsl:copy> </xsl:template> <xsl:template match="Drive"> <xsl:copy> <xsl:copy-of select="@*"/> </xsl:copy> </xsl:template> </xsl:stylesheet> ``` In .NET you would use the [`XslCompiledTransform`](http://msdn.microsoft.com/en-us/library/system.xml.xsl.xslcompiledtransform.aspx) class to make the change to your document. The linked MSDN page has enough material to get you started.
Sort XML with C# Before Write
[ "", "c#", ".net", "xml", "xslt", "" ]
I'm inserting into an SQLServer table with an autoincrementing key field. (I believe this is called an IDENTITY column in SQLServer.) In Oracle, I can use the RETURNING keyword to give my INSERT statement a results set like a SELECT query that will return the generated value: ``` INSERT INTO table (foreign_key1, value) VALUES (9, 'text') RETURNING key_field INTO :var; ``` How do I accomplish this in SQLServer? **Bonus**: Okay, nice answers so far, but how do I put it into a single statement, if possible? :)
In general, it can't be done in a single statement. But the SELECT SCOPE\_IDENTITY() can (and should) be placed directly after the INSERT statement, so it's all done in the same database call. Example: ``` mydb.ExecuteSql("INSERT INTO table(foreign_key1, value) VALUES(9, 'text'); SELECT SCOPE_IDENTITY();"); ``` You can use OUTPUT, but it has some limitations you should be aware of: <http://msdn.microsoft.com/en-us/library/ms177564.aspx>
``` SELECT SCOPE_IDENTITY() ``` Edit: Having a play... If only the [OUTPUT](http://msdn.microsoft.com/en-us/library/ms177564.aspx) clause supported local variables. Anyway, to get a range of IDs rather than a singleton ``` DECLARE @Mytable TABLE (keycol int IDENTITY (1, 1), valuecol varchar(50)) INSERT @Mytable (valuecol) OUTPUT Inserted.keycol SELECT 'harry' UNION ALL SELECT 'dick' UNION ALL SELECT 'tom' ``` Edit 2: In one call. I've never had occasion to use this construct. ``` DECLARE @Mytable TABLE (keycol int IDENTITY (1, 1), valuecol varchar(50)) INSERT @Mytable (valuecol) OUTPUT Inserted.keycol VALUES('foobar') ```
How do I return a new IDENTITY column value from an SQLServer SELECT statement?
[ "", "sql", "sql-server", "t-sql", "identity", "auto-increment", "" ]
A TCP layer in Scapy contains source port: ``` >>> a[TCP].sport 80 ``` Is there a simple way to convert port number to service name? I've seen Scapy has `TCP_SERVICES` and `UDP_SERVICES` to translate port number, but ``` print TCP_SERVICES[80] # fails print TCP_SERVICES['80'] # fails print TCP_SERVICES.__getitem__(80) # fails print TCP_SERVICES['www'] # works, but it's not what i need 80 ``` Someone know how can I map ports to services? Thank you in advance
If this is something you need to do frequently, you can create a reverse mapping of `TCP_SERVICES`: ``` >>> TCP_REVERSE = dict((TCP_SERVICES[k], k) for k in TCP_SERVICES.keys()) >>> TCP_REVERSE[80] 'www' ```
Python's [socket](http://docs.python.org/library/socket.html) module will do that: ``` >>> import socket >>> socket.getservbyport(80) 'http' >>> socket.getservbyport(21) 'ftp' >>> socket.getservbyport(53, 'udp') 'domain' ```
python-scapy: how to translate port numbers to service names?
[ "", "python", "tcp", "scapy", "" ]
I'm having some trouble looping over a HashMap to print out it's values to the screen. Could someone double check my code to see what I'm doing wrong. I can't seem to find anything wrong but there must be something. In a servlet, I am adding the following to the request: ``` Map<String, String> facetValues = new HashMap<String, String>(); // Filling the map req.setAttribute(facetField.getName(), facetValues); ``` In one case "facetField.getName()" evaluates to "discipline". So in my page I have the following: ``` <ui:repeat value="${requestScope.discipline}" var="item"> <li>Item: <c:out value="${item}"/>, Key: <c:out value="${item.key}"/>, Value: <c:out value="${item.item}"/></li> </ui:repeat> ``` The loop is ran once but all the outputs are blank?!? I would have at least expected something in item if it's gone over the loop once. Checking the debug popup for Facelets, discipline is there and on the loop. Printing it to the screen results in something that looks like a map to me (I've shortened the output) : ``` {300=0, 1600=0, 200=0, ... , 2200=0} ``` I've also tried with a c:forEach but I'm getting the same results. So does anyone have any ideas where I'm going wrong? Thanks for any input, Lee
`<ui:repeat>` only accepts List or DataModel, not Sets or Maps. This is on the roadmap for JSF 2.1.
with el 2.2 support you can iterate maps like below. ``` <ui:repeat value="#{myBean.stats.keySet().toArray()}" var="x"> <h:outputText value="#{myBean.stats.get(x)}" /><br /> </ui:repeat> ```
Troubles Iterating Over A HashMap with JSF, MyFaces & Facelets
[ "", "java", "jsf", "facelets", "myfaces", "" ]
If I have a sequence as follows (let's say it's an `IEnumerable<T>`): ``` [A, B, C, D, E] ``` Then what's the cleanest way to compute all possible (continuous and non-continuous) [subsequences](http://en.wikipedia.org/wiki/Subsequence) of a given length? Ordering of the results in the result set isn't important, but it shouldn't include duplicates. e.g. If I want to compute all possible subsequences of length 3 the result set would be: ``` [A, B, C] [A, B, D] [A, B, E] [A, C, D] [A, C, E] [A, D, E] [B, C, D] [B, C, E] [B, D, E] [C, D, E] ``` --- For the record, the accepted answer below gave me a good starting point, and here's the code I've gone with that is updated to use some of the new .NET 3.5 extension methods: ``` public static IEnumerable<IEnumerable<T>> Subsequences<T>( this IEnumerable<T> source, int count) { if (count == 0) { yield return Enumerable.Empty<T>(); } else { var skip = 1; foreach (var first in source) { foreach (var rest in source.Skip(skip).Subsequences(count - 1)) { yield return Enumerable.Repeat(first, 1).Concat(rest); } skip++; } } } ```
I've had success with IanG's [`PermuteUtils`](http://www.interact-sw.co.uk/iangblog/2004/09/16/permuterate) class: ``` char[] items = new char[] { 'A', 'B', 'C', 'D', 'E' }; foreach (IEnumerable<char> permutation in PermuteUtils.Permute(items, 3)) { Console.Write("["); foreach (char c in permutation) { Console.Write(" " + c); } Console.WriteLine(" ]"); } ``` Results in: ``` [ A B C ] [ A B D ] [ A B E ] [ A C B ] [ A C D ] [ A C E ] [ A D B ] [ A D C ] [ A D E ] [ A E B ] [ A E C ] [ A E D ] [ B A C ] [ B A D ] [ B A E ] [ B C A ] [ B C D ] [ B C E ] [ B D A ] [ B D C ] ... ```
Something like: ``` static void Main() { string[] data = { "A", "B", "C", "D", "E" }; WalkSubSequences(data, 3); } public static void WalkSubSequences<T>(IEnumerable<T> data, int sequenceLength) { T[] selected = new T[sequenceLength]; WalkSubSequences(data.ToArray(), selected, 0, sequenceLength); } private static void WalkSubSequences<T>(T[] data, T[] selected, int startIndex, int sequenceLength) { for (int i = startIndex; i + sequenceLength <= data.Length; i++) { selected[selected.Length - sequenceLength] = data[i]; if (sequenceLength == 1) { ShowResult(selected); } else { WalkSubSequences(data, selected, i + 1, sequenceLength - 1); } } } private static void ShowResult<T>(T[] selected) { StringBuilder sb = new StringBuilder(); sb.Append(selected[0]); for (int j = 1; j < selected.Length; j++) { sb.Append(';').Append(selected[j]); } Console.WriteLine(sb.ToString()); } ```
Calculating all possible sub-sequences of a given length (C#)
[ "", "c#", "algorithm", "" ]
When I compile the following code using `g++` ``` class A {}; void foo(A&) {} int main() { foo(A()); return 0; } ``` I get the following error messages: ``` > g++ test.cpp -o test test.cpp: In function ‘int main()’: test.cpp:10: error: invalid initialization of non-const reference of type ‘A&’ from a temporary of type ‘A’ test.cpp:6: error: in passing argument 1 of ‘void foo(A&)’ ``` After some reflection, these errors make plenty of sense to me. `A()` is just a temporary value, not an assignable location on the stack, so it wouldn't seem to have an address. If it doesn't have an address, then I can't hold a reference to it. Okay, fine. But wait! If I add the following conversion operator to the class `A` ``` class A { public: operator A&() { return *this; } }; ``` then all is well! My question is whether this even remotely safe. What exactly does `this` point to when `A()` is constructed as a temporary value? I am given some confidence by the fact that ``` void foo(const A&) {} ``` can accept temporary values according to `g++` and all other compilers I've used. The `const` keyword can always be cast away, so it would surprise me if there were any actual semantic differences between a `const A&` parameter and an `A&` parameter. So I guess that's another way of asking my question: why is a `const` reference to a temporary value considered safe by the compiler whereas a non-`const` reference is not?
It isn't that an address can't be taken (the compiler could always order it shoved on the stack, which it does with ref-to-const), it's a question of programmers intent. With an interface that takes a A&, it is saying "I will modify what is in this parameter so you can read after the function call". If you pass it a temporary, then the thing it "modified" doesn't exist after the function. This is (probably) a programming error, so it is disallowed. For instance, consider: ``` void plus_one(int & x) { ++x; } int main() { int x = 2; float f = 10.0; plus_one(x); plus_one(f); cout << x << endl << f << endl; } ``` This doesn't compile, but if temporaries could bind to a ref-to-non-const, it would compile but have surprising results. In plus\_one(f), f would be implicitly converted to an temporary int, plus\_one would take the temp and increment it, leaving the underlying float f untouched. When plus\_one returned, it would have had no effect. This is almost certainly not what the programmer intended. --- The rule does occasionally mess up. A common example (described [here](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1690.html)), is trying to open a file, print something, and close it. You'd want to be able to do: ``` ofstream("bar.t") << "flah"; ``` But you can't because operator<< takes a ref-to-non-const. Your options are break it into two lines, or call a method returning a ref-to-non-const: ``` ofstream("bar.t").flush() << "flah"; ```
When you assign an r-value to a const reference, you are guaranteed that the temporary won't be destroyed until the reference is destroyed. When you assign to a non-const reference, no such guarantee is made. ``` int main() { const A& a2= A(); // this is fine, and the temporary will last until the end of the current scope. A& a1 = A(); // You can't do this. } ``` You can't safely cast away const-ness willy nilly and expect things to work. There are different semantics on const and non-const references.
Reference-type conversion operators: asking for trouble?
[ "", "c++", "operators", "reference", "type-conversion", "operator-keyword", "" ]
I have a Java class that simply extends a library class and calls a method of its parent with a default parameter. How do I write a Junit test for that? A MockObjectTestCase is good too. Here is an example of what I'm talking about: ``` public class ResourceBundleMessageSource { public String getMessage(String key, Object[] objects, Locale locale) { //Spring library method } } public class MessageResource extends ResourceBundleMessageSource { public String getMessage(String key) { return (getMessage(key, null, Locale.getDefault()); } } ``` I know the wrapper method isn't even necessary, but makes frequent calls to it easier. Note the class works fine, I'm only interested in how the unit test is written.
For this particular example I probalby would not bother to test it. If you do need to test it, try something like: ``` @Test public void getDefaultMessage() { ResourceBundleMessageSource origSource = <create source> MessageResource subSource = <create with same criteria as origSource> String key = <some key that is locale-specific> assertEquals(origSource.getMessage(key, null, Locale.getDefault()), subSource.getMessage(key)); } ``` If the first two lines are hard to write, then it makes even more sense not to test it. If you have several tests like this, move the first two lines into a setup fixture.
If you would be willing to refactor your class slightly, I would recommend `MessageResource` delegate to a `MessageSource` instance, rather than extend `ResourceBundleMessageSource`. Then I'd use mocks in my unit test. Something like this: ``` public class MessageResource implements MessageSource { private final MessageSource delegate; public MessageResource(MessageSource delegate) { this.delegate = delegate; } public String getMessage(String key) { return delegate.getMessage(key, null, Locale.getDefault()); } // need to implement three other MessageSource methods, // simple pass-throughs to delegate } ``` and unit test ``` public class MessageResourceTest { private MessageSource mockDelegate; private MessageResource messageResource; @Before public void setUp() throws Exception { mockDelegate = //mock with your favorite framework, or by hand messageResource = new MessageResource(mockDelegate); } @Test public void testGetMessage() { String key = "foo"; String actualMessage = messageResource.getMessage(key); assertEquals(key, /* get key passed to mock delegate */ ); assertSame(Locale.getDefault(), /* get Locale passed to mock delegate */); assertEquals(/*expected message from mock*/, actualMessage); } } ```
Junit test case for wrapper class
[ "", "java", "junit", "spring", "" ]
I was wondering if it's considered a bad practice to globally convert all PHP Errors to Exceptions. Something like the following would be used: ``` function exception_error_handler($errno, $errstr, $errfile, $errline ) { throw new ErrorException($errstr, 0, $errno, $errfile, $errline); return false; } ``` I suppose the assumption is that you can just start using "try/catch" around certain pieces of code that would normally throw Errors. If it's not a case of Good/Bad, what are some of the Gotchas that could arise from this practice?
Unfortunately, this won't work on fatal/parse/etc. errors... Don't remember exactly, but I've tried this and in some cases got a message like "can't throw exception without workaround..." but I can't remember the conditions to get this result. But now I use this way and completely satisfied.
Use exceptions for things that are truly beyond your control. **Good:** ``` try { if (fopen('file.txt', 'w') === false) { throw new Exception('File could not be opened for write access.'); } } catch (Exception $e) { echo $e->getMessage(); } ``` **Bad:** ``` try { if (strlen($_POST['username']) < 5) { throw new Exception('Username too short'); } } catch (Exception $e) { echo $e->getMessage(); } ``` The first way is good because it occurs when its something that the user or the application cant control. It cant open the file because? could be many reasons. The second way is an overkill use of try /catch when you should use trigger\_error. The second way is down to the user not knowing the rules of the username validation. In short use exceptions when you cant control what your testing. Remember exceptions have more overhead then trigger\_error aswell :)
PHP - Converting all Errors to Exceptions - Good or Bad?
[ "", "php", "exception", "error-handling", "" ]
So I had a question on general organization of code for the Zend framework with regard to the layout. My layout is basically this: ``` (LAYOUT.PHTML) <div id='header'> <?= $this->Layout()->header ?> </div> <div id='main'> <?= $this->Layout()->main ?> </div> <div id='footer'> <?= $this->Layout()->footer ?> </div> ``` and so on and so forth. Now, in order to keep my code in my header separate from the code of my main and the code of my footer, I've created a folder for my view that holds header.phtml, main.phtml, footer.phtml. I then use this code to assign the content of header.phtml into $this->layout()->header: ``` (INDEX.PHTML) $this->Layout()->header = file_get_contents('index/header.phtml'); $this->Layout()->main = file_get_contents('index/main.phtml'); $this->Layout()->footer = file_get_contents('index/footer.phtml'); ``` That was working great, but I've hit a point where I don't want main to be static HTML anymore. I would like to be able to insert some values with PHP. So in my Controller in indexAction, I want to be able to load from my database and put values into index/main.phtml. Is there a way to do this without restructuring my site? If not is there a way to do it so that I can have: 1. The ability to put code into different sections of my layout, such as Layout()->header, Layout->footer. 2. Separate these pieces into different files, so that they're easy to find and organize, like my index/footer.phtml, index/main.phtml etc. 3. Not have to put that code into quotes unnecessarily to turn it into a string to pass it to Layout()->header etc. Thank you guys so much for your help. -Ethan
Here is an idea: * Assign layout()->header the filename instead of the contents.* Put your code in this file* In your layout file, include() or require() the layout->header(). Since your layout headers/footers are now parsed, you can use them just like a view.
The `->header` in `$this->layout()->header` is **response segment**. You can render parts of response using `$this->_helper->viewRenderer->setResponseSegment('header');` in an action.
Zend organization question
[ "", "php", "zend-framework", "layout", "organization", "" ]
I'm trying to run a query in SQL Server 2008 against a table where some of the data was entered inconsistently and I have to handle this. Table data example: ``` OrderID Qty Price MarkedUpTotal 1 10 1.00 11.00 1 -1 1.00 -1.10 1 -1 1.00 1.10 ``` I have to handle the situation where the Qty is negative but the MarkedUpTotal was entered as positive. I'd like to run the following query: ``` SELECT OrderID, SUM(Qty) as OrderTotalQty, SUM(Qty*Price) as InternalCost, CASE WHEN Qty < 0 and MarkedUpTotal > 0 THEN sum(-1*MarkedUpTotal) ELSE SUM(MarkedUpTotal) END as ClientCost FROM OrderItems GROUP BY OrderID ``` However, I get the following error when I run this query: **Column Qty is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.** **Column MarkedUpTotal is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.** I desire the following result: ``` OrderID OrderTotalQty InternalCost ClientCost 1 8 8.00 8.80 ``` It seems odd to me that I must GROUP BY Qty and MarkedUpTotal when they are only being used conditionally by the CASE statement. If I remove the last selection (the CASE statement) the query executes fine and does not require Qty or Price to be in the GROUP BY. Why does SQL require this? Is there a single query that could accomplish the above? Currently I'm resolving the issue by using a temp table. I modify each entry's MarkedUpTotal if needed and then do a simple SUM(MarkedUpTotal) in the main query from the temp table.
``` SELECT OrderID, SUM(Qty) as OrderTotalQty, SUM(Qty*Price) as InternalCost, SUM(CASE WHEN Qty < 0 and MarkedUpTotal > 0 THEN -1*MarkedUpTotal ELSE MarkedUpTotal) END as ClientCost FROM OrderItems GROUP BY OrderID ``` The reason it gives error is because, you are SUMming it up inside the CASE - which will return 1 value outside. To the SELECT with GROUP BY, it will look like you are passing in a numeric value (which could be a constant or comes from some other source) as a column. Think of your SQL Statement, similar to this ``` SELECT OrderID, SUM(Qty) as OrderTotalQty, SUM(Qty*Price) as InternalCost, CASE WHEN Qty < 0 and MarkedUpTotal > 0 THEN 10 ELSE 20 END as ClientCost FROM OrderItems GROUP BY OrderID ``` Now this is returning a new column (ClientCost), which is not using any aggregation. So, it asks you to use that in GROUP BY expression.
Bear in mind that the result of a GROUP BY statement, or of a statement where one or columns uses an aggregate function, has each row containing a summary of other rows. The CASE expression you're using is dependent on values of individual rows rather than summaries; you may only reference non-aggregate values (i.e. single-row values) in an aggregate function, or in the WHERE clause, so the solution would involve placing your CASE inside an aggregate function, in this case your SUM.
Why must you GROUP BY the columns in a CASE statement?
[ "", "sql", "group-by", "case-statement", "" ]
I am building a one off query to iterate through a set of joined tables. The select statement is using "SELECT \*". Since it's is a table with lots of fields, I don't want to specify each column as a variable. Is there a way to FETCH INTO an array or SET of some sort and just grab the values I want?
[Apparently not](http://msdn.microsoft.com/en-us/library/ms180152.aspx): ``` INTO @variable_name[ ,...n] ``` > "Allows data from the columns of a fetch to be placed into local variables. > Each variable in the list, from left to right, is associated with the corresponding column in the cursor result set. The data type of each variable must either match or be a supported implicit conversion of the data type of the corresponding result set column. The number of variables must match the number of columns in the cursor select list." --- If you are looking to use cursors you may find better flexibility with [CLR Stored procedures](http://msdn.microsoft.com/en-us/library/ms131094.aspx)
Even if there was, you wouldn't want to. Fetching extra fields is one of the most common causes of performance degredation in a SQL Server application. By doing so, you restrict the optimizer's ability to use indexes effectively. How would you propose to "grab the values that you want" without specifying column names?
T-SQL, Cursors, FETCH INTO. How to use SELECT *
[ "", "sql", "sql-server", "t-sql", "" ]
For my own personal amusement, I'm writing what I hope will be the foundation of a game to come later. At current, I'm working on the game "board". Please consider the following: ``` class Board { private Cube[,,] gameBoard; public Cube[, ,] GameBoard { get; } private Random rnd; private Person person; public Person _Person { get; } //default constructor public Board() { person = new Person(this); rnd = new Random(); gameBoard = new Cube[10, 10, 10]; gameBoard.Initialize(); int xAxis = rnd.Next(11); int yAxis = rnd.Next(11); int zAxis = rnd.Next(11); gameBoard[xAxis, yAxis, zAxis].AddContents(person); } } ``` And this: ``` class Person : IObject { public Board GameBoard {get; set;} public int Size { get; set; } public void Move() { throw new NotImplementedException(); } public void Move(Cube startLocation, Cube endLocation) { startLocation.RemoveContents(this); endLocation.AddContents(this); } public Person(Board gameBoard) { Size = 1; GameBoard = gameBoard; } public int[] GetLocation() { int[] currentLocation; var location = from cubes in GameBoard.GameBoard where cubes.GetContents.Contains(this) select cubes; } } ``` I know this is so wrong it's probably not even funny, but this is the roughest of rough cuts. I'm trying to get `GetLocation` to return the specific index of the `Cube` in which the `Person` is located. So that if the person is in `Board.GameBoard[1, 2, 10]` I'll be able to retrieve that location (probably as an `int[]` as listed above). However, at current, I'm unable to compile due to the following error: ``` Could not find an implementation of the query pattern for source type 'Cubes.Cube[*,*,*]'. 'Where' not found.' ``` I was pretty sure that LINQ should be able to query multi-dimensional arrays, but I haven't found any documentation on how to do it. Any suggestions, or am I on the completly wrong track here?
LINQ does not see multidimential arrays as you want it to because they do not implement `IEnumerable<T>` (although single index arrays do, which is what surprises people). There are several workarounds: you can avoid LINQ for searching the cube or you can write an extension method of your own that does the more traditional walks. This is a case where I wouldn't use LINQ do to the search, but more than that I probably would keep some references to the various playing pieces in a simple structure (probably a dictionary) that is easier to update and manage. As an idea, your piece object would know *where* it is on the board itself and could update the cube as it moved by removing itself from one cell and adding itself to another. It would be important to know if a single cell can contain more than one piece: if so, each cell would need to be a list of some type as well (it appears that way in your code). And once you get to this point, if there are vastly fewer playing pieces than cells, I probably would never actually create the "cube" itself as a datastructure. It would be drawn and the pieces displayed via some Z order drawing algorithm that pulled directly from the piece list, rather than an array. This would depend on the style of game though: if the pieces have attributes and are small in number this would work. If the game is more like 3D Go or similar, then your original cube would make sense... it really depends on how much "personality" (and thus data) your pieces have.
Makes a lot more sense to me to move the int[] currentLocation declaration to the top level inside your Person class, and provide getter/setter methods. Then each Person stores its own location. For the memory cost of 3 ints, you save yourself from having to query 1000 database entries every time you want to retrieve the person's location.
Select unknown item from multi-dimensional array using LINQ
[ "", "c#", "linq", "multidimensional-array", "" ]
Herb Sutter has said that the most object oriented way to write methods in C++ is using non-member non-friend functions. Should that mean that I should take private methods and turn them into non-member non-friend functions? Any member variables that these methods may need can be passed in as parameters. Example (before): ``` class Number { public: Number( int nNumber ) : m_nNumber( nNumber ) {} int CalculateDifference( int nNumber ) { return minus( nNumber ); } private: int minus( int nNumber ) { return m_nNumber - nNumber; } int m_nNumber; }; ``` Example (after): ``` int minus( int nLhsNumber, int nRhsNumber ) { return nLhsNumber - nRhsNumber; } class Number { public: Number( int nNumber ) : m_nNumber( nNumber ) {} int CalculateDifference( int nNumber ) { return minus( m_nNumber, nNumber ); } private: int m_nNumber; }; ``` Am I on the right track? Should all private methods be moved to non-member non-friend functions? What should be rules that would tell you otherwise?
I believe in free functions and agree with Sutter, but my understanding is in the opposite direction. It is not that you should have your public methods depend on free functions instead of private methods, but rather that you can build a richer interface outside of the class with free functions by using the provided public interface. That is, you don't push your privates outside of the class, but rather reduce the public interface to the minimum that allows you to build the rest of the functionality with the least possible coupling: only using the public interface. In your example, what I would move outside of the class is the CalculateDifference method if it can be represented effectively in terms of other operations. ``` class Number { // small simple interface: accessor to constant data, constructor public: explicit Number( int nNumber ) : m_nNumber( nNumber ) {} int value() const { return m_nNumber; } private: int m_nNumber; }; Number operator+( Number const & lhs, Number const & rhs ) // Add addition to the interface { return Number( lhs.value() + rhs.value() ); } Number operator-( Number const & lhs, Number const & rhs ) // Add subtraction to the interface { return Number( lhs.value() - rhs.value() ); } ``` The advantage is that if you decide to redefine your Number internals (there is not that much that you can do with such a simple class), as long as you keep your public interface constant then all other functions will work out of the box. Internal implementation details will not force you to redefine all the other methods. The hard part (not in the simplistic example above) is determining what is the least interface that you must provide. The article ([GotW#84](http://www.gotw.ca/gotw/084.htm)), referenced from a previous question here is a great example. If you read it in detail you will find that you can greatly reduce the number of methods in std::basic\_string while maintaining the same functionality and performance. The count would come down from 103 member functions to only 32 members. That means that implementation changes in the class will affect only 32 instead of 103 members, and as the interface is kept the 71 free functions that can implement the rest of the functionality in terms of the 32 members will not have to be changed. That is the important point: it is more encapsulated as you are limiting the impact of implementation changes on the code. Moving out of the original question, here is a simple example of how using free functions improve the locality of changes to the class. Assume a complex class with really complex addition operation. You could go for it and implement all operator overrides as member functions, or you can just as easily and effectively implement only some of them internally and provide the rest as free functions: ``` class ReallyComplex { public: ReallyComplex& operator+=( ReallyComplex const & rhs ); }; ReallyComplex operator+( ReallyComplex const & lhs, ReallyComplex const & rhs ) { ReallyComplex tmp( lhs ); tmp += rhs; return tmp; } ``` It can be easily seen that no matter how the original `operator+=` performs its task, the free `operator+` performs its duty correctly. Now, with any and all changes to the class, `operator+=` will have to be updated, but the external `operator+` will be untouched for the rest of its life. The code above is a common pattern, while usually instead of receiving the `lhs` operand by constant reference and creating a temporary object inside, it can be changed so that the parameter is itself a value copy, helping the compiler with some optimizations: ``` ReallyComplex operator+( ReallyComplex lhs, ReallyComplex const & rhs ) { lhs += rhs; return lhs; } ```
Not all private methods should be moved to non-member non-friend function, but those that **do not need access** to your private data members should be. You should give access to as little function as you can, to encapsulate your classes as mush a possible. I strongly recommend reading [Effective C++ from Scott Meyers](https://rads.stackoverflow.com/amzn/click/com/0321334876) which explain why you should do this and when it is appropriate. Edit : I would like to add that this is less true for private method then for public ones, although still valid. As encapsulation is proportionnal to the amount of code you would break by modifying your method, having a private member-function , even though it does not requires access to data members. That is because modifying that code would break little code and only code that you have control over.
Non-member non-friend functions vs private functions
[ "", "c++", "refactoring", "" ]
I currently have a windows application which is automated and runs daily. the purpose is to access a webservice to download a dataset, inserting into sql 2005 database. Is a windows service application suitable in this situation, would it be more flexible, and would it perform better.
You can definitely have it as a service, but I don't think you are going to get any benefit from it. Since a service is always running, they are normally used for applications which have to run, because they are constantly checking for a condition (waiting for remoting, checking every n minutes for information in a database etc.). Since yours runs once a day, you aren't going to have any advantage if you change it over. If your automated task is setup correctly, it should run if the machine is on, just like a service. The advantage to having a windows app (console specifically) over a service is that if something fails, you can just start the app again and run it. This won't be so easy with a service, because extra code will have to be in the program to make sure that it only runs so many times (in your case once) a day. You probably won't be able to have it execute your process on start up, because you have to take into account the server being restarted. This means that if your server goes down when the process is supposed to run, you are going to have to know how to "trick" the program into thinking that it should run the process for that time only. Window's apps don't suffer from this, because they terminate after the process has completed, so there's probably no additional code to prevent it from running the process again.
A Windows Service would allow you to run your task even though no user is actively logged on. I would say, for a task like that, a Windows Service is more suitable. I doubt, however, that there would be any performance improvement.
Is a Windows Service application the right approach
[ "", ".net", "sql", "web-services", "automation", "" ]
Suppose I have the following (trivially simple) base class: ``` public class Simple { public string Value { get; set; } } ``` I now want to do the following: ``` public class PathValue : Simple { [XmlAttribute("path")] public string Value { get; set; } } public class ObjectValue : Simple { [XmlAttribute("object")] public string Value { get; set; } } ``` But without actually redefining the property. I want to apply attributes to members of the base class. Is this possible? The real problem is that in my serialization mechanism from/to XML (which works brilliantly btw), I find a lot of similar elements where only the names of the attributes differ (they're not consistent, and I don't control the format). Right now I need to create a different class for every such element, whereas they're like 100% the same (apart from the attributes). I don't think it's possible, but you might never know. UPDATE: I tried Marc's approach, but to no avail: ``` public class Document { public PathValue Path; public ObjectValue Object; } class Program { static void Main(string[] args) { var doc = new Document() { Path = new PathValue() { Value = "some path" }, Object = new ObjectValue() { Value = "some object" } }; XmlAttributeOverrides overrides = new XmlAttributeOverrides(); overrides.Add(typeof(PathValue), "Value", new XmlAttributes() { XmlAttribute = new XmlAttributeAttribute("path") }); overrides.Add(typeof(ObjectValue), "Value", new XmlAttributes() { XmlAttribute = new XmlAttributeAttribute("object") }); XmlSerializer serializer = new XmlSerializer(typeof(Document), overrides); serializer.Serialize(Console.Out, doc); Console.WriteLine(); Console.ReadLine(); } } ``` ...doesn't do the trick.
I'm going to answer this question myself, so that I can accept this answer. I don't like the answer, but I suppose it's the only valid answer. The answer is: No, you can't do it.
Could you perhaps use the overload `XmlSerializer` constructor that lets you pass in the attributes to apply at runtime? Then you don't have to worry about it... caveat: you want to cache the serializer instance and re-use it; otherwise (with the complex constructors) it does dynamic type generation each time. Example: ``` using System; using System.Xml.Serialization; public class Simple { public string Value { get; set; } static void Main() { XmlAttributeOverrides overrides = new XmlAttributeOverrides(); overrides.Add(typeof(Simple), "Value", new XmlAttributes { XmlAttribute = new XmlAttributeAttribute("path") }); XmlSerializer pathSerializer = new XmlSerializer( typeof(Simple), overrides); // cache and re-use pathSerializer!!! Simple obj = new Simple(); obj.Value = "abc"; pathSerializer.Serialize(Console.Out, obj); } } ``` Output: ``` <Simple xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" path="abc" /> ```
Can I apply an attribute to an inherited member?
[ "", "c#", "xml-serialization", "attributes", "" ]
I am working on migration of data from an old system to a new system. As part of migration, the data from the legacy system, (stored in files) is pumped into MS SQL Server. Now my app runs on Oracle. I'm having a problem with the date/timestamp. The timestamp format in MS SQL Server data is: > 2008.12.23 00:00:00 Oracle expects: > 23/12/2008 00:00:00 or > 23-DEC-2008 00:00:00 What would be the best way to import the data? Oracle's `to_date()` function didn't work as I thought it would.
I assume you're using insert statements? Convert your dates using: ``` TO\_DATE(sql\_server\_value,'YYYY.MM.DD HH24:MI:SS') ```
You can put a second parameter on the to\_date function to specify in what format the incoming data is. You will likely have to make SQL server pump the data out as a string. <http://www.techonthenet.com/oracle/functions/to_date.php>
How can I convert a SQL Server date format to Oracle?
[ "", "sql", "sql-server-2005", "oracle", "" ]
I have a TextChanged Even on a textbox and when I enter data into it, it updates another textbox which in turn is supposed to fire a TextChanged Event, but it is not firing until I put my cursor in the TextBox. Is there a solution to this? Code for updating the Extended Price when Qty Changes: ``` protected void txtQty1_TextChanged(object sender, EventArgs e) { if (txtQty1.Text != string.Empty && txtUnitPrice1.Text != string.Empty) { int qty = Convert.ToInt32(txtQty1.Text); double unitPrice = Convert.ToDouble(txtUnitPrice1.Text); double extendTotal1 = qty * unitPrice; txtExtPrice1.Text = extendTotal1.ToString(); } } ``` Code for updating the extending price When Unit Price changes: ``` protected void txtUnitPrice1_TextChanged(object sender, EventArgs e) { if (txtQty1.Text != string.Empty && txtUnitPrice1.Text != string.Empty) { int qty = Convert.ToInt32(txtQty1.Text); double unitPrice = Convert.ToDouble(txtUnitPrice1.Text); double extendTotal1 = qty * unitPrice; txtExtPrice1.Text = extendTotal1.ToString(); } } ``` Finally, this should update the Grand Total When Extending Price Changes: ``` protected void txtExtPrice1_TextChanged(object sender, EventArgs e) { if (txtExtPrice1.Text != string.Empty) { double extendedTotal1 = Convert.ToDouble(txtExtPrice1.Text); double grandTotal = Convert.ToDouble(txtGrandTotal.Text); grandTotal += extendedTotal1; txtGrandTotal.Text = grandTotal.ToString(); } } ``` Is it true that I should probably make Grand Total a Static Variable?
Just call the code to update the grand total from the first textchanged event and not worry about it not working when you try and cascade into another one.
No clue if this will help or not, since the code (mostly) worked for me, but I was getting odd totals in the Grand Total, so I changed the event handlers to "Validating" for Quantity and UnitPrice (and hooked them both to the same event handler, since they're doing exactly the same thing...) (EDIT:Yes, I faked some of the logic, including arbitrailly setting the GrandTotal if it was empty). ``` private void textBox1_Validating(object sender, CancelEventArgs e) { if (!String.IsNullOrEmpty(textBox1.Text) && !String.IsNullOrEmpty(textBox2.Text)) { int qty = int.Parse(textBox1.Text); double price = double.Parse(textBox2.Text); double totalPrice = qty * price; textBox3.Text = totalPrice.ToString(); } } private void textBox3_TextChanged(object sender, EventArgs e) { double bTotal = double.Parse(textBox3.Text); if (String.IsNullOrEmpty(textBox4.Text)) textBox4.Text = "100.00"; double gTotal = double.Parse(textBox4.Text); gTotal += bTotal; textBox4.Clear(); textBox4.Text = gTotal.ToString(); } ```
TextChanged event only fires when I put my cursor in the textbox and change the text
[ "", "c#", "asp.net", "" ]
I'm using JDBC to get a large amount of data. The call completes successfully, but when `resultSet.next()` is called, I get the following error: ``` java.lang.OutOfMemoryError: allocLargeObjectOrArray - Object size: 15414016, Num elements: 7706998 ``` I've attempted to increase the JVM memory size, but this does not fix the problem. I'm not sure this problem can even be addressed as I'm not using JDBC to access a database, rather, the system is accessing a BEA AquaLogic service through JDBC. Has anyone run into this error?
Beware that until the first resultSet.next() call the results may not yet be read from the database or still be in another caching structure somewhere. You should try limit your Select to return a sane amount of results and maybe repeat the call until there are no more results left if you need all the data. Increasing the JVM memory size won't help unless you can be sure that there is an absolute limit on the amount of data which will be returned by your JDBC call. Furthermore, accessing any service through JDBC essentially boils down to using JDBC :) Another (unlikely) possibility could be that there is a bug in the JDBC driver you're using. Try a different implementation if it is possible and check if the problem persists.
First-- figure out if you really need to get that much data in memory at once. RDBMS's are good at aggregating/sorting/etc large data sets, and you should try to take advantage of that if possible. If not (and you really, really do need that much data in working memory for some reason)... and bumping up the JVM's memory args doesn't raise the bar enough... look into an in-memory distributed caching solution like [Coherence](http://www.oracle.com/technology/products/coherence/index.html) (COTS) or TerraCotta (open source).
Out of Memory allocLargeObjectOrArray from ResultSet
[ "", "java", "jdbc", "bea", "" ]
How can I iterate over a list of objects, accessing the previous, current, and next items? Like this C/C++ code, in Python? ``` foo = somevalue; previous = next = 0; for (i=1; i<objects.length(); i++) { if (objects[i]==foo) { previous = objects[i-1]; next = objects[i+1]; } } ```
This should do the trick. ``` foo = somevalue previous_item = next_item = None l = len(objects) for index, obj in enumerate(objects): if obj == foo: if index > 0: previous_item = objects[index - 1] if index < (l - 1): next_item = objects[index + 1] ``` Here's the docs on the [`enumerate`](http://docs.python.org/library/functions.html#enumerate) function.
Solutions until now only deal with lists, and most are copying the list. In my experience a lot of times that isn't possible. Also, they don't deal with the fact that you can have repeated elements in the list. The title of your question says "*Previous and next values inside a loop*", but if you run most answers here inside a loop, you'll end up iterating over the entire list again on each element to find it. So I've just created a function that. using the [`itertools`](http://docs.python.org/library/itertools.html) module, splits and slices the iterable, and generates tuples with the previous and next elements together. Not exactly what your code does, but it is worth taking a look, because it can probably solve your problem. ``` from itertools import tee, islice, chain, izip def previous_and_next(some_iterable): prevs, items, nexts = tee(some_iterable, 3) prevs = chain([None], prevs) nexts = chain(islice(nexts, 1, None), [None]) return izip(prevs, items, nexts) ``` Then use it in a loop, and you'll have previous and next items in it: ``` mylist = ['banana', 'orange', 'apple', 'kiwi', 'tomato'] for previous, item, nxt in previous_and_next(mylist): print "Item is now", item, "next is", nxt, "previous is", previous ``` The results: ``` Item is now banana next is orange previous is None Item is now orange next is apple previous is banana Item is now apple next is kiwi previous is orange Item is now kiwi next is tomato previous is apple Item is now tomato next is None previous is kiwi ``` It'll work with any size list (because it doesn't copy the list), and with any iterable (files, sets, etc). This way you can just iterate over the sequence, and have the previous and next items available inside the loop. No need to search again for the item in the sequence. A short explanation of the code: * `tee` is used to efficiently create 3 independent iterators over the input sequence * `chain` links two sequences into one; it's used here to append a single-element sequence `[None]` to `prevs` * `islice` is used to make a sequence of all elements except the first, then `chain` is used to append a `None` to its end * There are now 3 independent sequences based on `some_iterable` that look like: + `prevs`: `None, A, B, C, D, E` + `items`: `A, B, C, D, E` + `nexts`: `B, C, D, E, None` * finally `izip` is used to change 3 sequences into one sequence of triplets. Note that `izip` stops when any input sequence gets exhausted, so the last element of `prevs` will be ignored, which is correct - there's no such element that the last element would be its `prev`. We could try to strip off the last elements from `prevs` but `izip`'s behaviour makes that redundant Also note that `tee`, `izip`, `islice` and `chain` come from the `itertools` module; they operate on their input sequences on-the-fly (lazily), which makes them efficient and doesn't introduce the need of having the whole sequence in memory at once at any time. In Python 3 it will show an error while importing `izip`. You can use `zip` instead of `izip`. No need to import `zip`, it is predefined in Python 3 ([source](https://github.com/weinbe58/QuSpin/issues/20)).
Loop that also accesses previous and next values
[ "", "python", "loops", "iteration", "" ]
In mod\_wsgi I send the headers by running the function start\_response(), but all the page content is passed by yield/return. Is there a way to pass the page content in a similar fashion as start\_response()? Using the return.yield statement is very restrictive when it comes to working with chunked data. E.g. ``` def Application(): b = buffer() [... page code ...] while True: out = b.flush() if out: yield out class buffer: def __init__(self): b = [''] l = 0 def add(self, s): s = str(s) l += len(s) b.append(s) def flush(self): if self.l > 1000: out = ''.join(b) self.__init__() return out ``` I want to have the buffer outputting the content as the page loads, but only outputs the content once enough of it has piled up (in this eg. 1000 bytes).
No; But I don't think it is restrictive. Maybe you want to paste an example code where you describe your restriction and we can help. To work with chunk data you just `yield` the chunks: ``` def application(environ, start_response): start_response('200 OK', [('Content-type', 'text/plain')] yield 'Chunk 1\n' yield 'Chunk 2\n' yield 'Chunk 3\n' for chunk in chunk_data_generator(): yield chunk def chunk_data_generator() yield 'Chunk 4\n' yield 'Chunk 5\n' ``` --- **EDIT**: Based in the comments you gave, an example of piling data up to a certain length before sending forward: ``` BUFFER_SIZE = 10 # 10 bytes for testing. Use something bigger def application(environ, start_response): start_response('200 OK', [('Content-type', 'text/plain')] buffer = [] size = 0 for chunk in chunk_generator(): buffer.append(chunk) size += len(chunk) if size > BUFFER_SIZE: for buf in buffer: yield buf buffer = [] size = 0 def chunk_data_generator() yield 'Chunk 1\n' yield 'Chunk 2\n' yield 'Chunk 3\n' yield 'Chunk 4\n' yield 'Chunk 5\n' ```
It is *possible* for your application to "push" data to the WSGI server: > Some existing application framework APIs support unbuffered output in a different manner than WSGI. Specifically, they provide a "write" function or method of some kind to write an unbuffered block of data, or else they provide a buffered "write" function and a "flush" mechanism to flush the buffer. > > Unfortunately, such APIs cannot be implemented in terms of WSGI's "iterable" application return value, unless threads or other special mechanisms are used. > > Therefore, to allow these frameworks to continue using an imperative API, WSGI includes a special `write()` callable, returned by the `start_response` callable. > > New WSGI applications and frameworks **should not** use the `write()` callable if it is possible to avoid doing so. > > <http://www.python.org/dev/peps/pep-0333/#the-write-callable> But it isn't recommended. > Generally speaking, applications will achieve the best throughput by buffering their (modestly-sized) output and sending it all at once. This is a common approach in existing frameworks such as Zope: the output is buffered in a StringIO or similar object, then transmitted all at once, along with the response headers. > > The corresponding approach in WSGI is for the application to simply return a single-element iterable (such as a list) containing the response body as a single string. This is the recommended approach for the vast majority of application functions, that render HTML pages whose text easily fits in memory. > > <http://www.python.org/dev/peps/pep-0333/#buffering-and-streaming>
Passing data to mod_wsgi
[ "", "python", "mod-wsgi", "wsgi", "" ]
I'm attempting to capture mouse events on an element with another absolutely-positioned element on top of it. Right now, events on the absolutely-positioned element hit it and bubble up to its parent, but I want it to be "transparent" to these mouse events and forward them on to whatever is behind it. How should I implement this?
``` pointer-events: none; ``` Is a CSS property that makes events "pass through" the HTML-element to which the property is applied. It makes the event occur on the element "below". See for details: <https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events> It is supported by almost all browsers, including IE11; global support was ~98.2% in 05/'21): <http://caniuse.com/#feat=pointer-events> (thanks to @s4y for providing the link in the comments).
Also nice to know... Pointer-events can be disabled for a parent element (probably transparent div) and yet be enabled for child elements. This is helpful if you work with multiple overlapping div layers, where you want to be able click the child elements of any layer. For this all parenting divs get `pointer-events: none` and click-children get pointer-events reenabled by `pointer-events: all` ``` .parent { pointer-events:none; } .child { pointer-events:all; } <div class="some-container"> <ul class="layer-0 parent"> <li class="click-me child"></li> <li class="click-me child"></li> </ul> <ul class="layer-1 parent"> <li class="click-me-also child"></li> <li class="click-me-also child"></li> </ul> </div> ```
Pass mouse events through absolutely-positioned element
[ "", "javascript", "html", "dom", "events", "dom-events", "" ]
For example, if I have the following: ``` void foo(string* s) { bar(s); // this line fails to compile, invalid init. error } void bar(const string& cs) { // stuff happens here } ``` What conversions do I need to make to have the call the bar succeed?
Change it to: ``` bar(*s); ```
``` void foo(string* s) { bar(*s); } ``` `s` points to a string, and `bar` requires a (reference to a) string, so you need to give `bar` what `s` points to. The way you spell "what `s` points to" is `*s`.
How do I convert something of "string*" to "const string&" in C++?
[ "", "c++", "pointers", "reference", "constants", "" ]
Resolution: No I'm no longer extending the original parent. Original: Is there a way to annotate an inherited `final` setter method? I am extending a class which has a `final` setter which I would like to `@Autowire` with Spring. The parent class is from a library and cannot be modified. A workaround I have found is to write a proxy method, but this seems like more work than necessary. ``` public abstract class SqlMapClientDaoSupport ... { public final void setSqlMapClient(SqlMapClient smc) { ... } } @Component public class AccountDao extends SqlMapClientDaoSupport { // all this just to annotate an existing method? @Autowire public final void setSqlMapClientWorkaround(SqlMapClient smc) { super.setSqlMapClient(smc); } } ``` ***Edit 1:*** Above example modified to reflect use case: The use case is implementing DAO objects for Ibatis/Spring which extend a common [base class](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/orm/ibatis/support/SqlMapClientDaoSupport.html). Each DAO needs the same property set, and each needs to be configured as a bean. I currently do this by configuring each individually in `applicationContext.xml`. ``` <bean id="accountDAO" class="com.example.proj.dao.h2.AccountDAOImpl" p:sqlMapClient-ref="sqlMapClient" /> <bean id="companyDAO" class="com.example.proj.dao.h2.CompanyDAOImpl" p:sqlMapClient-ref="sqlMapClient" /> <!-- etc... --> ``` I would prefer to use component-scan to discover and autowire the DAO objects automatically, which I can't copy/paste botch. ``` <context:component-scan base-package="com.example.proj.dao.h2" /> ``` I do not see in the [annotation guide](http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html) how one would annotate a property/member other than where declared. I'm hoping that is something I'm missing though. ***Edit 2:*** I am no longer extending the SqlMapClientDaoSupport class, instead my AccountDao is a POJO which implements what little functionality was being provided by the Support class. This allows me to use @Autowire at will.
No, there is no way to annotate an inherited final method. Rather than extend the support class (`SqlMapClientDaoSupport`) I reimplemented it in my project (it's behavior is minimal) annotating the methods as needed, and my DAO extend that support class.
Have you tried configuring it with xml? Because it's an existing class which it looks like you can't change, it's a definite candidate for configuring it with xml. Then you can specify it as autowire", or even configure the property in the xml.
Can I annotate an inherited final property with @Autowire?
[ "", "java", "spring", "annotations", "ibatis", "" ]
I'm trying to read through a gmail account to get gps data that is being sent there ( in the text of a email) from an moble phone (my phone) ``` using (Pop3Client cl = new Pop3Client()) { cl.UserName = "crash893"; cl.Password = "password"; cl.ServerName = "pop.gmail.com"; cl.AuthenticateMode = Pop3AuthenticateMode.Pop; cl.Ssl = true; cl.Authenticate(); ///Get first mail of my mailbox Pop3Message mg = cl.GetMessage(1); <<<<<<<<<< ERROR String MyText = mg.BodyText; ///If the message have one attachment Pop3Content ct = mg.Contents[0]; ///you can save it to local disk ct.DecodeData("c:\\test.txt"); } ``` but I get a exception on the "get first mail of mailbox message ``` "Higuchi.Net.Pop3.Pop3ConnectException: Pop3 connection is closed at Higuchi.Net.Pop3.Pop3Client.SendCommand(String inCommand) at Higuchi.Net.Pop3.Pop3Client.Execute(String inCommand, Boolean inIsMultiLine) at Higuchi.Net.Pop3.Pop3Client.Execute(Pop3Command inCommand) at Higuchi.Net.Pop3.Pop3Client.GetMessage(Int64 inMailIndex)"} ``` Ideally what i would like to do is open this read all the new unread emails in this account for a certain subject line then read the data in the body and mark them as read does anyone know why its erroring out does anyone have any experince with c#mail that hey could point me in the right direction for reading and makring emails as read etc
``` using (Pop3Client cl = new Pop3Client()) { cl.UserName = "ewgsdssw"; cl.Password = "sdgwsegw"; cl.ServerName = "pop.gmail.com"; cl.AuthenticateMode = Pop3AuthenticateMode.Pop; cl.Port = 995; cl.Ssl = true; cl.Authenticate(); ///Get first mail of my mailbox /// int total = Convert.ToInt16(cl.GetTotalMessageCount()); while (total >= 1) { Pop3Message mg = cl.GetMessage(total); if (mg.Subject == "I am Here") { // http://maps.google.com/maps?q=38.89552,-77.43265 //(+/- 76 metres.) string location = mg.BodyText; location = location.Replace("http://maps.google.com/maps?q=","~"); location = location.Replace("metres.)\r\n\r\n","~"); location = location.Split('~')[1]; location = location.Replace("(+/- ", ","); location = location.Replace("\r\n", ""); string[] data = location.Split(','); string lat = data[0]; string lon = data[1]; string res = data[2]; DateTime time = mg.Date; textBox1.AppendText(string.Format("Lat: {0} LON: {1} Res: {2} TIME: {3}\r\n",lat,lon,res,time.ToString())); } total--; } } ```
It is not possible to mark emails as read using the POP protocol. Try using IMAP.
error using c#mail.dll
[ "", "c#", "email", "gmail", "" ]
I'm using .net 2.0 filewatcher to watch a folder for new files. It works perfectly except when I put more than ~80 files at once. The event just doesn't trigger anymore. It's as if the filewatcher is set to keep track of certain number of files. For the time being I have asked the user not to put more than 50 files at a time and that seems to work however I would like to fix it so that hundreds of files can be dropped into the folder at once. Here's the code I'm using for the event. It's pretty standard stuff nothing fancy. ``` FileWatcher = new FileSystemWatcher(); FileWatcher.Path = ConfigurationManager.AppSettings["FolderOfFilesToWatch"]; FileWatcher.NotifyFilter = NotifyFilters.FileName; FileWatcher.Filter = "*_*_*.*"; FileWatcher.Created += new FileSystemEventHandler(watcher_Created); FileWatcher.EnableRaisingEvents = true; static void watcher_Created(object sender, FileSystemEventArgs e) { Console.Write(e.Name); } ``` Any ideas?
You probably need to increase the FileSystemWatcher.[InternalBufferSize](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.internalbuffersize.aspx). By default, FileSystemWatcher uses a smaller buffer for performance, and can overflow if too many changes occur in a short time frame. Try setting a larger buffer size to prevent that from occurring.
I use FileWatcher but I took a "belt and suspenders" approach. Whenever I get a FileWatcher event I stick around and check for files I haven't seen before (in my case I have a file catalog). Believe me, there will be a time when you get thousands of files dropped in a folder and you must have another safeguard to account for all of them. Another alterative you may look into is [change journals](http://msdn.microsoft.com/en-us/library/aa363798(VS.85).aspx), although it is (AFAIK) limited to disks attached to your machine, whereas you can use FileWatcher to watch UNC paths as well.
.Net FileWatcher fails for ~80+ files
[ "", "c#", ".net", "" ]
I have a python template engine that heavily uses regexp. It uses concatenation like: ``` re.compile( regexp1 + "|" + regexp2 + "*|" + regexp3 + "+" ) ``` I can modify the individual substrings (regexp1, regexp2 etc). Is there any small and light expression that matches nothing, which I can use inside a template where I don't want any matches? Unfortunately, sometimes '+' or '\*' is appended to the regexp atom so I can't use an empty string - that will raise a "nothing to repeat" error.
This shouldn't match anything: ``` re.compile('$^') ``` So if you replace regexp1, regexp2 and regexp3 with '$^' it will be impossible to find a match. Unless you are using the multi line mode. --- After some tests I found a better solution ``` re.compile('a^') ``` It is impossible to match and will fail earlier than the previous solution. You can replace a with any other character and it will always be impossible to match
`(?!)` should always fail to match. It is the zero-width negative look-ahead. If what is in the parentheses matches then the whole match fails. Given that it has nothing in it, it will fail the match for anything (including nothing).
Regular expression syntax for "match nothing"?
[ "", "python", "regex", "" ]
I am trying to add an attribute to a web page control. ``` TextBox txt=new TextBox(); txt.Attributes["Foo"]="Bar" ``` I need to put this in a method, but my problems is that I do not know what kind of element I will be sending to it - maybe an input maybe a select. In essence I need this method below, but what is `oControl`? In VB I used to just call it an `object`. ``` protected void SetAttrib(oControl){ oControl.Attributes["Foo"]="Bar" } ``` Thanks
I think you want [`WebControl`](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.aspx): ``` protected void SetAttrib(WebControl oControl){ oControl.Attributes["Foo"]="Bar" } ```
WebControl
Type to use to set Attributes in an ASP.NET Control?
[ "", "c#", "" ]
I'm trying to get into the Clojure community. I've been working a lot with Python, and one of the features I make extensive use of is the zip() method, for iterating over pairs of values. Is there a (clever and short) way of achieving the same in Clojure?
Another way is to simply use map together with some function that collects its arguments in a sequence, like this: ``` user=> (map vector '(1 2 3) "abc") ([1 \a] [2 \b] [3 \c]) ```
``` (zipmap [:a :b :c] (range 3)) -> {:c 2, :b 1, :a 0} ``` Iterating over maps happens pairwise, e.g. like this: ``` (doseq [[k v] (zipmap [:a :b :c] (range 3))] (printf "key: %s, value: %s\n" k v)) ``` prints: ``` key: :c, value: 2 key: :b, value: 1 key: :a, value: 0 ```
Processing pairs of values from two sequences in Clojure
[ "", "python", "clojure", "zip", "" ]
I'm new to C#. And I would like to program something like, displaying the prime numbers in a listbox if user will input any integer in the textbox. (that means, if they write 10, it will display the prime numbers from 0-10, or 20 from 0-20, etc). What should I consider first, before I do the programming? I know there are many examples in the internet, but first I would like to know what will I need? Thanks for the tip;-) === Thanks guys. So you're suggesting that it's better to do it first in the Console application? I did an example of "For Loop" using Console Application a very simple one, but then when I tried to do it in the Windows Form Application, I'm not sure how to implement it. I'm afraid that if I keep doing examples in the Console, then I'll have difficulty to do it in Windows Form Apps. What do you think? ====== Hello again, I need some feedback with my code: ``` Console.WriteLine("Please enter your integer: "); long yourInteger; yourInteger = Int32.Parse(Console.ReadLine()); //displaying the first prime number and comparing it to the given integer for (long i = 2; i <= yourInteger; i = i + 1) { //Controls i if its prime number or not if ((i % 2 != 0) || (i == 2)) { Console.Write("{0} ", i); } } ```
Well, first of all I'd think about how to find prime numbers, and write that in a console app that reads a line, does the math, and writes the results (purely because that is the simplest thing you can do, and covers the same parsing etc logic you'll need later). When you are happy with the prime number generation, then look at how to do winforms - how to put a listbox, textbox and button on a form; how to handle the click event (of the button), and how to read from the textbox and write values into the listbox. Your prime code should be fairly OK to take "as is"... If you don't already have an IDE, then note that [C# Express](http://www.microsoft.com/express/vcsharp/) is free and will cover all of the above.
You'll need to know: * How to read user input from a Windows application * How to generate prime numbers within a range * How to write output in the way that you want I strongly suggest that you separate these tasks. Once you've got each of them working separately, you can put them together. (Marc suggests writing a console app for the prime number section - that's a good suggestion if you don't want to get into unit testing yet. If you've used unit testing in other languages, it's reasonably easy to get up and running with [NUnit](http://nunit.org). A console app will certainly be quicker to get started with though.) In theory, for a potentially long-running task (e.g. the user inputs 1000000 as the first number) you should usually use a background thread to keep the UI responsive. However, I would ignore that to start with. Be aware that while you're computing the primes, your application will appear to be "hung", but get it working at all first. Once you're confident with the simple version, you can look at `BackgroundWorker` and the like if you're feeling adventurous.
prime numbers c#
[ "", "c#", "primes", "" ]
I've been tearing my hair out over this issue for the last hour or so. I have some code that goes like this: ``` videoTile.Icon = new ImageSourceConverter().ConvertFrom(coDrivr4.Properties.Resources.Music.GetHbitmap()) as ImageSource; ``` When I run my code, it says a NullReferenceException occurred. Neither 'Music' nor the return of GetHbitmap() are null. I'm trying to get the image via the Properties because it's the only way I've figured out how to access the images in my Resources folder. I would just add them to the app.xaml file as a resource, but I'm not using an app.xaml file for a few reasons. Am I attempting this wrong? All I need to do is get an ImageSource object of an image I have in my Resource directory. I can use them just fine in my XAML, but can't for the life of me do it in any code. P.S.: I can't just add them as a resource to the XAML file because this is just a class and so there is no XAML file.
Well you've got plenty of things which *could* be null in there. I suggest you separate them out: ``` Bitmap bitmap = coDrivr4.Properties.Resources.Music; object source = new ImageSourceConverter().ConvertFrom(bitmap.GetHbitmap()); ImageSource imageSource = (ImageSource) source; videoTile.Icon = imageSource; ``` Note the use of a cast rather than the `as` operator here. If `source` *isn't* an `ImageSource`, this will throw an `InvalidCastException` which will be much more descriptive than just ending up as a null reference. EDIT: Okay, so now we know for sure that it's happening in `ConvertFrom`, I suggest the next step is to find out whether it's a bug in .NET 4.0 beta 1. Are you actually using any .NET 4.0 features? I suggest you try to extract *just that bit of code* into a separate project (you don't need to display an API, just convert the image. Try to run that code in .NET 3.5. If it fails in the same way, that's eliminated the beta-ness from the list of possible problems.
I hit exactly the same issue - I've got all my bitmaps in a nice, statically typed resource file and I just want to set an ImageSource with them. So, since the ImageSourceConverter was throwing null reference exceptions, I changed tack and used this piece of code instead: ``` Bitmap bitmap = entityCol.EntityCollectionImage; this.Image = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); // Image is an image source ``` Hope that helps.
ImageSourceConverter throws a NullReferenceException ... why?
[ "", "c#", "wpf", "resources", "" ]
I just recently started learning C++ - I am using [nuwen's](http://nuwen.net/mingw.html) version of MingW on Windows, using NetBeans as an IDE (I have also MSDN AA Version of MSVC 2008, though I don't use it very often). When compiling this simple program: ``` #include <iostream> using namespace std; int dog, cat, bird, fish; void f(int pet) { cout << "pet id number: " << pet << endl; } int main() { int i, j, k; cout << "f(): " << (long)&f << endl; cout << "dog: " << (long)&dog << endl; cout << "cat: " << (long)&cat << endl; cout << "bird: " << (long)&bird << endl; cout << "fish: " << (long)&fish << endl; cout << "i: " << (long)&i << endl; cout << "j: " << (long)&j << endl; cout << "k: " << (long)&k << endl; } ///:~ ``` my executable was about 1MB big. When I changed project configuration from *Debug* to *Release*, used -O1 -Os flags ( stripping debugging symbols along the way ), binary size was reduced from 1MB to 544KB. I am not a "size freak", but I am just wondering - is there any way, that I could reduce .exe size even more? I just think, that 544KB is just too much for such a simple application ).
The problem here is not so much with the library as it is with the way the library is linked. Granted, *iostream* is a moderately huge library but I don't think it can be so huge as to cause a program to generate an executable that is `900KB` larger than a similar one that uses `C` functions. The one to blame is not `iostream` but `gcc`. More accurately, `static linking` is to be blamed. How would you explain these results(with your program): ``` g++ test.cpp -o test.exe SIZE: 935KB gcc test.cpp -o test.exe -lstdc++ SIZE: 64.3KB ``` Different sizes of executables are being generated with exactly the same build options. The answer lies in the way **gcc** links the object files. When you compare the outputs from these two commands: ``` g++ -v test.cpp -o test.exe // c++ program using stream functions gcc -v test.c -o test.exe // c program that using printf ``` you'll find out that the only places they differ(apart from the paths to the temporary object files) is in the options used: ``` C++(iostream) | C(stdio) ------------------------------- -Bstatic | (Not There) -lstdc++ | (Not There) -Bdynamic | (Not There) -lmingw32 | -lmingw32 -lgcc | -lgcc -lmoldname | -lmoldname -lmingwex | -lmingwex -lmsvcrt | -lmsvcrt -ladvapi32 | -ladvapi32 -lshell32 | -lshell32 -luser32 | -luser32 -lkernel32 | -lkernel32 -lmingw32 | -lmingw32 -lgcc | -lgcc -lmoldname | -lmoldname -lmingwex | -lmingwex -lmsvcrt | -lmsvcrt ``` You've got your culprit right there at the top. `-Bstatic` is the option that comes exactly after the object file which may look something like this: ``` "AppData\\Local\\Temp\\ccMUlPac.o" -Bstatic -lstdc++ -Bdynamic .... ``` If you play around with the options and remove 'unnecessary' libraries, you can reduce the size of the executable from `934KB` to `4.5KB` max in my case. I got that `4.5KB` by using `-Bdynamic`, the `-O` flag and the most crucial libraries that your application can't live without, i.e `-lmingw32`, `-lmsvcrt`, `-lkernel32`. You'll get a **25KB** executable at that point. Strip it to **10KB** and **UPX** it to around `4.5KB-5.5KB`. Here's a Makefile to play with, for kicks: ``` ## This makefile contains all the options GCC passes to the linker ## when you compile like this: gcc test.cpp -o test.exe CC=gcc ## NOTE: You can only use OPTIMAL_FLAGS with the -Bdynamic option. You'll get a ## screenfull of errors if you try something like this: make smallest type=static OPTIMAL_FLAGS=-lmingw32 -lmsvcrt -lkernel32 DEFAULT_FLAGS=$(OPTIMAL_FLAGS) \ -lmingw32 \ -lgcc \ -lmoldname \ -lmingwex \ -lmsvcrt \ -ladvapi32 \ -lshell32 \ -luser32 \ -lkernel32 \ -lmingw32 \ -lgcc \ -lmoldname \ -lmingwex \ -lmsvcrt LIBRARY_PATH=\ -LC:\MinGW32\lib\gcc\mingw32\4.7.1 \ -LC:\mingw32\lib\gcc \ -LC:\mingw32\lib\mingw32\lib \ -LC:\mingw32\lib\ OBJECT_FILES=\ C:\MinGW32\lib\crt2.o \ C:\MinGW32\lib\gcc\mingw32\4.7.1\crtbegin.o COLLECT2=C:\MinGW32\libexec\gcc\mingw32\4.7.1\collect2.exe normal: $(CC) -c test.cpp $(COLLECT2) -Bdynamic $(OBJECT_FILES) test.o -B$(type) -lstdc++ -Bdynamic $(DEFAULT_FLAGS) $(LIBRARY_PATH) -o test.exe optimized: $(CC) -c -O test.cpp $(COLLECT2) -Bdynamic $(OBJECT_FILES) test.o -B$(type) -lstdc++ -Bdynamic $(DEFAULT_FLAGS) $(LIBRARY_PATH) -o test.exe smallest: $(CC) -c -O test.cpp $(COLLECT2) -Bdynamic $(OBJECT_FILES) test.o -B$(type) -lstdc++ -Bdynamic $(OPTIMAL_FLAGS) $(LIBRARY_PATH) -o test.exe ultimate: $(CC) -c -O test.cpp $(COLLECT2) -Bdynamic $(OBJECT_FILES) test.o -B$(type) -lstdc++ -Bdynamic $(OPTIMAL_FLAGS) $(LIBRARY_PATH) -o test.exe strip test.exe upx test.exe CLEAN: del *.exe *.o ``` Results(YMMV): ``` // Not stripped or compressed in any way make normal type=static SIZE: 934KB make normal type=dynamic SIZE: 64.0KB make optimized type=dynamic SIZE: 30.5KB make optimized type=static SIZE: 934KB make smallest type=static (Linker Errors due to left out libraries) make smallest type=dynamic SIZE: 25.6KB // Stripped and UPXed make ultimate type=dynamic (UPXed from 9728 bytes to 5120 bytes - 52.63%) make ultimate type=static (Linker Errors due to left out libraries) ``` A possible reason for the inclusion of `-Bstatic` in the default build options is for better performance. I tried building `astyle` with `-Bdynamic` and got a speed decrease of 1 second on average, even though the application was way smaller than the original(400KB vs 93KB when UPXed).
The ``` #include <iostream> ``` causes a lot of the standard library to be linked in, at least with g++. If you are really concerned about executable size, try replacing all uses of iostreams with printf or similar. This will typically give you a smaller, faster executable (I got yours down to about 6K) at the cost of convenience and type-safety.
GCC C++ "Hello World" program -> .exe is 500kb big when compiled on Windows. How can I reduce its size?
[ "", "c++", "optimization", "gcc", "netbeans", "size", "" ]
I have config.properties file containing properties in Java Properties format. I need to replace the value of a property with a known name with a new value. The comments and formatting of the file should be preserved. My current approach is to use RegEx to match the property name and then replace its value. However, Java Properties supports multi-line values, which I have hard time matching. Here is an example. Suppose config.properties contains the following text: ``` # A property A = 1\ 2 # B property B = 2 ``` I would like to replace the value of property A with "3". The end result should be: ``` # A property A = 3 # B property B = 2 ``` My current RegEx `(?s)(A[\\s]*=[\\s]*)(.*)` does not work correctly. Please suggest a RegEx or an a different way of doing this. Thanks!
Try this: ``` String regex = "(?m)^(A\\s*+=\\s*+)" + "(?:[^\r\n\\\\]++|\\\\(?:\r?\n|\r|.))*+$"; ``` I left the first part as you wrote it so I could concentrate on matching the value; the rules governing the key and separator are actually much more complicated than that. The value consists of zero or more of any character except carriage return, linefeed or backslash, or a backslash followed by a line separator or any single non-line-separator character. The line separator can be any of the three most common forms: DOS/Windows (`\r\n`), Unix/Linux/OSX (`\n`) or pre-OSX Mac (`\r`). Note that the regex is in multiline mode so the line anchors will work, but *not* singleline (DOTALL) mode. I also used possessive quantifiers throughout because I know backtracking will never be useful.
You have tools in Java to load, read, modify and save properties files. Personally I like [Jakarta Commons Configuration](http://commons.apache.org/configuration/).
Replace the property value using RegEx
[ "", "java", "regex", "properties", "" ]
How can I use an interface (from which classes implement) in an XML web service? When I do so, I get a YSOD claiming the interface is not serializable. If I add the Serializable attribute to the interface's class, there's another error which hampers progress (can't remember which).
For the most part interfaces are not serializable without some work. Usually this error is encountered when the class being serialized contains an object that is using an interface as a variable, or some variation of this. For instance, a property like this would throw an error: ``` [Serializable] public class TestClass { private ICustomInterface _iCustomInterfaceObject; public ICustomInterface CustomInterfaceProperty { get { return _iCustomInterfaceObject; } set { _iCustomInterfaceObject = value; } } } ``` For the sake of the argument (and not making me type additional validation code), let's say that you always are assigning CustomInterfaceProperty to an object that inherits from ICustomInterface (as is required when using interface types like this). Even if it is 100% sure to always be populated, it won't allow you to serialize the TestClass. To get around this, you need to make sure the interface you are using, the one that is throwing the error, also inherits from ISerializable. That way you are promising that all of the objects inheriting from ICustomInterface also have serialization methods implemented. Unfortunately, this is not the case when using xml serialization. If you are using the serializers found in System.Xml.Serialization then this method won't work, since, as Robert Harvey pointed out, an interface does not contain a parameterless constructor (which is required when using the xml serializers). My suggestion for now, if you are set on this method of serialization, attach the attribute [XmlIgnore] to the section in question and move on from there.
My advice is to treat the objects that go over the wire as basic data transfer objects and nothing more. You're tempted to just use your domain objects and serialize them, but as you're already seeing, normal in-memory objects can have far more complexity than can be serialized without a lot of work, and sometimes not at all. You can also end up limiting functionality of your domain classes just to keep them serializable. Finally, a more subtle bug to avoid, and a reason to have separate DTO's, is that you otherwise are tightly coupling your domain objects to a publicly published interface i.e. the web service itself. Versioning a web service can be a hassle, and it's easier if your service interface isn't tightly coupled to your domain classes.
Using an interface in a C# xml web service
[ "", "c#", "web-services", "" ]
I need to remove the first forward slash inside link formatted like this: ``` /directory/link.php ``` I need to have: ``` directory/link.php ``` I'm not literate in regular expressions (preg\_replace?) and those slashes are killing me.. I need your help stackoverflow! Thank you very much!
Just because nobody has mentioned it before: ``` $uri = "/directory/link.php"; $uri = ltrim($uri, '/'); ``` The benefit of this one is: * **compared to the [`substr()` solution](https://stackoverflow.com/questions/955212/remove-first-forward-slash-in-a-link/955233#955233):** it works also with paths that do not start with a slash. So using the same procedure multiple times on an uri is safe. * **compared to the [`preg_replace()` solution](https://stackoverflow.com/questions/955212/remove-first-forward-slash-in-a-link/955223#955223):** it's certainly much more faster. Actuating the regex-engine for such a trivial task is, in my opinion, overkill.
``` preg_replace('/^\//', '', $link); ```
Remove first forward slash in a link?
[ "", "php", "regex", "preg-replace", "" ]
I have an html file which passes values into a java servlet to insert into the database. Here is my code: ``` <html> <head> <script type="text/javascript"> function masinsert(id) { var currentTime=new Date(); var button = document.getElementById("m"+id); button.onclick=""; button.value="Inserting"; var partnumber = document.getElementById("partnumber"+id).value; var itemcost = document.getElementById("itemcost"+id).value; var itemlistprice = document.getElementById("itemlistprice"+id).value; var sUnitMeasKey = document.getElementById("UnitMeasKey"+id); var sPurchProdLine = document.getElementById("PurchProdLine"+id); var sItemClassKey = document.getElementById("itemclasskey"+id); var UMKselected = getSelected(sUnitMeasKey); var PPLselected = getSelected(sPurchProdLine); var ICKselected = getSelected(sItemClassKey); function handleHttpResponse() { if (http.readyState == 4) { button.value="Imported"; } } var http = getHTTPObject(); // We create the HTTP Object var tempUrl = "\MASInsert2"; tempUrl += "?partnumber="+partnumber+"&"+"itemcost="+itemcost+"&"+"itemlistprice="+itemlistprice+"&"+"UnitMeasure="+UMKselected+"&"+"PurchProdLine="+PPLselected+"&"+"itemclasskey="+ICKselected; alert(tempUrl); http.open("POST", tempUrl, true); http.onreadystatechange = handleHttpResponse; http.send(null); } function getSelected(ele) { return ele.options[ele.selectedIndex].value; } function getHTTPObject(){ var xmlhttp; /*@cc_on @if (@_jscript_version >= 5) try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }catch (e){ try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }catch (E) { xmlhttp = false; } } @else xmlhttp = false; @end @*/ if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp = false; } } return xmlhttp; } </script> </head> <body> <form name=bob method=get> <input type=hidden id="partnumber321" name="partnumber321" value="884910U"> <input type=hidden id="itemcost321" name="itemcost321" value="1027.39"> <input type=hidden id="itemlistprice321" name="itemlistprice321" value="1129.0"> <input type=hidden id="itemdescription321" name="itemdescription321" value="XSERIES 306M SS P4 3.0GHZ 1MB"> <select id="UnitMeasKey321" name="UnitMeasKey321"><option value="112">Each</select> <select id="PurchProdLine321" name="PurchProdLine321"><option value="18">IBM</select> <select id="itemclasskey321" name="itemclasskey321"><option value="48">Hardware</select> <input id="m321" type="button" onclick="masinsert('321')" value="Add"> </form> </body> </html> ``` When I hit the button, the alert(partnumber) returns null (firefox) or object (IE). Am I passing these values incorrectly for the servlet to process? Any ideas why? shouldn't it return a value? thanks in advance
Firefox is returning null because there is no ID by that name. Call `GetElementByName` if you don't want to assign ids to your inputs. IE is returning an object because DOM elements are objects. You need to check one of its attributes (`value` most likely) to see what it's actually set to. IE shouldn't return an object, but it naively assumes that `GetElementById` is the same as `GetElementByName`.
Classic IE bug **[ID vs. Name](http://webbugtrack.blogspot.com/2007/08/bug-152-getelementbyid-returns.html)**. You will either need to specify and use id attributes, or use getElementsByName (beware it will return a "set" of matches) or the form.elements[nameOrIndex] format. e.g. ``` alert(document.forms[myFormNameOrIndex].elements[myElementNameOrIndex].value); ```
javascript : trouble passing value to alert from hidden tag or text
[ "", "javascript", "" ]
What is the meaning of ``` *(int *)0 = 0; ``` It does compile successfully
It will usually cause an access violation at runtime. The following is done: first 0 is cast to an `int *` and that yields a null pointer. Then a value 0 is written to that address (null address) - that causes undefined behaviour, usually an access violation. Effectively it is this code: ``` int* address = reinterpret_cast<int*>( 0 ); *address = 0; ```
It has no meaning. That's an error. It's parsed as this ``` (((int)0) = 0) ``` Thus, trying to assign to an rvalue. In this case, the right side is a cast of `0` to `int` (it's an int already, anyway). The result of a cast to something not a reference is always an rvalue. And you try to assign `0` to that. What Rvalues miss is an object identity. The following would work: ``` int a; (int&)a = 0; ``` Of course, you could equally well write it as the following ``` int a = 0; ``` **Update**: Question was badly formatted. The actual code was this ``` *(int*)0 = 0 ``` Well, now it *is* an lvalue. But a fundamental invariant is broken. The Standard says > An lvalue refers to an object or function The lvalue you assign to is neither an object nor a function. The Standard even explicitly says that dereferencing a null-pointer (`(int*)0` creates such a null pointer) is undefined behavior. A program usually will crash on an attempt to write to such a dereferenced "object". "Usually", because the act of dereferencing is already declared undefined by C++. --- Also, note that the above is not the same as the below: ``` int n = 0; *(int*)n = 0; ``` While the above writes to something where certainly no object is located, this one will write to something that results from reinterpreting n to a pointer. The mapping to the pointer value is implementation defined, but most compilers will just create a pointer referring to address zero here. Some systems may keep data on that location, so this one may have more chances to stay alive - depending on your system. This one is not undefined behavior necessarily, but depends on the compiler and runtime-environment it is invoked in. If you understand the difference between the above dereference of a null pointer (only constant expressions valued 0 converted to pointers yield null pointers!) and the below dereference of a reinterpreted zero value integer, i think you have learned something important.
Pointers assignment
[ "", "c++", "" ]
I'm running Tomcat6 in Sun's JRE6 and every couple deploys I get OutOfMemoryException: PermGen. I've done the Googling of PermGen solutions and tried many fixes. None work. I read a lot of good things about Oracle's JRockit and how its PermGen allocation can be gigs in size (compare to Sun's 128M) and while it doesn't solve the problem, it would allow me to redeploy 100 times between PermGen exceptions compared to 2 times now. The problem with JRockit is to use it in production you need to buy WebLogic which costs thousands of dollars. What other (free) options exist that are more forgiving of PermGen expansion? How do the below JVMs do in this area? * IBM JVM * Open JDK * Blackdown * Kaffe ...others? **Update:** Some people have asked why I thought PermGen max was 128M. The reason is because any time I try to raise it above 128M my JVM fails to initialize: `[2009-06-18 01:39:44] [info] Error occurred during initialization of VM [2009-06-18 01:39:44] [info] Could not reserve enough space for object heap [2009-06-18 01:39:44] [395 javajni.c] [error] CreateJavaVM Failed` It's strange that it fails trying to reserve space for the object **heap**, though I'm not sure it's "the" heap instead of "a" heap. I boot the JVM with 1024MB initial and 1536MB max heap. I will close this question since it has been answered, ie. "switching is useless" and ask instead [Why does my Sun JVM fail with larger PermGen settings?](https://stackoverflow.com/questions/1010986/why-does-my-sun-jvm-fail-to-initialize-when-i-set-permgen-above-128m)
I agree with Michael Borgwardt in that you can increase the PermGen size, I disagree that it's primarily due to memory leaks. PermGen space gets eaten up aggressively by applications which implement heavy use of Reflection. So basically if you have a Spring/Hibernate application running in Tomcat, be prepared to bump that PermGen space up a lot.
What gave you the idea that Sun's JVM is restricted to 128M PermGen? You can set it freely with the -XX:MaxPermSize command line option; the default is 64M. However, the real cause of your problem is probably a memory leak in your application that prevents the classes from getting garbage collected; these can be very subtle, especially when ClassLoaders are involved, since all it takes is a single reference to any of the classes, anywhere. [This article](http://blogs.oracle.com/fkieviet/entry/classloader_leaks_the_dreaded_java) describes the problem in detail, and [this one](http://blogs.oracle.com/fkieviet/entry/how_to_fix_the_dreaded) suggests ways to fix it.
What free JVM implementation has the best PermGen handling?
[ "", "java", "jvm", "permgen", "" ]
I saw an example of using Expression Builders, and creating your own Custom Expression Builder Classes here: <https://web.archive.org/web/20210513211719/http://aspnet.4guysfromrolla.com/articles/022509-1.aspx> However, I fail to see the value in using this approach. It doesn't seem much easier than programmatically setting values in your code behind. As far as I can tell, the only thing you can do with them is set properties. Maybe they would be useful for setting defaults on certain controls? Can anyone shed light on where this ASP.NET feature becomes powerful?
We are using a custom expression builder to localize our application. E.g. the markup looks like this: ``` <asp:LinkButton Text="<%$ Str:SomeString %>" ... /> ``` The expression builder reads a string with the ID SomeString from a resource file (taking into account the current user's language preferences) and assigns it to the Text property of the LinkButton. This is quite flexible: we can add languages by simply copying a resource file into the application directory. And if a customer wants to have a different text for that linkbutton, he just adds his custom string to the resource files and changes the string-ID in the expression builder (without having to change the code-behind).
Custom Expressions are handy if you care about ViewState (you should). See [TRULY Understanding ViewState](http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/truly-understanding-viewstate.aspx).
When are ASP.NET Expression Builders most useful?
[ "", "c#", "asp.net", "vb.net", "expressionbuilder", "" ]
Duplicate of: [In C#, how can I rethrow InnerException without losing stack trace?](https://stackoverflow.com/questions/57383/in-c-how-can-i-rethrow-innerexception-without-losing-stack-trace) I have some operations that I invoke asynchronously on a background thread. Sometimes, things go bad. When this happens, I tend to get a TargetInvocationException, which, while appropriate, is quite useless. What I really need is the TargetInvocationException's InnerException, like this: ``` try { ReturnValue = myFunctionCall.Invoke(Target, Parameters); } catch (TargetInvocationException err) { throw err.InnerException; } ``` That way, my callers are served up with the REAL exception that occured. The problem is, that the throw statement seems to reset the stack trace. I'd like to basically rethrow the inner exception, but keep the stack trace it originally had. How do I do that? **CLARIFICATION:** The reason I want only the inner exception is that this class tries to 'abstract away' the whole fact that these functions (delegates supplied by caller) are run on other threads and whatnot. If there is an exception, then odds are it has nothing to do with being run on a background thread, and the caller would really like the stack trace that goes into their delegate and finds the real issue, not my call to invoke.
It **is** possible to preserve the stack trace before rethrowing without reflection: ``` static void PreserveStackTrace (Exception e) { var ctx = new StreamingContext (StreamingContextStates.CrossAppDomain) ; var mgr = new ObjectManager (null, ctx) ; var si = new SerializationInfo (e.GetType (), new FormatterConverter ()) ; e.GetObjectData (si, ctx) ; mgr.RegisterObject (e, 1, si) ; // prepare for SetObjectData mgr.DoFixups () ; // ObjectManager calls SetObjectData // voila, e is unmodified save for _remoteStackTraceString } ``` This wastes a lot of cycles compared to InternalPreserveStackTrace, but has the advantage of relying only on public functionality. Here are a couple of common usage patterns for stack-trace preserving functions: ``` // usage (A): cross-thread invoke, messaging, custom task schedulers etc. catch (Exception e) { PreserveStackTrace (e) ; // store exception to be re-thrown later, // possibly in a different thread operationResult.Exception = e ; } // usage (B): after calling MethodInfo.Invoke() and the like catch (TargetInvocationException tiex) { PreserveStackTrace (tiex.InnerException) ; // unwrap TargetInvocationException, so that typed catch clauses // in library/3rd-party code can work correctly; // new stack trace is appended to existing one throw tiex.InnerException ; } ```
No, that isn't possible. Your only real opportunity is to follow the recommended pattern and throw your own exception with the appropriate `InnerException`. **Edit** If your concern is the presence of the `TargetInvocationException` and you want to disregard it (not that I recommend this, as it could *very well* have something to do with the fact that it's being run on another thread) then nothing is stopping you from throwing your own exception here and attaching the `InnerException` from the `TargetInvocationException` as your own `InnerException`. It's a little smelly, but it might accomplish what you want.
How can I rethrow an Inner Exception while maintaining the stack trace generated so far?
[ "", "c#", ".net", "exception", "stack-trace", "" ]
Ok, so I have a list of dicts: ``` [{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surname': 'headroom', 'age': 108}, ] ``` and I want the 'frequency' of the items within each column. So for this I'd get something like: ``` {'name': {'johnny': 2, 'jakob': 1, 'aaron': 1, 'max': 1}, 'surname': {'smith': 2, 'ryan': 1, 'specter': 1, 'headroom': 1}, 'age': {53:1, 13:1, 27: 1. 22:1, 108:1}} ``` Any modules out there that can do stuff like this?
`collections.defaultdict` from the standard library to the rescue: ``` from collections import defaultdict LofD = [{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surname': 'headroom', 'age': 108}, ] def counters(): return defaultdict(int) def freqs(LofD): r = defaultdict(counters) for d in LofD: for k, v in d.items(): r[k][v] += 1 return dict((k, dict(v)) for k, v in r.items()) print freqs(LofD) ``` emits ``` {'age': {27: 1, 108: 1, 53: 1, 22: 1, 13: 1}, 'surname': {'headroom': 1, 'smith': 2, 'specter': 1, 'ryan': 1}, 'name': {'jakob': 1, 'max': 1, 'aaron': 1, 'johnny': 2}} ``` as desired (order of keys apart, of course -- it's irrelevant in a dict).
``` items = [{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surname': 'headroom', 'age': 108}] global_dict = {} for item in items: for key, value in item.items(): if not global_dict.has_key(key): global_dict[key] = {} if not global_dict[key].has_key(value): global_dict[key][value] = 0 global_dict[key][value] += 1 print global_dict ``` Simplest solution and actually tested.
item frequency in a python list of dictionaries
[ "", "python", "dictionary", "" ]
I'm trying to do something which is very easy to do in the regular MSVC, but not supported easily in VC++ Express. There is no resource editor in VC++ Express. So I added a file named version.rc into my DLL project. The file has the below content, which is compiled by the resource compiler and added to the final DLL. This resource is viewable in the DLL using reshacker, though not when right-clicking the DLL in Windows Explorer. What is missing from my RC file to make it appear when right-clicking? ``` VS_VERSION_INFO VERSIONINFO FILEVERSION 1,0,0,1 PRODUCTVERSION 1,0,0,1 FILEFLAGSMASK 0x17L #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x4L FILETYPE 0x1L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "something Application" VALUE "FileVersion", "1, 0, 0, 1" VALUE "InternalName", "something" VALUE "LegalCopyright", "Copyright (C) 2008 Somebody" VALUE "OriginalFilename", "something.exe" VALUE "ProductName", "something Application" VALUE "ProductVersion", "1, 0, 0, 1" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END ```
The correct solution is to add to the top of your .rc file: ``` #include <windows.h> ```
I was able to see (using reshacker) one difference between my resource and resources that appear on right-click, and that was the name of the resource. So I changed VS\_VERSION\_INFO to 1; and now the resource is visible on right-click. ``` 1 VERSIONINFO FILEVERSION 1,0,0,1 PRODUCTVERSION 1,0,0,1 FILEFLAGSMASK 0x17L #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x4L FILETYPE 0x1L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "something Application" VALUE "FileVersion", "1, 0, 0, 1" VALUE "InternalName", "something" VALUE "LegalCopyright", "Copyright (C) 2008 Somebody" VALUE "OriginalFilename", "something.exe" VALUE "ProductName", "something Application" VALUE "ProductVersion", "1, 0, 0, 1" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END ```
Version resource in DLL not visible with right-click
[ "", "c++", "visual-studio-2008", "dll", "resources", "visual-c++-2008-express", "" ]
I rewrite my urls to be user friendly. For example I have a page called user.php that I rewrite to /user. But a user can still use user.php. Can I redirect to a 404 if they request a page with a .php extension? ``` Options -MultiViews +FollowSymlinks -Indexes RewriteEngine on RewriteRule ^user/([0-9]+)$ user.php?id=$1 [L,QSA] ``` Thanks.
``` RewriteCond %{THE_REQUEST} \.php[\ /?].*HTTP/ RewriteRule ^.*$ - [R=404,L] ```
This should do the trick, I think: ``` RewriteRule (.*)\.php$ path/to/your/404file [L] ```
mod_rewrite error 404 if .php
[ "", "php", "mod-rewrite", "" ]
My question is as follows: I have a base controller (ASP.Net MVC controller) called ApplicationController, and I want all my controller to inherit from it. this base controller has a ILogger property, marked with a [Dependency] attribute. (yes, I know I should use constructor injection, I'm just curious about this attribute). I created the container, registered types, changed the default factory, everything is fine. the problem is that when I try to use my Logger property in the derived controller, it's not resolved. what am I doing wrong? why doesn't the container resolves the base class dependencies when creating the derived controller? code samples: --- ApplicationController: ``` public class ApplicationController : Controller { [Dependency] protected ILogger _logger { get; set; } } ``` derived controller: ``` public class HomeController : ApplicationController { public HomeController() { } public ActionResult Index() { _logger.Log("Home controller constructor started."); ViewData["Message"] = "Welcome to ASP.NET MVC!"; return View(); } public ActionResult About() { return View(); } } ``` Unity controller factory: ``` public class UnityControllerFactory : DefaultControllerFactory { private readonly IUnityContainer _container; public UnityControllerFactory(IUnityContainer container) { _container = container; } protected override IController GetControllerInstance(Type controllerType) { return _container.Resolve(controllerType) as IController; } } ``` Global.asax.cs sample: ``` protected void Application_Start() { _container = new UnityContainer(); _container.RegisterType<ILogger, Logger.Logger>(); UnityControllerFactory factory = new UnityControllerFactory(_container); ControllerBuilder.Current.SetControllerFactory(factory); RegisterRoutes(RouteTable.Routes); } ``` --- I'm quite new to Unity, so maybe I did something wrong. thanks, Ami.
AFAIK, Unity will only resolve public properties. Therefore your protected property will not be resolved.
I'm not sure if this is related, but usually, I avoid having namespaces and classes with the same name (in your case, Logger.Logger), for I had problems with this in the past. But that may be not the problem. I'm also not sure if the [Dependency] attribute works for derived types. If you change it for constructor injection, does this still not work? Something like: ``` public class ApplicationController : Controller { protected ILogger _logger { get; set; } public ApplicationController(ILogger logger) { this._logger = logger; } } ``` and ``` public class HomeController : ApplicationController { public HomeController(ILogger logger) : base(logger) { } public ActionResult Index() { _logger.Log("Home controller constructor started."); ViewData["Message"] = "Welcome to ASP.NET MVC!"; return View(); } public ActionResult About() { return View(); } } ``` and the rest just the same. The code looks ok.
Unity [dependency] injection and Inheritance
[ "", "c#", "inheritance", "dependency-injection", "unity-container", "" ]
If I have two queries ``` SELECT Id, Forename, Surname FROM Person WHERE PersonName Like(‘%frank%’) ``` And ``` SELECT * FROM Person WHERE PersonName Like(‘%frank%’) ``` Which query will run faster? Is the where clause / table joining the biggest factor, or the number of columns returned? I’m asking because I’m building a series of objects that map to database tables. Typically each object will have at least these three methods: `Select` – Selects everything `List` – Selects enough that is can be used to populate a dropdown list `Search` – Selects everything that is viewable in the results, typically about 6 or so columns. If each query returned exactly the same set of columns the maintenance and testing of the code should be more trivial. The database is unlikely to get above 50,000 rows in any given table, so if the difference in performance is small then I’ll take the saving in development time. If the performance is going to drop through the floor, then I’ll work at in from a different angle. So, for ease of development, is `SELECT *` sensible, or is it naive?
You better avoid `SELECT *` * It leads to confusion when you change the table layout. * It selects unneeded columns, and your data packets get larger. * The columns can get duplicate names, which is also not good for some applications * If all the columns you need are covered by an index, `SELECT columns` will only use this index, while `SELECT *` will need to visit the table records to get the values you don't need. Also bad for performance.
`SELECT *` is usually never a good idea. It may not slow down your DBMS fetch a lot but it will probably result in more data being transmitted over the network than you need. However, that's likely to be swamped into insignificance by the use of the `LIKE '%frank%'` clause which is basically non-indexable and will result in a full table scan. You might want to consider cleaning up the data as it enters the database since that will almost certainly make subsequent queries run much faster. If you're after frank, then make sure it's stored as frank and use: ``` select x,y,z from table where name = 'frank' ``` If you want to get franklin as well, use: ``` select x,y,z from table where name like 'frank%' ``` Both of these will be able to use an index on the name column, `"%frank%"` will not.
Does the number of columns returned affect the speed of a query?
[ "", "sql", "performance", "" ]
I have a weird problem that sometimes when I make a change to a Linq object using the O/R designer (usually by adding a field that I've added in the DB), when I save the project, the designer.cs file gets deleted! Fortunately I have my source control to fall back on; I undelete the file and back out the changes to the csproj file. But this is really annoying, and doesn't appear to have any good reason (the fact that my project contains about 100 objects is not an excuse). Has anyone else had this trouble? Any idea what could be causing this to happen? **Edit** - additional info - my DataContext class is set up with a custom base class. D'ya think this might have something to do with it...?
It may be too early to tell, because the behavior is erratic, but it seems to me that if I keep the designer.cs file open in the IDE editor when I make changes on the .dbml file, then it doesn't get removed when I hit "Save". I've tried that a few times, and it seems to work... No good explanation why that should be, but then the problem is not one that can be subjected to logical scrutiny, either... ## Later... Having tried this out a few times, I can say that this consistently works, so I'm marking this as the answer! Thanks to all for your help!
Have you added a partial class to add functionality (etc) to the generated classes? If so - odd though it sounds, the position of any `using` statements in your partial class file can actually be a problem that breaks code generation. Try moving them inside the namespace. No, I am not kidding. The error message in this case is "The custom tool 'MSLinqToSQLGenerator' failed. Unspecified error". Changing from: ``` using System; namespace MyNamespace { partial class MyDataContext {} } ``` to: ``` namespace MyNamespace { using System; partial class MyDataContext {} } ``` fixes it. Freaky bug.
My O/R Designer keeps deleting the designer.cs file!
[ "", "c#", "visual-studio-2008", "linq", "linq-to-sql", "or-designer", "" ]
I'm vaguely aware that on a computer joined to a domain IE can be asked to send some extra headers that I could use to automatically sign on to an application. I've got apache running on a windows server with mod\_php. I'd like to be able to avoid the user having to log in if necessary. I've found some links talking about Kerberos and Apache modules. <http://www.onlamp.com/pub/a/onlamp/2003/09/11/kerberos.html?page=last> <https://metacpan.org/pod/Apache2::AuthenNTLM> Since I'm running on Windows it's proven to be non-trivial to get Perl or Apache modules installed. But doesn't PHP already have access to HTTP headers? I found this but it doesn't do any authentication, it just shows that PHP can read the NTLM headers. <http://siphon9.net/loune/2007/10/simple-lightweight-ntlm-in-php/> I'd like to be able to have my users just point to the application and have them automatically authenticated. Has anyone had any experience with this or gotten it to work at all? **UPDATE** Since originally posting this question, we've changed setups to nginx and php-fcgi still running on windows. Apache2 and php-cgi on windows is probably one of the slowest setups you could configure on windows. It's looking like Apache might still be needed (it works with php-fcgi) but I would prefer a nginx solution. I also still don't understand (and would love to be educated) why HTTP server plugins are necessary and we can't have a PHP, web server agnostic solution.
All you need is the [`mod_auth_sspi`](http://mod-auth-sspi.sourceforge.net/) Apache module. Sample configuration: ``` AuthType SSPI SSPIAuth On SSPIAuthoritative On SSPIDomain mydomain # Set this if you want to allow access with clients that do not support NTLM, or via proxy from outside. Don't forget to require SSL in this case! SSPIOfferBasic On # Set this if you have only one domain and don't want the MYDOMAIN\ prefix on each user name SSPIOmitDomain On # AD user names are case-insensitive, so use this for normalization if your application's user names are case-sensitive SSPIUsernameCase Lower AuthName "Some text to prompt for domain credentials" Require valid-user ``` And don't forget that you can also [use Firefox for transparent SSO in a Windows domain](http://kb.mozillazine.org/Network.automatic-ntlm-auth.trusted-uris): Simply go to `about:config`, search for `network.automatic-ntlm-auth.trusted-uris`, and enter the host name or FQDN of your internal application (like myserver or myserver.corp.domain.com). You can have more than one entry, it's a comma-separated list.
I had a similar problem which I needed to solve for my organization. I was looking into using [adLDAP](http://adldap.sourceforge.net). There is some documentation on the site for achieving seamless authentication with Active Directory too.
How can I implement single sign-on (SSO) using Microsoft AD for an internal PHP app?
[ "", "php", "active-directory", "apache2", "nginx", "single-sign-on", "" ]
Say I have two classes A and B, with B depending on A. ``` public class A {} public class B { public B(A a) {} } ``` It's easy to resolve B in a single PicoContainer. ``` final MutablePicoContainer root = new PicoBuilder().build(); root.addComponent(new A()); root.addComponent(B.class, B.class); System.out.println(root.getComponent(B.class)); ``` But I'd like to have different instances of `B` for different sessions, with variable instances of `A`. I'm thinking about something like this. ``` // during startup final MutablePicoContainer root = new PicoBuilder().build(); root.addComponent(B.class, B.class); // later, initialize sessions final MutablePicoContainer session = new PicoBuilder(root) .implementedBy(TransientPicoContainer.class) .build(); session.addComponent(new A()); // some request System.out.println(session.getComponent(B.class)); ``` Above code isn't working, because when asking `session` for a `B` it asks the parent container `root` for it. `B` is found there, but resolved only within `root` and its parents, leading to an `UnsatisfiableDependenciesException.` Is there any good way to make this work? Or is this an anti-pattern, and I'm solving the problem in the wrong way?
I would register B within the session container as well. Any other dependency of B you can leave in the root container. Assume B has another dependency on C. So you can do the following: ``` // during startup final MutablePicoContainer root = new PicoBuilder().build(); root.addComponent(C.class, C.class); // later, initialize sessions final MutablePicoContainer session = new PicoBuilder(root) .implementedBy(TransientPicoContainer.class) .build(); session.addComponent(B.class, B.class); session.addComponent(new A()); // some request System.out.println(session.getComponent(B.class)); ```
Solving a performance problem that doesn't exist isn't a good approach. Have you done any profiling to verify the problem? If not, consider doing that first.
How do I manage dynamic dependencies with PicoContainer?
[ "", "java", "inversion-of-control", "ioc-container", "picocontainer", "" ]
I'm looking for a c++ class/library that provides 1024 bit and bigger integers and bit operations like: - bit shifting, - bitwise OR/AND, - position first zero bit speed is crucial, so it would have to be implemented with some SIMD assembly.
There are several, including [GMP](http://gmplib.org/), but for speed, the best is likely [TTmath](http://www.ttmath.org/ttmath). TTmath's design decision to use templated fixed lengths at compiletime lets it be quite fast.
try [gmp library](http://gmplib.org/). It is a C library. Beginning with GMP 4.0 a C++ wrapper is bundled with the release.
Bigint (bigbit) library
[ "", "c++", "biginteger", "" ]
So, let's say I have this code (VB.Net): ``` Sub Main() dim xxx as string = "HELLO WORLD" DetectName(xxx) End Sub Public Sub (theVariable as string) dim output as string = "The Value: {0} was stored in the variable named: {1}." debug.writeline(string.format(output, theVariable, What Goes Here????)) End Sub ``` Te output I want to see is: The Value: HELLO WORLD was stored in the variable named: xxx. Is this somehow possible, through reflection possibly?? (And if you *definitively know it isn't* possible, thats useful to know also). In case you are wondering why I want to do this...I am trying to find some decent way to write a custom binding class (for forms, not grids) for asp.net because I can't seem to find anything that works well enough to be worth the trouble of using it. (NOTE: I am working with webforms and cannot use MVC to solve this problem). I'm thinking my convention for supplying the binding information will be something like: asp:TextBox id="myClassInstanceName.myPropertyName" ... So, then I can have a function like so: ``` Public Sub Bind(webForm as System.Web.UI.Page, bindingObjects as HashTable) For each ctl in webForm.flattenedControls that contains "." within ID ' Here, which property is set would actually depends on control type ' magicGetValue() would find the property class instance within bindingObjects, which is indexed by variable *NAME* (not type), and then return the proper property value via reflection ctl.Text = magicGetValue(ctl.ID, bindingObjects) End Sub End Sub ``` Personally, I think this is a much easier syntax and much more powerful than the recommended asp:FormView, Bind("") approach. For example: - if I want to implement the ability to render as read only, its quite a simple change in my underlying Bind function. - if I want to have more than one class used to populate the UI, I can - if I want to traverse a rich domain model, I can, ie: asp:TextBox id="\_Customer.Address.State" What I don't like is: - relies upon reflection - loosely typed (no compile time checking) - I'd rather store the binding information somewhere other than ID, but don't know where else it could go within the aspx definition. Moving the binding declaration to the code behind would be better in some ways, but worse in others. If anyone has any insight or advice, I'd be very grateful!
You can't detect a variable's name directly, but you can workaround this by wrapping it in an anonymous type when passing it to the function. You can then interrogate the anonymous type using reflection. The names of the type's properties will match the names of the original variables, thanks to [name inferencing](http://msdn.microsoft.com/en-us/library/bb531357.aspx). ``` Sub Main() Dim xxx As String = "HELLO WORLD" Dim yyy As Integer = 42 Dim zzz As DateTime = DateTime.Now DetectName(New With { xxx }) DetectName(New With { yyy }) DetectName(New With { zzz }) ' or... ' DetectName(New With { xxx, yyy, zzz }) End Sub Public Sub DetectName(Of T As Class)(test As T) Dim piArray As PropertyInfo() = GetType(T).GetProperties() Dim pi As PropertyInfo For Each pi In piArray Dim name As String = pi.Name Dim value As Object = pi.GetValue(test, Nothing) Dim output As String = _ "The Value: {0} was stored in the variable named: {1}." Debug.WriteLine(String.Format(output, value, name)) Next End Sub ``` And, for completeness, here's the C# version: ``` void Main() { string xxx = "HELLO WORLD"; int yyy = 42; DateTime zzz = DateTime.Now; DetectName(new { xxx }); DetectName(new { yyy }); DetectName(new { zzz }); // or.. // DetectName(new { xxx, yyy, zzz }); } public void DetectName<T>(T test) where T : class { PropertyInfo[] piArray = typeof(T).GetProperties(); foreach (PropertyInfo pi in piArray) { string name = pi.Name; object value = pi.GetValue(test, null); string output = "The Value: {0} was stored in the variable named: {1}."; Debug.WriteLine(string.Format(output, value, name)); } } ```
It will definitely not work the way you want it, as local variable names are not even included in the assembly after it is compiled. It **might** be possible if the variable is a field of a class (by passing a FieldInfo instead of the actual value or when the variable is passed ByRef).
How to detect variable *name* (not type) within a function (Why? For a custom ASP.Net databinding implementation)
[ "", "c#", ".net", "asp.net", "vb.net", "" ]
I've written a bookmarklet to look a word up in a Chinese dictionary: ``` javascript:Qr=document.getSelection();if(!Qr){void(Qr=prompt('%E8%AF%8D%E8%AF%AD',''))};if(Qr)(function(){window.open('http://nciku.com/search/all/'+Qr);})(); ``` This opens a new tab with search results for your selected word or a word you type in at the prompt. Is there a way to load the new tab in the background? I'd like to keep the focus on the page I'm looking at, and look at the search results later. There is an option "When I open a link in a new tab, switch to it immediately" in Firefox, this doesn't help. Edit: Note that this is for my use, so an answer that tells me how to change Firefox (3.0.11) settings to do this would work as well. Also I've tried the following modification, but it's still focusing the new tab. ``` javascript:Qr=document.getSelection();if(!Qr){void(Qr=prompt('%E8%AF%8D%E8%AF%AD',''))};if(Qr)(function(){var%20oldWin=this;window.open('http://nciku.com/search/all/'+Qr);oldWin.focus()})(); ``` Edit 2: Looking around to see if I can find an answer I see this guy who's got the opposite problem (new tabs don't get focus, but he wants them to have it), but with no resolution: [Possible to set tab focus in IE7 from JavaScript](https://stackoverflow.com/questions/72943/possible-to-set-tab-focus-in-ie7-from-javascript) There's apparently talk about a \_tab target in HTML 5, but that doesn't help me much. http:/ /forums.whatwg.org/viewtopic.php?t=185&highlight=tab+focus (apparently as a new user I can only post one link, so I've mauled it) This seems pretty broken browser behaviour if this is impossible.
In FireFox type about:config and change browser.tabs.loadDivertedInBackground to true. This has worked for me with browser bookmarklets. source: <http://lifehacker.com/263940/force-links-to-open-in-the-background>
Apparently this is only possible with previously opened windows, not the root window. > Calls to window.open with the same > window name as an already existing > window, loads the URL into that window > and gives a reference to the window > back. The window isn't given focus, > its opener property isn't changed, and > a third argument to window.open is > ignored. You can use the focus method > to give the window focus manually. ``` var oldWin = window.open("url.html","oldName"); oldWin.focus(); // give focus ```
Firefox javascript bookmarklet open tab in background
[ "", "javascript", "firefox", "background", "tabs", "bookmarklet", "" ]
Why this code does not write 0 as a last element but 18446744073709551615? (compiled with g++) ``` #include <iostream> using namespace std; int main(){ unsigned long long x = (unsigned long long) (-1); for(int i=0; i <= 64; i++) cout << i << " " << (x >> i) << endl; cout << (x >> 64) << endl; return 0; } ```
When you shift a value by more bits than word size, it **usually** gets shifted by `mod word-size`. Basically, shifting it by 64 means shifting by 0 bits which is equal to no shifting at all. You shouldn't rely on this though as it's not defined by the standard and it can be different on different architectures.
Shifting a number a number of bits that is equal to or larger than its width is undefined behavior. You can only safely shift a 64-bit integer between 0 and 63 positions.
64bit shift problem
[ "", "c++", "64-bit", "" ]
Hello i have a problem with c# Arrays. I need a array to store some data in there... My Code is that ``` double[] ATmittelMin; ATmittelMin[zaehlMittel] = Gradient(x, xATmax, y, yATmax); ``` But the compiler says: not defined var How can i define a double array without a fixed size ? Thanks a lot!
Arrays are always fixed in size, and have to be defined like so: ``` double[] items1 = new double[10]; // This means array is double[3] and cannot be changed without redefining it. double[] items2 = {1.23, 4.56, 7.89}; ``` The `List<T>` class uses an array in the background and redefines it when it runs out of space: ``` List<double> items = new List<double>(); items.Add(1.23); items.Add(4.56); items.Add(7.89); // This will give you a double[3] array with the items of the list. double[] itemsArray = items.ToArray(); ``` You can iterate through a `List<T>` just as you would an array: ``` foreach (double item in items) { Console.WriteLine(item); } // Note that the property is 'Count' rather than 'Length' for (int i = 0; i < items.Count; i++) { Console.WriteLine(items[i]); } ```
From what I see you did not declare the `zaehlMittel` variable. I guess this is what the compiler complains about. Apart from that, even though you can of course determine the value of that variable programmatically, the moment you want to create an array its size must be known. This is the way arrays work. In case you cannot do that easily, I suggest using some sort of dynamic datastructure, like a list or a set. Then, once all elements have been added, you are of course still free to create an array from that, as by that time you know the number of elements (even though there are convenience methods like `toArray()` that will even take care of that).
Define a double array without a fixed size?
[ "", "c#", "arrays", "list", "double", "" ]
Is there any justifiable reason to in Java something like ``` Long l = new Long(SOME_CONSTANT) ``` This creates an extra object and is tagged by FindBugs, and is obviously a bad practice. My question is whether there is ever a good reason to do so? I previously [asked this about String constructors and got a good answer](https://stackoverflow.com/questions/390703/what-is-the-purpose-of-the-expression-new-string-in-java), but that answer doesn't seem to apply to numbers.
Only if you want to make sure you get a unique instance, so practically never. Some numbers can be cached when autoboxed (although [`Longs` aren't guaranteed to be](http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#190730)), which might cause problems. But any code that would break because of caching probably has deeper issues. Right now, I can't think of a single valid case for it.
> My question is whether there is ever a good reason to do so? You might still use it if you want to write code compatible with older JREs. [valueOf(long)](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Long.html#valueOf(long)) was only introduced in Java 1.5, so in [Java 1.4](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Long.html#Long(long)) and before the constructor was the only way to go directly from a *long* to a *Long*. I expect it isn't deprecated because the constructor is still used internally.
Is there any justifiable reason to use new and a constructor on a number class in Java?
[ "", "java", "numbers", "constructor", "" ]
I have a website with the following files in the root folder: index.wml index.php How do I get it to open index.php if you are accessing via non-wap browsers, but open index.wml automatically when it is a wap browser. I suspect something must go in the .htaccess file?
take a look at this script: <http://tom.anu007.googlepages.com/wapredirect> lets you specify different redirects depending on browser. Josh
I would suggest that you use the [Mobile Device Browser File](http://mdbf.codeplex.com/). It's a database containing capability information for tons of known devices. Even though it was created to be used in ASP.NET applications, it's an XML file and thus you can use it from PHP as well (take a look at the file [schema](http://msdn.microsoft.com/en-us/library/ms228122.aspx)). I greatly recommend that you use capabilities to decide how to send content to the devices, instead of any simple "`if not desktop and not laptop then send_wap()`". Take a look at the [list of capabilities included](http://mdbf.codeplex.com/Wiki/View.aspx?title=capabilities&referringTitle=Home).
Make a site automatically choose between the WAP or normal version?
[ "", "php", "xml", "apache", "wap", "wml", "" ]
Wondering if anyone has experience and/or sample code for making DDE calls from Java. I've done DDE using win32 calls from the stddde library (DdeInitialize, DdeClientTransaction), and could write a JNI wrapper for this, but I was thinking that it might be nice to do it from [JNA](https://github.com/twall/jna/) I also have some concerns about the fact that DDE calls need to occur from a thread with message pump, and I'm not entirely certain of how to force that in Java. The calls we'll be doing are pretty simple (equivalent to VBA's DDInitiate, DDEExcecute and DDETerminate functions).
JNA now has a DDE implementation in its contrib repository (the compiled classes are available in the jna-platform artifact): <https://github.com/java-native-access/jna/blob/master/contrib/platform/src/com/sun/jna/platform/win32/DdemlUtil.java> The unit tests contain many usage examples: <https://github.com/java-native-access/jna/blob/master/contrib/platform/test/com/sun/jna/platform/win32/DdemlUtilTest.java>
<http://jdde.pretty-tools.com/>
Making DDE calls from Java
[ "", "java", "winapi", "native", "dde", "" ]
I'm using JPA (Hibernate implementation) to save objects to the database. Selecting works fine, but for some reason, saving doesn't work. I don't get any errors, but the database doesn't get changed either. This goes for both new entities and existing ones. ``` EPayment pay = new EPayment(); pay.setAmount(payment.getAmount()); ... pay.setUserByToUserId(receiver); CompayDAO.get().save(pay); ``` CompayDAO.save() ``` public void save(Object ent) { System.out.println("Persisting: " + ent + " using " + this); this.em.persist(ent); } ``` Console output: ``` Opening DOA nl.compay.entities.CompayDAO@b124fa Persisting: nl.compay.entities.EUser@1e2fe5d using nl.compay.entities.CompayDAO@b124fa Persisting: nl.compay.entities.EUser@30b601 using nl.compay.entities.CompayDAO@b124fa Persisting: nl.compay.entities.EPayment@ed3b53 using nl.compay.entities.CompayDAO@b124fa Closing DOA nl.compay.entities.CompayDAO@b124fa ``` EPayment ``` package nl.compay.entities; // Generated 21-mei-2009 12:27:07 by Hibernate Tools 3.2.2.GA import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * Payment generated by hbm2java */ @Entity @Table(name = "payment", catalog = "compay") public class EPayment implements java.io.Serializable { private static final long serialVersionUID = -2578493336948256566L; private Integer id; private EUser userByToUserId; private EUser userByFromUserId; private String description; private float amount; private String method; private Date paydate; public EPayment() { } public EPayment(EUser userByToUserId, EUser userByFromUserId, float amount, Date paydate) { this.userByToUserId = userByToUserId; this.userByFromUserId = userByFromUserId; this.amount = amount; this.paydate = paydate; } public EPayment(EUser userByToUserId, EUser userByFromUserId, String description, float amount, String method, Date paydate) { this.userByToUserId = userByToUserId; this.userByFromUserId = userByFromUserId; this.description = description; this.amount = amount; this.method = method; this.paydate = paydate; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "to_user_id", nullable = false) public EUser getUserByToUserId() { return this.userByToUserId; } public void setUserByToUserId(EUser userByToUserId) { this.userByToUserId = userByToUserId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "from_user_id", nullable = false) public EUser getUserByFromUserId() { return this.userByFromUserId; } public void setUserByFromUserId(EUser userByFromUserId) { this.userByFromUserId = userByFromUserId; } @Column(name = "description", length = 1024) public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } @Column(name = "amount", nullable = false, precision = 8) public float getAmount() { return this.amount; } public void setAmount(float amount) { this.amount = amount; } @Column(name = "method", length = 50) public String getMethod() { return this.method; } public void setMethod(String method) { this.method = method; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "paydate", nullable = false, length = 0) public Date getPaydate() { return this.paydate; } public void setPaydate(Date paydate) { this.paydate = paydate; } } ```
As Sherkaner mentioned, a save doesn't result in an INSERT or UPDATE directly. You have to flush the session or - better in my opinion - close the unit of work / commit the transaction. You do have transactions?
use `@Transactional` on your method..... ``` @Transactional public void save(Object ent){ ..... ..... } ```
JPA/Hibernate persist does not appear to work
[ "", "java", "hibernate", "jpa", "" ]
I like the concept of C++ namespaces, because they help to keep the source code concise while avoiding name conflicts. In .cpp files this works very well, using the "using namespace" declaration. However, in header files this cannot be used, as it "breaks open" the namespace, meaning that the "using namespace" not only applies within the current header file, but to everything that is compiled thereafter. This partly nullifies the advantage of namespaces. Consider for example a header file in which the classes "ourlib::networking::IpAddress" and "ourlib::filesystem::Path" are frequently used. Is there a way to limit the effect of the "using namespace"-declaration in header files?
No, it can't be done :(
You **may** put, most of frequently use classes in ::ourlib namespace like ``` namespace ourlib { using networking::lpAddress; } ``` So, if they unique in the project, most likely you would not have problem. So in, any place in headers you would be able access `lpAddress` directly without putting in into global namespace (I assume all your headers inside `namespace ourlib`)
Is there a way to limit the effect of "using namespace" directives in a header file?
[ "", "c++", "namespaces", "header-files", "using-directives", "" ]
I want to decode JPEG files and obtain uncompressed decoded output in BMP/RGB format.I am using GNU/Linux, and C/C++. I had a look at libjpeg, but there seemed not to be any good documentation available. So my questions are: 1. Where is documentation on libjpeg? 2. Can you suggest other C-based jpeg-decompression libraries?
The documentation for libjpeg comes with the source-code. Since you haven't found it yet: Download the source-code archive and open the file **libjpeg.doc**. It's a plain ASCII file, not a word document, so better open it in notepad or another ASCII editor. There are some other .doc files as well. Most of them aren't that interesting though. Unfortunately I cannot recommend any other library besides libjpeg. I tried a couple of alternatives, but Libjpeg always won. Is pretty easy to work with once you have the basics done. Also it's the most complete and most stable jpeg library out there.
MagickWand is the C API for ImageMagick: <http://imagemagick.org/script/magick-wand.php> I have not used it, but the documentation looks quite extensive.
Decode JPEG to obtain uncompressed data
[ "", "c++", "c", "linux", "jpeg", "decode", "" ]
Basically my dilemma is this. I have a list of x servers that host files. There is another server, that hosts the site's mysql db and application. When a file is uploaded (to the frontend server), the application checks to see which server has the most free space on it, and moves the file there. This works fine if you started with 2+ empty servers with identical amount of free space. If you introduce another server into the mix at a later point.... which will have more free space than the current servers, this method isnt so effective, because all the new files will be uploaded elusively to the new server, which would overload since it will be handling most of the new traffic till it catches up with the rest of the boxes in terms of free space. So I thought to introduce a weighting system as well, which will help normalize the distribution of files. So if the 3 servers are set at 33% each, and 1 server has significantly more free space, it would still get more uploads than the other servers (even though it has the same weight), but the load would be spread out over all the servers. Can anyone suggest a good php-only implementation of this?
One approach would be to sum all available space on all of the servers that have the space to hold the file (so a server with available space but not enough to hold the file would obviously be excluded). Then determine the percentage of that space that each server accounts for (so a new server would account for a proportionally larger percentage). Use a random number and align it with the percentages to determine which server to pick. For instance, consider having five servers with the following free space levels: ``` Server 1: 2048MB Server 2: 51400MB Server 3: 1134MB Server 4: 140555MB ``` You need to store a 1500MB file. That knocks Server 3 out of the running, leaving us with 194003MB total free space. ``` Server 1: 1.0% Server 2: 26.5% Server 4: 72.5% ``` You then choose a random number between 0 and 100: 40 ``` Numbers between 0 and 1 (inclusive) would go to Server 1 Numbers > 1 and <= 26.5 would go to Server 2 Numbers > 26.5 and <= 100 would go to Server 4 ``` So in this case, 40 means it gets stored on Server 4.
Traffic balancing is usually very crucial. You can add some sort of weighting system to balance it (although, as you say, the new server will still be overloaded more than the others), or some other alternating method where one server never gets hit twice in a row, just as an example. But I think I would probably artificially balance out the servers data so that they're almost equal to each other by moving content from one to the other, and then let the original or weighted/alternating algorithm do its job normally. That's not a php-only implementation, but just some ideas to consider.
Whats the best way to implement weighted random selection, based on 2 types variables (in php)?
[ "", "php", "weighting", "" ]
I have 3 classes named maths, alphabets and main. The Maths Class contains Add function and alphabet class contains a function same as Maths class. But the third class is for calling the function which is used for calling the above functions defined in the above classes. How it will work?
If the functions are static you'll have to explicitly tell which class they belong to - the compiler will be unable to resolve otherwise: ``` Maths.Add(); ``` If they are not static the compiler will determine this based on the object type: ``` Maths maths = new Maths(); maths.Add(); // the necessary class and function will be resolved automatically ```
Is this what you mean? ``` public class Maths { public Maths() { } public Double Add(Double numberOne, Double numberTwo) { return numberOne + numberTwo; } } public class Alphabet { public Alaphabet() { } public String Add(Char characterOne, Char characterTwo) { return characterOne.ToString() + characterTwo.ToString(); } } public void Main() { Alphabet alaphatbet = new Alphabet(); String alphaAdd = alphabet.Add('a', 'b'); // Gives "ab" Maths maths = new Maths(); Double mathsAdd = maths.Add(10, 5); // Gives 15 } ```
classes and functions
[ "", "c#", "class", "" ]
I am using VSTS 2008 + C# + .NET 3.0. I am using a self-hosted WCF service. When executing the following statement, there is the following "binding not found" error. I have posted my whole app.config file, any ideas what is wrong? ``` ServiceHost host = new ServiceHost(typeof(MyWCFService)); ``` Error message: > Could not find a base address that matches scheme http for the > endpoint with binding MetadataExchangeHttpBinding. Registered base > address schemes are [https]. Full app.config: ``` <?xml version="1.0"?> <configuration> <system.serviceModel> <bindings> <wsHttpBinding> <binding name="MyBinding" closeTimeout="00:00:10" openTimeout="00:00:20" receiveTimeout="00:00:30" sendTimeout="00:00:40" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="WeakWildcard" maxReceivedMessageSize="100000000" messageEncoding="Mtom" proxyAddress="http://foo/bar" textEncoding="utf-16" useDefaultWebProxy="false"> <reliableSession ordered="false" inactivityTimeout="00:02:00" enabled="true" /> <security mode="Transport"> <transport clientCredentialType="Digest" proxyCredentialType="None" realm="someRealm" /> </security> </binding> </wsHttpBinding> </bindings> <services> <service name="MyWCFService" behaviorConfiguration="mexServiceBehavior"> <host> <baseAddresses> <add baseAddress="https://localhost:9090/MyService"/> </baseAddresses> </host> <endpoint address="" binding="wsHttpBinding" bindingConfiguration="MyBinding" contract="IMyService"/> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="mexServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> <startup><supportedRuntime version="v2.0.50727"/></startup></configuration> ```
The base address for your service defines "HTTPS://" - but your mex address is "HTTP". If you want your service to use https://, you'll need to use the **mexHttpsBinding** as well: ``` <services> <service name="MyWCFService" behaviorConfiguration="mexServiceBehavior"> <host> <baseAddresses> <add baseAddress="https://localhost:9090/MyService"/> </baseAddresses> </host> <endpoint address="" binding="wsHttpBinding" bindingConfiguration="MyBinding" contract="IMyService" /> <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" /> </service> </services> ``` Marc
Can I go for the double score? :) As you're using WS-Http you are binding to an HTTPS protocol, so you need to use the correct MEX binding; ``` <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" /> ```
mex binding error in WCF
[ "", "c#", ".net", "wcf", "visual-studio-2008", "wshttpbinding", "" ]
In C# i am doing ``` context.Response.ContentType = "image/png"; context.RewritePath(sz); context.Response.ContentType = "image/png"; ``` It seems to redirect the path as i can see see images on my pages. However in firefox when i right click and select "view image" i get a download. Using this c++ code i can see the mime being application/octet-stream ``` #include <curl/curl.h> #include <ios> #include <iostream> #include <string> #pragma comment(lib, "curllib") using namespace std; size_t function( void *ptr, size_t size, size_t nmemb, void *stream) { cout << (char*)ptr; return size*nmemb; } size_t function2( void *ptr, size_t size, size_t nmemb, void *stream) { return size*nmemb; } int main() { CURL *c = curl_easy_init(); curl_easy_setopt(c, CURLOPT_HEADERFUNCTION, function); curl_easy_setopt(c, CURLOPT_WRITEHEADER , 1); curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, function2); curl_easy_setopt(c, CURLOPT_WRITEDATA, 0); curl_easy_setopt(c, CURLOPT_URL, "http://localhost:3288/s/main/4/AAA.png"); curl_easy_perform(c); curl_easy_cleanup(c); return 0; } ``` My question is how do i set the mime to the correct type? Above i hardcode it to png which doesnt work. However i rather not hardcode any mime and have it work. I was able to redirect an XML file to somefile.aspx and have that the page set the content type and generate the XML. However rewriting to the image path seems to let the image work i just dont get the correct type. How do i correct the content/mime type? As plan B i'll rewrite to a aspx file. Whats the best way to send an image? Could i do something like context.Response.OutputStream=stream("filename"); ?
When you use `RewritePath`, whatever you have written to the head is discarded. Whatever is handling the new path is providing the header. If you want to specify the content type, you can't use `RewritePath`. Instead you can use `Response.BinaryWrite` or `Response.WriteFile` to output the file data to the response stream after setting the header.
Check out: [Create PNG image with C# HttpHandler webservice](https://stackoverflow.com/questions/887985/create-png-image-with-c-httphandler-webservice/888039) It should give you an example of dumping a PNG into the response.
ContentType doesnt work, mime=application/octet-stream
[ "", "c#", "asp.net", "content-type", "mime-types", "" ]
I have 60k items that need to be checked against a 20k lookup list. Is there a collection object (like `List`, `HashTable`) that provides an exceptionly fast `Contains()` method? Or will I have to write my own? In otherwords, is the default `Contains()` method just scan each item or does it use a better search algorithm. ``` foreach (Record item in LargeCollection) { if (LookupCollection.Contains(item.Key)) { // Do something } } ``` **Note**. The lookup list is already sorted.
In the most general case, consider [`System.Collections.Generic.HashSet`](http://msdn.microsoft.com/en-us/library/bb359438.aspx) as your default "Contains" workhorse data structure, because it takes constant time to evaluate `Contains`. The actual answer to "What is the fastest searchable collection" depends on your specific data size, ordered-ness, cost-of-hashing, and search frequency.
If you don't need ordering, try `HashSet<Record>` (new to .Net 3.5) If you do, use a `List<Record>` and call `BinarySearch`.
What .NET collection provides the fastest search
[ "", "c#", ".net", "search", "collections", "" ]
I am connecting to a SQL Server database via LINQ in my ASP.NET application (returning results to a web service). The problem is that it only returns results when I'm running it in debug/test mode - When I publish the service I get an error telling me "Login failed for user 'NT AUTHORITY\NETWORK SERVICE' " So how do I set / provide the credentials I want the site to use to log into SQL Server? Thanks in advance for any help
A few questions first 1. Is the SQL server on the same machine? 2. If it's on a different machine is it in a domain? 3. Are you using a full SQL installation, or SQL Express? I'm going to assume you're using a full version of SQL, because if you're using SQL Express user instances will not give you this problem. If it's on the same machine then you need to add Network Service to the list of allowed users in SQL. To do this start SQL Management studio, expand the security folder, then right click on Logins and choose New Login. Click search on the "Login - New" dialog, making sure Windows Authentication is selected then enter Network Service in the object name box and click Ok. Choose the database you want it to access from the drop down list in the Login - new page and click ok. Finally expand out the databases folder and for each database you wish to grant access to expand out security, right click on users, then select the network service login name, give it a name in the dialog of Network Service and grant it the right access by checking the role in the Database role membership list. If you're messing around db\_owner will be fine, you will want to lock this down later. If the SQL server is on a different box and you are in a domain you can run the application pool as a domain user and grant that access on the SQL box. How to do this varies on the version of IIS. Finally you can use SQL logins and passwords if the SQL server is configured to do this. Create a SQL user and then add them to the connection string like so ``` Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword; ```
You have to set the credentials in the connection string. It's possible that the connection string to use on the server will be different than the credentials to use during Development. Ask your DBA which credentials you should use.
LINQ in ASP.NET -- throws exception when deployed to the server
[ "", "c#", "asp.net", "sql-server", "linq", "" ]
I found this [snippet](http://www.c-sharpcorner.com/UploadFile/mahesh/RandomNumber11232005010428AM/RandomNumber.aspx) of code that generates a string of random characters. But is there a more elegant/faster/more reliable way to do this? This seems to rely on the fact that the numbers 26-91 are valid characters given the current encoding. ``` /// <summary> /// Generates a random string with the given length /// </summary> /// <param name="size">Size of the string</param> /// <param name="lowerCase">If true, generate lowercase string</param> /// <returns>Random string</returns> private string RandomString(int size, bool lowerCase) { StringBuilder builder = new StringBuilder(); Random random = new Random(); char ch; for(int i = 0; i < size; i++) { ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); builder.Append(ch); } if(lowerCase) return builder.ToString().ToLower(); return builder.ToString(); } ```
I'd prefer to pass the `Random` instance into the method - then you can reuse the same instance multiple times, which is important if you need to generate lots of random strings in quick succession. However, I'd also modify it somewhat anyway: ``` public const string LowerCaseAlphabet = "abcdefghijklmnopqrstuvwyxz"; public const string UpperCaseAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static string GenerateUpperCaseString(int size, Random rng) { return GenerateString(size, rng, UpperCaseAlphabet); } public static string GenerateLowerCaseString(int size, Random rng) { return GenerateString(size, rng, LowerCaseAlphabet); } public static string GenerateString(int size, Random rng, string alphabet) { char[] chars = new char[size]; for (int i=0; i < size; i++) { chars[i] = alphabet[rng.Next(alphabet.Length)]; } return new string(chars); } ``` * There's no need to use a StringBuilder when you know the final length * Using `Random.NextDouble()` indicates a lack of knowledge of the Random class. (In particular `Random.Next(int, int)` * Creating a new Random on each call is likely to result in duplicate strings * Calling Convert.ToInt32 and Convert.ToChar seems ugly compared with just casting * Lower-casing *afterwards* seems pointless compared with picking lower case letters to start with * Providing an alphabet to pick from is a lot more flexible (with helper methods for common cases)
If I were to do this (and I have, but in Java, squirreled away somewhere), I would provide an array of allowable characters, and use a RNG simply to pick the index of the character. This would also let you disallow characters you don't want to generate (if you're creating a human-enterable license key, you don't want to generate characters that can be confused with each other; 0 and O, for instance, or 1 and l). **EDIT**: yeah, like what Jon did...
Is this a good way to generate a string of random characters?
[ "", "c#", "string", "random", "" ]
Expect is a module used for spawning child applications and controlling them. I'm interested in Python and Ruby.
There is [WExpect for Python](https://pypi.org/project/wexpect/). Notes in the `wexpect.py` file (typos unchanged and highlighting added) > **Wexpect** is a port of pexpext to Windows. Since python for Windows lacks > the requisite modules (pty, tty, select, termios, fctnl, and resource) to run > pexpect, it was necessary to create a back-end that implemented any functions > that were used that relied on these modules. **Wtty.py** is this back-end. In > the Windows world consoles are not homogeneous. They can use low level or high > level input and output functions, and to correctly deal with both cases two > child processes are created for instacne of Spawn, with an intermidate child > that can continuously read from the console, and send that data over a pipe > to an instance of wtty. **Spawner.py** is resposible from reading and piping > data. > > I've left as much code intact as I could and also tried to leave as many comments > intact is possible (espicially for functions that have not been changed) so many > of the comments will be misleading in their relationship to os specific > functionality. Also, **the functions sendcontrol and sendeof are unimplemnted at > this time, as I could not find meaningful Windows versions of these functions.** > additionally, consoles do not have associated fild descriptors on Windows, so the > global variable child\_fd will always be None.
`winpexpect` is a native port of `pexpect` to Windows. It can be found here: <https://github.com/geertj/winpexpect>
Can I use Expect on Windows without installing Cygwin?
[ "", "python", "ruby", "expect", "" ]
I have a class I've marked as Serializable, with a Uri property. How can I get the Uri to serialize/Deserialize without making the property of type string?
Based on one of the answers for [how to serialize `TimeSpan`](https://stackoverflow.com/questions/637933/net-how-to-serialize-a-timespan-to-xml) I ended up with this which works quite well for me and doesn't require the additional property: ``` public class XmlUri : IXmlSerializable { private Uri _Value; public XmlUri() { } public XmlUri(Uri source) { _Value = source; } public static implicit operator Uri(XmlUri o) { return o == null ? null : o._Value; } public static implicit operator XmlUri(Uri o) { return o == null ? null : new XmlUri(o); } public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { _Value = new Uri(reader.ReadElementContentAsString()); } public void WriteXml(XmlWriter writer) { writer.WriteValue(_Value.ToString()); } } ``` Then you can use it like this ``` public class Settings { public XmlUri Uri { get; set; } } ... var s = new Settings { Uri = new Uri("http://www.example.com") }; ``` And it will nicely serialize and deserialize. Note: Can't use the trick with the `XmlElement(Type = typeof(...))` attribute as given in another answer in the above linked question as the `XmlSerializer` checks for an empty default constructor first on the original type.
With xml serializer, you are limited - it isn't as versatile as (say) some of the binaryformatter/`ISerializable` options. One frequent trick is to have a second property for serialization: ``` [XmlIgnore] public Uri Uri {get;set;} [XmlAttribute("uri")] [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public string UriString { get {return Uri == null ? null : Uri.ToString();} set {Uri = value == null ? null : new Uri(value);} } ``` The two browsable attributes hide it from view (but it needs to be on the public API for `XmlSerializer` to use it). The `XmlIgnore` tells it not to try the `Uri`; and the `[XmlAttribute(...)]` (or `[XmlElement(...)]`) tells it to rename `UriString` when (de)serializing it. (note that `EditorBrowsable` only applies to code outside the assembly declaring the type)
How to (xml) serialize a uri
[ "", "c#", ".net", "xml-serialization", "" ]
I was just reading [this question](https://stackoverflow.com/questions/954417/make-alias-to-document-getelementbyid-in-javascript) and wanted to try the alias method rather than the function-wrapper method, but I couldn't seem to get it to work in either Firefox 3 or 3.5beta4, or Google Chrome, both in their debug windows and in a test web page. Firebug: ``` >>> window.myAlias = document.getElementById function() >>> myAlias('item1') >>> window.myAlias('item1') >>> document.getElementById('item1') <div id="item1"> ``` If I put it in a web page, the call to myAlias gives me this error: ``` uncaught exception: [Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "JS frame :: file:///[...snip...]/test.html :: <TOP_LEVEL> :: line 7" data: no] ``` Chrome (with >>>'s inserted for clarity): ``` >>> window.myAlias = document.getElementById function getElementById() { [native code] } >>> window.myAlias('item1') TypeError: Illegal invocation >>> document.getElementById('item1') <div id=?"item1">? ``` And in the test page, I get the same "Illegal invocation". Am I doing something wrong? Can anyone else reproduce this? Also, oddly enough, I just tried and it works in IE8.
You have to bind that method to the document object. Look: ``` >>> $ = document.getElementById getElementById() >>> $('bn_home') [Exception... "Cannot modify properties of a WrappedNative" ... anonymous :: line 72 data: no] >>> $.call(document, 'bn_home') <body id="bn_home" onload="init();"> ``` When you’re doing a simple alias, the function is called on the global object, not on the document object. Use a technique called closures to fix this: ``` function makeAlias(object, name) { var fn = object ? object[name] : null; if (typeof fn == 'undefined') return function () {} return function () { return fn.apply(object, arguments) } } $ = makeAlias(document, 'getElementById'); >>> $('bn_home') <body id="bn_home" onload="init();"> ``` This way you don’t loose the reference to the original object. In 2012, there is the new `bind` method from ES5 that allows us to do this in a fancier way: ``` >>> $ = document.getElementById.bind(document) >>> $('bn_home') <body id="bn_home" onload="init();"> ```
I dug deep to understand this particular behavior and I think I have found a good explanation. Before I get in to why you are not able to alias `document.getElementById`, I will try to explain how JavaScript functions/objects work. Whenever you invoke a JavaScript function, the JavaScript interpreter determines a scope and passes it to the function. Consider following function: ``` function sum(a, b) { return a + b; } sum(10, 20); // returns 30; ``` This function is declared in the Window scope and when you invoke it the value of `this` inside the sum function will be the global `Window` object. For the 'sum' function, it doesn't matter what the value of 'this' is as it is not using it. --- Consider following function: ``` function Person(birthDate) { this.birthDate = birthDate; this.getAge = function() { return new Date().getFullYear() - this.birthDate.getFullYear(); }; } var dave = new Person(new Date(1909, 1, 1)); dave.getAge(); //returns 100. ``` When you call dave.getAge function, the JavaScript interpreter sees that you are calling getAge function on the `dave` object, so it sets `this` to `dave` and calls the `getAge` function. `getAge()` will correctly return `100`. --- You may know that in JavaScript you can specify the scope using the `apply` method. Let's try that. ``` var dave = new Person(new Date(1909, 1, 1)); //Age 100 in 2009 var bob = new Person(new Date(1809, 1, 1)); //Age 200 in 2009 dave.getAge.apply(bob); //returns 200. ``` In the above line, instead of letting JavaScript decide the scope, you are passing the scope manually as the `bob` object. `getAge` will now return `200` even though you 'thought' you called `getAge` on the `dave` object. --- What's the point of all of the above? Functions are 'loosely' attached to your JavaScript objects. E.g. you can do ``` var dave = new Person(new Date(1909, 1, 1)); var bob = new Person(new Date(1809, 1, 1)); bob.getAge = function() { return -1; }; bob.getAge(); //returns -1 dave.getAge(); //returns 100 ``` --- Let's take the next step. ``` var dave = new Person(new Date(1909, 1, 1)); var ageMethod = dave.getAge; dave.getAge(); //returns 100; ageMethod(); //returns ????? ``` `ageMethod` execution throws an error! What happened? If you read my above points carefully, you would note that `dave.getAge` method was called with `dave` as `this` object whereas JavaScript could not determine the 'scope' for `ageMethod` execution. So it passed global 'Window' as 'this'. Now as `window` doesn't have a `birthDate` property, `ageMethod` execution will fail. How to fix this? Simple, ``` ageMethod.apply(dave); //returns 100. ``` --- Did all of the above make sense? If it does, then you will be able to explain why you are not able to alias `document.getElementById`: ``` var $ = document.getElementById; $('someElement'); ``` `$` is called with `window` as `this` and if `getElementById` implementation is expecting `this` to be `document`, it will fail. Again to fix this, you can do ``` $.apply(document, ['someElement']); ``` So why does it work in Internet Explorer? I don't know the internal implementation of `getElementById` in IE, but a comment in jQuery source (`inArray` method implementation) says that in IE, `window == document`. If that's the case, then aliasing `document.getElementById` should work in IE. To illustrate this further, I have created an elaborate example. Have a look at the `Person` function below. ``` function Person(birthDate) { var self = this; this.birthDate = birthDate; this.getAge = function() { //Let's make sure that getAge method was invoked //with an object which was constructed from our Person function. if(this.constructor == Person) return new Date().getFullYear() - this.birthDate.getFullYear(); else return -1; }; //Smarter version of getAge function, it will always refer to the object //it was created with. this.getAgeSmarter = function() { return self.getAge(); }; //Smartest version of getAge function. //It will try to use the most appropriate scope. this.getAgeSmartest = function() { var scope = this.constructor == Person ? this : self; return scope.getAge(); }; } ``` For the `Person` function above, here's how the various `getAge` methods will behave. Let's create two objects using `Person` function. ``` var yogi = new Person(new Date(1909, 1,1)); //Age is 100 var anotherYogi = new Person(new Date(1809, 1, 1)); //Age is 200 ``` --- ``` console.log(yogi.getAge()); //Output: 100. ``` Straight forward, getAge method gets `yogi` object as `this` and outputs `100`. --- ``` var ageAlias = yogi.getAge; console.log(ageAlias()); //Output: -1 ``` JavaScript interepreter sets `window` object as `this` and our `getAge` method will return `-1`. --- ``` console.log(ageAlias.apply(yogi)); //Output: 100 ``` If we set the correct scope, you can use `ageAlias` method. --- ``` console.log(ageAlias.apply(anotherYogi)); //Output: 200 ``` If we pass in some other person object, it will still calculate age correctly. ``` var ageSmarterAlias = yogi.getAgeSmarter; console.log(ageSmarterAlias()); //Output: 100 ``` The `ageSmarter` function captured the original `this` object so now you don't have to worry about supplying correct scope. --- ``` console.log(ageSmarterAlias.apply(anotherYogi)); //Output: 100 !!! ``` The problem with `ageSmarter` is that you can never set the scope to some other object. --- ``` var ageSmartestAlias = yogi.getAgeSmartest; console.log(ageSmartestAlias()); //Output: 100 console.log(ageSmartestAlias.apply(document)); //Output: 100 ``` The `ageSmartest` function will use the original scope if an invalid scope is supplied. --- ``` console.log(ageSmartestAlias.apply(anotherYogi)); //Output: 200 ``` You will still be able to pass another `Person` object to `getAgeSmartest`. :)
JavaScript function aliasing doesn't seem to work
[ "", "javascript", "function", "closures", "alias", "" ]
``` MyControl.Margin.Left = 10; ``` Error: > Cannot modify the return value of 'System.Windows.FrameworkElement.Margin' because it is not a variable
The problem is that [`Margin`](http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.margin.aspx) is a property, and its type ([`Thickness`](http://msdn.microsoft.com/en-us/library/system.windows.thickness.aspx)) is a value type. That means when you access the property you're getting a *copy* of the value back. Even though you *can* change the value of the [`Thickness.Left`](http://msdn.microsoft.com/en-us/library/system.windows.thickness.left.aspx) property for a particular value (grr... mutable value types shouldn't exist), it wouldn't change the margin. Instead, you'll need to set the `Margin` property to a new value. For instance (coincidentally the same code as Marc wrote): ``` Thickness margin = MyControl.Margin; margin.Left = 10; MyControl.Margin = margin; ``` As a note for library design, I would have vastly preferred it if `Thickness` were immutable, but with methods that returned a new value which was a copy of the original, but with one part replaced. Then you could write: ``` MyControl.Margin = MyControl.Margin.WithLeft(10); ``` No worrying about odd behaviour of mutable value types, nice and readable, all one expression...
The `Margin` property returns a `Thickness` structure, of which `Left` is a property. What the statement does is copying the structure value from the `Margin` property and setting the `Left` property value on the copy. You get an error because the value that you set will not be stored back into the `Margin` property. (Earlier versions of C# would just let you do it without complaining, causing a lot of questions in newsgroups and forums on why a statement like that had no effect at all...) To set the property you would need to get the `Thickness` structure from the `Margin` property, set the value and store it back: ``` Thickness m = MyControl.Margin; m.Left = 10; MyControl.Margin = m; ``` If you are going to set all the margins, just create a `Thickness` structure and set them all at once: ``` MyControl.Margin = new Thickness(10, 10, 10, 10); ```
Setting Margin Properties in code
[ "", "c#", "wpf", "margin", "" ]
Long story short, I have two regex patterns. One pattern matches things that I want to replace, and the other pattern matches a special case of those patterns that should not be replace. For a simple example, imagine that the first one is "\{.\*\}" and the second one is "\{\{.\*\}\}". Then "{this}" should be replaced, but "{{this}}" should not. Is there an easy way to take a string and say "substitute all instances of the first string with "hello" so long as it is not matching the second string"? In other words, is there a way to make a regex that is "matches the first string but not the second" easily without modifying the first string? I know that I could modify my first regex by hand to never match instances of the second, but as the first regex gets more complex, that gets very difficult.
You can give replace a function ([reference](http://docs.python.org/howto/regex.html#search-and-replace)) But make sure the first regex contain the second one. This is just an example: ``` regex1 = re.compile('\{.*\}') regex2 = re.compile('\{\{.*\}\}') def replace(match): match = match.group(0) if regex2.match(match): return match return 'replacement' regex1.sub(replace, data) ```
Using negative look-ahead/behind assertion ``` pattern = re.compile( "(?<!\{)\{(?!\{).*?(?<!\})\}(?!\})" ) pattern.sub( "hello", input_string ) ``` Negative look-ahead/behind assertion allows you to compare against more of the string, but is not considered as using up part of the string for the match. There is also a normal look ahead/behind assertion which will cause the string to match only if the string IS followed/preceded by the given pattern. That's a bit confusing looking, here it is in pieces: ``` "(?<!\{)" #Not preceded by a { "\{" #A { "(?!\{)" #Not followed by a { ".*?" #Any character(s) (non-greedy) "(?<!\})" #Not preceded by a } (in reference to the next character) "\}" #A } "(?!\})" #Not followed by a } ``` So, we're looking for a { without any other {'s around it, followed by some characters, followed by a } without any other }'s around it. By using negative look-ahead/behind assertion, we condense it down to a single regular expression which will successfully match only single {}'s anywhere in the string. Also, note that \* is a greedy operator. It will match as much as it possibly can. If you use `"\{.*\}"` and there is more than one {} block in the text, everything between will be taken with it. > "This is some example text {block1} more text, watch me disappear {block2} even more text" becomes > "This is some example text hello even more text" instead of > "This is some example text hello more text, watch me disappear hello even more text" To get the proper output we need to make it non-greedy by appending a ?. The python docs do a good job of presenting the re library, but the only way to really learn is to experiment.
Substituting a regex only when it doesn't match another regex (Python)
[ "", "python", "regex", "" ]
How can I create a war file of my project in NetBeans?
It's possible that you already have a war file and don't know it - netbeans does most of the work for you and I believe it creates a distributable war file by default. If you created a web project and successfully built it, it will be in the "dist" directory off your project root.
As DPA says, the easiest way to generate a war file of your project is through the IDE. Open the Files tab from your left hand panel, right click on the build.xml file and tell it what type of ant target you want to run. ![NetBeans - Create a WAR file](https://i.stack.imgur.com/6Kh8q.png)
How can I create a war file of my project in NetBeans?
[ "", "java", "jsp", "netbeans", "" ]
I'm looking to create a form where pressing the enter key causes focus to go to the "next" form element on the page. The solution I keep finding on the web is... ``` <body onkeydown="if(event.keyCode==13){event.keyCode=9; return event.keyCode}"> ``` Unfortunately, that only seems to work in IE. So the real meat of this question is if anybody knows of a solution that works for FF and Chrome? Additionally, I'd rather not have to add *onkeydown* events to the form elements themselves, but if that's the only way, it will have to do. This issue is similar to [question 905222](https://stackoverflow.com/questions/905222/javascriptenter-key-press-event), but deserving of it's own question in my opinion. Edit: also, I've seen people bring up the issue that this isn't good style, as it diverges from form behavior that users are used to. I agree! It's a client request :(
I used the logic suggested by Andrew which is very effective. And this is my version: ``` $('body').on('keydown', 'input, select', function(e) { if (e.key === "Enter") { var self = $(this), form = self.parents('form:eq(0)'), focusable, next; focusable = form.find('input,a,select,button,textarea').filter(':visible'); next = focusable.eq(focusable.index(this)+1); if (next.length) { next.focus(); } else { form.submit(); } return false; } }); ``` KeyboardEvent's keycode (i.e: `e.keycode`) depreciation notice :- <https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode>
The simplest vanilla JS snippet I came up with: ``` document.addEventListener('keydown', function (event) { if (event.keyCode === 13 && event.target.nodeName === 'INPUT') { var form = event.target.form; var index = Array.prototype.indexOf.call(form, event.target); form.elements[index + 1].focus(); event.preventDefault(); } }); ``` Works in IE 9+ and modern browsers.
Enter key press behaves like a Tab in Javascript
[ "", "javascript", "html", "cross-browser", "dom-events", "" ]
Im creating a custom template. On the front page I want to display an article and a readmore link. The article is called "Article 1" and is in the section "Test" catagory "Cat". Its access level is public. How can i show the first 100 words of the article, and its title, on the front page and have a readmore link under it which will point to the full article. I tried using a mod\_newsflash but it just doesnt show the readmore link. I am using Joomla 1.5. Thx
I use the same mod\_newsflash on a couple of sites and have had no problems so far. It's very important that you activate the "Read more... Link" option to "Show" under "Module - Edit -> Parameters". Another thing is that your article must have exactly one "Read more..." on your desired position. Where do you find this "Read more..." thing? Just go to your article, edit it and down there next to "Image", "Pagebreak" should be this button. If you really want it to always break exactly after 100 words or after a specific amount of characters, I think you need to come up with something on your own. For example: Just take the whole article, use strip\_tags() to get the pure text and after that just split(" ", $input, 100)/implode(" ", $input) the text. Good luck!
There is a extension named auto readmore wich does exactly what you need
Joomla Readmore Link To Article
[ "", "php", "joomla", "joomla1.5", "" ]
I have a div which has width of say 200px. It does not show horizontal scroll bar. Now if anyone types any word more than 200px worth, it is simply hidden. I am wondering if its possible to automatically put a newline tag after every word reaches 200px length? Thank you for your time.
You can achive this using simple CSS using ``` WORD-BREAK: break-ALL. <div style="width: 200px; word-break: break-all">Content goes here</div> ``` Hope this is what you were looking for...
It's a tricky problem, but you should probably read <http://www.quirksmode.org/oddsandends/wbr.html>. basically, there is somewhat inconsistent support and the linked article proposes use of: ``` wbr:after { content: "\00200B" } ``` in your css, and using the `<wbr/>` tag in your html
Break long text
[ "", "javascript", "" ]
I've a Java object 'ChildObj' which is extended from 'ParentObj'. Now, if it is possible to retrieve all the attribute names and values of ChildObj, including the inherited attributes too, using Java reflection mechanism? [Class.getFields](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getFields()) gives me the array of public attributes, and [Class.getDeclaredFields](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getDeclaredFields()) gives me the array of all fields, but none of them includes the inherited fields list. Is there any way to retrieve the inherited attributes also?
no, you need to write it yourself. It is a simple recursive method called on [Class.getSuperClass()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getSuperclass()): ``` public static List<Field> getAllFields(List<Field> fields, Class<?> type) { fields.addAll(Arrays.asList(type.getDeclaredFields())); if (type.getSuperclass() != null) { getAllFields(fields, type.getSuperclass()); } return fields; } @Test public void getLinkedListFields() { System.out.println(getAllFields(new LinkedList<Field>(), LinkedList.class)); } ```
``` public static List<Field> getAllFields(Class<?> type) { List<Field> fields = new ArrayList<Field>(); for (Class<?> c = type; c != null; c = c.getSuperclass()) { fields.addAll(Arrays.asList(c.getDeclaredFields())); } return fields; } ```
Retrieving the inherited attribute names/values using Java Reflection
[ "", "java", "reflection", "introspection", "" ]
Lets say we have this interface: ``` public interface ILog { void Add(Message message); } ``` It should of course also have some way of accessing those added messages. But what do you think is more natural and correct? That ILog implements IEnumerable property? Or maybe both? Or will having both be a bit weird and unecessary? Or should it maybe be an IEnumerator instead of IEnumerable? (Or that is maybe completely wrong? Haven't quite grasped the difference between those...) ``` public interface ILog : IEnumerable<Message> { void Add(Message message); } public interface ILog { IEnumerable<Message> Messages { get; } void Add(Message message); } public interface ILog : IEnumerable<Message> { IEnumerable<Message> Messages { get; } void Add(Message message); } ``` This is of course probably a bit subjective, but I would like to hear others opinion. I don't really know, nor have I anyone else to ask :p
I'd suggest that `ILog` shouldn't have an enumerator at all - the code that is doing the logging has no need to enumerate through all of the messages. The key is that one class can implement multiple interfaces - so you can (and *should*) keep each interface focussed on a particular use. So, I'd create a second interface (say, `ILogStore`) that implements an enumerator of the messages: ``` public interface ILogStore { IEnumerable<LogMessage> GetMessages(); } ``` I'd make this a member function to allow for possible future overloads. Say, you want to get all of the log messages from a particular subsystem: ``` public interface ILogStore { IEnumerable<LogMessage> GetMessages(); IEnumerable<LogMessage> GetMessagesBySubsystem(string subsystem); } ``` and so on.
Going the .NET Framework way, you should define a collection-class ("MessageCollection") that inherits from Collection{T}. This provides the functionality to add or remove messages and implements the interface IEnumerable{T} . Your interface should define a read-only property "Message" that returns an instance of your defined collection-class. ``` public interface ILog { MessageCollection Messages {get;} void AddMessage(Message message); // Additional method. } public class MessageCollection : Collection<Message>{ // Addional methods. } ```
C#: Should an ILog interface be or have an IEnumerable<Message>?
[ "", "c#", "interface", "" ]
I need to change the primary key of a table to an identity column, and there's already a number of rows in table. I've got a script to clean up the IDs to ensure they're sequential starting at 1, works fine on my test database. What's the SQL command to alter the column to have an identity property?
You can't alter the existing columns for identity. You have 2 options, 1. Create a new table with identity & drop the existing table 2. Create a new column with identity & drop the existing column Approach 1. (*New table*) Here you can retain the existing data values on the newly created identity column. Note that you will lose all data if 'if not exists' is not satisfied, so make sure you put the condition on the drop as well! ``` CREATE TABLE dbo.Tmp_Names ( Id int NOT NULL IDENTITY(1, 1), Name varchar(50) NULL ) ON [PRIMARY] go SET IDENTITY_INSERT dbo.Tmp_Names ON go IF EXISTS ( SELECT * FROM dbo.Names ) INSERT INTO dbo.Tmp_Names ( Id, Name ) SELECT Id, Name FROM dbo.Names TABLOCKX go SET IDENTITY_INSERT dbo.Tmp_Names OFF go DROP TABLE dbo.Names go Exec sp_rename 'Tmp_Names', 'Names' ``` Approach 2 (*New column*) You can’t retain the existing data values on the newly created identity column, The identity column will hold the sequence of number. ``` Alter Table Names Add Id_new Int Identity(1, 1) Go Alter Table Names Drop Column ID Go Exec sp_rename 'Names.Id_new', 'ID', 'Column' ``` See the following Microsoft SQL Server Forum post for more details: [How to alter column to identity(1,1)](http://social.msdn.microsoft.com/forums/en-US/transactsql/thread/04d69ee6-d4f5-4f8f-a115-d89f7bcbc032)
In SQL 2005 and above, there's a trick to solve this problem without changing the table's data pages. This is important for large tables where touching every data page can take minutes or hours. The trick also works even if the identity column is a primary key, is part of a clustered or non-clustered index, or other gotchas which can trip up the the simpler "add/remove/rename column" solution. Here's the trick: you can use SQL Server's [ALTER TABLE...SWITCH](https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-table-transact-sql) statement to change the schema of a table without changing the data, meaning you can replace a table with an IDENTITY with an identical table schema, but without an IDENTITY column. The same trick works to add IDENTITY to an existing column. Normally, [ALTER TABLE...SWITCH](https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-table-transact-sql) is used to efficiently replace a full partition in a partitioned table with a new, empty partition. But it can also be used in non-partitioned tables too. I've used this trick to convert, in under 5 seconds, a column of a 2.5 billion row table from IDENTITY to a non-IDENTITY (in order to run a multi-hour query whose query plan worked better for non-IDENTITY columns), and then restored the IDENTITY setting, again in less than 5 seconds. Here's a code sample of how it works. ``` CREATE TABLE Test ( id int identity(1,1), somecolumn varchar(10) ); INSERT INTO Test VALUES ('Hello'); INSERT INTO Test VALUES ('World'); -- copy the table. use same schema, but no identity CREATE TABLE Test2 ( id int NOT NULL, somecolumn varchar(10) ); ALTER TABLE Test SWITCH TO Test2; -- drop the original (now empty) table DROP TABLE Test; -- rename new table to old table's name EXEC sp_rename 'Test2','Test'; -- update the identity seed DBCC CHECKIDENT('Test'); -- see same records SELECT * FROM Test; ``` This is obviously more involved than the solutions in other answers, but if your table is large this can be a real life-saver. There are some caveats: * As far as I know, identity is the only thing you can change about your table's columns with this method. Adding/removing columns, changing nullability, etc. isn't allowed. * You'll need to drop foriegn keys before you do the switch and restore them after. * Same for WITH SCHEMABINDING functions, views, etc. * new table's indexes need to match exactly (same columns, same order, etc.) * Old and new tables need to be on the same filegroup. * Only works on SQL Server 2005 or later * I previously believed that this trick only works on the Enterprise or Developer editions of SQL Server (because partitions are only supported in Enterprise and Developer versions), but Mason G. Zhwiti in his comment below says that it also works in SQL Standard Edition too. I assume this means that the restriction to Enterprise or Developer doesn't apply to ALTER TABLE...SWITCH. There's a good [article on TechNet](https://technet.microsoft.com/en-us/library/ms191160.aspx) detailing the requirements above. UPDATE - [Eric Wu](https://stackoverflow.com/users/2713582/eric-wu) had a comment below that adds important info about this solution. Copying it here to make sure it gets more attention: > There's another caveat here that is worth mentioning. Although the > new table will happily receive data from the old table, and all the > new rows will be inserted following a identity pattern, they will > start at 1 and potentially break if the said column is a primary key. > Consider running `DBCC CHECKIDENT('<newTableName>')` immediately after > switching. See [msdn.microsoft.com/en-us/library/ms176057.aspx](http://msdn.microsoft.com/en-us/library/ms176057.aspx) for more > info. If the table is actively being extended with new rows (meaning you don't have much if any downtime between adding IDENTITY and adding new rows, then instead of `DBCC CHECKIDENT` you'll want to manually set the identity seed value in the new table schema to be larger than the largest existing ID in the table, e.g. `IDENTITY (2435457, 1)`. You might be able to include both the `ALTER TABLE...SWITCH` and the `DBCC CHECKIDENT` in a transaction (or not-- haven't tested this) but seems like setting the seed value manually will be easier and safer. Obviously, if no new rows are being added to the table (or they're only added occasionally, like a daily ETL process) then this race condition won't happen so `DBCC CHECKIDENT` is fine.
Adding an identity to an existing column
[ "", "sql", "sql-server", "alter-table", "identity-column", "" ]