Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
None of the guides/notes/articles that discuss `IDisposable` pattern suggest that one should set the internal members to `null` in the `Dispose(bool)` method (especially if they are memory hogging beasts). I've come to realize the importance of it while debugging an internal benchmark tool. What used to happen was that, there was this buffer that contained a big array inside it. We used to use a static buffer for the whole benchmark program. Once we're done with the buffer, there was no way we could release this internal array, neither could we make this buffer releasable (as it was static). So, I believe that, after `Dispose()` is called, the class should do everything it can so that it releases all the resources it is using and make them available again, even if the object being disposed itself is not collected back by GC, and not setting members to null, thereby, not allowing the internal objects to be collected by the GC implies that the Dispose implementation is not perfect. What's your opinion on this ?
Releasing any additional references during `Dispose` is certainly something I try to do, for two reasons: * it allows the inner objects to be garbage collected even if the disposed object is still in scope * if the inner objects are disposable, it means we only dispose them once even if `Dispose()` is called repeatedly on the outer object For example, I tend to use things like: ``` if(someDisposableObject != null) { someDisposableObject.Dispose(); someDisposableObject = null; } (for non-disposable, just set to null) someNonDisposableObject = null; // etc ``` You might also want to set any events to null: ``` someEventHandler = null; ``` This can help minimise the impact if the caller can't fully release their reference (or simply forgets) at the moment. While you should try to release the outer object (for GC), it is relatively easy to accidentally extend the life of the object, for example via a captured variable (anonymous method/lambda), an event, etc. If you have a finalizer, then during the GC process there is no benefit doing this, and you shouldn't really call methods on external objects (even `Dispose()`) - so in short: don't do any of this during a GC sweep.
Maybe I'm missing your point, but once your object is disposed, the root or 'sub-root' it represented relative to it's members has been detached. It seems like you are thinking of garbage collection like a ref count system (which can be done, but ... usually isn't). Instead, think of it as a many-rooted tree, where every object has branches for what it links to. At the end of the day the 'final roots' are statics and anything instantiated from a 'main' loop. When the garbage collector runs, the easiest way to think about what it does is to consider that it will walk the list of 'real roots' and apply a 'color' to everything it can 'reach'. Now, assumed the collector has access to 'everything', whether it was rooted or not. Anything not colored can be cleaned up. Getting back to your original question, when your object is disposed, one assumes (or at least hopes) that no one references it anymore. If this is the case, it is no longer rooted, and so it will not contribute to 'coloring' anything it touches. Long story longer - if nulling out members in a Dispose routine is fixing something - I would be you have a different, and real, problem that someone is holding a link to your disposed object, and keeping it 'reachable' when it should not be. I apologize for what may be the most over-quote-filled message I've ever written, but I'm sort of abusing standard terms.
In the Dispose(bool) method implementation, Shouldn't one set members to null?
[ "", "c#", ".net", "memory-management", "garbage-collection", "dispose", "" ]
Is there a way, in C# code, to send an email without having to know the SMTP server configuration, etc on the server, or have any of that stuff set up? The code I'm developing will be deployed to a live server, but I know nothing about the configuration, so I can't predict what the SMTP server will be.
The best answer is if you know nothing until live, can you move all the settings into web.config? This will allow configuration up until the last minute. Below is some code to dump into your web.config file. I would question as to why you don't have access to this information though ``` <system.net> <mailSettings> <smtp from="you@yourdomain.com"> <network host="SMTP SERVER ADDRESS" port="25" userName="USERNAME" password="PASSWORD"> </smtp> </mailSettings> </system.net> ```
Add this to your web.config ([MSDN reference here](http://msdn.microsoft.com/en-us/library/ms164240.aspx)): ``` <system.net> <mailSettings> <smtp deliveryMethod="Network" from="jdoe@example.com"> <network host="localhost" port="25" /> </smtp> </mailSettings> </system.net> ``` Using SmtpClient without specifying configuration settings will use the values from the web.config: ``` MailMessage msg = new MailMessage(...); // build message contents SmtpClient client = new SmtpClient(); client.Send(msg); ```
C# code for sending an email without knowing much about the server configuration?
[ "", "c#", "email", "configuration", "smtp", "" ]
I am using HTML, and I'd like to hide the `script` tag from the user's view. When the user views the page source, the definitions should not appear. How do I accomplish this? ### Example ``` <script type="text/javascript" src="My1.js"></script> <script type="text/javascript" src="My2.js"></script> <script type="text/javascript" src="jquery.js"></script> ``` I'd like to hide the definitions, any idea?
You cannot hide HTML. If you want a closed-source solution, use a proprietary format, such as [Flash](http://en.wikipedia.org/wiki/Adobe_Flash) or [Flex](http://en.wikipedia.org/wiki/Adobe_Flex). You can, however, obfuscate your JavaScript code (you should shrinkwrap or minify it anyhow) which makes reading it harder.
You can limit it to one script tag by making an include file that references the other scripts.. Other than that, no.
How to hide the 'script' HTML tag?
[ "", "javascript", "jquery", "html", "" ]
I have a MySql database with three tables I need to combine in a query: schedule, enrolled and waitlist. They are implementing a basic class enrollment system. Schedule contains the scheduled classes. When a user enrolls in a class, their user account id and the id of the scheduled class are stored in enrolled. If a class is at capacity, they are stored in waitlist instead. All three tables share a scheduleId column which identifies each class. When I query the schedule table, I need to also return enrolled and waitlist columns that represent the number of users enrolled and waiting for that particular scheduleId. A preliminary query I came up with to accomplish this was: ``` select s.id, s.classDate, s.instructor, COUNT(e.id) as enrolled from schedule as s left outer join enrolled as e on s.id = e.scheduleId group by s.id ``` which works ok for one or the other, but obviously I can't get the values for both the enrolled and waitlist tables this way. Can anybody suggest a good way of doing this?
I would do it with another left join and two inline count(distincts) ``` select s.id, s.classDate, s.instructor , count(distinct e.id) as enrolled, count(distinct w.id) as waiting from schedule as s left outer join enrolled as e on s.id = e.scheduleID left outer join waitlist as w on s.id = w.scheduleID group by s.id ``` When I ran this approach versus the subqueries it executed about twice as fast, but I am looking at a pretty small result set.
Use nested SELECT queries. Assuming a bit about your schema, how about something like this (might not work on some flavors of SQL): ``` select s.id, s.classDate, s.instructor, (select COUNT(e.id) from enrolled e where e.scheduleId = s.id) as enrolled, (select COUNT(w.id) from waitlist w where w.scheduleId = s.id) as waiting from schedule as s group by s.id ```
How do I include filtered rowcounts from two other tables in a query of a third?
[ "", "sql", "mysql", "rowcount", "" ]
I am doing something like this: ``` class Class(object): def __init__(self): self.var=#new instance name string# ``` How do I make the \_\_ init \_\_ method of my instance to use the instance name string for 'c'? Say in case: ``` c=Class() ``` I want c.var equal to 'c'. Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want \_\_ init \_\_ to add an entry to the database when: ``` c=Class() ``` Then, suppose: ``` del c ``` Later on: ``` c=Class() ``` sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry. --- Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want \_\_ init \_\_ to add an entry to the database when: ``` c=Class() ``` Then, suppose: ``` del c ``` Later on: ``` c=Class() ``` sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.
To persist data objects you need to use the database record's unique ID. **pesudo code because I don't know what database module you're using** ``` import db # assume this is your db module class Class(object): def __init__(self): self.id = None self.name = None def get_by_id(self, id): records = db.execute('select * from table where id=%s' % str(id)) if records: self.id = records[0]['id'] self.name = records[0]['name'] def save(self): db.execute('update table set name=%s where id=%s' % (self.name, str(self.id))) ``` Again, this is pseudo code, the string injection technique I'm using is NOT advised as its fairly insecure, its just there to illustrate how to persist using classes with a db.
Python doesn't have variables, it has [objects and names](http://effbot.org/zone/python-objects.htm). When you do ``` c = Class() ``` you're doing two things: 1. Creating a new object of type `Class` 2. Binding the object to the name `c` in the current scope. The object you created doesn't have any concept of a "variable name" -- If later you do ``` a = c ``` then the same object is accessible in exactly the same way using the names `a` and `c`. You can delete the name `a`, and the object would still exist. If the objects you create need to have a name, the best way is to pass it to them [explicitly](http://www.python.org/dev/peps/pep-0020/), ``` class Class(object): def __init__(self, name): self.name = name var = Class('var') ```
Addressing instance name string in __init__(self) in Python
[ "", "python", "instance", "instantiation", "" ]
We have a hosted site that has a CMS we built running on a LAMP stack. We noticed that when you save HTML that has a tag embedded in the HTML the request immediately dies. This does not occur on the staging or local development instances of the CMS, so I'm assuming its a server configuration issue. Any ideas what might cause this behavior? I've looked through the PHP.INI and apache confige files but nothing stood out as a possible culprit. UPDATE I've filed a ticket with the host that runs our VPS, so far they haven't been helpful. As someone suggested I checked the apache logs to see if there were any problems. The only error I'm seeing is "Directory index forbidden by Options directive". That error seems to be happening independent of the form submit timing out. We built the CMS using CakePHP and the CakePHP logs reveal no other useful information either. The request isn't making it to PHP at all as we put a die() call in the root index.php page and it still times out. UPDATE2 Thanks for the suggestions. I'm confident that this will be resolved but figured it was worth taking it here first. UPDATE3 MediaTemple was able to replicate the issue and said it was a Top Level Filtering Rule that was causing the issue, surely something out of my realm of control. All the same I appreciate the responses :)
I've had similar problems caused by apaches mod\_security. If you have mod\_security enabled on the server, you can try something like this (in a .htaccess file): ``` <IfModule mod_security.c> SecFilterEngine Off </IfModule> ```
Since you have system where this error does not appear it is a configuration error. Find the difference between the failing and the other systems. If you have too many files to compare. Start reducing the complexity of the system as far as possible.
Submitting form fails when the form data contains a <script> tag LAMP
[ "", "php", "apache", "forms", "scripting", "lamp", "" ]
Is there an elegant way to handle exceptions that are thrown in `finally` block? For example: ``` try { // Use the resource. } catch( Exception ex ) { // Problem with the resource. } finally { try{ resource.close(); } catch( Exception ex ) { // Could not close the resource? } } ``` How do you avoid the `try`/`catch` in the `finally` block?
I usually do it like this: ``` try { // Use the resource. } catch( Exception ex ) { // Problem with the resource. } finally { // Put away the resource. closeQuietly( resource ); } ``` Elsewhere: ``` protected void closeQuietly( Resource resource ) { try { if (resource != null) { resource.close(); } } catch( Exception ex ) { log( "Exception during Resource.close()", ex ); } } ```
I typically use one of the `closeQuietly` methods in `org.apache.commons.io.IOUtils`: ``` public static void closeQuietly(OutputStream output) { try { if (output != null) { output.close(); } } catch (IOException ioe) { // ignore } } ```
throws Exception in finally blocks
[ "", "java", "exception", "try-catch", "finally", "" ]
I've got an empty DIV element in which I append images by using function createElement("img") and append them with appendChild. So now I've got DIV element full of images. I would like to use one button to clean this DIV and add new images in it simultaneously. Thanks for your help
Are you just looking for method `replaceChild? Or you could remove all child elements before adding new images:` ``` // assuming yor div is in variable divelement while (divelement.firstChild) divelement.removeChild(divelement.firstChild); ```
what do you mean by clean? If you just want to empty it, you can do ``` document.getElementById('mydiv').innerHTML = ''; ``` And then add on whatever new images you want.
How do I "refresh" element in DOM?
[ "", "javascript", "dom", "" ]
i have a tiny little problem with xslt, js and html entities, eg. within a template: ``` <script type="text/javascript"> <xsl:value-of select="/some/node"/> for (var i = 0; i &lt; 5; i++) { // ^^^ js error } </script> <script type="text/javascript"> <xsl:value-of select="/some/node"/> for (var i = 0; i < 5; i++) { // ^ xslt error } </script> <script type="text/javascript"> <xsl:value-of select="/some/node"/> // <![CDATA[ for (var i = 0; i < 5; i++) { // ^ becomes &lt; } // ]]> </script> <script type="text/javascript"> <xsl:value-of select="/some/node"/> for (var i = 0; i <xsl:value-of disable-output-escaping="yes" select="string('&lt;')"/> 5; i++) { // works of course } </script> ``` does anyone have an idea where my problem could come from? i always thought the xslt processor would leave the content of a <script/> element unescaped when using the html output method ... i run libxslt2 version 1.1.24 on OSX which was installed using macportsports ...
ok. long story, short answer: it seems that with **some libxslt versions** the xslt processor leaves the content of a <script/> element unescaped when using the html output method, **with others not** ... therefore the following is recommended: ``` <script type="text/javascript"> <xsl:value-of select="/some/node"/> <xsl:text disable-output-escaping="yes"> // ^ does the trick ... for (var i = 0; i < 5; i++) { // ^ works } </xsl:text> </script> ```
> i always thought the xslt processor would leave the content of a script element unescaped when using the html output method You are correct: <http://www.w3.org/TR/xslt#section-HTML-Output-Method> ``` The html output method should not perform escaping for the content of the script and style elements. For example, a literal result element written in the stylesheet as <script>if (a &lt; b) foo()</script> or <script><![CDATA[if (a < b) foo()]]></script> should be output as <script>if (a < b) foo()</script> ``` If your XSLT processor is doing otherwise, it's a bug. However, in any case it's a good idea to avoid '<' and '&' in embedded scripts, and an even better idea to kick all the code out into a linked .js file.
xslt, javascript and unescaped html entities
[ "", "javascript", "xslt", "html-entities", "" ]
How do I get the current GLOBAL mouse cursor type (hourglass/arrow/..)? In Windows. Global - I need it **even if the mouse is ouside of my application** or even if my program is windlowless. In C#, Delphi or pure winapi, nevermind... Thank you very much in advance!!
After thee years its time to answer my own question. Here's how you check if the current global cursor is hourglass in C# (extend the code for you own needs if you need): ``` private static bool IsWaitCursor() { var h = Cursors.WaitCursor.Handle; CURSORINFO pci; pci.cbSize = Marshal.SizeOf(typeof(CURSORINFO)); if(!GetCursorInfo(out pci)) throw new Win32Exception(Marshal.GetLastWin32Error()); return pci.hCursor == h; } [StructLayout(LayoutKind.Sequential)] struct POINT { public Int32 x; public Int32 y; } [StructLayout(LayoutKind.Sequential)] struct CURSORINFO { public Int32 cbSize; // Specifies the size, in bytes, of the structure. // The caller must set this to Marshal.SizeOf(typeof(CURSORINFO)). public Int32 flags; // Specifies the cursor state. This parameter can be one of the following values: // 0 The cursor is hidden. // CURSOR_SHOWING The cursor is showing. public IntPtr hCursor; // Handle to the cursor. public POINT ptScreenPos; // A POINT structure that receives the screen coordinates of the cursor. } [DllImport("user32.dll", SetLastError = true)] static extern bool GetCursorInfo(out CURSORINFO pci); ```
To get the information on global cursor, use [GetCursorInfo](http://msdn.microsoft.com/en-us/library/ms648389.aspx "GetCursorInfo on MSDN").
get current mouse cursor type
[ "", "c#", "delphi", "winapi", "vb6", "" ]
I am using `<a>` tags for links on a web page. How do I disable the `Tab` key from selecting either of them?
**EDIT:** Hi, original author of this answer here. Don't use this one. Scroll down. StackOverflow won't let me remove this answer since it was accepted. --- You could do something like this for those links: ``` <a href="http://foo.bar" onfocus="this.blur()">Can't focus on this!</a> ``` You should use the answer below, though. <https://stackoverflow.com/a/457115/974680>
Alternatively you could go for plain HTML solution. ``` <a href="http://foo.bar" tabindex="-1">inaccessible by tab link</a> ``` The [HTML5 spec says](http://www.w3.org/TR/html5/editing.html#attr-tabindex): > **If the value is a negative integer** > The user agent must set the element's tabindex focus flag, but should not allow the element to be reached using sequential focus navigation.
How do I disable tabs for <a> tag
[ "", "javascript", "html", "dom-events", "" ]
How can I ignore an output parameter of a stored procedure? I'm calling the procedure from another procedure, e.g.: ``` DECLARE @param1 integer EXEC mystoredprocedure @in_param_1, @in_param2_, @param1 OUTPUT, -- what do I type here to ignore the second output param?? ``` I'm using T-SQL (MS SQL 2005).
You can just use NULL as the last parameter, and it should work fine - as long as that parameter isn't expected for input logic in the proc as well. In your case, you'd call the proc as ``` exec mystoredproc @in_param_1, @in_param2_, @param1 OUTPUT, null ``` Here's another example that for the same scenario... ``` create proc MyTempProc (@one int, @two int out, @three int out) AS begin set @two = 2 set @three = 3 select @one as One end go declare @p1 int, @p2 int set @p1 = 1 exec MyTempProc @p1, @p2 out, null print @p1 print @p2 ```
The output parameter has to have a default in order for you to not pass it. See below ``` create proc x (@in int = null, @out int = null OUTPUT) as Begin Select @in End exec x 1 ``` **EDIT** To clarify a little, the error is being returned because the stored procedure that is being called has a parameter defined (in this case @param1), for which no default is defined. (i.e. @param1 int rather than @param int = -1) In the case where neither a parameter or default is specified for a defined parameter of a stored procedure when calling the stored procedure an error will occur. The same thing would happen if you tired to omit an input parameter that does not have a default specified.
Is it possible to ignore an output param of a stored procedure?
[ "", "sql", "sql-server-2005", "t-sql", "stored-procedures", "" ]
I am not familiar with PHP at all and had a quick question. I have 2 variables `pricePerUnit` and `InvoicedUnits`. Here's the code that is setting these to values: ``` $InvoicedUnits = ((string) $InvoiceLineItem->InvoicedUnits); $pricePerUnit = ((string) $InvoiceLineItem->PricePerUnit); ``` If I output this, I get the correct values. Lets say `5000` invoiced units and `1.00` for price. Now, I need to show the total amount spent. When I multiply these two together it doesn't work (as expected, these are strings). But I have no clue how to parse/cast/convert variables in PHP. What should I do?
``` $rootbeer = (float) $InvoicedUnits; ``` Should do it for you. Check out [Type-Juggling](https://www.php.net/language.types.type-juggling). You should also read [String conversion to Numbers](https://www.php.net/manual/en/language.types.string.php#language.types.string.conversion).
You want the [non-locale-aware `floatval` function](http://php.net/function.floatval): > float floatval ( mixed $var ) - Gets the float value of a string. Example: ``` $string = '122.34343The'; $float = floatval($string); echo $float; // 122.34343 ```
PHP String to Float
[ "", "php", "string", "casting", "floating-point", "" ]
I encountered a, at least to my expectations, strange behavior in the binary serialization of .NET. All items of a `Dictionary` that are loaded are added to their parent AFTER the `OnDeserialization` callback. In contrast `List` does the other way. This can be really annoying in real world repository code, for example when you need to add some delegates to dictionary items. Please check the example code and watch the asserts. Is it normal behaviour? ``` [Serializable] public class Data : IDeserializationCallback { public List<string> List { get; set; } public Dictionary<string, string> Dictionary { get; set; } public Data() { Dictionary = new Dictionary<string, string> { { "hello", "hello" }, { "CU", "CU" } }; List = new List<string> { "hello", "CU" }; } public static Data Load(string filename) { using (Stream stream = File.OpenRead(filename)) { Data result = (Data)new BinaryFormatter().Deserialize(stream); TestsLengthsOfDataStructures(result); return result; } } public void Save(string fileName) { using (Stream stream = File.Create(fileName)) { new BinaryFormatter().Serialize(stream, this); } } public void OnDeserialization(object sender) { TestsLengthsOfDataStructures(this); } private static void TestsLengthsOfDataStructures(Data data) { Debug.Assert(data.List.Count == 2, "List"); Debug.Assert(data.Dictionary.Count == 2, "Dictionary"); } } ```
I can reproduce the problem. Had a look around Google and found this: <http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=94265> although I'm not sure it's the exact same problem, it seems pretty similar. EDIT: I think that adding this code may have fixed the problem? ``` public void OnDeserialization(object sender) { this.Dictionary.OnDeserialization(sender); } ``` No time to exhaustively test, and I want to beat Marc to the answer ;-)
Yes, you've discovered an annoying quirk in `Dictionary<TKey, TValue>` deserialization. You can get around it by manually calling the dictionary's `OnDeserialization()` method: ``` public void OnDeserialization(object sender) { Dictionary.OnDeserialization(this); TestsLengthsOfDataStructures(this); } ``` Incidentally, you can also use the `[OnDeserialized]` attribute rather than `IDeserializationCallback`: ``` [OnDeserialized] public void OnDeserialization(StreamingContext context) { Dictionary.OnDeserialization(this); TestsLengthsOfDataStructures(this); } ```
Strange behaviour of .NET binary serialization on Dictionary<Key, Value>
[ "", "c#", ".net", "serialization", "dictionary", "binary", "" ]
I'm generating code dynamically, currently using String.Format and embedding placeholders - but reformatting the C# code for use as a template is a pain, and I think using a T4 template would be better. However, the code generation will be happening on a running system, so I need to know that I can safely and legally redistribute the Microsoft T4 Engine with my product. Anyone else done this? Or know the (legal) answer?
It looks like there may soon be another option. Yesterday, Miguel de Icaza posted about T4 integration in MonoDevelop, so I'm expecting there to be a mono equivalent T4 toolset any time now. See: <http://tirania.org/blog/archive/2009/Mar-10.html>
You can redistribute T4 as part of [DSLToolsRedist](http://www.microsoft.com/downloads/details.aspx?familyid=693EE22D-4BB1-450D-835C-59EEBCB9F2AE&displaylang=en), however, it requires Visual Studio 2005 standard edition or higher to be already installed. I don't believe that T4 can be legally redistributed without Visual Studio at this time. The scenario you described will be [directly supported in Visual Studio 2010](http://blogs.msdn.com/garethj/archive/2008/11/11/dsl-2010-feature-dives-t4-preprocessing-rationale.aspx)
Can I redistribute the Microsoft T4 Engine with my product?
[ "", "c#", "t4", "" ]
Switch statements are typically faster than equivalent if-else-if statements (as e.g. descibed in this [article](http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx)) due to compiler optimizations. How does this optimization actually work? Does anyone have a good explanation?
The compiler can build jump tables where applicable. For example, when you use the reflector to look at the code produced, you will see that for huge switches on strings, the compiler will actually generate code that uses a hash table to dispatch these. The hash table uses the strings as keys and delegates to the `case` codes as values. This has asymptotic better runtime than lots of chained `if` tests and is actually faster even for relatively few strings.
This is a slight simplification as typically any modern compiler that encounters a `if..else if ..` sequence that could trivially be converted into a switch statement by a person, the compiler will as well. But just to add extra fun the compiler is not restricted by syntax so can generate "switch" like statements internally that have a mix of ranges, single targets, etc -- and they can (and do) do this for both switch and if..else statements. Anyhoo, an extension to Konrad's answer is that the compiler may generate a jump table, but that's not necessarily guaranteed (nor desirable). For a variety of reasons jump tables do bad things to the branch predictors on modern processors, and the tables themselves do bad things to cache behaviour, eg. ``` switch(a) { case 0: ...; break; case 1: ...; break; } ``` If a compiler actually generated a jump table for this it would likely be slower that the alternative `if..else if..` style code because of the jump table defeating branch prediction.
If vs. Switch Speed
[ "", "c#", "performance", "switch-statement", "if-statement", "" ]
For my university assignment I have to make a networkable version of pacman. I thought I would best approach this problem with making a local copy of pacman first and then extend this functionality for network play. I would have to say that I am relatively new to java GUI development and utilizing such features within java. * <http://www.planetalia.com/cursos/Java-Invaders/> * <http://javaboutique.internet.com/PacMan/source.html> I have started following the above links with regards to game development within java and an example of the pacman game. I decided to represent the maze as an int array with different values meaning different things. However when the paint method inside the main game loop is run i am redrawing the whole maze with this method. ``` for (int i : theGame.getMaze()) { if (i == 4) { g.setColor(mazeWallColour); g.fillRect(curX, curY, cellSize, cellSize); curX += 25; } else { curX += cellSize; } index++; // Move to new row if (index == 25) { index = 0; curX = 10; curY += cellSize; } } ``` However this is providing me with less then 1fps. Although i've noticed the example linked above uses a similar way of redrawing each time the paint method is called and i believe does this on a image that is not viewable (kinda like double buffering [I've used a BufferStrategy like the first link explains]) What would be a better way to redraw the maze? Any pointers/advice with this would be useful. Thank you for your time. <http://pastebin.com/m25052d5a> - for the main game class. Edit: I have just noticed something very weird happening after trying to see what code was taking so long to execute. In the paintClear(Graphics g) method i have added ``` ocean = sprites.getSprite("oceano.gif"); g.setPaint(new TexturePaint(ocean, new Rectangle(0,t,ocean.getWidth(),ocean.getHeight()))); g.fillRect(10, 10,getWidth() - 20,getHeight() - 110); ``` which made the whole thing run smoothly - however when i removed these lines the whole thing slowed down? What could have caused this? [Updated code](http://pastebin.com/m15d0d70)
It looks like your call to Thread.sleep doesn't do what you intended, but I don't think it's the source of your trouble. You have: `Thread.sleep(Math.max(0, startTime - System.currentTimeMillis()));` startTime will always be less than System.currentTimeMillis(), so startTime - System.currentTimeMillis() will always be negative and thus your sleep will always be for 0 milliseconds. It's different from the example you showed because the example increments startTime by 40 milliseconds before doing the calculation. It is calculating how long to sleep for to pad out the drawing time to 40 milliseconds. Anyway, back to your problem. I'd recommend measurement to figure out where your time is being spent. There's no point optimising until you know what's slow. You already know how to use System.currentTimeMillis(). Try using that to measure where all the time goes. Is it all spent drawing the walls? --- EDIT - I see this got marked as accepted, so should I infer that the problem went away when you fixed the sleep time? I don't have a lot of Java GUI experience, but I can speculate that perhaps your code was starving out other important threads. By setting your thread to have maximum priority and only ever calling sleep(0), you pretty much guarantee that no other thread in your process can do anything. Here's [a post from Raymond Chen's blog](http://blogs.msdn.com/oldnewthing/archive/2005/10/04/476847.aspx) that explains why.
First off, I'd recommend that you use named constants rather than having random magic numbers in your code and consider using enums for your cell types. While it won't make your code run any faster, it certainly will make it easier to understand. Also, 'i' is normally used as a counter, not for a return value. You should probably call it `cellType` or something similar. I'd also recommend that you use a 2D array for your stage map since it makes a number of things easier, both logistically and conceptually. That said, here are a few things to try: Pull the `setColor()` out of the loop and do it once. The compiler might be able to do loop-invariant hoisting and thus do this for you (and probably will), but conceptually, you should probably do this anyway since it appears you want all of your walls to be one color anyway. Try calling `drawRect()` instead of `fillRect()` and see if that draws faster. I don't think it will, but it is worth a shot, even if it looks uglier. Similarly, you can try creating an `Image` and then drawing that. This has the advantage that it is really easy to tell your Graphics object to implement a transform on your image. Also, consider taking this out completely and make sure that it is being a significant performance hit. Also, normally you don't need to ask for the parent for its Graphics object and implement painting directly on it. Rather, you should override its `paintComponent()` method and just utilize the Graphics given to you (possibly calling helper methods as you do). Swing components are double-buffered by default, so you don't need to implement that yourself; just let the swing object do its job and let you know when to paint. Also, you end up repainting the entire screen, which is something of overkill. If you call `repaint(Rectangle)`, Swing can choose to redraw only the sections of your board that are explicitly marked dirty. When you update one of your sprites, call repaint(r) only on the area of the sprite's old and new locations. When you complete a level and need a new board, then you can call repaint() (without parameters) to redraw the entire map. You should also look at [Sun's tutorial](http://java.sun.com/products/jfc/tsc/articles/painting/) to get some tips for efficiency in Swing.
Pacman in Java questions
[ "", "java", "network-programming", "pacman", "" ]
I have a method which takes String argument. In some cases I want to pass int value to that method. For invoking that method I want to convert int into String. For that I am doing the following: ``` aMethod(""+100); ``` One more option is: ``` aMethod(String.valueOf(100)); ``` Both are correct. I don't know which is appropriate? Which gives better performance? Mostly this is happen in GWT. In GWT for setting size of panels and widgets I want to do this.
Since you're mostly using it in GWT, I'd go with the ""+ method, since it's the neatest looking, and it's going to end up converted to javascript anyway, where there is no such thing as a StringBuilder. Please don't hurt me Skeet Fanboys ;)
Using `+` on strings creates multiple string instances, so using `valueOf` is probably a bit more performant.
String conversions in Java
[ "", "java", "string", "" ]
I'm speaking of this module: <http://docs.python.org/library/operator.html> From the article: > The operator module exports a set of > functions implemented in C > corresponding to the intrinsic > operators of Python. For example, > operator.add(x, y) is equivalent to > the expression x+y. The function names > are those used for special class > methods; variants without leading and > trailing \_\_ are also provided for > convenience. I'm not sure I understand the benefit or purpose of this module.
Possibly the most popular usage is operator.itemgetter. Given a list `lst` of tuples, you can sort by the ith element by: `lst.sort(key=operator.itemgetter(i))` Certainly, you could do the same thing without operator by defining your own key function, but the operator module makes it slightly neater. As to the rest, python allows a functional style of programming, and so it can come up -- for instance, Greg's reduce example. You might argue: "Why do I need `operator.add` when I can just do: `add = lambda x, y: x+y`?" The answers are: 1. `operator.add` is (I think) slightly faster. 2. It makes the code easier to understand for you, or another person later, looking at it. They don't need to look for the definition of add, because they know what the operator module does. 3. `operator.add` is picklable, while `lambda` is not. This means that the function can be saved to disk or passed between processes.
One example is in the use of the `reduce()` function: ``` >>> import operator >>> a = [2, 3, 4, 5] >>> reduce(lambda x, y: x + y, a) 14 >>> reduce(operator.add, a) 14 ```
In what situation should the built-in 'operator' module be used in python?
[ "", "python", "operators", "" ]
My question is best phrase as: [Remove a child with a specific attribute, in SimpleXML for PHP](https://stackoverflow.com/questions/262351/remove-a-child-with-a-specific-attribute-in-simplexml-for-php) except I'm not using simpleXML. I'm new to XML for PHP so I may not be doing the best way I have a xml created using the $dom->save($xml) for each individual user. (not placing all in one xml due to undisclosed reasons) It gives me that xml declaration `<?xml version="1.0"?>` (no idea how to make it to others, but that's not the point, hopefully) ``` <?xml version="1.0"?> <details> <person>name</person> <data1>some data</data1> <data2>some data</data2> <data3>some data</data3> <category id="0"> <categoryName>Cat 1</categoryName> <categorydata1>some data</categorydata1> </category> <category id="1"> <categoryName>Cat 2</categoryName> <categorydata1>some data</categorydata1> <categorydata2>some data</categorydata2> <categorydata3>some data</categorydata3> <categorydata4>some data</categorydata4> </category> </details> ``` And I want to remove a category that has a specific attribute named id with the DOM class in php when i run a function activated from using a remove button. the following is the debug of the function im trying to get to work. Can i know what I'm doing wrong? ``` function CatRemove($myXML){ $xmlDoc = new DOMDocument(); $xmlDoc->load( $myXML ); $categoryArray = array(); $main = $xmlDoc->getElementsByTagName( "details" )->item(0); $mainElement = $xmlDoc->getElementsByTagName( "details" ); foreach($mainElement as $details){ $currentCategory = $details->getElementsByTagName( "category" ); foreach($currentCategory as $category){ $categoryID = $category->getAttribute('id'); array_push($categoryArray, $categoryID); if($categoryID == $_POST['categorytoremoveValue']) { return $categoryArray; } } } $xmlDoc->save( $myXML ); } ``` Well the above prints me an array of [0]->0 all the time when i slot the return outside the if. is there a better way? I've tried using getElementbyId as well but I've no idea how to work that. I would prefer not to use an attribute though if that would make things easier.
Ok, let’s try this complete example of use: ``` function CatRemove($myXML, $id) { $xmlDoc = new DOMDocument(); $xmlDoc->load($myXML); $xpath = new DOMXpath($xmlDoc); $nodeList = $xpath->query('//category[@id="'.(int)$id.'"]'); if ($nodeList->length) { $node = $nodeList->item(0); $node->parentNode->removeChild($node); } $xmlDoc->save($myXML); } // test data $xml = <<<XML <?xml version="1.0"?> <details> <person>name</person> <data1>some data</data1> <data2>some data</data2> <data3>some data</data3> <category id="0"> <categoryName>Cat 1</categoryName> <categorydata1>some data</categorydata1> </category> <category id="1"> <categoryName>Cat 2</categoryName> <categorydata1>some data</categorydata1> <categorydata2>some data</categorydata2> <categorydata3>some data</categorydata3> <categorydata4>some data</categorydata4> </category> </details> XML; // write test data into file file_put_contents('untitled.xml', $xml); // remove category node with the id=1 CatRemove('untitled.xml', 1); // dump file content echo '<pre>', htmlspecialchars(file_get_contents('untitled.xml')), '</pre>'; ```
So you want to remove the `category` node with a specific `id`? ``` $node = $xmlDoc->getElementById("12345"); if ($node) { $node->parentNode->removeChild($node); } ``` You could also use XPath to get the node, for example: ``` $xpath = new DOMXpath($xmlDoc); $nodeList = $xpath->query('//category[@id="12345"]'); if ($nodeList->length) { $node = $nodeList->item(0); $node->parentNode->removeChild($node); } ``` I haven’t tested it but it should work.
How do I remove a specific node using its attribute value in PHP XML Dom?
[ "", "php", "xml", "dom", "xml-attribute", "" ]
I've seen a couple .net applications that allow you to select a C# .cs source file and the program itself will compile this code and run it. How is this done?
It probably uses the CSharpCodeProvider class in the Microsoft.CSharp namespace. You would want to look at the following methods to compile code: ``` CompileAssemblyFromDom CompileAssemblyFromFile CompileAssemblyFromSource ```
[CodeDOM](http://msdn.microsoft.com/en-us/library/650ax5cx.aspx) is your friend
How do I allow my .net program to compile C# code while running?
[ "", "c#", ".net", "compiler-construction", "runtime", "" ]
Is it possible that using jQuery, I **cancel/abort an Ajax request** that I have not yet received the response from?
Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use `abort()`. See the documentation: * [abort Method](http://msdn.microsoft.com/en-us/library/ms535920%28VS.85%29.aspx) ([MSDN](http://en.wikipedia.org/wiki/Microsoft_Developer_Network)). Cancels the current HTTP request. * [abort()](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/abort) ([MDN](http://en.wikipedia.org/wiki/Mozilla_Developer_Network)). If the request has been sent already, this method will abort the request. ``` var xhr = $.ajax({ type: "POST", url: "some.php", data: "name=John&location=Boston", success: function(msg){ alert( "Data Saved: " + msg ); } }); //kill the request xhr.abort() ``` **UPDATE:** As of jQuery 1.5 the returned object is a wrapper for the native XMLHttpRequest object called jqXHR. This object appears to expose all of the native properties and methods so the above example still works. See *[The jqXHR Object](http://api.jquery.com/jQuery.ajax/#jqXHR)* (jQuery API documentation). **UPDATE 2:** As of jQuery 3, the ajax method now returns a promise with extra methods (like abort), so the above code still works, though the object being returned is not an `xhr` any more. See the [3.0 blog here](http://blog.jquery.com/2016/01/14/jquery-3-0-beta-released/). **UPDATE 3**: `xhr.abort()` still works on jQuery 3.x. Don't assume the *update 2* is correct. [More info on jQuery Github repository](https://github.com/jquery/jquery/issues/2084#issuecomment-308173243).
You can't recall the request but you can set a timeout value after which the response will be ignored. See this [page](http://docs.jquery.com/Ajax/jQuery.ajax#options) for jquery AJAX options. I believe that your error callback will be called if the timeout period is exceeded. There is already a default timeout on every AJAX request. You can also use the [abort()](https://developer.mozilla.org/en/DOM/XMLHttpRequest#abort%28%29) method on the request object but, while it will cause the client to stop listening for the event, it may probably will not stop the server from processing it.
Abort Ajax requests using jQuery
[ "", "javascript", "jquery", "ajax", "" ]
Many of the standard c library (fwrite, memset, malloc) functions have direct equivalents in the Windows Api (WriteFile, FillMemory/ ZeroMemory, GlobalAlloc). Apart from portability issues, what should be used, the CLIB or Windows API functions? Will the C functions call the Windows Api functions or is it the other way around?
There's nothing magical about the C library. It's just a standardized API for accessing common services from the OS. That means it's implemented on top of the OS, using the API's provided by the OS. Use whichever makes sense in your situation. The C library is portable, Win32 isn't. On the other hand, Win32 is often more flexible, and exposes more functionality.
It's probably more information than you're looking for (and maybe not exactly what you asked) but Catch22.net has an article entitled "[Techniques for reducing Executable size](http://catch22.net/tuts/minexe)" that may help point out the differences in Win32 api calls and c runtime calls.
C library vs WinApi
[ "", "c++", "c", "winapi", "visual-c++", "" ]
My main window has spawned a child window that's positioned on top to look like part of the main. I would like to move the child window in sync with the main but I'm not sure how. My main window has my own title bar which event MouseLeftButtonDown calls this function: ``` public void DragWindow(object sender, MouseButtonEventArgs args) { DragMove(); UpdateChildWindowPosition(); } ``` This results in DragMove() executing on the main window moves the main window alone as I drag the title bar. UpdateChildWindowPosition() is not executed until I release the mouse at which it reads some element coordinates and sets the child window position - you see the child window snap to the location which is not desired. How can I have the child window move in sync with the main window?
AH HAH! My Main window has an event LocationChanged which I've tied to my UpdateChildWindowPosition(). LocationChange fires when (duh) the location changes so it's continuously firing as I move the window when DragMove() is being executed in my DragWindow posted above.
You can use the window's Left and Top properties to place the secondary window. Here's a rough bit of code as an example: In the MainWindow code: ``` mDebugWindow.Left = this.Left + this.ActualWidth; mDebugWindow.Top = this.Top; ``` In this case mDebugWindow is my child window. This code tells it to sit on the right hand side of the main window, with the tops of the windows aligned. Hope this helps.
Move two WPF windows at once?
[ "", "c#", ".net", "wpf", "" ]
I have a list/queue of 200 commands that I need to run in a shell on a Linux server. I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few seconds to complete, other processes will take much longer. When a process finishes I want the next command to be "popped" from the queue and executed. Does anyone have code to solve this problem? **Further elaboration:** There's 200 pieces of work that need to be done, in a queue of some sort. I want to have at most 10 pieces of work going on at once. When a thread finishes a piece of work it should ask the queue for the next piece of work. If there's no more work in the queue, the thread should die. When all the threads have died it means all the work has been done. The actual problem I'm trying to solve is using `imapsync` to synchronize 200 mailboxes from an old mail server to a new mail server. Some users have large mailboxes and take a long time tto sync, others have very small mailboxes and sync quickly.
I would imagine you could do this using make and the make -j xx command. Perhaps a makefile like this ``` all : usera userb userc.... usera: imapsync usera userb: imapsync userb .... ``` make -j 10 -f makefile
On the shell, `xargs` can be used to queue parallel command processing. For example, for having always 3 sleeps in parallel, sleeping for 1 second each, and executing 10 sleeps in total do ``` echo {1..10} | xargs -d ' ' -n1 -P3 sh -c 'sleep 1s' _ ``` And it would sleep for 4 seconds in total. If you have a list of names, and want to pass the names to commands executed, again executing 3 commands in parallel, do ``` cat names | xargs -n1 -P3 process_name ``` Would execute the command `process_name alice`, `process_name bob` and so on.
Parallel processing from a command queue on Linux (bash, python, ruby... whatever)
[ "", "python", "ruby", "bash", "shell", "parallel-processing", "" ]
I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size. After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a page object the results were not what I had expected and appeared to be quite random. Has anyone had any experience with this? Code examples would be well appreciated, preferably in python.
[pyPdf](https://pypi.org/project/pyPdf/) does what I expect in this area. Using the following script: ``` #!/usr/bin/python # from pyPdf import PdfFileWriter, PdfFileReader with open("in.pdf", "rb") as in_f: input1 = PdfFileReader(in_f) output = PdfFileWriter() numPages = input1.getNumPages() print "document has %s pages." % numPages for i in range(numPages): page = input1.getPage(i) print page.mediaBox.getUpperRight_x(), page.mediaBox.getUpperRight_y() page.trimBox.lowerLeft = (25, 25) page.trimBox.upperRight = (225, 225) page.cropBox.lowerLeft = (50, 50) page.cropBox.upperRight = (200, 200) output.addPage(page) with open("out.pdf", "wb") as out_f: output.write(out_f) ``` The resulting document has a trim box that is 200x200 points and starts at 25,25 points inside the media box. The crop box is 25 points inside the trim box. Here is how my sample document looks in acrobat professional after processing with the above code: [![crop pages screenshot](https://i.stack.imgur.com/vM7e6.png)](https://i.stack.imgur.com/vM7e6.png) This document will appear blank when loaded in acrobat reader.
Use this to get the dimension of pdf ``` from PyPDF2 import PdfWriter, PdfReader, PdfMerger reader = PdfReader("/Users/user.name/Downloads/sample.pdf") page = reader.pages[0] print(page.cropbox.lower_left) print(page.cropbox.lower_right) print(page.cropbox.upper_left) print(page.cropbox.upper_right) ``` After this get page reference and then apply crop command ``` page.mediabox.lower_right = (lower_right_new_x_coordinate, lower_right_new_y_coordinate) page.mediabox.lower_left = (lower_left_new_x_coordinate, lower_left_new_y_coordinate) page.mediabox.upper_right = (upper_right_new_x_coordinate, upper_right_new_y_coordinate) page.mediabox.upper_left = (upper_left_new_x_coordinate, upper_left_new_y_coordinate) #f or example :- my custom coordinates # page.mediabox.lower_right = (611, 500) # page.mediabox.lower_left = (0, 500) # page.mediabox.upper_right = (611, 700) # page.mediabox.upper_left = (0, 700) ```
Cropping pages of a .pdf file
[ "", "python", "pdf", "pypdf", "" ]
I would like to have a function that modifies some variable list of parameters but they are all value types (int, string). There is a way to make the params keyword work with ref keyword or something close to that? ``` public void funcParams(params object[] list) { /* Make something here to change 'a', 'b' and 'c' */ } public void testParams() { int a = 1, b = 2, c = 3; funcParams(a, b, c); } ``` The problem is, I'm trying to make my life easier making a method that modifies the object fields. I'm doing some dynamic code generation using Cecil and I'm trying to avoid writing too much IL generated code. To simplify I would like to pass the list of fields by reference I need to change to a function that changes them instead of changing them by generating the respective IL. Some of the parameters are nullable and make the code generation a little more painful. Making some overload methods instead of params won't be much useful in this case.
Yes. It is possible. However, the resulting code is "unsafe" which makes it unverifiable. That may or may not be an issue depending on your requirements. In any case, here is the code: ``` using System; namespace unsafeTest { class MainClass { public static void Main(string[] args) { Console.WriteLine("Hello World!"); unsafe { int x = 0; int y = 0; int z = 0; bar(&x, &y, &z); Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } } unsafe static void bar(params int *[] pInts) { int i = 0; foreach (var pInt in pInts) { *pInt = i++; } } } } ```
Well, you could declare a few overloads, i.e. ``` public void FuncParams(ref int a) {...} public void FuncParams(ref int a, ref int b) {...} ``` etc Otherwise, you'll have to read back from the array (as `params` really means "implicit array"): ``` object[] args = {1,2,3}; funcParams(args); Console.WriteLine(args[0]); // updated Console.WriteLine(args[1]); // updated Console.WriteLine(args[2]); // updated ``` (of course, if it only accepts `int`s, it would be better to use an `int[]` throughout)
There is a way to pass-by-reference using variable parameters in C#?
[ "", "c#", "reference", "parameters", "" ]
``` this.String = { Get : function (val) { return function() { return val; } } }; ``` What is the ':' doing?
Others have already explained what this code does. It creates an object (called `this.String`) that contains a single function (called `Get`). I'd like to explain when you could use this function. This function can be useful in cases where you need a higher order function (that is a function that expects another function as its argument). Say you have a function that does something to each element of an `Array`, lets call it `map`. You could use this function like so: ``` function inc (x) { return x + 1; } var arr = [1, 2, 3]; var newArr = arr.map(inc); ``` What the `map` function will do, is create a new array containing the values `[2, 3, 4]`. It will do this by calling the function `inc` with each element of the array. Now, if you use this method a lot, you might continuously be calling `map` with all sorts of arguments: ``` arr.map(inc); // to increase each element arr.map(even); // to create a list of booleans (even or odd) arr.map(toString); // to create a list of strings ``` If for some reason you'd want to replace the entire array with the same string (but keeping the array of the same size), you could call it like so: ``` arr.map(this.String.Get("my String")); ``` This will create a new array of the same size as `arr`, but just containing the string `"my String"` over and over again. Note that in some languages, this function is predefined and called `const` or `constant` (since it will always return the same value, each time you call it, no matter what its arguments are). --- Now, if you think that this example isn't very useful, I would agree with you. But there are cases, when programming with higher order functions, when this technique is used. For example, it can be useful if you have a tree you want to 'clear' of its values but keep the structure of the tree. You could do `tree.map(this.String.Get("default value"))` and get a whole new tree is created that has the exact same shape as the original, but none of its values.
`this.String = {}` specifies an object. `Get` is a property of that object. In javascript, object properties and their values are separated by a colon ':'. So, per the example, you would call the function like this ``` this.String.Get('some string'); ``` More examples: ``` var foo = { bar : 'foobar', other : { a : 'wowza' } } alert(foo.bar); //alerts 'foobar' alert(foo.other.a) //alerts 'wowza' ```
What is this javascript code doing?
[ "", "javascript", "" ]
If I have sequence of sequences (maybe a list of tuples) I can use itertools.chain() to flatten it. But sometimes I feel like I would rather write it as a comprehension. I just can't figure out how to do it. Here's a very construed case: Let's say I want to swap the elements of every pair in a sequence. I use a string as a sequence here: ``` >>> from itertools import chain >>> seq = '012345' >>> swapped_pairs = zip(seq[1::2], seq[::2]) >>> swapped_pairs [('1', '0'), ('3', '2'), ('5', '4')] >>> "".join(chain(*swapped_pairs)) '103254' ``` I use zip on the even and odd slices of the sequence to swap the pairs. But I end up with a list of tuples that now need to be flattened. So I use chain(). Is there a way I could express it with a comprehension instead? If you want to post your own solution to the basic problem of swapping elements of the pairs, go ahead, I'll up-vote anything that teaches me something new. But I will only mark as accepted an answer that is targeted on my question, even if the answer is "No, you can't.".
With a comprehension? Well... ``` >>> seq = '012345' >>> swapped_pairs = zip(seq[1::2], seq[::2]) >>> ''.join(item for pair in swapped_pairs for item in pair) '103254' ```
Quickest I've found is to start with an empty array and extend it: ``` In [1]: a = [['abc', 'def'], ['ghi'],['xzy']] In [2]: result = [] In [3]: extend = result.extend In [4]: for l in a: ...: extend(l) ...: In [5]: result Out[5]: ['abc', 'def', 'ghi', 'xzy'] ``` This is over twice as fast for the example in Alex Martelli's attempt on: [Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python) ``` $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]' 10000 loops, best of 3: 86.3 usec per loop $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'b = []' 'extend = b.extend' 'for sub in l:' ' extend(sub)' 10000 loops, best of 3: 36.6 usec per loop ``` I came up with this because I had a hunch that behind the scenes, extend would allocate the right amount of memory for the list, and probably uses some low-level code to move items in. I have no idea if this is true, but who cares, it is faster. By the way, it's only a linear speedup: ``` $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]' 'b = []' 'extend = b.extend' 'for sub in l:' ' extend(sub)' 1000000 loops, best of 3: 0.844 usec per loop $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]' '[item for sublist in l for item in sublist]' 1000000 loops, best of 3: 1.56 usec per loop ``` You can also use the `map(results.extend, a)`, but this is slower as it is building its own list of Nones. It also gives you some of the benefits of not using functional programming. i.e. * you can extend an existing list instead of creating an empty one, * you can still understand the code at a glance, minutes, days or even months later. By the way, probably best to avoid list comprehensions. Small ones aren't too bad, but in general list comprehensions don't actually save you much typing, but are often harder to understand and very hard to change or refactor (ever seen a three level list comprehension?). [Google coding guidelines advise against them except in simple cases.](http://google-styleguide.googlecode.com/svn/trunk/pyguide.html#List_Comprehensions) My opinion is that they are only useful in 'throw-away' code, i.e. code where the author doesn't care about readability, or code that is known to never require future maintenance. Compare these two ways of writing the same thing: ``` result = [item for sublist in l for item in sublist] ``` with this: ``` result = [] for sublist in l: for item in sublist: result.append(item) ``` YMMV, but the first one stopped me in my tracks and I had to think about it. In the second the nesting is made obvious from the indentation.
Comprehension for flattening a sequence of sequences?
[ "", "python", "sequences", "list-comprehension", "" ]
Are there any free libraries that would "print" to a PDF without actually having to install a PDF printer on the system. I want something that can be completely self contained in my application. The reason I say I want it to "print" is that I've tried and tried to find a solution for directly converting from HTML with CSS to PDF, but it does't seem very possible. So I want to use the System.Windows.Forms.WebBrowser control to render the page first and then output that rendering to PDF. I just don't want the user to be required to install a PDFPrinter.
[PDFsharp](http://pdfsharp.com/)
Does it have to be free? Last time I looked at [ABCpdf](http://www.websupergoo.com/abcpdf-1.htm) it looked quite good, and claims to support css ([here](http://www.websupergoo.com/helppdf5net/source/3-concepts/g-htmlrender.htm)). [HTMLDOC](http://www.easysw.com/htmldoc/) should support css at some point, but last time I checked the css stuff was still in beta. And has been for "some time"; I've given up waiting... It isn't .NET, but you can use `Process` to invoke it.
C# PDF Printing Library
[ "", "c#", "html", "pdf", "pdf-generation", "" ]
I have a cache which has soft references to the cached objects. I am trying to write a functional test for behavior of classes which use the cache specifically for what happens when the cached objects are cleared. The problem is: I can't seem to reliably get the soft references to be cleared. Simply using up a bunch of memory doesn't do the trick: I get an OutOfMemory before any soft references are cleared. Is there any way to get Java to more eagerly clear up the soft references? --- **Found [here](https://stackoverflow.com/questions/299659/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java)**: > "It is guaranteed though that all > SoftReferences will get cleared before > OutOfMemoryError is thrown, so they > theoretically can't cause an OOME." So does this mean that the above scenario MUST mean I have a memory leak somewhere with some class holding a hard reference on my cached object?
> The problem is: I can't seem to > reliably get the soft references to be > cleared. This is not unique to SoftReferences. Due to the nature of garbage collection in Java, there is no guarantee that anything that is garbage-collectable will actually be collected at any point in time. Even with a simple bit of code: ``` Object temp = new Object(); temp = null; System.gc(); ``` there is no guarantee that the Object instantiated in the first line is garbage collected at this, or in fact any point. It's simply one of the things you have to live with in a memory-managed language, you're giving up declarative power over these things. And yes, that can make it hard to definitively test for memory leaks at times. --- That said, as per the Javadocs you quoted, SoftReferences should definitely be cleared before an OutOfMemoryError is thrown (in fact, that's the entire point of them and the only way they differ from the default object references). It would thus sound like there is some sort of memory leak in that you're holding onto harder references to the objects in question. If you use the `-XX:+HeapDumpOnOutOfMemoryError` option to the JVM, and then load the heap dump into something like [jhat](http://java.sun.com/javase/6/docs/technotes/tools/share/jhat.html), you should be able to see all the references to your objects and thus see if there are any references beside your soft ones. Alternatively you can achieve the same thing with a profiler while the test is running.
There is also the following JVM parameter for tuning how soft references are handled: ``` -XX:SoftRefLRUPolicyMSPerMB=<value> ``` Where 'value' is the number of milliseconds a soft reference will remain for every free Mb of memory. The default is 1s/Mb, so if an object is only soft reachable it will last 1s if only 1Mb of heap space is free.
How to cause soft references to be cleared in Java?
[ "", "java", "garbage-collection", "soft-references", "" ]
For a typical J2EE web application, the datasource connection settings are stored as part of the application server configuration. Is there a way to version control these configuration details? I want more control on the datasource and other application server config changes. What is the standard practice for doing this?
Tracking configuration changes to your application server through version control is a good thing to ask for. However, It does imply that all changes are done via scripting, instead of the administrative web interface. I recommend <http://www.ibm.com/developerworks/java/library/j-ap01139/index.html?ca=drs-> as a good background information article on this topic. Update: Just recently, part 2 has been published here: <http://www.ibm.com/developerworks/java/library/j-ap02109/index.html?ca=drs->
Websphere canbe tricky as the directory structure is a mess of files - often there appears to be duplicates and it's hard to figure which is the magic file you need to backup / restore . The question of how to go about this should not detract from the need to do it. - which is a definite yes.
Should I implement source control for j2ee application server configuration files?
[ "", "java", "version-control", "jakarta-ee", "configuration-management", "" ]
How do I do this in linq? ``` var p = new pmaker(); foreach (var item in itemlist) { var dlist = new List<Dummy>(); foreach (var example in item.examples) { dlist.Add(example.GetDummy()); } p.AddStuff(item.X,item.Y,dlist); } // .. do stuff with p ```
How about: ``` var qry = from item in itemlist select new {item.X, item.Y, Dummies = item.examples.Select( ex => ex.GetDummy()) }; foreach (var item in qry) { p.AddStuff(item.X, item.Y, item.Dummies.ToList()); } ``` Not sure it is much clearer like this, though... personally I think I might just use the original `foreach` version... maybe splitting out the `GetDummy` bit: ``` foreach (var item in itemlist) { var dlist = item.examples.Select(ex => ex.GetDummy()).ToList(); p.AddStuff(item.X,item.Y,dlist); } ```
if `itemlist` is a `List<T>` collection you could do: ``` var p = new pmaker(); itemlist.ForEach(item => p.AddStuff(item.X, item.Y, (from ex in item.examples select ex.GetDummy()).ToList()) ); ``` but if it's clearer this way? I think not, you should not use LINQ and delegates just because you like to, but because it states the intent of your code better.
foreach to linq tip wanted
[ "", "c#", "linq", "" ]
I've been struggling with this one SQL query requirement today that I was wondering if someone could help me with. I have a table of sports questions. One of the columns is the team related to the question. My requirement is to return a set number of random questions where the teams are unique. So lets say we have the following table and want 5 questions: ``` Question Answer Team ----------------------------------- question 1 answer 1 team A question 2 answer 2 team B question 3 answer 3 team B question 4 answer 3 team D question 5 answer 3 team A question 6 answer 3 team C question 7 answer 3 team F question 8 answer 3 team C question 9 answer 3 team G question 10 answer 3 team D ``` A valid result would return: ``` question 1 answer 1 team A question 2 answer 2 team B question 4 answer 3 team D question 6 answer 3 team C question 7 answer 3 team F ``` I feel that it should be possible to accomplish this as a clean SQL statement with some clever use of Distinct and Take but I haven't been able to get it right yet. Best solution so far is from [Mladen Prajdic](https://stackoverflow.com/users/31345/mladen-prajdic). I have just updated it slightly to improve on it's randomness: ``` SELECT TOP 10 * FROM (SELECT ROW_NUMBER() OVER(PARTITION BY Team ORDER BY Team, NEWID()) AS RN, * FROM Question ) teams WHERE RN = 2 ORDER BY NEWID() ```
for sql 2005 you can do this: ``` select top 5 * from ( select ROW_NUMBER() over(partition by team order by team) as RN, * from @t ) t where RN = 1 order by NEWID() ```
This should do what you need, in oracle; for a different database you'll need to use their random number source, obviously. There's probably a better way; lets hope someone else will point it out to us :p ``` select question, answer, team from ( select question, answer, team, r from ( select question, answer, team, rank() over (partition by team order by dbms_random.value) r from questions ) where r = 1 order by dbms_random.value ) where rownum<=5; ``` Test code: ``` create table questions(question varchar2(16), answer varchar2(16), team varchar2(16)); insert into questions(question, answer, team) values ('question 1', 'answer 1', 'team A'); insert into questions(question, answer, team) values ('question 2', 'answer 2', 'team B'); insert into questions(question, answer, team) values ('question 3', 'answer 3', 'team B'); insert into questions(question, answer, team) values ('question 4', 'answer 3', 'team D'); insert into questions(question, answer, team) values ('question 5', 'answer 3', 'team A'); insert into questions(question, answer, team) values ('question 6', 'answer 3', 'team C'); insert into questions(question, answer, team) values ('question 7', 'answer 3', 'team F'); insert into questions(question, answer, team) values ('question 8', 'answer 3', 'team C'); insert into questions(question, answer, team) values ('question 9', 'answer 3', 'team G'); insert into questions(question, answer, team) values ('question 10', 'answer 3', 'team D'); commit; ```
How to select a set number of random records where one column is unique?
[ "", "sql", "random", "" ]
How do I create test suites with JUnit 4? All the documentation I've seen doesn't seem to be working for me. And if I use the Eclipse wizard it doesn't give me an option to select any of the test classes I have created.
``` import org.junit.runners.Suite; import org.junit.runner.RunWith; @RunWith(Suite.class) @Suite.SuiteClasses({TestClass1.class, TestClass2.class}) public class TestSuite { //nothing } ```
You can create a suite like so. For example an `AllTest` suite would look something like this. ``` package my.package.tests; @RunWith(Suite.class) @SuiteClasses({ testMyService.class, testMyBackend.class, ... }) public class AllTests {} ``` Now you can run this in a couple different ways: 1. right-click and run in Eclipse as Junit test 2. create a runable Java Application; **Main class**='org.junit.runner.JUnitCore' and **Args**='my.package.tests.AllTests' 3. run from the command line: ``` $ java -cp build/classes/:/usr/share/java/junit4.jar:/usr/share/java/hamcrest-core.jar org.junit.runner.JUnitCore my.package.tests.AllTests ```
JUnit 4 Test Suites
[ "", "java", "junit", "test-suite", "" ]
I am using the Asp.net OutputCache on a page containing a usercontrol that in certain circumstances when the usercontrol is edited i want to be able to expire the page cache and reload the page with fresh data. Is there any way i can do this from within the usercontrol? If not, what are some other methods of caching the page that will allow me to edit in this way. ----------- EDIT ----------- After some more research I found a method that seems to work well. ``` Dim cachekey As String = String.Format("Calendar-{0}", calendarID) HttpContext.Current.Cache.Insert(cachekey, DateTime.Now, Nothing, System.DateTime.MaxValue, System.TimeSpan.Zero, System.Web.Caching.CacheItemPriority.NotRemovable, Nothing) Response.AddCacheItemDependency(cachekey) ``` that will add a dependency to the page cache object, then to expire I do this: ``` Dim cachekey as string = String.Format("Calendar-{0}", CalendarID) HttpContext.Current.Cache.Insert(cachekey, DateTime.Now, Nothing, System.DateTime.MaxValue, System.TimeSpan.Zero, System.Web.Caching.CacheItemPriority.NotRemovable, Nothing) ``` Now as long as the dependency cachekey is known a page can be expired.
After some more research I found a method that seems to work well. ``` Dim cachekey As String = String.Format("Calendar-{0}", calendarID) HttpContext.Current.Cache.Insert(cachekey, DateTime.Now, Nothing, System.DateTime.MaxValue, System.TimeSpan.Zero, System.Web.Caching.CacheItemPriority.NotRemovable, Nothing) Response.AddCacheItemDependency(cachekey) ``` that will add a dependency to the page cache object, then to expire I do this: ``` Dim cachekey as string = String.Format("Calendar-{0}", CalendarID) HttpContext.Current.Cache.Insert(cachekey, DateTime.Now, Nothing, System.DateTime.MaxValue, System.TimeSpan.Zero, System.Web.Caching.CacheItemPriority.NotRemovable, Nothing) ``` Now as long as the dependency cachekey is known a page can be expired.
You could try this: ``` private void RemoveButton_Click(object sender, System.EventArgs e) { HttpResponse.RemoveOutputCacheItem("/caching/CacheForever.aspx"); } ``` From: <http://aspalliance.com/668> Thanks.
Asp.Net OutputCache and Expiration
[ "", "c#", "asp.net", "vb.net", "caching", "outputcache", "" ]
I have two expressions of type `Expression<Func<T, bool>>` and I want to take to OR, AND or NOT of these and get a new expression of the same type ``` Expression<Func<T, bool>> expr1; Expression<Func<T, bool>> expr2; ... //how to do this (the code below will obviously not work) Expression<Func<T, bool>> andExpression = expr AND expr2 ```
Well, you can use `Expression.AndAlso` / `OrElse` etc to combine logical expressions, but the problem is the parameters; are you working with the same `ParameterExpression` in expr1 and expr2? If so, it is easier: ``` var body = Expression.AndAlso(expr1.Body, expr2.Body); var lambda = Expression.Lambda<Func<T,bool>>(body, expr1.Parameters[0]); ``` This also works well to negate a single operation: ``` static Expression<Func<T, bool>> Not<T>( this Expression<Func<T, bool>> expr) { return Expression.Lambda<Func<T, bool>>( Expression.Not(expr.Body), expr.Parameters[0]); } ``` Otherwise, depending on the LINQ provider, you might be able to combine them with `Invoke`: ``` // OrElse is very similar... static Expression<Func<T, bool>> AndAlso<T>( this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right) { var param = Expression.Parameter(typeof(T), "x"); var body = Expression.AndAlso( Expression.Invoke(left, param), Expression.Invoke(right, param) ); var lambda = Expression.Lambda<Func<T, bool>>(body, param); return lambda; } ``` Somewhere, I have got some code that re-writes an expression-tree replacing nodes to remove the need for `Invoke`, but it is quite lengthy (and I can't remember where I left it...) --- Generalized version that picks the simplest route: ``` static Expression<Func<T, bool>> AndAlso<T>( this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) { // need to detect whether they use the same // parameter instance; if not, they need fixing ParameterExpression param = expr1.Parameters[0]; if (ReferenceEquals(param, expr2.Parameters[0])) { // simple version return Expression.Lambda<Func<T, bool>>( Expression.AndAlso(expr1.Body, expr2.Body), param); } // otherwise, keep expr1 "as is" and invoke expr2 return Expression.Lambda<Func<T, bool>>( Expression.AndAlso( expr1.Body, Expression.Invoke(expr2, param)), param); } ``` Starting from .NET 4.0, there is the `ExpressionVisitor` class which allows you to build expressions that are EF safe. ``` public static Expression<Func<T, bool>> AndAlso<T>( this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) { var parameter = Expression.Parameter(typeof (T)); var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter); var left = leftVisitor.Visit(expr1.Body); var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter); var right = rightVisitor.Visit(expr2.Body); return Expression.Lambda<Func<T, bool>>( Expression.AndAlso(left, right), parameter); } private class ReplaceExpressionVisitor : ExpressionVisitor { private readonly Expression _oldValue; private readonly Expression _newValue; public ReplaceExpressionVisitor(Expression oldValue, Expression newValue) { _oldValue = oldValue; _newValue = newValue; } public override Expression Visit(Expression node) { if (node == _oldValue) return _newValue; return base.Visit(node); } } ```
You can use Expression.AndAlso / OrElse to combine logical expressions, but you have to make sure the ParameterExpressions are the same. I was having trouble with EF and the [PredicateBuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx) so I made my own without resorting to Invoke, that I could use like this: ``` var filterC = filterA.And(filterb); ``` Source code for my PredicateBuilder: ``` public static class PredicateBuilder { public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> a, Expression<Func<T, bool>> b) { ParameterExpression p = a.Parameters[0]; SubstExpressionVisitor visitor = new SubstExpressionVisitor(); visitor.subst[b.Parameters[0]] = p; Expression body = Expression.AndAlso(a.Body, visitor.Visit(b.Body)); return Expression.Lambda<Func<T, bool>>(body, p); } public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> a, Expression<Func<T, bool>> b) { ParameterExpression p = a.Parameters[0]; SubstExpressionVisitor visitor = new SubstExpressionVisitor(); visitor.subst[b.Parameters[0]] = p; Expression body = Expression.OrElse(a.Body, visitor.Visit(b.Body)); return Expression.Lambda<Func<T, bool>>(body, p); } } ``` And the utility class to substitute the parameters in a lambda: ``` internal class SubstExpressionVisitor : System.Linq.Expressions.ExpressionVisitor { public Dictionary<Expression, Expression> subst = new Dictionary<Expression, Expression>(); protected override Expression VisitParameter(ParameterExpression node) { Expression newValue; if (subst.TryGetValue(node, out newValue)) { return newValue; } return node; } } ```
Combining two expressions (Expression<Func<T, bool>>)
[ "", "c#", "linq", "lambda", "expression", "" ]
Sorry if this is a comp-sci 101 question. I'm just unsure if I'm missing something obvious. So let's say some user input throws an error, and I want to catch it and return some feedback. The error will be a number, 0 - 8. 0 means "No Error". I want to give the user very specific feedback if the error is 3 (No numbers allowed, let's say). For the other 7 possibilities, I just want to end the script and echo the error. I was working this out and decided to go with this: ``` $no_errors ($_error != 0 || $_error != 3) ? FALSE : TRUE; if (!$no_errors) echo $error_msg['$_error']; $error_3 ($no_errors && $_error == 3) ? TRUE : FALSE; if ($error_3) bunch of stuff happens; else bunch of other stuff; ``` Anyways, I was then noticing the OR operator on the first line and was thinking that it might be better/safer to user an AND operator. But the more I contemplate, the less I see a difference. So the real question is, if you want to eliminate two possibilities of a specific variable, are AND and OR identical, or is one logically/functionally more optimal?
logically the following are identical ( excuse my pseudo code ) ``` (! expression_one || ! expression_two) /** this is the same as the one below **/ ! (expression_one && expression_two) ``` Functionally which one is more optimal? They are both as optimal as each other. Both ways (&& and ||) allow short circuiting if the first expression is true (in the || case) or false ( in the && case)
It will be much more readable if you use a switch statement: ``` switch ($_error) { case 0; nothing happens; break; case 3: bunch of stuff happens; break; default: bunch of other stuff; break; } ```
Logical Operators: is AND better than OR?
[ "", "php", "error-handling", "logic", "" ]
I have a struct like this: ``` class Items { private: struct item { unsigned int a, b, c; }; item* items[MAX_ITEMS]; } ``` Say I wanted to 'delete' an item, like so: ``` items[5] = NULL; ``` And I created a new item on that same spot later: ``` items[5] = new item; ``` Would I still need to call `delete[]` to clean this up? Or won't this be needed since bounds of array `items[]` are known before compiling? Is setting that pointer to NULL valid or should I be calling delete there?
You need to call `delete` before setting it to NULL. (Setting it to NULL isn't required, it just helps reduce bugs if you accidentally try to dereference the pointer after deleting it.) Remember that every time you use `new`, you will need to use `delete` later on the same pointer. Never use one without the other. Also, `new []` and `delete []` go together in the same way, but you should never mix `new []` with `delete` or `new` with `delete []`. In your example, since you created the object with `new` (rather than `new []` which would create an array of objects) you must delete the object with `delete` (rather than `delete []`).
As Kluge pointed out, you'd leak the object at index 5 like that. But this one really sounds like you shouldn't do this manually but use a container class inside `Item`. If you don't actually need to store these `item` objects as pointers, use `std::vector<item>` instead of that array of `MAX_ITEMS` pointers. You can always insert or erase vector elements in the middle as well if you need to. In case you need to store the objects as pointers (usually if struct `item` is actually polymorphic, unlike in your example), you can use boost::ptr\_vector<item> from [Boost.PtrContainer](http://www.boost.org/doc/libs/1_37_0/libs/ptr_container/doc/ptr_container.html) instead. Example: ``` class Items { private: struct item { unsigned int a, b, c; }; std::vector<item> items; } if (items.size() > 5) // (just to ensure there is an element at that position) items.erase(items.begin() + 5); // no need to use operator delete at all ```
Array of structs and new / delete
[ "", "c++", "arrays", "memory-management", "struct", "new-operator", "" ]
I have been programming in C# and Java for a little over a year and have a decent grasp of object oriented programming, but my new side project requires a database-driven model. I'm using C# and Linq which seems to be a very powerful tool but I'm having trouble with designing a database around my object oriented approach. My two main question are: **How do I deal with inheritance in my database?** Let's say I'm building a staff rostering application and I have an abstract class, Event. From Event I derive abstract classes ShiftEvent and StaffEvent. I then have concrete classes Shift (derived from ShiftEvent) and StaffTimeOff (derived from StaffEvent). There are other derived classes, but for the sake of argument these are enough. Should I have a separate table for ShiftEvents and StaffEvents? Maybe I should have separate tables for each concrete class? Both of these approaches seem like they would give me problems when interacting with the database. Another approach could be to have one Event table, and this table would have nullable columns for every type of data in any of my concrete classes. All of these approaches feel like they could impede extensibility down the road. More than likely there is a third approach that I have not considered. My second question: **How do I deal with collections and one-to-many relationships in an object oriented way?** Let's say I have a Products class and a Categories class. Each instance of Categories would contain one or more products, but the products themselves should have no knowledge of categories. If I want to implement this in a database, then each product would need a category ID which maps to the categories table. But this introduces more coupling than I would prefer from an OO point of view. The products shouldn't even know that the categories exist, much less have a data field containing a category ID! Is there a better way?
Linq to SQL using a table per class solution: <http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/10/01/linq-to-sql-inheritance.aspx> Other solutions (such as my favorite, LLBLGen) allow other models. Personally, I like the single table solution with a discriminator column, but that is probably because we often query across the inheritance hierarchy and thus see it as the normal query, whereas querying a specific type only requires a "where" change. All said and done, I personally feel that mapping OO into tables is putting the cart before the horse. There have been continual claims that the impedance mismatch between OO and relations has been solved... and there have been plenty of OO specific databases. None of them have unseated the powerful simplicity of the relation. Instead, I tend to design the database with the application in mind, map those tables to entities and build from there. Some find this as a loss of OO in the design process, but in my mind the data layer shouldn't be talking high enough into your application to be affecting the design of the higher order systems, just because you used a relational model *for storage*.
I had the opposite problem: how to get my head around OO after years of database design. Come to that, a decade earlier I had the problem of getting my head around SQL after years of "structured" flat-file programming. There are jsut enough similarities betwwen class and data entity decomposition to mislead you into thinking that they're equivalent. They aren't. I tend to agree with the view that once you're committed to a relational database for storage then you should design a normalised model and compromise your object model where unavoidable. This is because you're more constrained by the DBMS than you are with your own code - building a compromised data model is more likley to cause you pain. That said, in the examples given, you have choices: if ShiftEvent and StaffEvent are mostly similar in terms of attributes and are often processed together as Events, then I'd be inclined to implement a single Events table with a type column. Single-table views can be an effective way to separate out the sub-classes and on most db platforms are updatable. If the classes are more different in terms of attributes, then a table for each might be more appropriate. I don't think I like the three-table idea:"has one or none" relationships are seldom necessary in relational design. Anyway, you can always create an Event view as the union of the two tables. As to Product and Category, if one Category can have many Products, but not vice versa, then the normal relational way to represent this is for the product to contain a category id. Yes, it's coupling, but it's only data coupling, and it's not a mortal sin. The column should probably be indexed, so that it's efficient to retrieve all products for a category. If you're really horrified by the notion then pretend it's a many-to-many relationship and use a separate ProductCategorisation table. It's not that big a deal, although it implies a potential relationship that doesn't really exist and might mislead somone coming to the app in future.
How can an object-oriented programmer get his/her head around database-driven programming?
[ "", "sql", "linq", "database-design", "oop", "" ]
I'm looking to connect or glue together two shapes or objects with a Line. These shapes will be generated dynamically, meaning I'll be calling a Web service on the backend to determine how many objects/shapes need to be created. Once this is determined, I'll need to have the objects/shapes connected together. The method signature may look like this (similar to Visio's drawing capabilities): ``` GlueTogether(objButton1, objButton2); ``` I may need to get the position of each Rectangle shape or Button to determine where the starting Line point is. Then determine the second shape/objects position to draw the line. Any help or suggestions would be great!
1. Use a Path or a Line below the shapes in stacking order or z index 2. Use instance.TransformToVisual() to get the transform of each shape 3. Use the transform to transform the centerpoint of each shape 4. Draw a line between the two centerpoints. --- ``` var transform1 = shape1.TransformToVisual(shape1.Parent as UIElement); var transform2 = shape2.TransformToVisual(shape2.Parent as UIElement); var lineGeometry = new LineGeometry() { StartPoint = transform1.Transform(new Point(shape1.ActualWidth / 2, shape1.ActualHeight / 2.0)), EndPoint = transform2.Transform(new Point(shape2.ActualWidth / 2.0, shape2.ActualHeight / 2.0)) }; var path = new Path() { Data = lineGeometry }; ```
I am trying much the same, but instead of the line going from one centre to the other I want the lines to stop at the edge of the two shapes. In particular I have arrows at the end of the lines, and the arrows need to stop at the bounds of the shapes instead of going inside/behind the shape to its centre. My shape is a usercontrol with a grid and rectangle, and some labels and other stuff. I can't find any methods that provide me with a geometry for the edge of the shape (which is a rounded rectangle). I figured out a solution that uses the bounding box and intersection points to connect my elements by lines at their approximate edges, and it works well for me using arrow ended lines. See [Connecting two WPF canvas elements by a line, without using anchors?](https://stackoverflow.com/questions/1737509/connecting-two-wpf-canvas-elements-by-a-line-without-using-anchors/1737536#1737536)
Connecting two shapes together, Silverlight 2
[ "", "c#", "wpf", "silverlight", "expression", "" ]
``` public class WrapperTest { static { print(10); } static void print(int x) { System.out.println(x); System.exit(0); } } ``` In the above code `System.exit(0)` is used to stop the program. What argument does that method take? Why do we gave it as `0`. Can anyone explain the concept?
From the [JAVA Documentation](http://java.sun.com/javase/6/docs/api/java/lang/System.html#exit(int)): > The argument serves as a status code; > by convention, a nonzero status code > indicates abnormal termination. And [Wikipedia](http://en.wikipedia.org/wiki/Exitcode) adds additional information.
It's the return value that the Java process will report to the calling process. It hasn't really got a precise definition, but the usual convention is that `0` means success and any non-zero value represents a failure.
Use of System.exit(0)
[ "", "java", "exit-code", "" ]
I hope you know, because I don't see it. Bonus points for whoever figures out how one can achieve what this test is trying to achieve. ``` using NUnit.Framework; using Moq; [TestFixture] public class MoqHuh { public class A {} public class B : A {} public interface IHelper { void DoIt(A a); } [Test] public void Huh() { var mock = new Mock<IHelper>(); mock.Expect(helper => helper.DoIt(It.IsAny<B>())).Verifiable(); mock.Object.DoIt(new B()); mock.VerifyAll(); } } ```
Turns out this was sort of pilot error. I incorrectly assumed Moq working fine on Mono. (which it looks like it does just fine). This issue only happens when compiled with mono's gmcs, not when compiled with Microsofts csc. I have reported the appropriate bugs with the mono team, and will continue towards making sure the full Moq test suite passes when compiled with mono's gmcs.exe Sorry for the noise. Lucas
This test works fine. Since there is no system under test, you are testing that moq works as expected.
Why does this NUnit+Moq test fail?
[ "", "c#", "nunit", "moq", "" ]
I'm trying to iterate through an array of elements. jQuery's documentation says: [jquery.Each() documentation](http://docs.jquery.com/Utilities/jQuery.each#objectcallback) > Returning non-false is the same as a continue statement in a for loop, it will skip immediately to the next iteration. I've tried calling 'return non-false;' and 'non-false;' (sans return) neither of which skip to the next iteration. Instead, they break the loop. What am i missing?
What they mean by non-false is: ``` return true; ``` So this code: ``` var arr = ["one", "two", "three", "four", "five"]; $.each(arr, function(i) { if (arr[i] == 'three') { return true; } console.log(arr[i]); }); ``` ``` <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> ``` will log `one`, `two`, `four`, `five`.
By 'return non-false', they mean to return any value which would not work out to boolean false. So you could return `true`, `1`, `'non-false'`, or whatever else you can think up.
How to skip to next iteration in jQuery.each() util?
[ "", "javascript", "jquery", "iteration", "" ]
Given a `List<T>` in c# is there a way to extend it (within its capacity) and set the new elements to `null`? I'd like something that works like a `memset`. I'm not looking for sugar here, I want fast code. I known that in C the operation could be done in something like 1-3 asm ops per entry. The best solution I've found is [this](https://stackoverflow.com/questions/481334/best-c-data-structure-for-random-order-population#481350): ``` list.AddRange(Enumerable.Repeat(null, count-list.Count)); ``` however that is c# 3.0 (<3.0 is preferred) and might be generating and evaluating an enumerator. My current code uses: ``` while(list.Count < lim) list.Add(null); ``` so that's the starting point for time cost. The [motivation for this](https://stackoverflow.com/questions/481334/best-c-data-structure-for-random-order-population) is that I need to set the n'th element even if it is after the old Count.
The simplest way is probably by creating a temporary array: ``` list.AddRange(new T[size - count]); ``` Where `size` is the required new size, and `count` is the count of items in the list. ~~However, for relatively large values of `size - count`, this can have bad performance, since it can cause the list to reallocate multiple times.~~(`*`) It also has the disadvantage of allocating an additional temporary array, which, depending on your requirements, may not be acceptable. You could mitigate both issues at the expense of more explicit code, by using the following methods: ``` public static class CollectionsUtil { public static List<T> EnsureSize<T>(this List<T> list, int size) { return EnsureSize(list, size, default(T)); } public static List<T> EnsureSize<T>(this List<T> list, int size, T value) { if (list == null) throw new ArgumentNullException("list"); if (size < 0) throw new ArgumentOutOfRangeException("size"); int count = list.Count; if (count < size) { int capacity = list.Capacity; if (capacity < size) list.Capacity = Math.Max(size, capacity * 2); while (count < size) { list.Add(value); ++count; } } return list; } } ``` The only C# 3.0 here is the use of the "`this`" modifier to make them extension methods. Remove the modifier and it will work in C# 2.0. Unfortunately, I never compared the performance of the two versions, so I don't know which one is better. Oh, and did you know you could resize an array by calling [`Array.Resize<T>`](http://msdn.microsoft.com/en-us/library/bb348051.aspx)? I didn't know that. :) **Update:** (`*`) Using `list.AddRange(array)` will *not* cause an enumerator to be used. Looking further through Reflector showed that the array will be casted to `ICollection<T>`, and the `Count` property will be used so that allocation is done only once.
``` static IEnumerable<T> GetValues<T>(T value, int count) { for (int i = 0; i < count; ++i) yield return value; } list.AddRange(GetValues<object>(null, number_of_nulls_to_add)); ``` This will work with 2.0+
Set/extend List<T> length in c#
[ "", "c#", "list", "" ]
I want to suppress the web browser's default tooltip display when a user hovers over certain links and elements. I know it's possible but I don't know how. Can anyone help? The reason for this is to suppress the tooltip for microformatted date-times. The BBC dropped support for hCalendar because the appearane of the machine-readable date was an accessibility issue for those with cognitive disabilities aswell as some screen reader users. <http://www.bbc.co.uk/blogs/bbcinternet/2008/07/why_the_bbc_removed_microforma.html> **EDIT:** I whipped up a jquery plugin along the same lines as Aron's suggestion... ``` // uFsuppress plugin v1.0 - toggle microformatted dates (function($){ $.ufsuppress = function() { $(".dtstart,.dtend,.bday").hover(function(){ $(this).attr("ufdata",$(this).attr("title")); $(this).removeAttr("title"); },function(){ $(this).attr("title",$(this).attr("ufdata")); $(this).removeAttr("ufdata"); }); } })(jQuery); // Usage $.ufsuppress(); ```
**As far as I know it is not possible to actually *suppress* showing the title tag.** There are some workarounds however. Assuming you mean you want to preserve the title property on your links and elements, you could use Javascript to remove the title property at `onmouseover()` and set it again at `onmouseout()`. ``` // Suppress tooltip display for links that have the classname 'suppress' var links = document.getElementsByTagName('a'); for (var i = 0; i < links.length; i++) { if (links[i].className == 'suppress') { links[i]._title = links[i].title; links[i].onmouseover = function() { this.title = ''; } links[i].onmouseout = function() { this.title = this._title; } } } ```
Add this element to your html ``` onmouseover="title='';" ``` For example i have a asp.net checkbox I store a hidden variable but do not want the user to see on as the tooltip.
Disabling browser tooltips on links and <abbr>s
[ "", "javascript", "jquery", "accessibility", "microformats", "" ]
How can I convert a BITMAP in byte array format to JPEG format using .net 2.0?
What type of `byte[]` do you mean? The raw file-stream data? In which case, how about something like (using `System.Drawing.dll` in a client application): ``` using(Image img = Image.FromFile("foo.bmp")) { img.Save("foo.jpg", ImageFormat.Jpeg); } ``` Or use `FromStream` with a `new MemoryStream(arr)` if you really do have a `byte[]`: ``` byte[] raw = ...todo // File.ReadAllBytes("foo.bmp"); using(Image img = Image.FromStream(new MemoryStream(raw))) { img.Save("foo.jpg", ImageFormat.Jpeg); } ```
If it is just a buffer of raw pixel data, and not a complete image file(including headers etc., such as a JPEG) then you can't use Image.FromStream. I think what you might be looking for is System.Drawing.Bitmap.LockBits, returning a System.Drawing.Imaging.ImageData; this provides access to reading and writing the image's pixels using a pointer to memory.
C#: How to convert BITMAP byte array to JPEG format?
[ "", "c#", ".net", "jpeg", "bmp", "" ]
I can implement the error function, erf, myself, but I'd prefer not to. Is there a python package with no external dependencies that contains an implementation of this function? I have found [this](http://pylab.sourceforge.net/packages/included_functions.html) but this seems to be part of some much larger package (and it's not even clear which one!).
Since v.2.7. the standard *math* module contains *erf* function. This should be the easiest way. <http://docs.python.org/2/library/math.html#math.erf>
I recommend SciPy for numerical functions in Python, but if you want something with no dependencies, here is a function with an error error is less than 1.5 \* 10-7 for all inputs. ``` def erf(x): # save the sign of x sign = 1 if x >= 0 else -1 x = abs(x) # constants a1 = 0.254829592 a2 = -0.284496736 a3 = 1.421413741 a4 = -1.453152027 a5 = 1.061405429 p = 0.3275911 # A&S formula 7.1.26 t = 1.0/(1.0 + p*x) y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*math.exp(-x*x) return sign*y # erf(-x) = -erf(x) ``` The algorithm comes from [Handbook of Mathematical Functions](https://rads.stackoverflow.com/amzn/click/com/0486612724), formula 7.1.26.
Is there an easily available implementation of erf() for Python?
[ "", "python", "math", "" ]
A related post [here](https://stackoverflow.com/questions/435553/java-reflection-performance) pretty much established reflection in Java as a performance hog. Does that apply to the CLR as well? (C#, VB.NET, etc). ***EDIT***: How does the CLR compare to Java when it comes to reflection? Was that ever benchmarked?
I wouldn't really care about the instantiation performance of the object using reflection itself but the actual performance of methods and such since those are after all what I'll be using from the class anyway. Surely the instantiation takes a lot of time as can be seen in the linked post but since you're most likely using the object's methods instead of just instantiating it, you shouldn't worry too much about reflection performance - as long as you're not doing the method calls by invoking reflected `Method` objects! Besides you only need one reflected instance of the object, use `.clone()` and other clever tricks if you need to create more copies.
Yeah, reflection in .NET is a performance intensive operation too as it requires querying metadata tables in assemblies.
Reflection runtime performance - Java vs CLR
[ "", "java", "reflection", "clr", "performance", "" ]
I want to use java.util.ConcurrentLinkedQueue as a non-durable queue for a Servlet. Here's the blurb from the javadoc for the class. > An unbounded thread-safe queue based on linked nodes. A ConcurrentLinkedQueue is an appropriate choice when many threads will share access to a common collection. This queue does not permit null elements. Now imagine I have 1000 concurrent requests on the servlet, and each thread will need to enque an object into the ConcurrentLinkedQueue. From the description, should I conclude that it will have no problems handling the load ? The guarantee that I will need is that: 1. I automatically receive the thread-safe guarantee without needing to do my own synchronization. 2. I will not lose any requests if the traffic load goes beyond 1000 concurrent request. Thanks
You're essentially asking three different questions (two of them explicitly and one implicitly.) Here they are, with my answers: **1. Do I need to do my own synchronization if I use `java.util.ConcurrentLinkedQueue`?** Atomic operations on the concurrent collections are synchronized for you. In other words, each individual call to the queue is guaranteed thread-safe without any action on your part. What is **not** guaranteed thread-safe are any operations you perform on the collection that are non-atomic. For example, this is threadsafe without any action on your part: ``` queue.add(obj); ``` or ``` queue.poll(obj); ``` However; non-atomic calls to the queue are not automatically thread-safe. For example, the following operations are **not** automatically threadsafe: ``` if(!queue.isEmpty()) { queue.poll(obj); } ``` That last one is not threadsafe, as it is very possible that between the time isEmpty is called and the time poll is called, other threads will have added or removed items from the queue. The threadsafe way to perform this is like this: ``` synchronized(queue) { if(!queue.isEmpty()) { queue.poll(obj); } } ``` Again...atomic calls to the queue are automatically thread-safe. Non-atomic calls are not. **2. Am I guaranteed not to lose calls to `java.util.ConcurrentLinkedQueue` if there are 1000 simultaneous requests?** Because this is an unbounded implementation you are guaranteed that no matter how many simultaneous requests to make, the queue will not lose those requests (because of the queue's concurrency...you might run out of memory or some such...but the queue implementation itself will not be your limiting factor.) In a web application, there are other opportunities to "lose" requests, but the synchronization (or lack thereof) of the queue won't be your cause. **3. Will the `java.util.ConcurrentLinkedQueue` perform well enough?** Typically, we talk about "correctness" when we talk about concurrency. What I mean, is that Concurrent classes guarantee that they are thread-safe (or robust against dead-lock, starvation, etc.) When we talk about that, we aren't making any guarantees about performance (how fast calls to the collection are) - we are only guaranteeing that they are "correct." However; the ConcurrentLinkedQueue is a "wait-free" implementation, so this is probably as performant as you can get. The only way to guarantee load performance of your servlet (including the use of the concurrent classes) is to test it under load.
Remember that the queue is only threadsafe for calls to a single member. Don't write code like this and expect it to work: ``` if (queue.Count!=0) queue.Dequeue().DoSomething(); ``` In between these two operations, another thread may have dequeued the last element. I'm not intimate with Java collections, but I guess Dequeue in such a case would return `null`, giving you an exception.
java.util.ConcurrentLinkedQueue
[ "", "java", "tomcat", "servlets", "concurrency", "queue", "" ]
I hope this question is not a RTFM one. I am trying to write a Python script that extracts links from a standard HTML webpage (the `<link href...` tags). I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links? Adam **UPDATE:** I am actually looking for two different answers: 1. What's the library solution for parsing HTML links. [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) seems to be a good solution (thanks, `Igal Serban` and `cletus`!) 2. Can a link be defined using a regex?
As others have suggested, if real-time-like performance isn't necessary, BeautifulSoup is a good solution: ``` import urllib2 from BeautifulSoup import BeautifulSoup html = urllib2.urlopen("http://www.google.com").read() soup = BeautifulSoup(html) all_links = soup.findAll("a") ``` As for the second question, yes, HTML links ought to be well-defined, but the HTML you actually encounter is very unlikely to be standard. The beauty of BeautifulSoup is that it uses browser-like heuristics to try to parse the non-standard, malformed HTML that you are likely to actually come across. If you are certain to be working on standard XHTML, you can use (much) faster XML parsers like expat. Regex, for the reasons above (the parser must maintain state, and regex can't do that) will never be a general solution.
Regexes with HTML get messy. Just use a DOM parser like Beautiful Soup.
Regex for links in html text
[ "", "python", "html", "regex", "hyperlink", "href", "" ]
I'm currently working on a project that contains many different Eclipse projects referencing each other to make up one large project. Is there a point where a developer should ask themselves if they should rethink the way their development project is structured? **NOTE:** My project currently contains 25+ different Eclipse projects.
My general rule of thumb is I would create a new project for every reusable component. So for example if I have some isolated functionality that can be packaged say as a jar, I would create a new project so I can build,package and distribute the component independently. Also, if there are certain projects that you do not need to make frequent changes to, you can build them only when required and keep them "closed" in eclipse to save time on indexing, etc. Even if you think that a certain component is not reusable, as long as it is separated from the rest of the code base in terms of logic/concerns you may be well served by just separating it out. Sometimes seemingly specific code might be reusable in another project or in a future version of the same project.
If your project has *that* many sub-projects, or modules, needed to actually compose your final artifact then it is time to look at having something like Maven and setting up a multi-module project. It will a) allow you to work on each module independently without ide worries and allow easy setup in your ide (and others' IDEs) through the `mvn eclipse:eclipse` goal. In addition, when building your entire top level project, maven will be able to derive from list of dependencies you have described what modules need to be built in what order. [Here's a quick link via google](http://docs.codehaus.org/display/MAVENUSER/Multi-modules+projects) and a l[ink to the book Maven: The Definitive Guide](http://books.sonatype.com/maven-book/reference/multimodule-sect-simple-weather.html), which will explain things in much better detail in chapter 6 (once you have the basics). This will also force your project to not be explicitly tied to Eclipse. Being able to build independent from an ide means that any Joe Schmoe can come along and easily work with your code base using whatever tools he/she needs.
How many multiple "Eclipse Projects" is considered too excessive for one actual development project?
[ "", "java", "eclipse", "" ]
I need to be able to list the command line arguments (if any) passed to other running processes. I have the PIDs already of the running processes on the system, so basically I need to determine the arguments passed to process with given PID *XXX*. I'm working on a core piece of a [Python module for managing processes](http://code.google.com/p/psutil/). The code is written as a Python extension in C and will be wrapped by a higher level Python library. The goal of this project is to avoid dependency on third party libs such as the pywin32 extensions, or on ugly hacks like calling 'ps' or taskkill on the command line, so I'm looking for a way to do this in C code. I've Googled this around and found some brief suggestions of using [CreateRemoteThread()](http://msdn.microsoft.com/en-us/library/ms682437(VS.85).aspx) to inject myself into the other process, then run [GetCommandLine()](http://msdn.microsoft.com/en-us/library/ms683156(VS.85).aspx) but I was hoping someone might have some working code samples and/or better suggestions. **UPDATE**: I've found full working demo code and a solution using NtQueryProcessInformation on CodeProject: <http://www.codeproject.com/KB/threads/GetNtProcessInfo.aspx> - It's not ideal since it's "unsupported" to cull the information directly from the NTDLL structures but I'll live with it. Thanks to all for the suggestions. **UPDATE 2**: I managed through more Googling to dig up a C version that does not use C++ code, and is a little more direct/concisely pointed toward this problem. See <http://wj32.wordpress.com/2009/01/24/howto-get-the-command-line-of-processes/> for details. Thanks!
To answer my own question, I finally found a CodeProject solution that does exactly what I'm looking for: <http://www.codeproject.com/KB/threads/GetNtProcessInfo.aspx> As @Reuben already pointed out, you can use [NtQueryProcessInformation](http://msdn.microsoft.com/en-us/library/ms684280(VS.85).aspx) to retrieve this information. Unfortuantely it's not a recommended approach, but given the only other solution seems to be to incur the overhead of a WMI query, I think we'll take this approach for now. Note that this seems to not work if using code compiled from 32bit Windows on a 64bit Windows OS, but since our modules are compiled from source on the target that should be OK for our purposes. I'd rather use this existing code and should it break in Windows 7 or a later date, we can look again at using WMI. Thanks for the responses! **UPDATE**: A more concise and C only (as opposed to C++) version of the same technique is illustrated here: <http://wj32.wordpress.com/2009/01/24/howto-get-the-command-line-of-processes/>
The cached solution: <http://74.125.45.132/search?q=cache:-wPkE2PbsGwJ:windowsxp.mvps.org/listproc.htm+running+process+command+line&hl=es&ct=clnk&cd=1&gl=ar&client=firefox-a> ``` in CMD WMIC /OUTPUT:C:\ProcessList.txt PROCESS get Caption,Commandline,Processid or WMIC /OUTPUT:C:\ProcessList.txt path win32_process get Caption,Processid,Commandline ``` Also: <http://mail.python.org/pipermail/python-win32/2007-December/006498.html> ``` http://tgolden.sc.sabren.com/python/wmi_cookbook.html#running_processes seems to do the trick: import wmi c = wmi.WMI () for process in c.Win32_Process (): print process.CommandLine ```
Reading Command Line Arguments of Another Process (Win32 C code)
[ "", "python", "c", "winapi", "" ]
I have two models, `Room` and `Image`. `Image` is a generic model that can tack onto any other model. I want to give users a form to upload an image when they post information about a room. I've written code that works, but I'm afraid I've done it the hard way, and specifically in a way that violates DRY. Was hoping someone who's a little more familiar with django forms could point out where I've gone wrong. **Update:** I've tried to clarify why I chose this design in comments to the current answers. To summarize: I didn't simply put an `ImageField` on the `Room` model because I wanted more than one image associated with the Room model. I chose a generic Image model because I wanted to add images to several different models. The alternatives I considered were were multiple foreign keys on a single `Image` class, which seemed messy, or multiple `Image` classes, which I thought would clutter my schema. I didn't make this clear in my first post, so sorry about that. Seeing as none of the answers so far has addressed how to make this a little more DRY I did come up with my own solution which was to add the upload path as a class attribute on the image model and reference that every time it's needed. ``` # Models class Image(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') image = models.ImageField(_('Image'), height_field='', width_field='', upload_to='uploads/images', max_length=200) class Room(models.Model): name = models.CharField(max_length=50) image_set = generic.GenericRelation('Image') # The form class AddRoomForm(forms.ModelForm): image_1 = forms.ImageField() class Meta: model = Room # The view def handle_uploaded_file(f): # DRY violation, I've already specified the upload path in the image model upload_suffix = join('uploads/images', f.name) upload_path = join(settings.MEDIA_ROOT, upload_suffix) destination = open(upload_path, 'wb+') for chunk in f.chunks(): destination.write(chunk) destination.close() return upload_suffix def add_room(request, apartment_id, form_class=AddRoomForm, template='apartments/add_room.html'): apartment = Apartment.objects.get(id=apartment_id) if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): room = form.save() image_1 = form.cleaned_data['image_1'] # Instead of writing a special function to handle the image, # shouldn't I just be able to pass it straight into Image.objects.create # ...but it doesn't seem to work for some reason, wrong syntax perhaps? upload_path = handle_uploaded_file(image_1) image = Image.objects.create(content_object=room, image=upload_path) return HttpResponseRedirect(room.get_absolute_url()) else: form = form_class() context = {'form': form, } return direct_to_template(request, template, extra_context=context) ```
You don't have to use the Image class. As [DZPM](https://stackoverflow.com/users/30300/dzpm) suggested, convert the image field to an ImageField. You also need to make some changes to the view. Instead of using an upload handler, you can create a Image object with the uploaded data and attach the Image object to the Room object. To save the Image object you need to do something like this in the view: ``` from django.core.files.base import ContentFile if request.FILES.has_key('image_1'): image_obj = Image() image_obj.file.save(request.FILES['image_1'].name,\ ContentFile(request.FILES['image_1'].read())) image_obj.save() room_obj.image_set.create(image_obj) room_obj.save() ``` Also, I think instead of the GenericRelation, you should use a ManyToManyField, in which case the syntax for adding an Image to a Room will change slightly.
Why don't you just use `ImageField`? I don't see the need for the `Image` class. ``` # model class Room(models.Model): name = models.CharField(max_length=50) image = models.ImageField(upload_to="uploads/images/") # form from django import forms class UploadFileForm(forms.Form): name = forms.CharField(max_length=50) image = forms.FileField() ``` Take a look at [Basic file uploads](http://docs.djangoproject.com/en/dev/topics/http/file-uploads/#basic-file-uploads) and [How do I use image and file fields?](http://docs.djangoproject.com/en/dev/faq/usage/#how-do-i-use-image-and-file-fields)
Adding a generic image field onto a ModelForm in django
[ "", "python", "django", "django-forms", "" ]
EIMI being an explicit interface member implementation. So instead of: ``` public int SomeValue{get;} ``` you have ``` int SomeInterface.SomeValue {get;} ``` I'm currently considering using one as i'm using an internal interface (to decouple, yet restrict) and I don't want to make the methods on the implementing object to appear in its public API. Is this a good use case?
Yep, that's a good use case. According to [C# Language Specification](http://msdn.microsoft.com/en-us/library/aa664591(VS.71).aspx) on MSDN: > Explicit interface member implementations serve two primary purposes: > > * Because explicit interface member implementations are not accessible through class or struct instances, they allow interface implementations to be excluded from the public interface of a class or struct. This is particularly useful when a class or struct implements an internal interface that is of no interest to a consumer of that class or struct. > * Explicit interface member implementations allow disambiguation of interface members with the same signature. Without explicit interface member implementations it would be impossible for a class or struct to have different implementations of interface members with the same signature and return type, as would it be impossible for a class or struct to have any implementation at all of interface members with the same signature but with different return types.
A very good example is in the .Net generic collections classes. For example, `List<T>` implements 'IList' implicitly and `IList` (non generic interface) explicitly. That means when you use the class directly you'll only see the specialized methods and not the ones that work with Object. Let's say you instantiate a `List<Person>`. If IList was implemented implicitly you'd have two add methods directly accessible on the class Add(Person item) and Add(Object item), which will break type safety provided by generics. Calling list.Add("Foo") will compile just fine as the Add(Object) overload will get chosen automatically, and type safety provided by generics is gone.
Whats a good use case for an EIMI?
[ "", "c#", ".net", "interface", "" ]
Previously I've asked about [inserting a column into a dataset](https://stackoverflow.com/questions/351557/how-does-one-insert-a-column-into-a-dataset-between-two-existing-columns). I now have a similar question...namely merging two or more columns into a single column. Lets say I have the following data set: ``` DataSet ds = new DataSet(); ds.Tables.Add(new DataTable()); ds.Tables[0].Columns.Add("id", typeof(int)); ds.Tables[0].Columns.Add("firstname", typeof(string)); ds.Tables[0].Columns.Add("lastname", typeof(string)); ``` I am needing to combine the "firstname" and "lastname" columns into a single column called "name". Would it be best for me to create a method that merges two columns together or a more general one that can be used to merge multiple columns together? My idea is to create a generalized method sort of like the following: MergeColumns(string format, string mergedColumn, DataTable dt, params string[] columnsToMerge) The user supplies a format as follows: "{0} {1}" mergedColumn is the name of the new column...but it must be able to be the same as one of the columns that will be merged cause in my real world case I'm merging "name" and "given\_names" into "name"...but I still want to be able to use it if I ever needed to merge "street", "city", "state" "postcode" etc into a column called "address". The way I am thinking this would be used is as follows: MergeColumns("{0} {1}", "name", dataTable, "firstname", "lastname"); given the above dataset, I would expect the resultant data set to look as follows: ``` DataSet ds = new DataSet(); ds.Tables.Add(new DataTable()); ds.Tables[0].Columns.Add("id", typeof(int)); ds.Tables[0].Columns.Add("name", typeof(string)); ``` Does this seem like a reasonable approach? Does a method like this already exist? I don't want to reinvent the wheel. Also, am I creating a method that does more than I actually need right now?
it seems to me that this should happen in the data layer and not the logic layer. presumably the dataset consumer knows what data it needs and could request it from the datastore explicitly, without having to manipulate datasets. in a database scenario, i'm essentially proponing a multiple stored procedure approach and the dataset consumer would retrieve the data from the appropriate one.
``` public partial class Form1 : Form { public Form1() { InitializeComponent(); DataSet ds = new DataSet(); ds.Tables.Add(new DataTable()); ds.Tables[0].Columns.Add("id", typeof(int)); ds.Tables[0].Columns.Add("firstname", typeof(string)); ds.Tables[0].Columns.Add("lastname", typeof(string)); ds.Tables[0].Rows.Add(1,"torvalds", "linus"); ds.Tables[0].Rows.Add(2,"lennon", "john"); ds.Tables[0].MergeColumns("name", "lastname", "firstname"); foreach (DataRow dr in ds.Tables[0].Rows) MessageBox.Show(dr["name"].ToString()); } } public static class Helper { public static void MergeColumns(this DataTable t, string newColumn, params string[] columnsToMerge) { t.Columns.Add(newColumn, typeof(string)); var sb = new StringBuilder(); sb.Append("{0}, "); for (int i = 1; i < columnsToMerge.Length; ++i) sb.Append("{" + i.ToString() + "}"); string format = sb.ToString(); foreach(DataRow r in t.Rows) r[newColumn] = string.Format(format, columnsToMerge.Select(col => r[col]).ToArray() ); } } ```
How do I merge two columns in a DataSet?
[ "", "c#", "merge", "dataset", "" ]
I'm trying to generate a sales reports which lists each product + total sales in a given month. Its a little tricky because the prices of products can change throughout the month. For example: * Between Jan-01 and Jan-15, my company sells 50 Widgets at a cost of $10 each * Between Jan-15 and Jan-31, my company sells 50 more Widgets at a cost of $15 each * The total sales of Widgets for January = (50 \* 10) + (50 \* 15) = $1250 This setup is represented in the database as follows: ``` Sales table Sale_ID ProductID Sale_Date 1 1 2009-01-01 2 1 2009-01-01 3 1 2009-01-02 ... 50 1 2009-01-15 51 1 2009-01-16 52 1 2009-01-17 ... 100 1 2009-01-31 Prices table Product_ID Sale_Date Price 1 2009-01-01 10.00 1 2009-01-16 15.00 ``` When a price is defined in the prices table, it is applied to all products sold with the given ProductID from the given SaleDate going forward. Basically, I'm looking for a query which returns data as follows: ``` Desired output Sale_ID ProductID Sale_Date Price 1 1 2009-01-01 10.00 2 1 2009-01-01 10.00 3 1 2009-01-02 10.00 ... 50 1 2009-01-15 10.00 51 1 2009-01-16 15.00 52 1 2009-01-17 15.00 ... 100 1 2009-01-31 15.00 ``` I have the following query: ``` SELECT Sale_ID, Product_ID, Sale_Date, ( SELECT TOP 1 Price FROM Prices WHERE Prices.Product_ID = Sales.Product_ID AND Prices.Sale_Date < Sales.Sale_Date ORDER BY Prices.Sale_Date DESC ) as Price FROM Sales ``` **This works, but is there a more efficient query than a nested sub-select?** And before you point out that it would just be easier to include "price" in the Sales table, I should mention that the schema is maintained by another vendor and I'm unable to change it. And in case it matters, I'm using SQL Server 2000.
If you start storing start and end dates, or create a view that includes the start and end dates (you can even create an indexed view) then you can heavily simplify your query. (provided you are certain there are no range overlaps) ``` SELECT Sale_ID, Product_ID, Sale_Date, Price FROM Sales JOIN Prices on Sale_date > StartDate and Sale_Date <= EndDate -- careful not to use between it includes both ends ``` Note: A technique along these lines will allow you to do this with a view. Note, if you need to index the view, it will have to be juggled around quite a bit .. ``` create table t (d datetime) insert t values(getdate()) insert t values(getdate()+1) insert t values(getdate()+2) go create view myview as select start = isnull(max(t2.d), '1975-1-1'), finish = t1.d from t t1 left join t t2 on t1.d > t2.d group by t1.d select * from myview start finish ----------------------- ----------------------- 1975-01-01 00:00:00.000 2009-01-27 11:12:57.383 2009-01-27 11:12:57.383 2009-01-28 11:12:57.383 2009-01-28 11:12:57.383 2009-01-29 11:12:57.383 ```
It's well to avoid these types of correlated subqueries. Here's a classic technique for such cases. ``` SELECT Sale_ID, Product_ID, Sale_Date, p1.Price FROM Sales AS s LEFT JOIN Prices AS p1 ON s.ProductID = p1.ProductID AND s.Sale_Date >= p1.Sale_Date LEFT JOIN Prices AS p2 ON s.ProductID = p2.ProductID AND s.Sale_Date >= p2.Sale_Date AND p2.Sale_Date > p1.Sale_Date WHERE p2.Price IS NULL -- want this one not to be found ``` Use a left outer join on the pricing table as p2, and look for a NULL record demonstrating that the matched product-price record found in p1 is the most recent on or before the sales date. (I would have inner-joined the first price match, but if there is none, it's nice to have the product show up anyway so you know there's a problem.)
Optimizing Query With Subselect
[ "", "sql", "sql-server", "optimization", "" ]
Suppose assembly Assembly1.dll contains 3 classes: Class C1, C2, C3. I want to expose only class C1 to the outside world. Classes C2 and C3 will not be accessible. How to acheive this? Note: Making classes C2 and C3 private is not an option as this will make them unaccessible inside the assembly itself.
Make classes C2 and C3 internal, as in: ``` internal class C2 { //... } ```
As others have said, you use `internal` visibility. A couple more points though: * For non-nested types, internal is actually the default in C#, so you don't *have* to specify it. Whether or not you explicitly specify the default access is a matter of personal taste. (I'm currently on the fence, leaning towards being explicit.) * Only nested types can be private in the first place - and again, that's the default visibility for nested types.
How to expose only one particular class from an assembly?
[ "", "c#", "oop", "assemblies", "" ]
I've managed to find the Regex to get almost the result I want here i.e. ``` Regex r1 = new Regex(@"\[(.*?)\]"); string row = HEADERNAMES[COL1,COL2,COL3,COL4]; Match match = r1.Match(row); string result = match.ToString(); ``` Outputs: "[COL1,COL2,COL3,COL4]"; I know I can then use: ``` result.Replace("[", ""); result.Replace("]", ""); ``` to get exactly what I want but I was wondering if there was a way to ommit the delimeters [ and ] from the Regex result without performing the String methods. I would have thought there was a more elegant solution using Regex itself?? Thanks in advance.
``` Regex r1 = new Regex(@"\[(.+)\]"); string row = "HEADERNAMES[COL1, COL2, COL3, COL4]"; // Regex puts capture groups (i.e. things captured between ( and ) ) // in Groups collection string match = r1.Match(row).Groups[1].Value; //match = "COL1, COL2, COL3, COL4" ```
There's one major point to observe in the solution presented by "Aku" (I don't yet have the rep to comment) You should note that the 2nd item in the Groups collection provides the value you need. The first item (Groups(0)) is equivalent to the entire matched string (Match.ToString() or Match.Value)
Regex to match a substring within 2 brackets, e.g. [i want this text] BUT leave out the brackets?
[ "", "c#", ".net", "regex", "" ]
Are there any tools that can take a fully-constructed/wired Spring application context and export a visualization of it? I'm talking about a live context that shows the order in which aspects were applied, what beans were auto-wired into other beans, etc. I know it can be done with the context files themselves (re: Spring IDE). However, I believe the new annotation-driven paradigm defeats this approach. An Eclipse plug-in or command-line solution is preferred, but I'd also be interested to see if anything like this exists at all.
I am looking for the same tool. Unfortunately, I do not see any other possibility than to wait for Spring 3.2 where should be that feature. See <https://jira.springsource.org/browse/SPR-9662>
I have written an ApplicationContextDumper to dump live spring application context into log. It shows autowired beans and beans loaded by component scan, but can't show which aspect is applied. Source code and example in <https://gist.github.com/aleung/1347171>
Is there tooling to visualize a live Spring application context?
[ "", "java", "spring", "spring-ide", "" ]
We have a bit of a messy database situation. Our main back-office system is written in Visual Fox Pro with local data (yes, I know!) In order to effectively work with the data in our websites, we have chosen to regularly export data to a SQL database. However the process that does this basically clears out the tables each time and does a re-insert. This means we have two SQL databases - one that our FoxPro export process writes to, and another that our websites read from. This question is concerned with the transform from one SQL database to the other (SqlFoxProData -> SqlWebData). For a particular table (one of our main application tables), because various data transformations take places during this process, it's not a straightforward UPDATE, INSERT and DELETE statements using self-joins, but we're having to use cursors instead (I know!) This has been working fine for many months but now we are starting to hit upon performance problems when an update is taking place (this can happen regularly during the day) Basically when we are updating SqlWebData.ImportantTable from SqlFoxProData.ImportantTable, it's causing occasional connection timeouts/deadlocks/other problems on the live websites. I've worked hard at optimising queries, caching etc etc, but it's come to a point where I'm looking for another strategy to update the data. One idea that has come to mind is to have two copies of ImportantTable (A and B), some concept of which table is currently 'active', updating the non-active table, then switching the currenly actice table i.e. websites read from ImportantTableA whilst we're updating ImportantTableB, then we switch websites to read from ImportantTableB. Question is, is this feasible and a good idea? I have done something like it before but I'm not convinced it's necessarily good for optimisation/indexing etc. Any suggestions welcome, I know this is a messy situation... and the long term goal would be to get our FoxPro application pointing to SQL. (We're using SQL 2005 if it helps) I should add that data consistency isn't particularly important in the instance, seeing as the data is always slightly out of date
There are a lot of ways to skin this cat. I would attack the locking issues first. It is extremely rare that I would use CURSORS, and I think improving the performance and locking behavior there might resolve a lot of your issues. I expect that I would solve it by using two separate staging tables. One for the FoxPro export in SQL and one transformed into the final format in SQL side-by-side. Then either swapping the final for production using sp\_rename, or simply using 3 INSERT/UPDATE/DELETE transactions to apply all changes from the final table to production. Either way, there is going to be some locking there, but how big are we talking about?
You should be able to maintain one db for the website and just replicate to that table from the other sql db table. This is assuming that you do not update any data from the website itself.
Effectively transforming data from one SQL database to another in live environment
[ "", "sql", "sql-server-2005", "visual-foxpro", "foxpro", "" ]
I want to repeatedly execute a function in Python every 60 seconds forever (just like an [NSTimer](http://web.archive.org/web/20090823012700/http://developer.apple.com:80/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html) in Objective C or setTimeout in JS). This code will run as a daemon and is effectively like calling the python script every minute using a cron, but without requiring that to be set up by the user. In [this question about a cron implemented in Python](https://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python), the solution appears to effectively just [sleep()](http://docs.python.org/library/time.html#time.sleep) for x seconds. I don't need such advanced functionality so perhaps something like this would work ``` while True: # Code executed here time.sleep(60) ``` Are there any foreseeable problems with this code?
If your program doesn't have a event loop already, use the [sched](http://docs.python.org/library/sched.html) module, which implements a general purpose event scheduler. ``` import sched, time def do_something(scheduler): # schedule the next call first scheduler.enter(60, 1, do_something, (scheduler,)) print("Doing stuff...") # then do your stuff my_scheduler = sched.scheduler(time.time, time.sleep) my_scheduler.enter(60, 1, do_something, (my_scheduler,)) my_scheduler.run() ``` If you're already using an event loop library like `asyncio`, `trio`, `tkinter`, `PyQt5`, `gobject`, `kivy`, and many others - just schedule the task using your existing event loop library's methods, instead.
Lock your time loop to the system clock like this: ``` import time starttime = time.monotonic() while True: print("tick") time.sleep(60.0 - ((time.monotonic() - starttime) % 60.0)) ``` Use a 'monotonic' clock to work properly; time() is adjusted by solar/legal time changes, ntp synchronization, etc...
How to repeatedly execute a function every x seconds?
[ "", "python", "timer", "" ]
I create a plugin which includes the following folder structure: * src * native/so/libsystemcommand.so * META-INF/MANIFEST.MF The manifest include the command ``` Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: Commands Plug-in Bundle-SymbolicName: de.system.commands;singleton:=true Bundle-Version: 1.0.0 Bundle-Activator: de.system.commands.CommandsPlugin Bundle-Localization: plugin Bundle-NativeCode: native/so/libsystemcommand.so; osname = Linux; processor = x86 Require-Bundle: org.eclipse.core.runtime, org.apache.commons.logging Eclipse-AutoStart: true Export-Package: de.system.commands, de.system.commands.jni, de.system.commands.utils Bundle-ClassPath: . ``` The build.properties looks like ``` source.. = src/ output.. = bin/ bin.includes = META-INF/,\ .,\ native/ ``` In the start method of my `Activator` class I call ``` System.loadLibrary("systemcommand"); ``` At runtime the library is not found and a **UnsatisfiedLinkError** is thrown. ``` java.lang.UnsatisfiedLinkError: no libsystemcommand in java.library.path ``` Do I have to set more attributes in the plugin? Do I have to unzip some informations on the target platform? **EDIT:** ``` java.library.path=/opt/jdk/j2re1.4.2_16/lib/i386/client:/opt/jdk/j2re1.4.2_16/lib/i386:/opt/jdk/j2re1.4.2_16/../lib/i386::/opt/dsa/lib:/opt/dsa/lib ```
I think i found the solution. We only build the plugin which was not working and copy it to the destination platform directory. After this we start the application as wtach the log files whether the library was foud or not. What we miss, was to **delete the configurations folder**. The new plugin was not unzipp and the library was not existing in the configurations directory. Im sorry and thank you for your answers. **EDIT :** The configuration folder is placed at ``` <installation>/eclipse/configuration/ ``` At least delete everything without the file ``` <installation>/eclipse/configuration/config.ini ```
I wonder if the library needs to be specified without the lib prefix? E.g., ``` System.loadLibrary("systemcommand"); ``` Since that is how the library would be passed on a gcc link line.
Use Bundle-NativeCode on Linux does not work
[ "", "java", "linux", "eclipse-plugin", "shared-libraries", "bundle", "" ]
Is it possible to use If Else conditional in a LINQ query? Something like ``` from p in db.products if p.price>0 select new { Owner=from q in db.Users select q.Name } else select new { Owner = from r in db.ExternalUsers select r.Name } ```
This might work... ``` from p in db.products select new { Owner = (p.price > 0 ? from q in db.Users select q.Name : from r in db.ExternalUsers select r.Name) } ```
I assume from `db` that this is LINQ-to-SQL / Entity Framework / similar (not LINQ-to-Objects); Generally, you do better with the conditional syntax ( a ? b : c) - however, I don't know if it will work with your different queries like that (after all, how would your write the TSQL?). For a trivial example of the type of thing you *can* do: ``` select new {p.PriceID, Type = p.Price > 0 ? "debit" : "credit" }; ``` You can do much richer things, but I really doubt you can pick the *table* in the conditional. You're welcome to try, of course...
If Else in LINQ
[ "", "c#", "linq", "linq-to-sql", "" ]
I have a date input field that allows the user to enter in a date and I need to validate this input (I already have server side validation), but the trick is that the format is locale dependent. I already have a system for translating the strptime format string to the the user's preference and I would like to use this same format for validating on the Javascript side. Any ideas or links to a `strptime()` implementation in Javascript?
After a few days of googling I found [this implementation](https://web.archive.org/web/20210726055034/http://www.logilab.org/blogentry/6731) which, although not complete, seems to handle all of the cases I have right now.
I've just added our php.js implementation of [strptime()](http://github.com/kvz/phpjs/blob/master/functions/datetime/strptime.js); I've tested it a bit, but it needs further unit testing. Anyhow, feel free to give it a shot; it should cover everything that PHP does (except for not yet supporting the undocumented %E... (alternative locale format) specifiers). Note that it also depends on our implementation of setlocale() and array\_map()... * <https://github.com/kvz/phpjs/blob/master/functions/strings/setlocale.js> * <https://github.com/kvz/phpjs/blob/master/functions/array/array_map.js>
strptime in Javascript
[ "", "javascript", "strptime", "phpjs", "" ]
A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?
The only way I can think of to do this amounts to giving the function a name: ``` fact = lambda x: 1 if x == 0 else x * fact(x-1) ``` or alternately, for earlier versions of python: ``` fact = lambda x: x == 0 and 1 or x * fact(x-1) ``` **Update**: using the ideas from the other answers, I was able to wedge the factorial function into a single unnamed lambda: ``` >>> map(lambda n: (lambda f, *a: f(f, *a))(lambda rec, n: 1 if n == 0 else n*rec(rec, n-1), n), range(10)) [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] ``` So it's possible, but not really recommended!
without reduce, map, named lambdas or python internals: ``` (lambda a:lambda v:a(a,v))(lambda s,x:1 if x==0 else x*s(s,x-1))(10) ```
Can a lambda function call itself recursively in Python?
[ "", "python", "recursion", "lambda", "y-combinator", "" ]
I'm trying to work with [fractions](http://en.wikipedia.org/wiki/Fraction_%28mathematics%29#Vulgar.2C_proper.2C_and_improper_fractions) in Java. I want to implement arithmetic functions. For this, I will first require a way to normalize the functions. I know I can't add 1/6 and 1/2 until I have a common denominator. I will have to add 1/6 and 3/6. A naive approach would have me add 2/12 and 6/12 and then reduce. How can I achieve a common denominator with the least performance penalty? What algorithm is best for this? --- Version 8 (thanks to [hstoerr](https://stackoverflow.com/users/21499/hstoerr)): > Improvements include: > > * the equals() method is now consistent with the compareTo() method ``` final class Fraction extends Number { private int numerator; private int denominator; public Fraction(int numerator, int denominator) { if(denominator == 0) { throw new IllegalArgumentException("denominator is zero"); } if(denominator < 0) { numerator *= -1; denominator *= -1; } this.numerator = numerator; this.denominator = denominator; } public Fraction(int numerator) { this.numerator = numerator; this.denominator = 1; } public int getNumerator() { return this.numerator; } public int getDenominator() { return this.denominator; } public byte byteValue() { return (byte) this.doubleValue(); } public double doubleValue() { return ((double) numerator)/((double) denominator); } public float floatValue() { return (float) this.doubleValue(); } public int intValue() { return (int) this.doubleValue(); } public long longValue() { return (long) this.doubleValue(); } public short shortValue() { return (short) this.doubleValue(); } public boolean equals(Fraction frac) { return this.compareTo(frac) == 0; } public int compareTo(Fraction frac) { long t = this.getNumerator() * frac.getDenominator(); long f = frac.getNumerator() * this.getDenominator(); int result = 0; if(t>f) { result = 1; } else if(f>t) { result = -1; } return result; } } ``` --- I have removed all previous versions. My thanks to: * [Dave Ray](https://stackoverflow.com/users/40310/dave-ray) * [cletus](https://stackoverflow.com/users/18393/cletus) * [duffymo](https://stackoverflow.com/users/37213/duffymo) * [James](https://stackoverflow.com/users/41039/james) * [Milhous](https://stackoverflow.com/users/17712/milhous) * [Oscar Reyes](https://stackoverflow.com/users/20654/oscar-reyes) * [Jason S](https://stackoverflow.com/users/44330/jason-s) * [Francisco Canedo](https://stackoverflow.com/users/54591/francisco-canedo) * [Outlaw Programmer](https://stackoverflow.com/users/1471/outlaw-programmer) * [Beska](https://stackoverflow.com/users/57120/beska)
It just so happens that I wrote a BigFraction class not too long ago, for [Project Euler problems](http://projecteuler.net). It keeps a BigInteger numerator and denominator, so it'll never overflow. But it'll be a tad slow for a lot of operations that you know will never overflow.. anyway, use it if you want it. I've been dying to show this off somehow. :) **Edit**: Latest and greatest version of this code, including unit tests is [now hosted on GitHub](https://github.com/kiprobinson/BigFraction) and also [available via Maven Central](https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.github.kiprobinson%22%20AND%20a%3A%22bigfraction%22). I'm leaving my original code here so that this answer isn't just a link... --- ``` import java.math.*; /** * Arbitrary-precision fractions, utilizing BigIntegers for numerator and * denominator. Fraction is always kept in lowest terms. Fraction is * immutable, and guaranteed not to have a null numerator or denominator. * Denominator will always be positive (so sign is carried by numerator, * and a zero-denominator is impossible). */ public final class BigFraction extends Number implements Comparable<BigFraction> { private static final long serialVersionUID = 1L; //because Number is Serializable private final BigInteger numerator; private final BigInteger denominator; public final static BigFraction ZERO = new BigFraction(BigInteger.ZERO, BigInteger.ONE, true); public final static BigFraction ONE = new BigFraction(BigInteger.ONE, BigInteger.ONE, true); /** * Constructs a BigFraction with given numerator and denominator. Fraction * will be reduced to lowest terms. If fraction is negative, negative sign will * be carried on numerator, regardless of how the values were passed in. */ public BigFraction(BigInteger numerator, BigInteger denominator) { if(numerator == null) throw new IllegalArgumentException("Numerator is null"); if(denominator == null) throw new IllegalArgumentException("Denominator is null"); if(denominator.equals(BigInteger.ZERO)) throw new ArithmeticException("Divide by zero."); //only numerator should be negative. if(denominator.signum() < 0) { numerator = numerator.negate(); denominator = denominator.negate(); } //create a reduced fraction BigInteger gcd = numerator.gcd(denominator); this.numerator = numerator.divide(gcd); this.denominator = denominator.divide(gcd); } /** * Constructs a BigFraction from a whole number. */ public BigFraction(BigInteger numerator) { this(numerator, BigInteger.ONE, true); } public BigFraction(long numerator, long denominator) { this(BigInteger.valueOf(numerator), BigInteger.valueOf(denominator)); } public BigFraction(long numerator) { this(BigInteger.valueOf(numerator), BigInteger.ONE, true); } /** * Constructs a BigFraction from a floating-point number. * * Warning: round-off error in IEEE floating point numbers can result * in answers that are unexpected. For example, * System.out.println(new BigFraction(1.1)) * will print: * 2476979795053773/2251799813685248 * * This is because 1.1 cannot be expressed exactly in binary form. The * given fraction is exactly equal to the internal representation of * the double-precision floating-point number. (Which, for 1.1, is: * (-1)^0 * 2^0 * (1 + 0x199999999999aL / 0x10000000000000L).) * * NOTE: In many cases, BigFraction(Double.toString(d)) may give a result * closer to what the user expects. */ public BigFraction(double d) { if(Double.isInfinite(d)) throw new IllegalArgumentException("double val is infinite"); if(Double.isNaN(d)) throw new IllegalArgumentException("double val is NaN"); //special case - math below won't work right for 0.0 or -0.0 if(d == 0) { numerator = BigInteger.ZERO; denominator = BigInteger.ONE; return; } final long bits = Double.doubleToLongBits(d); final int sign = (int)(bits >> 63) & 0x1; final int exponent = ((int)(bits >> 52) & 0x7ff) - 0x3ff; final long mantissa = bits & 0xfffffffffffffL; //number is (-1)^sign * 2^(exponent) * 1.mantissa BigInteger tmpNumerator = BigInteger.valueOf(sign==0 ? 1 : -1); BigInteger tmpDenominator = BigInteger.ONE; //use shortcut: 2^x == 1 << x. if x is negative, shift the denominator if(exponent >= 0) tmpNumerator = tmpNumerator.multiply(BigInteger.ONE.shiftLeft(exponent)); else tmpDenominator = tmpDenominator.multiply(BigInteger.ONE.shiftLeft(-exponent)); //1.mantissa == 1 + mantissa/2^52 == (2^52 + mantissa)/2^52 tmpDenominator = tmpDenominator.multiply(BigInteger.valueOf(0x10000000000000L)); tmpNumerator = tmpNumerator.multiply(BigInteger.valueOf(0x10000000000000L + mantissa)); BigInteger gcd = tmpNumerator.gcd(tmpDenominator); numerator = tmpNumerator.divide(gcd); denominator = tmpDenominator.divide(gcd); } /** * Constructs a BigFraction from two floating-point numbers. * * Warning: round-off error in IEEE floating point numbers can result * in answers that are unexpected. See BigFraction(double) for more * information. * * NOTE: In many cases, BigFraction(Double.toString(numerator) + "/" + Double.toString(denominator)) * may give a result closer to what the user expects. */ public BigFraction(double numerator, double denominator) { if(denominator == 0) throw new ArithmeticException("Divide by zero."); BigFraction tmp = new BigFraction(numerator).divide(new BigFraction(denominator)); this.numerator = tmp.numerator; this.denominator = tmp.denominator; } /** * Constructs a new BigFraction from the given BigDecimal object. */ public BigFraction(BigDecimal d) { this(d.scale() < 0 ? d.unscaledValue().multiply(BigInteger.TEN.pow(-d.scale())) : d.unscaledValue(), d.scale() < 0 ? BigInteger.ONE : BigInteger.TEN.pow(d.scale())); } public BigFraction(BigDecimal numerator, BigDecimal denominator) { if(denominator.equals(BigDecimal.ZERO)) throw new ArithmeticException("Divide by zero."); BigFraction tmp = new BigFraction(numerator).divide(new BigFraction(denominator)); this.numerator = tmp.numerator; this.denominator = tmp.denominator; } /** * Constructs a BigFraction from a String. Expected format is numerator/denominator, * but /denominator part is optional. Either numerator or denominator may be a floating- * point decimal number, which in the same format as a parameter to the * <code>BigDecimal(String)</code> constructor. * * @throws NumberFormatException if the string cannot be properly parsed. */ public BigFraction(String s) { int slashPos = s.indexOf('/'); if(slashPos < 0) { BigFraction res = new BigFraction(new BigDecimal(s)); this.numerator = res.numerator; this.denominator = res.denominator; } else { BigDecimal num = new BigDecimal(s.substring(0, slashPos)); BigDecimal den = new BigDecimal(s.substring(slashPos+1, s.length())); BigFraction res = new BigFraction(num, den); this.numerator = res.numerator; this.denominator = res.denominator; } } /** * Returns this + f. */ public BigFraction add(BigFraction f) { if(f == null) throw new IllegalArgumentException("Null argument"); //n1/d1 + n2/d2 = (n1*d2 + d1*n2)/(d1*d2) return new BigFraction(numerator.multiply(f.denominator).add(denominator.multiply(f.numerator)), denominator.multiply(f.denominator)); } /** * Returns this + b. */ public BigFraction add(BigInteger b) { if(b == null) throw new IllegalArgumentException("Null argument"); //n1/d1 + n2 = (n1 + d1*n2)/d1 return new BigFraction(numerator.add(denominator.multiply(b)), denominator, true); } /** * Returns this + n. */ public BigFraction add(long n) { return add(BigInteger.valueOf(n)); } /** * Returns this - f. */ public BigFraction subtract(BigFraction f) { if(f == null) throw new IllegalArgumentException("Null argument"); return new BigFraction(numerator.multiply(f.denominator).subtract(denominator.multiply(f.numerator)), denominator.multiply(f.denominator)); } /** * Returns this - b. */ public BigFraction subtract(BigInteger b) { if(b == null) throw new IllegalArgumentException("Null argument"); return new BigFraction(numerator.subtract(denominator.multiply(b)), denominator, true); } /** * Returns this - n. */ public BigFraction subtract(long n) { return subtract(BigInteger.valueOf(n)); } /** * Returns this * f. */ public BigFraction multiply(BigFraction f) { if(f == null) throw new IllegalArgumentException("Null argument"); return new BigFraction(numerator.multiply(f.numerator), denominator.multiply(f.denominator)); } /** * Returns this * b. */ public BigFraction multiply(BigInteger b) { if(b == null) throw new IllegalArgumentException("Null argument"); return new BigFraction(numerator.multiply(b), denominator); } /** * Returns this * n. */ public BigFraction multiply(long n) { return multiply(BigInteger.valueOf(n)); } /** * Returns this / f. */ public BigFraction divide(BigFraction f) { if(f == null) throw new IllegalArgumentException("Null argument"); if(f.numerator.equals(BigInteger.ZERO)) throw new ArithmeticException("Divide by zero"); return new BigFraction(numerator.multiply(f.denominator), denominator.multiply(f.numerator)); } /** * Returns this / b. */ public BigFraction divide(BigInteger b) { if(b == null) throw new IllegalArgumentException("Null argument"); if(b.equals(BigInteger.ZERO)) throw new ArithmeticException("Divide by zero"); return new BigFraction(numerator, denominator.multiply(b)); } /** * Returns this / n. */ public BigFraction divide(long n) { return divide(BigInteger.valueOf(n)); } /** * Returns this^exponent. */ public BigFraction pow(int exponent) { if(exponent == 0) return BigFraction.ONE; else if (exponent == 1) return this; else if (exponent < 0) return new BigFraction(denominator.pow(-exponent), numerator.pow(-exponent), true); else return new BigFraction(numerator.pow(exponent), denominator.pow(exponent), true); } /** * Returns 1/this. */ public BigFraction reciprocal() { if(this.numerator.equals(BigInteger.ZERO)) throw new ArithmeticException("Divide by zero"); return new BigFraction(denominator, numerator, true); } /** * Returns the complement of this fraction, which is equal to 1 - this. * Useful for probabilities/statistics. */ public BigFraction complement() { return new BigFraction(denominator.subtract(numerator), denominator, true); } /** * Returns -this. */ public BigFraction negate() { return new BigFraction(numerator.negate(), denominator, true); } /** * Returns -1, 0, or 1, representing the sign of this fraction. */ public int signum() { return numerator.signum(); } /** * Returns the absolute value of this. */ public BigFraction abs() { return (signum() < 0 ? negate() : this); } /** * Returns a string representation of this, in the form * numerator/denominator. */ public String toString() { return numerator.toString() + "/" + denominator.toString(); } /** * Returns if this object is equal to another object. */ public boolean equals(Object o) { if(!(o instanceof BigFraction)) return false; BigFraction f = (BigFraction)o; return numerator.equals(f.numerator) && denominator.equals(f.denominator); } /** * Returns a hash code for this object. */ public int hashCode() { //using the method generated by Eclipse, but streamlined a bit.. return (31 + numerator.hashCode())*31 + denominator.hashCode(); } /** * Returns a negative, zero, or positive number, indicating if this object * is less than, equal to, or greater than f, respectively. */ public int compareTo(BigFraction f) { if(f == null) throw new IllegalArgumentException("Null argument"); //easy case: this and f have different signs if(signum() != f.signum()) return signum() - f.signum(); //next easy case: this and f have the same denominator if(denominator.equals(f.denominator)) return numerator.compareTo(f.numerator); //not an easy case, so first make the denominators equal then compare the numerators return numerator.multiply(f.denominator).compareTo(denominator.multiply(f.numerator)); } /** * Returns the smaller of this and f. */ public BigFraction min(BigFraction f) { if(f == null) throw new IllegalArgumentException("Null argument"); return (this.compareTo(f) <= 0 ? this : f); } /** * Returns the maximum of this and f. */ public BigFraction max(BigFraction f) { if(f == null) throw new IllegalArgumentException("Null argument"); return (this.compareTo(f) >= 0 ? this : f); } /** * Returns a positive BigFraction, greater than or equal to zero, and less than one. */ public static BigFraction random() { return new BigFraction(Math.random()); } public final BigInteger getNumerator() { return numerator; } public final BigInteger getDenominator() { return denominator; } //implementation of Number class. may cause overflow. public byte byteValue() { return (byte) Math.max(Byte.MIN_VALUE, Math.min(Byte.MAX_VALUE, longValue())); } public short shortValue() { return (short)Math.max(Short.MIN_VALUE, Math.min(Short.MAX_VALUE, longValue())); } public int intValue() { return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, longValue())); } public long longValue() { return Math.round(doubleValue()); } public float floatValue() { return (float)doubleValue(); } public double doubleValue() { return toBigDecimal(18).doubleValue(); } /** * Returns a BigDecimal representation of this fraction. If possible, the * returned value will be exactly equal to the fraction. If not, the BigDecimal * will have a scale large enough to hold the same number of significant figures * as both numerator and denominator, or the equivalent of a double-precision * number, whichever is more. */ public BigDecimal toBigDecimal() { //Implementation note: A fraction can be represented exactly in base-10 iff its //denominator is of the form 2^a * 5^b, where a and b are nonnegative integers. //(In other words, if there are no prime factors of the denominator except for //2 and 5, or if the denominator is 1). So to determine if this denominator is //of this form, continually divide by 2 to get the number of 2's, and then //continually divide by 5 to get the number of 5's. Afterward, if the denominator //is 1 then there are no other prime factors. //Note: number of 2's is given by the number of trailing 0 bits in the number int twos = denominator.getLowestSetBit(); BigInteger tmpDen = denominator.shiftRight(twos); // x / 2^n === x >> n final BigInteger FIVE = BigInteger.valueOf(5); int fives = 0; BigInteger[] divMod = null; //while(tmpDen % 5 == 0) { fives++; tmpDen /= 5; } while(BigInteger.ZERO.equals((divMod = tmpDen.divideAndRemainder(FIVE))[1])) { fives++; tmpDen = divMod[0]; } if(BigInteger.ONE.equals(tmpDen)) { //This fraction will terminate in base 10, so it can be represented exactly as //a BigDecimal. We would now like to make the fraction of the form //unscaled / 10^scale. We know that 2^x * 5^x = 10^x, and our denominator is //in the form 2^twos * 5^fives. So use max(twos, fives) as the scale, and //multiply the numerator and deminator by the appropriate number of 2's or 5's //such that the denominator is of the form 2^scale * 5^scale. (Of course, we //only have to actually multiply the numerator, since all we need for the //BigDecimal constructor is the scale. BigInteger unscaled = numerator; int scale = Math.max(twos, fives); if(twos < fives) unscaled = unscaled.shiftLeft(fives - twos); //x * 2^n === x << n else if (fives < twos) unscaled = unscaled.multiply(FIVE.pow(twos - fives)); return new BigDecimal(unscaled, scale); } //else: this number will repeat infinitely in base-10. So try to figure out //a good number of significant digits. Start with the number of digits required //to represent the numerator and denominator in base-10, which is given by //bitLength / log[2](10). (bitLenth is the number of digits in base-2). final double LG10 = 3.321928094887362; //Precomputed ln(10)/ln(2), a.k.a. log[2](10) int precision = Math.max(numerator.bitLength(), denominator.bitLength()); precision = (int)Math.ceil(precision / LG10); //If the precision is less than 18 digits, use 18 digits so that the number //will be at least as accurate as a cast to a double. For example, with //the fraction 1/3, precision will be 1, giving a result of 0.3. This is //quite a bit different from what a user would expect. if(precision < 18) precision = 18; return toBigDecimal(precision); } /** * Returns a BigDecimal representation of this fraction, with a given precision. * @param precision the number of significant figures to be used in the result. */ public BigDecimal toBigDecimal(int precision) { return new BigDecimal(numerator).divide(new BigDecimal(denominator), new MathContext(precision, RoundingMode.HALF_EVEN)); } //-------------------------------------------------------------------------- // PRIVATE FUNCTIONS //-------------------------------------------------------------------------- /** * Private constructor, used when you can be certain that the fraction is already in * lowest terms. No check is done to reduce numerator/denominator. A check is still * done to maintain a positive denominator. * * @param throwaway unused variable, only here to signal to the compiler that this * constructor should be used. */ private BigFraction(BigInteger numerator, BigInteger denominator, boolean throwaway) { if(denominator.signum() < 0) { this.numerator = numerator.negate(); this.denominator = denominator.negate(); } else { this.numerator = numerator; this.denominator = denominator; } } } ```
* Make it [immutable](http://en.wikipedia.org/wiki/Immutable_object); * Make it [canonical](http://en.wikipedia.org/wiki/Canonical#Mathematics), meaning 6/4 becomes 3/2 ([greatest common divisor](http://en.wikipedia.org/wiki/Greatest_common_divisor) algorithm is useful for this); * Call it Rational, since what you're representing is a [rational number](http://en.wikipedia.org/wiki/Rational_number); * You could use [`BigInteger`](http://java.sun.com/javase/6/docs/api/java/math/BigInteger.html) to store arbitrarilyy-precise values. If not that then `long`, which has an easier implementation; * Make the denominator always positive. Sign should be carried by the numerator; * Extend [`Number`](http://java.sun.com/javase/6/docs/api/java/lang/Number.html); * Implement [`Comparable<T>`](http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html); * Implement [`equals()`](http://java.sun.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object)) and [`hashCode()`](http://java.sun.com/javase/6/docs/api/java/lang/Object.html#hashCode()); * Add factory method for a number represented by a `String`; * Add some convenience factory methods; * Add a [`toString()`](http://java.sun.com/javase/6/docs/api/java/lang/Object.html#toString()); and * Make it [`Serializable`](http://java.sun.com/javase/6/docs/api/java/io/Serializable.html). In fact, try this on for size. It runs but may have some issues: ``` public class BigRational extends Number implements Comparable<BigRational>, Serializable { public final static BigRational ZERO = new BigRational(BigInteger.ZERO, BigInteger.ONE); private final static long serialVersionUID = 1099377265582986378L; private final BigInteger numerator, denominator; private BigRational(BigInteger numerator, BigInteger denominator) { this.numerator = numerator; this.denominator = denominator; } private static BigRational canonical(BigInteger numerator, BigInteger denominator, boolean checkGcd) { if (denominator.signum() == 0) { throw new IllegalArgumentException("denominator is zero"); } if (numerator.signum() == 0) { return ZERO; } if (denominator.signum() < 0) { numerator = numerator.negate(); denominator = denominator.negate(); } if (checkGcd) { BigInteger gcd = numerator.gcd(denominator); if (!gcd.equals(BigInteger.ONE)) { numerator = numerator.divide(gcd); denominator = denominator.divide(gcd); } } return new BigRational(numerator, denominator); } public static BigRational getInstance(BigInteger numerator, BigInteger denominator) { return canonical(numerator, denominator, true); } public static BigRational getInstance(long numerator, long denominator) { return canonical(new BigInteger("" + numerator), new BigInteger("" + denominator), true); } public static BigRational getInstance(String numerator, String denominator) { return canonical(new BigInteger(numerator), new BigInteger(denominator), true); } public static BigRational valueOf(String s) { Pattern p = Pattern.compile("(-?\\d+)(?:.(\\d+)?)?0*(?:e(-?\\d+))?"); Matcher m = p.matcher(s); if (!m.matches()) { throw new IllegalArgumentException("Unknown format '" + s + "'"); } // this translates 23.123e5 to 25,123 / 1000 * 10^5 = 2,512,300 / 1 (GCD) String whole = m.group(1); String decimal = m.group(2); String exponent = m.group(3); String n = whole; // 23.123 => 23123 if (decimal != null) { n += decimal; } BigInteger numerator = new BigInteger(n); // exponent is an int because BigInteger.pow() takes an int argument // it gets more difficult if exponent needs to be outside {-2 billion,2 billion} int exp = exponent == null ? 0 : Integer.valueOf(exponent); int decimalPlaces = decimal == null ? 0 : decimal.length(); exp -= decimalPlaces; BigInteger denominator; if (exp < 0) { denominator = BigInteger.TEN.pow(-exp); } else { numerator = numerator.multiply(BigInteger.TEN.pow(exp)); denominator = BigInteger.ONE; } // done return canonical(numerator, denominator, true); } // Comparable public int compareTo(BigRational o) { // note: this is a bit of cheat, relying on BigInteger.compareTo() returning // -1, 0 or 1. For the more general contract of compareTo(), you'd need to do // more checking if (numerator.signum() != o.numerator.signum()) { return numerator.signum() - o.numerator.signum(); } else { // oddly BigInteger has gcd() but no lcm() BigInteger i1 = numerator.multiply(o.denominator); BigInteger i2 = o.numerator.multiply(denominator); return i1.compareTo(i2); // expensive! } } public BigRational add(BigRational o) { if (o.numerator.signum() == 0) { return this; } else if (numerator.signum() == 0) { return o; } else if (denominator.equals(o.denominator)) { return new BigRational(numerator.add(o.numerator), denominator); } else { return canonical(numerator.multiply(o.denominator).add(o.numerator.multiply(denominator)), denominator.multiply(o.denominator), true); } } public BigRational multiply(BigRational o) { if (numerator.signum() == 0 || o.numerator.signum( )== 0) { return ZERO; } else if (numerator.equals(o.denominator)) { return canonical(o.numerator, denominator, true); } else if (o.numerator.equals(denominator)) { return canonical(numerator, o.denominator, true); } else if (numerator.negate().equals(o.denominator)) { return canonical(o.numerator.negate(), denominator, true); } else if (o.numerator.negate().equals(denominator)) { return canonical(numerator.negate(), o.denominator, true); } else { return canonical(numerator.multiply(o.numerator), denominator.multiply(o.denominator), true); } } public BigInteger getNumerator() { return numerator; } public BigInteger getDenominator() { return denominator; } public boolean isInteger() { return numerator.signum() == 0 || denominator.equals(BigInteger.ONE); } public BigRational negate() { return new BigRational(numerator.negate(), denominator); } public BigRational invert() { return canonical(denominator, numerator, false); } public BigRational abs() { return numerator.signum() < 0 ? negate() : this; } public BigRational pow(int exp) { return canonical(numerator.pow(exp), denominator.pow(exp), true); } public BigRational subtract(BigRational o) { return add(o.negate()); } public BigRational divide(BigRational o) { return multiply(o.invert()); } public BigRational min(BigRational o) { return compareTo(o) <= 0 ? this : o; } public BigRational max(BigRational o) { return compareTo(o) >= 0 ? this : o; } public BigDecimal toBigDecimal(int scale, RoundingMode roundingMode) { return isInteger() ? new BigDecimal(numerator) : new BigDecimal(numerator).divide(new BigDecimal(denominator), scale, roundingMode); } // Number public int intValue() { return isInteger() ? numerator.intValue() : numerator.divide(denominator).intValue(); } public long longValue() { return isInteger() ? numerator.longValue() : numerator.divide(denominator).longValue(); } public float floatValue() { return (float)doubleValue(); } public double doubleValue() { return isInteger() ? numerator.doubleValue() : numerator.doubleValue() / denominator.doubleValue(); } @Override public String toString() { return isInteger() ? String.format("%,d", numerator) : String.format("%,d / %,d", numerator, denominator); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BigRational that = (BigRational) o; if (denominator != null ? !denominator.equals(that.denominator) : that.denominator != null) return false; if (numerator != null ? !numerator.equals(that.numerator) : that.numerator != null) return false; return true; } @Override public int hashCode() { int result = numerator != null ? numerator.hashCode() : 0; result = 31 * result + (denominator != null ? denominator.hashCode() : 0); return result; } public static void main(String args[]) { BigRational r1 = BigRational.valueOf("3.14e4"); BigRational r2 = BigRational.getInstance(111, 7); dump("r1", r1); dump("r2", r2); dump("r1 + r2", r1.add(r2)); dump("r1 - r2", r1.subtract(r2)); dump("r1 * r2", r1.multiply(r2)); dump("r1 / r2", r1.divide(r2)); dump("r2 ^ 2", r2.pow(2)); } public static void dump(String name, BigRational r) { System.out.printf("%s = %s%n", name, r); System.out.printf("%s.negate() = %s%n", name, r.negate()); System.out.printf("%s.invert() = %s%n", name, r.invert()); System.out.printf("%s.intValue() = %,d%n", name, r.intValue()); System.out.printf("%s.longValue() = %,d%n", name, r.longValue()); System.out.printf("%s.floatValue() = %,f%n", name, r.floatValue()); System.out.printf("%s.doubleValue() = %,f%n", name, r.doubleValue()); System.out.println(); } } ``` Output is: ``` r1 = 31,400 r1.negate() = -31,400 r1.invert() = 1 / 31,400 r1.intValue() = 31,400 r1.longValue() = 31,400 r1.floatValue() = 31,400.000000 r1.doubleValue() = 31,400.000000 r2 = 111 / 7 r2.negate() = -111 / 7 r2.invert() = 7 / 111 r2.intValue() = 15 r2.longValue() = 15 r2.floatValue() = 15.857142 r2.doubleValue() = 15.857143 r1 + r2 = 219,911 / 7 r1 + r2.negate() = -219,911 / 7 r1 + r2.invert() = 7 / 219,911 r1 + r2.intValue() = 31,415 r1 + r2.longValue() = 31,415 r1 + r2.floatValue() = 31,415.857422 r1 + r2.doubleValue() = 31,415.857143 r1 - r2 = 219,689 / 7 r1 - r2.negate() = -219,689 / 7 r1 - r2.invert() = 7 / 219,689 r1 - r2.intValue() = 31,384 r1 - r2.longValue() = 31,384 r1 - r2.floatValue() = 31,384.142578 r1 - r2.doubleValue() = 31,384.142857 r1 * r2 = 3,485,400 / 7 r1 * r2.negate() = -3,485,400 / 7 r1 * r2.invert() = 7 / 3,485,400 r1 * r2.intValue() = 497,914 r1 * r2.longValue() = 497,914 r1 * r2.floatValue() = 497,914.281250 r1 * r2.doubleValue() = 497,914.285714 r1 / r2 = 219,800 / 111 r1 / r2.negate() = -219,800 / 111 r1 / r2.invert() = 111 / 219,800 r1 / r2.intValue() = 1,980 r1 / r2.longValue() = 1,980 r1 / r2.floatValue() = 1,980.180176 r1 / r2.doubleValue() = 1,980.180180 r2 ^ 2 = 12,321 / 49 r2 ^ 2.negate() = -12,321 / 49 r2 ^ 2.invert() = 49 / 12,321 r2 ^ 2.intValue() = 251 r2 ^ 2.longValue() = 251 r2 ^ 2.floatValue() = 251.448975 r2 ^ 2.doubleValue() = 251.448980 ```
Best way to represent a fraction in Java?
[ "", "java", "math", "fractions", "" ]
AFAIK ROWID in Oracle represents physical location of a record in appropriate datafile. In which cases ROWID of a record may change ? The one known to me is UPDATE on partitioned table that "moves" the record to another partition. Are there another cases ? Most of our DBs are Oracle 10.
As you have said, it occurs anytime the row is physically moved on disk, such as: * Export/import of the table * ALTER TABLE XXXX MOVE * ALTER TABLE XXXX SHRINK SPACE * FLASHBACK TABLE XXXX * Splitting a partition * Updating a value so that it moves to a new partition * Combining two partitions If is in an index organized table, then an update to the primary key would give you a different ROWID as well.
Another +1 to WW, but just to add a little extra... If the driving question is whether you can store ROWIDs for later use, I would say "don't do it". You are fine to use ROWIDs within a transaction - for example collecting a set of ROWIDs on which to carry out a subsequent operations - but you should *never* store the ROWIDs in a table and assume they're going to be ok to use at a later date.
What can cause an Oracle ROWID to change?
[ "", "sql", "database", "oracle", "rowid", "" ]
I'm planning to start on a new project and am looking at the current state-of-the-art Java web frameworks. I decided to build my application around Guice, and am likely to use a very lightweight ORM like Squill/JEQUEL/JaQu or similar, but I can't decide on the web framework. Which one would fit best in such a lightweight environment? And which one integrates best with Guice?
I have gathered some experience on this topic, as I started to program on a new project in November. The project is in a late stage now. For me, the following design guidelines were important: * Use a modern technology stack that is both fun to use and will be in general use in future. * Reduce the number of project artifacts - use annotations/Java code where it makes sense, omit XML. * Use frameworks that are open-source * Have an active community * Are not alpha stage * Are lightweight * Avoid duplication of concepts * I can explain the concepts in it to my two fellow developers, who - despite being good programmers - have never used [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection) (DI) or web frameworks. * Can serve as a techological basis for future projects [Google Guice](http://en.wikipedia.org/wiki/Google_Guice) as a DI container was an obvious choice - clearly the most well-thought DI contianer, with brilliant developers and a good community. It fulfills all the bullet points mentioned above. So I set up my basic techology stack. Started with Guice, added [Hibernate](http://en.wikipedia.org/wiki/Hibernate_%28Java%29) for persistence (along with [warp-persist](http://www.wideplay.com/guicewebextensions) and [warp-servlet](http://www.wideplay.com/warp%3A%3Aservlet)). Then I wrote some basic [DAO](http://en.wikipedia.org/wiki/Data_access_object) that selects something. Then I tried to do the following: added a different web framework on top of that. * [XSLT](http://www.w3schools.com/xsl/) with [xStream](http://xstream.codehaus.org) using regular HTTP servlets * [JSF- MyFaces](http://myfaces.apache.org) * [Apache Wicket](http://wicket.apache.org/) * [warp-widgets](http://code.google.com/p/warp-core/) I created a simple page with a table, populated by the DAO, headers and a textfield with all four frameworks. These were my findings when comparing the four frameworks. XSLT and XStream is kind of a hardcore-approach. It's not really a framework, but a viable completely stateless techology for high-performance applications. This was by far the fastest way of serving the test page. In debug mode, 3 ms on localhost versus about 30-50 ms with the other framworks. Guice integration was relatively smooth and good using warp-servlet which enabled me to inject into servlets and injects httprequest, httpresponse, session in other objects, without passing them around. Disadvantages: no community at all, since I am the only person who would consider this stack. - no ready-to-use components. Then I took a look at JSF and Guice: it is of course possible to put the injector in the servlet context and use guice as a service locator. With the straightforward approach it's impossible to inject backing beans somewhere else. Using a custom variable resolver solves this partially, but then you lose all [IDE](http://en.wikipedia.org/wiki/Integrated_development_environment) integration in your JSF files plus you will have to use ugly [FQN](http://en.wikipedia.org/wiki/Fully_qualified_name) for your backing beans, or build a string->Guice key mapping somewhere. Both are ugly as: * Advantages: good community, many developers in the job market (no criteria for me). You won't get fired for chosing JSF if something goes wrong. * Disadvantages: brings its own [Inversion of control](http://en.wikipedia.org/wiki/Inversion_of_control) (IoC) mechanism which clashes conceptually with guice. warp-widgets: I created my simple example using this for fun; it's early alpha stage. It was nice to use and its components are easy to implement and reuse by myself. It aims to provide typesafe HTML with perfect Guice integration. Since it looked like it had only one active developer back then, who is now propably working on Guice 2.0, I would say the community is nearly non-existent. It worked like a charm, was reasonably fast, but I would have been alpha tester. That was simply too risky for me to consider it for a commercial project. Apache Wicket: this project first suprised me with wicket-ioc and wicket-guice coming together in the core download. Constructor injection in web pages is not possible, only setter+field. Injection in Wicket web pages is easy, just add `@Inject` to the fields you want to fill - but you're not supposed to understand [how it works in background](http://cwiki.apache.org/WICKET/guice-integration-pitfall.html). Tricky stuff happening. Injection of web pages is theoretically possible - but I have not used it once, since this makes it impossible to use mounted URLs, plus it will mess with the persisted/serialized state. Injected members of classes are dealt transparently with web page serialisation, which is necessary for enabling browser-back support. Wicket uses zero external artifacts - just a little configuration of the [URLs](http://en.wiktionary.org/wiki/configuration) in a application class. So all configuration is done in Java - which fits the Guice model well. Clear seperation of HTML and Java. It's open-source just like the majority of the components that are numerous and of good quality. It's around since 2005(?) and is a top-level Apache project. Although it's a feature-rich framework, its [API](http://en.wikipedia.org/wiki/Application_programming_interface) is reasonable compact (all core classes fit in a single [JPEG](http://en.wikipedia.org/wiki/JPEG) on my screen). Unlike others, it does not bring a IoC mechanism of its own, but rather thinks of IoC as a service that can be provided by [Spring Framework](http://en.wikipedia.org/wiki/Spring_Framework), Guice, etc. and that philosophy makes it superior w.r.t. Guice integration. Did I mention really smart and easy Ajax support? Frameworks not deeply evaluated: tapestry5 - brings its own IoC. [Seam](http://en.wikipedia.org/wiki/JBoss_Seam): not a framework on its own, but a meta-framwwork which normally comines Spring, JSF. Hibernate. (Though Spring may theoretically be replaced by Guice.) Summary: of the evaluated framworks, **Apache Wicket was the clear winner** - with respect to Guice integration + all other criteria mentioned. Besides us two, some other people [have had this problem before](http://static.raibledesigns.com/repository/presentations/ComparingJavaWebFrameworks-ApacheConUS2007.pdf).
[Wicket has a Guice module built in](http://herebebeasties.com/2007-06-20/wicket-gets-guicy/), which I haven't used (but I have used [Wicket](http://en.wikipedia.org/wiki/Apache_Wicket) quite a bit, and liked it).
Which Java Web Framework fits best with Google Guice?
[ "", "java", "dependency-injection", "guice", "" ]
I've found a few articles & discussions on how to import data from Access to SQL Server or SQL Server Express, but not to SQL Server CE. I can access both the the Access data and CE data in the VS database explorer with seperate connections, but don't know how to move the data from one to the other. (I'm using c#.) Any suggestions? Thanks.
You might look at [PrimeWorks' DataPort Wizard](http://www.primeworks-mobile.com/Products/DataPortWizard.html).
You can do it using [SSIS](http://en.wikipedia.org/wiki/SQL_Server_Integration_Services), or even in SQL Server Explorer if you are not looking to do it programmatically.
Import Access data into SQL Server CE (.mdb to .sdf)
[ "", "c#", ".net", "sql-server-ce", "" ]
I know VB.Net and am trying to brush up on my C#. Is there a `With` block equivalent in C#?
This is what Visual C# program manager has to say: [Why doesn't C# have a 'with' statement?](https://learn.microsoft.com/en-us/archive/blogs/csharpfaq/why-doesnt-c-have-vb-nets-with-operator) > Many people, including the C# language designers, believe that 'with' > often harms readability, and is more of a curse than a blessing. It is > clearer to declare a local variable with a meaningful name, and use > that variable to perform multiple operations on a single object, than > it is to have a block with a sort of implicit context.
Although C# doesn't have any direct equivalent for the general case, C# 3 gain object initializer syntax for constructor calls: ``` var foo = new Foo { Property1 = value1, Property2 = value2, etc }; ``` See chapter 8 of C# in Depth for more details - you can download it for free from [Manning's web site](http://manning.com/skeet). (Disclaimer - yes, it's in my interest to get the book into more people's hands. But hey, it's a free chapter which gives you more information on a related topic...)
With block equivalent in C#?
[ "", "c#", ".net", "vb.net", "" ]
I am working on a script that will process user uploads to the server, and as an added layer of security I'd like to know: Is there a way to detect a file's true extension/file type, and ensure that it is not another file type masked with a different extension? Is there a byte stamp or some unique identifier for each type/extension? I'd like to be able to detect that someone hasn't applied a different extension onto the file they are uploading.
Not really, no. You will need to read the first few bytes of each file and interpret it as a header for a finite set of known filetypes. Most files have distinct file headers, some sort of metadata in the first few bytes or first few kilobytes in the case of MP3. Your program will have to simply try parsing the file for each of your accepted filetypes. For my program, I send the uploaded image to imagemagick in a try-catch block, and if it blows up, then I guess it was a bad image. This should be considered insecure, because I am loading arbitrary (user supplied) binary data into an external program, which is generally an attack vector. here, I am trusting imageMagick to not do anything to my system. I recommend writing your own handlers for the significant filetypes you intend to use, to avoid any attack vectors. Edit: I see in PHP there are some tools to do this for you. Also, MIME types are what the user's browser claims the file to be. It is handy and useful to read those and act on them in your code, but it is not a secure method, because anyone sending you bad files will fake the MIME headers easily. It's sort of a front line defense to keep your code that expects a JPEG from barfing on a PNG, but if someone embedded a virus in a .exe and named it JPEG, there's no reason not to have spoofed the MIME type.
PHP has a couple of ways of reading file contents to determine its MIME type, depending on which version of PHP you are using: Have a look at the [Fileinfo functions](http://php.net/manual/en/ref.fileinfo.php) if you're running PHP 5.3+ ``` $finfo = finfo_open(FILEINFO_MIME); $type = finfo_file($finfo, $filepath); finfo_close($finfo); ``` Alternatively, check out [mime\_content\_type](http://php.net/mime_content_type) for older versions. ``` $type = mime_content_type($filepath); ``` Note that just validating the file type isn't enough if you want to be truly secure. Someone could, for example, upload a valid JPEG file which exploits a vulnerability in a common renderer. To guard against this, you would need a well maintained virus scanner.
How can I determine a file's true extension/type programmatically?
[ "", "php", "security", "file-upload", "file-type", "" ]
## I challenge you :) I have a process that someone already implemented. I will try to describe the requirements, and I was hoping I could get some input to the "best way" to do this. --- It's for a financial institution. I have a routing framework that will allow me to recieve files and send requests to other systems. I have a database I can use as I wish but it is only me and my software that has access to this database. **The facts** * Via the routing framework I recieve a file. * Each line in this file follows a fixed length format with the identification of a person and an amount (+ lots of other stuff). * This file is 99% of the time im below 100MB ( around 800bytes per line, ie 2,2mb = 2600lines) * Once a year we have 1-3 gb of data instead. * Running on an "appserver" * I can fork subprocesses as I like. (within reason) * I can not ensure consistency when running for more than two days. subprocesses may die, connection to db/framework might be lost, files might move * I can NOT send reliable messages via the framework. The call is synchronus, so I must wait for the answer. + It's possible/likely that sending these getPerson request will crash my "process" when sending LOTS. * We're using java. **Requirements** * I must return a file with all the data + I must add some more info for somelines. (about 25-50% of the lines : 25.000 at least) * This info I can only get by doing a getPerson request via the framework to another system. One per person. Takes between 200 and 400msec. * It must be able to complete within two days **Nice to have** * Checkpointing. If im going to run for a long time I sure would like to be able to restart the process without starting from the top. ... How would you design this? *I will later add the current "hack" and my brief idea* **========== Current solution ================** It's running on BEA/Oracle Weblogic Integration, not by choice but by definition When the file is received each line is read into a database with ``` id, line, status,batchfilename ``` and status 'Needs processing' When all lines is in the database the rows are seperated by mod 4 and a process is started per each quarter of the rows and each line that needs it is enriched by the getPerson call and status is set to 'Processed'. (38.0000 in the current batch). When all 4 quaters of the rows has been Processed a writer process startes by select 100 rows from that database, writing them to file and updating their status to 'Written'. When all is done the new file is handed back to the routing framework, and a "im done" email is sent to the operations crew. The 4 processing processes can/will fail so its possible to restart them with a http get to a servlet on WLI.
Simplify as much as possible. The batches (trying to process them as units, and their various sizes) appear to be discardable in terms of the simplest process. It sounds like the rows are atomic, not the batches. Feed all the lines as separate atomic transactions through an asynchronous FIFO message queue, with a good mechanism for detecting (and appropriately logging and routing failures). Then you can deal with the problems strictly on an exception basis. (A queue table in your database can probably work.) Maintain batch identity only with a column in the message record, and summarize batches by that means however you need, whenever you need.
When you receive the file, parse it and put the information in the database. Make one table with a record per line that will need a getPerson request. Have one or more threads get records from this table, perform the request and put the completed record back in the table. Once all records are processed, generate the complete file and return it.
Designing a process
[ "", "java", "" ]
I have a windows forms app with a textbox control that I want to only accept integer values. In the past I've done this kind of validation by overloading the KeyPress event and just removing characters which didn't fit the specification. I've looked at the MaskedTextBox control but I'd like a more general solution that could work with perhaps a regular expression, or depend on the values of other controls. Ideally this would behave such that pressing a non numeric character would either produce no result or immediately provide the user with feedback about the invalid character.
Two options: 1. Use a [`NumericUpDown`](http://msdn.microsoft.com/en-us/library/system.windows.forms.numericupdown(v=vs.110).aspx) instead. NumericUpDown does the filtering for you, which is nice. Of course it also gives your users the ability to hit the up and down arrows on the keyboard to increment and decrement the current value. 2. Handle the appropriate keyboard events to prevent anything but numeric input. I've had success with this two event handlers on a standard TextBox: ``` private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) { e.Handled = true; } // only allow one decimal point if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1)) { e.Handled = true; } } ``` You can remove the check for `'.'` (and the subsequent check for more than one `'.'`) if your TextBox shouldn't allow decimal places. You could also add a check for `'-'` if your TextBox should allow negative values. If you want to limit the user for number of digit, use: `textBox1.MaxLength = 2; // this will allow the user to enter only 2 digits`
And just because it's always more fun to do stuff in one line... ``` private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar); } ``` NOTE: This DOES NOT prevent a user from Copy / Paste into this textbox. It's not a fail safe way to sanitize your data.
How do I make a textbox that only accepts numbers?
[ "", "c#", ".net", "winforms", "textbox", "" ]
I've been trying to develop a linq query that returns the ItemNumber column of all my tables in the database, but so far I haven't been able to do it successfully. Basically I have a table for each kind of hardware component in a computer, and each table has a ItemNumber column. I need to query all of the tables in one bang, and return the ItemNumber values in a flat list/array. (Essentially I want to be able to do the below) ``` foreach (var c in items) { Console.WriteLine(c.ItemNumber); } ``` Searching the net to no avail, could someone show me an example of how to do this? My best attempt at it is the following, but I don't understand Sql enough to accomplish this. ``` var items = from hc in dc.DataBoxPCHardwareCases from hhd in dc.DataBoxPCHardwareHardDrives from hkb in dc.DataBoxPCHardwareKeyboards from hmm in dc.DataBoxPCHardwareMemories from hmo in dc.DataBoxPCHardwareMonitors from hmb in dc.DataBoxPCHardwareMotherboards from hms in dc.DataBoxPCHardwareMouses from hod in dc.DataBoxPCHardwareOpticalDrives from hps in dc.DataBoxPCHardwarePowerSupplies from hpc in dc.DataBoxPCHardwareProcessors from hsp in dc.DataBoxPCHardwareSpeakers from hvc in dc.DataBoxPCHardwareVideoCards from sos in dc.DataBoxPCSoftwareOperatingSystems select new { hc, hhd, hkb, hmm, hmo, hmb, hms, hod, hps, hpc, hsp, hvc, sos }; ```
What you are describing is a union: SELECT ItemNumber FROM tbl1 UNION SELECT ItemNumber FROM tbl2 In LINQ: ``` var itemCounts = (from hhd in dc.HHD select hhd.ItemNumber) .Union((from hkb in dc.HKB select hkb.ItemNumber) .Union(from hmm in dc.HMM select hmm.ItemNumber)) and so on ``` Note that using UNIONs like this is not really very efficient. You are getting the entire data set in one round-trip to the database, but the database server must do a separate query for each UNION, so if you are planning on doing something complex against a lot of data, you might be better off rethinking your database design.
Don't use Union - instead use [Concat](http://msdn.microsoft.com/en-us/library/bb351755.aspx)! * LinqToSql's *Union* is mapped to T-Sql's *Union*. * LinqToSql's **Concat** is mapped to T-Sql's **Union All**. The difference is that *Union* requires that the lists be checked against each other and have duplicates removed. This checking costs time and I would expect your part numbers are globally unique (appears in a single list only) anyway. **Union All** skips this extra checking and duplicate removal. ``` List<string> itemNumbers = dc.DataBoxPCHardwareCases.Select(hc => hc.ItemNumber) .Concat(dc.DataBoxPCHardwareHardDrives.Select( hkd => hkd.ItemNumber )) .Concat(dc.DataBoxPCHardwareKeyboards.Select( hkb => hkb.ItemNumber )) .Concat(dc.DataBoxPCHardwareMemories.Select( hhh => hhh.ItemNumber )) .Concat(dc.DataBoxPCHardwareMonitors.Select( hmo => hmo.ItemNumber )) .Concat(dc.DataBoxPCHardwareMotherboards.Select( hmb => hmb.ItemNumber )) .Concat(dc.DataBoxPCHardwareMouses.Select( hms => hms.ItemNumber )) .Concat(dc.DataBoxPCHardwareOpticalDrives.Select( hod => hod.ItemNumber )) .Concat(dc.DataBoxPCHardwarePowerSupplies.Select( hps => hps.ItemNumber )) .Concat(dc.DataBoxPCHardwareProcessors.Select( hpc => hpc.ItemNumber )) .Concat(dc.DataBoxPCHardwareSpeakers.Select( hsp => hsp.ItemNumber )) .Concat(dc.DataBoxPCHardwareVideoCards.Select( hvc => hvc.ItemNumber )) .Concat(dc.DataBoxPCSoftwareOperatingSystems.Select( sos => sos.ItemNumber )) .ToList(); ```
Linq to SQl, select same column from multiple tables
[ "", "c#", ".net", "linq", "linq-to-sql", "" ]
Is there an online Java book like *Dive into Python* for learning Python? Other resources online besides the standard Java documentation (which is awesome but almost too technical) .
Definitely "[Thinking in Java](http://www.mindview.net/Books/TIJ/)" by Bruce Eckel.
Hard to tell if you meant this by "standard online documentation" but the [Java Tutorial](http://java.sun.com/docs/books/tutorial/) is excellent and what many of us old-timers started with.
Online Java Book
[ "", "java", "" ]
I've been searching for a way to get all the strings that map to function names in a dll. I mean by this all the strings for which you can call GetProcAddress. If you do a hex dump of a dll the symbols (strings) are there but I figure there must me a system call to acquire those names.
It takes a bit of work, but you can do this programmaticly using the [DbgHelp](http://msdn.microsoft.com/en-us/library/ms679291(VS.85).aspx "MSDN: DbgHelp Debugging Libraries") library from Microsoft. [Debugging Applications for Microsoft .Net and Microsoft Windows, by John Robbins](https://rads.stackoverflow.com/amzn/click/com/0735615365 "Amazon: Debugging Applications for Microsoft .Net and Microsoft Windows") is an excellent (if a little older) book which contains use details and full source. And, you can pick it up on Amazon for the cheap!
If you have MS Visual Studio, there is a command line tool called DUMPBIN. ``` dumpbin /exports <nameofdll> ```
Is there a way to find all the functions exposed by a dll
[ "", "c++", "c", "winapi", "dll", "" ]
I have this factory method in java: ``` public static Properties getConfigFactory() throws ClassNotFoundException, IOException { if (config == null) { InputStream in = Class.forName(PACKAGE_NAME).getResourceAsStream(CONFIG_PROP); config = new Properties(); config.load(in); } return config; } ``` And I want to transform the two checked exceptions into unchecked exceptions. What is the best way to go about this? Should I just catch the exception and throw a new RuntimeException using the caught exception as the inner exception? Is there a better way to do this or should I even be attempting to do this in the first place? **EDIT:** Just to clarify. These exceptions will be fatal, as the configuration file is essentially to the operation of the program and all exception will be caught and logged at the top level of my program. My purpose is to avoid an unnecessary throws exception, exception added to the signature of every method that calls my factory.
A `RuntimeException` should be used only when the client cannot recover from whatever the problem is. It is occasionally appropriate to do what you are talking about, but more often it is not appropriate. If you are using a JDK >= 1.4, then you can do something like: ``` try { // Code that might throw an exception } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } ``` and the rethrown `RuntimeException` will have the original cause included inside it. This way, someone at the top of the thread catching the `RuntimeException` -- your threads do catch `RuntimeException` so they don't just silently die, right? -- can at least print out the FULL stack trace of the cause. But as others have said and will say, exceptions are checked for a reason. Only do this when you are positive that your clients cannot recover from the problem that you are rethrowing as an unchecked exception. NOTE: Better than just `RuntimeException` would be to use a more specific unchecked exception if one is available. For example, if the only reason your method could throw a `ClassNotFoundException` is because a configuration file is missing, you could rethrow a `MissingResourceException`, which is an unchecked exception but gives more information about why you are throwing it. Other good `RuntimeException`s to use if they describe the problem you are rethrowing are `IllegalStateException`, `TypeNotPresentException` and `UnsupportedOperationException`. Also note that it is ALWAYS a good idea for your threads to catch RuntimeException and at a minimum log it. At least this way you understand why your threads are going away.
Two points regarding exception handling best practices: * **Caller code cannot do anything** about the exception -> Make it an **unchecked exception** * **Caller code will take some useful recovery action** based on information in exception -> Make it a **checked exception** And you may throw the RuntimeException with or without inner exception, depending on what the caller can do with it. If you're not rethrowing the inner exception then you should log it in your method, if important.
Wrapping a checked exception into an unchecked exception in Java?
[ "", "java", "exception", "checked-exceptions", "" ]
I'm currently doing something like this in some code I'm working on right now: ``` public CommandType GetCommandTypeFromCommandString(String command) { if(command.StartsWith(CommandConstants.Acknowledge)) return CommandType.Acknowledge; else if (command.StartsWith(CommandConstants.Status)) return CommandType.Status; else if (command.StartsWith(CommandConstants.Echo)) return CommandType.Echo; else if (command.StartsWith(CommandConstants.Warning)) return CommandType.Warning; // and so on return CommandType.None; } ``` I'd like to know if there is a more efficient way of doing this in C#. This code needs to execute many, many times a second, and I'm not too happy with the time it takes to do all of those string comparisons. Any suggestions? :)
One optimization would be to use the StringComparison enum to specify that you only want ordinal comparison. Like this: ``` if(command.StartsWith(CommandConstants.Acknowledge, StringComparison.Ordinal)) return CommandType.Acknowledge; ``` If you don't specify a string comparison method the current culture will be used for comparison and that slows things down a bit. I did some (really really naive) benchmarking: ``` var a = "foo bar foo"; var b = "foo"; int numTimes = 1000000; Benchmark.Time(() => a.StartsWith(b, StringComparison.Ordinal), "ordinal", numTimes); Benchmark.Time(() => a.StartsWith(b), "culture sensitive", numTimes); ``` Which produced the following results: ``` ordinal ran 1000000 times in 35.6033 ms culture sensitive ran 1000000 times in 175.5859 ms ``` You should also order your comparisons so that the most likely tokens are being compared first (happy path). Theese optimizations are a simple way of making your current implementation perform better but if performance really is critical (and I mean really critical) you should be looking towards implementing some sort of state machine.
Similar in concept to the FSM answer by Vojislav, you could try putting the constants into a [trie](http://en.wikipedia.org/wiki/Trie). You can then replace your sequence of comparisons with a single traversal of the trie. There is a C# trie implementation described [here](http://www.kerrywong.com/2006/04/01/implementing-a-trie-in-c/).
More efficient way to determine if a string starts with a token from a set of tokens?
[ "", "c#", "optimization", "" ]
In my C# application, I use a regular expression to validate the basic format of a US phone number to make sure that the user isn't just entering bogus data. Then, I strip out everything except numbers, so this: > (123) 456-7890 x1234 becomes > 12345678901234 in the database. In various parts of my application, however, I would like to convert this normalized phone number back to > (123) 456-7890 x1234 What's the best way to do such a thing? (Don't worry about accounting for international phone number formats, by the way.)
``` String.Format("{0:(###) ###-#### x ###}", double.Parse("1234567890123")) ``` Will result in (123) 456-7890 x 123
Using a regex you can replace: ``` (\d{3})(\d{3})(\d{4})(\d{4}) ``` with: ``` (\1) \2-\3 x\4 ``` (Though I'm not familiar with US phone numbers so maybe there's more to it.)
Converting a normalized phone number to a user-friendly version
[ "", "c#", "regex", "formatting", "phone-number", "" ]
In javascript I have an array as follows: ``` var foo = [2, 2, 4, 4, 128, 2, 2, 1, 4, 18, 27, 16, 2, 1, 18, 21, 5, 1, 128, 1, 2, 2, 1, 18, 12, 60, 2, 28, 1, 17, 2, 3, 4, 2, 2, 2, 1, 27, 2, 17, 7, 2, 2, 2, 5, 1, 2, 4, 7, 1, 2, 1, 1, 1, 2, 1, 5, 7, 2, 7, 6, 1, 7, 1, 5, 8, 4]; ``` And I am interested in finding a way (within one loop, not multiple) to derive a subset array of the highest 10 values, where the previous position of the value is the 'key' (so simulating a Map object): eg: ``` var fooTopTen = [[4, 128], [18, 128], [25, 60], [27, 28], [10, 27], [37, 27], [15, 21], [9, 18], [14, 18], [23, 18]]; ```
My previous answer used a reverse index table, but contained some bugs - which are now fixed - and was harder to understand than the following code. This is actually the slowest of all solutions given in the answers - for maximum performance, check my other answer. ``` var foo = [2, 2, 4, 4, 128, 2, 2, 1, 4, 18, 27, 16, 2, 1, 18, 21, 5, 1, 128, 1, 2, 2, 1, 18, 12, 60, 2, 28, 1, 17, 2, 3, 4, 2, 2, 2, 1, 27, 2, 17, 7, 2, 2, 2, 5, 1, 2, 4, 7, 1, 2, 1, 1, 1, 2, 1, 5, 7, 2, 7, 6, 1, 7, 1, 5, 8, 4]; var fooTopTen = []; // add index to values for(var i = 0, len = foo.length; i < len; ++i) fooTopTen.push([i, foo[i]]); // sort first by value (descending order), then by index (ascending order) fooTopTen.sort(function(t1, t2) { return t2[1] - t1[1] || t1[0] - t2[0]; }); // shorten array to correct size fooTopTen.length = 10; // output top ten to check result document.writeln('[[' + fooTopTen.join('], [') + ']]'); ``` The second part of the comparison function (the one comparing the indices) is not needed, as `sort()` is stable in most implementations (this isn't required by ECMA [according to MDC](https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array/Sort)). I'll leave it in as an example to how sorting with multiple requirements can be done...
Here's the de-bugged version of my previous answer using an index table. I did a little benchmarking and for the input given in the question, this solition will be faster than anything else which has been suggested in this thread till now: ``` var foo = [2, 2, 4, 4, 128, 2, 2, 1, 4, 18, 27, 16, 2, 1, 18, 21, 5, 1, 128, 1, 2, 2, 1, 18, 12, 60, 2, 28, 1, 17, 2, 3, 4, 2, 2, 2, 1, 27, 2, 17, 7, 2, 2, 2, 5, 1, 2, 4, 7, 1, 2, 1, 1, 1, 2, 1, 5, 7, 2, 7, 6, 1, 7, 1, 5, 8, 4]; var indexTable = {}, uniqueValues = []; // --- build reverse index table, find unique values for(var i = foo.length; i--; ) { var value = foo[i]; if(indexTable.hasOwnProperty(value)) indexTable[value].push(i); else { indexTable[value] = [i]; uniqueValues.push(value); } } // --- sort unique values in ascending order uniqueValues.sort(function(i1, i2) { return i1 - i2; }); // --- find ten greatest values var fooTopTen = [], k = 0; for(var i = uniqueValues.length; k < 10 && i--; ) { var value = uniqueValues[i], indices = indexTable[value]; for(var j = indices.length; k < 10 && j--; ) fooTopTen[k++] = [indices[j], value]; } // --- output result document.writeln('[[' + fooTopTen.join('], [') + ']]'); ```
Easiest way to derive subset array of highest 10 values?
[ "", "javascript", "" ]
I am writing a web service in Java, and I am **trying to figure out the best way to define error codes and their associated error strings**. I need to have a numerical error code and an error string grouped together. Both the error code and error string will be sent to the client accessing the web service. For example, when a SQLException occurs, I might want to do the following: ``` // Example: errorCode = 1, // errorString = "There was a problem accessing the database." throw new SomeWebServiceException(errorCode, errorString); ``` The client program might be shown the message: > "Error #1 has occured: There was a > problem accessing the database." My first thought was to used an `Enum` of the error codes and override the `toString` methods to return the error strings. Here is what I came up with: ``` public enum Errors { DATABASE { @Override public String toString() { return "A database error has occured."; } }, DUPLICATE_USER { @Override public String toString() { return "This user already exists."; } }, // more errors follow } ``` **My question is:** Is there a better way to do this? I would prefer an solution in code, rather than reading from an external file. I am using Javadoc for this project, and being able to document the error codes in-line and have them automatically update in the documentation would be helpful.
Well there's certainly a better implementation of the enum solution (which is generally quite nice): ``` public enum Error { DATABASE(0, "A database error has occurred."), DUPLICATE_USER(1, "This user already exists."); private final int code; private final String description; private Error(int code, String description) { this.code = code; this.description = description; } public String getDescription() { return description; } public int getCode() { return code; } @Override public String toString() { return code + ": " + description; } } ``` You may want to override toString() to just return the description instead - not sure. Anyway, the main point is that you don't need to override separately for each error code. Also note that I've explicitly specified the code instead of using the ordinal value - this makes it easier to change the order and add/remove errors later. Don't forget that this isn't internationalised at all - but unless your web service client sends you a locale description, you can't easily internationalise it yourself anyway. At least they'll have the error code to use for i18n at the client side...
As far as I am concerned, I prefer to externalize the error messages in a properties files. This will be really helpful in case of internationalization of your application (one properties file per language). It is also easier to modify an error message, and it won't need any re-compilation of the Java sources. On my projects, generally I have an interface that contains errors codes (String or integer, it doesn't care much), which contains the key in the properties files for this error: ``` public interface ErrorCodes { String DATABASE_ERROR = "DATABASE_ERROR"; String DUPLICATE_USER = "DUPLICATE_USER"; ... } ``` in the properties file: ``` DATABASE_ERROR=An error occurred in the database. DUPLICATE_USER=The user already exists. ... ``` Another problem with your solution is the maintenability: you have only 2 errors, and already 12 lines of code. So imagine your Enumeration file when you will have hundreds of errors to manage!
Best way to define error codes/strings in Java?
[ "", "java", "enums", "" ]
I know that there are many free and not so free compression libraries out there, but for the project i am working on, i need to be able to take file data from a stream and put it into some kind zip or pack file, but without compression, because i will need to access these files quickly without having to wait for them to decompress. Anyone know how this could be approached, or if there are some libraries out there that do this that i am not aware of?
You can use Zip for this. You would use a compression level of something like "none" or "store", which just combines the files without compression. [This site](http://help.globalscape.com/help/cutezip2/Compression_levels__effects.htm) enumerates some of them: > * Maximum - The slowest of the > compression options, but the most > useful for creating small archives. > * Normal - The default value. > * Low - Faster than the default, but > less effective. > * Minimum - Extremely fast > compression, but not as efficient as > other methods. > * **None** - Creates a ZIP file but **does > not compress it**. File size may be > slightly larger if archive is > encrypted or made self-extracting. Here are some C# examples: * [CodeProject](http://www.codeproject.com/KB/recipes/ZipStorer.aspx) * [EggheadCafe](http://www.eggheadcafe.com/tutorials/aspnet/9ce6c242-c14c-4969-9251-af95e4cf320f/zip--unzip-folders-and-f.aspx) For the unix unaware, this is exactly what `tar` does. When you see .tar.gz files, it's just a bunch of files combined into a `tar` file, and then run through gzip.
Have a look at [System.IO.Packaging](http://msdn.microsoft.com/en-us/library/system.io.packaging.aspx) namespace. Quote from MSDN: > System.IO.Packaging > > Provides classes that support storage > of multiple data objects in a single > container. > > Package is an abstract class that can > be used to organize objects into a > single entity of a defined physical > format for portability and efficient > access. > > A ZIP file is the primary physical > format for the Package. Other Package > implementations might use other > physical formats such as an XML > document, a database, or Web service. You can select different [compression options](http://msdn.microsoft.com/en-us/library/system.io.packaging.compressionoption.aspx) for your package: * **NotCompressed** - Compression is turned off. * **Normal** - Compression is optimized for a balance between size and performance. * **Maximum** - Compression is optimized for size. * **Fast** - Compression is optimized for performance. * **SuperFast** - Compression is optimized for high performance.
Create zip style file without compression
[ "", "c#", "" ]
I have to use a smart pointer and I found "shared\_ptr" from boost looks good. I downloaded the boost library and I can see many files and libraries there. Is there any way to use only the shared\_ptr ?
[`boost bcp`](http://www.boost.org/doc/libs/1_37_0/tools/bcp/bcp.html) is your friend. It allows extracting individual boost libraries out of its tree. I used it with success in the past. shared\_ptr consists only of headers, so that will be especially good for you.
You can use bcp as litb suggested, but if you're worried about dragging in extra library code, you shouldn't be. Boost, in general, follows the C++ philosophy of "you only pay for what you use". So, if you include only the shared\_ptr headers, that's all that your code will use.
Using boost shared_ptr
[ "", "c++", "boost", "" ]
``` public class WrapperTest { public static void main(String[] args) { Integer i = 100; Integer j = 100; if(i == j) System.out.println("same"); else System.out.println("not same"); } } ``` The above code gives the output of `same` when run, however if we change the value of `i` and `j` to 1000 the output changes to `not same`. As I'm preparing for SCJP, need to get the concept behind this clear. Can someone explain this behavior.Thanks.
In Java, Integers between -128 and 127 (inclusive) are generally represented by the same Integer object instance. This is handled by the use of a inner class called IntegerCache (contained inside the Integer class, and used e.g. when Integer.valueOf() is called, or during autoboxing): ``` private static class IntegerCache { private IntegerCache(){} static final Integer cache[] = new Integer[-(-128) + 127 + 1]; static { for(int i = 0; i < cache.length; i++) cache[i] = new Integer(i - 128); } } ``` See also: [http://www.owasp.org/index.php/Java\_gotchas](http://www.owasp.org/index.php/Java_gotchas#Immutable_Objects_.2F_Wrapper_Class_Caching)
Basically Integers between -127 and 127 are 'cached' in such a way that when you use those numbers you always refer to the same number in memory, which is why your `==` works. Any Integer outside of that range are not cached, thus the references are not the same.
Java Wrapper equality test
[ "", "java", "wrapper", "" ]
I'm using Zend Framework 1.7.2, MySQL and the MySQLi PDO adapter. I would like to call multiple stored procedures during a given action. I've found that on Windows there is a problem calling multiple stored procedures. If you try it you get the following error message: > SQLSTATE[HY000]: General error: 2014 > Cannot execute queries while other > unbuffered queries are active. > Consider using > PDOStatement::fetchAll(). > Alternatively, if your code is only > ever going to run against mysql, you > may enable query buffering by setting > the PDO::MYSQL\_ATTR\_USE\_BUFFERED\_QUERY > attribute. I found that to work around this issue I could just close the connection to the database after each call to a stored procedure: ``` if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { //If on windows close the connection $db->closeConnection(); } ``` This has worked well for me, however, now I want to call multiple stored procedures wrapped in a transaction. Of course, closing the connection isn't an option in this situation, since it causes a rollback of the open transaction. Any ideas, how to fix this problem and/or work around the issue. * [More info about the work around](http://www.zfforums.com/zend-framework-components-13/databases-20/how-stored-procedure-using-mysqli-pdo-successfully-662.html) * [Bug report about the problem](http://framework.zend.com/issues/browse/ZF-2101)
I has same errors when called queries like this(variables to use in next query) ``` $db->query("SET @curr = 0.0;"); ``` To fix this I've changed my config file to ``` 'database' => array( 'adapter' => 'mysqli', ```
This pattern of preparing, executing and then closing each $sql statement that calls a stored procedure does work. ``` public function processTeams($leagueid,$raceid,$gender) { $db = Zend_Db_Table::getDefaultAdapter(); $sql = $db->prepare(sprintf("CALL addScoringTeams(%d,%d,'%s')",$leagueid,$raceid,$gender)); $sql->execute(); $sql->closeCursor(); $this->logger->info(sprintf("CALL addScoringTeams(%d,%d,'%s')",$leagueid,$raceid,$gender)); $sql1 = $db->prepare(sprintf("CALL updateScoringTeamTotals(%d)",$raceid)); $sql1->execute(); $sql1->closeCursor(); $this->logger->info(sprintf("CALL updateScoringTeamTotals(%d)",$raceid)); $sql2 = $db->prepare(sprintf("CALL updateScoringTeamClasses(%d,'%s')",$raceid,$gender)); $sql2->execute(); $sql2->closeCursor(); $this->logger->info(sprintf("CALL updateScoringTeamClasses(%d,'%s')",$raceid,$gender)); } ```
Call Multiple Stored Procedures with the Zend Framework
[ "", "php", "mysql", "zend-framework", "stored-procedures", "" ]
I have a list of Python objects that I want to sort by a specific attribute of each object: ``` [Tag(name="toe", count=10), Tag(name="leg", count=2), ...] ``` How do I sort the list by `.count` in descending order?
To sort the list in place: ``` orig_list.sort(key=lambda x: x.count, reverse=True) ``` To return a new list, use `sorted`: ``` new_list = sorted(orig_list, key=lambda x: x.count, reverse=True) ``` Explanation: * `key=lambda x: x.count` sorts by count. * `reverse=True` sorts in descending order. More on [sorting by keys](http://wiki.python.org/moin/HowTo/Sorting#Sortingbykeys).
A way that can be fastest, especially if your list has a lot of records, is to use `operator.attrgetter("count")`. However, this might run on an pre-operator version of Python, so it would be nice to have a fallback mechanism. You might want to do the following, then: ``` try: import operator except ImportError: keyfun= lambda x: x.count # use a lambda if no operator module else: keyfun= operator.attrgetter("count") # use operator since it's faster than lambda ut.sort(key=keyfun, reverse=True) # sort in-place ```
How do I sort a list of objects based on an attribute of the objects?
[ "", "python", "list", "sorting", "reverse", "" ]
I'm using levenshtein algorithm to meet these requirements: When finding a word of N characters, the words to suggest as correction in my dictionary database are: Every dictionary word of N characters that has 1 character of difference with the found word. Example: found word:bearn, dictionary word: bears Every dictionary word of N+1 characters that has N characters equal to the found word. Example: found word:bear, dictionary word: bears Every dictionary word of N-1 characters that has N-1 characters equal to the found word. Example: found word: bears, dictionary word: bear I'm using this implementation of Levenshtein algorithm in C++ to find when a word has a Levenshtein number of 1 (which is the Levenshtein number for all three cases), but then how do I choose the word to suggest? I read about Boyer-Moore-Horspool and Knuth-Morris-Pratt but I'm not sure on how either of them can be helpful. ``` #include <string> #include <vector> #include <algorithm> using namespace std; int levenshtein(const string &s1, const string &s2) { string::size_type N1 = s1.length(); string::size_type N2 = s2.length(); string::size_type i, j; vector<int> T(N2+1); for ( i = 0; i <= N2; i++ ) T[i] = i; for ( i = 0; i < N1; i++ ) { T[0] = i+1; int corner = i; for ( j = 0; j < N2; j++ ) { int upper = T[j+1]; if ( s1[i] == s2[j] ) T[j+1] = corner; else T[j+1] = min(T[j], min(upper, corner)) + 1; corner = upper; } } return T[N2]; } ```
You may also want to add [Norvig's excellent article on spelling correction](http://norvig.com/spell-correct.html) to your reading. It's been a while since I've read it but I remember it being very similar to what your writing about.
As I've said elsewhere, Boyer-Moore isn't really apt for this. Since you want to search for multiple stings simultanously, the algorithm of Wu and Manber should be more to your liking. I've posted a proof of concept C++ code in answer to [another question](https://stackoverflow.com/questions/154365/search-25-000-words-within-a-text#154410). Heed the caveats mentioned there.
Levenshtein algorithm: How do I meet this text editing requirements?
[ "", "c++", "algorithm", "pattern-matching", "levenshtein-distance", "" ]
Edit--@Uri correctly pointed out that this was an abuse of annotations; trying to actually create the menu data itself in annotations is just silly. They are good for binding however, I think I'll stick with using them to link the text data to the methods (the @Menu ("File") portion) since it's more explicit and flexible than reflecting to a method name. Also I learned quite a bit in messing with it. I'll post the code here in a few days as an answer. --original post-- I haven't used these new-fangled annotations, but they look amazingly interesting. I'm having trouble figuring out the syntax though (or more appropriately, the best way to use it). In writing some code in response to this [question](https://stackoverflow.com/questions/473540/correct-way-to-use-actions-to-create-menus-toolbars-and-other-components-in-jav#473879) It occurred to me that my methods are quite outdated. I used to parse a string to define my method structure, then use reflection to pass it out to classes, but I think annotations could make a much better menu structure. I'd like to replace my test class in the file with something like this: ``` @TopMenu("File,Edit") @Menu(name="File","Save,Load,Print,Preview,Quit") @Menu(name="Print","Preview,Print") @Menu(name="Edit","Copy,Paste") public class TestMenu { @MenuItem ("Save") public void save() { System.out.println("saved"); } @MenuItem ("Load") public void load() { System.out.println("loaded"); } ... ``` and pass the entire class off to a method that manufactures and returns a JMenuBar bound to the class instance with no further input. First problem is that I can't figure out how to pass a "Default" of a string, they all want to have (attribute="value") instead of just ("value"), can this be done? I can live without it, but it's a little verbose. It'd be even better if I could get rid of the parens and/or quotes, but I'm not holding my breath (I think to do that I'd have to define an individual interface for each menu item, that's not acceptable). Secondly it doesn't like the multiple @Menu tags on a single class. I could get around this by parsing a single string, but I was wondering if there was another way. Most importantly, is there a library that does this already? (If nobody comes up with one, I'll publish code to this thread when I get it working in case anyone else is interested.)
The way I've seen multiple annotations attached is to use a container annotation, and then specify the items as an array. ``` @Retention(RetentionPolicy.RUNTIME) public @interface Menu { String name(); String[] children(); } @Retention(RetentionPolicy.RUNTIME) public @interface MenuBar { Menu[] value(); } @Retention(RetentionPolicy.RUNTIME) public @interface MenuItem { String value(); } @MenuBar( { @Menu(name="File", children= {"Save","Load","Print","Preview","Quit"}), @Menu(name="Print", children= {"Preview","Print"}), @Menu(name="Edit", children= {"Copy","Paste"}) } ) public class TestMenu { @MenuItem ("Save") public void save() { System.out.println("saved"); } @MenuItem ("Load") public void load() { System.out.println("loaded"); } } ```
I know I'll get downvoted for this, but I really think people are starting to overabuse the annotation mechanism in Java. All it was designed for was to be a mechanism for providing metainformation about classes and methods for the purpose of the compiler or of programming-support tools (e.g., testing infrastructure, model checkers, code generators, etc.) It was not meant for actual production-oriented code, macro metaprogramming, and all that. This is just as inelegant as using preprocessor macros in C instead of actual functions. If menus are first-class entities in your program, I really don't feel that you should be using the annotation mechanism for them. As for your specific questions, you can easily define a default value. However, you can't start doing things like nesting annotations to overcome the menu problem. It really wasn't designed for this.
Help with annotations
[ "", "java", "user-interface", "swing", "reflection", "annotations", "" ]
I'm implementing `compareTo()` method for a simple class such as this (to be able to use `Collections.sort()` and other goodies offered by the Java platform): ``` public class Metadata implements Comparable<Metadata> { private String name; private String value; // Imagine basic constructor and accessors here // Irrelevant parts omitted } ``` I want the *natural ordering* for these objects to be: 1) sorted by name and 2) sorted by value if name is the same; both comparisons should be case-insensitive. For both fields null values are perfectly acceptable, so `compareTo` must not break in these cases. The solution that springs to mind is along the lines of the following (I'm using "guard clauses" here while others might prefer a single return point, but that's beside the point): ``` // primarily by name, secondarily by value; null-safe; case-insensitive public int compareTo(Metadata other) { if (this.name == null && other.name != null){ return -1; } else if (this.name != null && other.name == null){ return 1; } else if (this.name != null && other.name != null) { int result = this.name.compareToIgnoreCase(other.name); if (result != 0){ return result; } } if (this.value == null) { return other.value == null ? 0 : -1; } if (other.value == null){ return 1; } return this.value.compareToIgnoreCase(other.value); } ``` This does the job, but I'm not perfectly happy with this code. Admittedly it isn't *very* complex, but is quite verbose and tedious. The question is, **how would you make this less verbose** (while retaining the functionality)? Feel free to refer to Java standard libraries or Apache Commons if they help. Would the only option to make this (a little) simpler be to implement my own "NullSafeStringComparator", and apply it for comparing both fields? **Edits 1-3**: Eddie's right; fixed the "both names are null" case above ## About the accepted answer I asked this question back in 2009, on Java 1.6 of course, and at the time **[the pure JDK solution by Eddie](https://stackoverflow.com/a/481836/56285)** was my preferred accepted answer. I never got round to changing that until now (2017). There are also [3rd party library solutions](https://stackoverflow.com/a/500643/56285)—a 2009 Apache Commons Collections one and a 2013 Guava one, both posted by me—that I did prefer at some point in time. I now made the clean **[Java 8 solution by Lukasz Wiktor](https://stackoverflow.com/a/23908426/56285)** the accepted answer. That should definitely be preferred if on Java 8, and these days Java 8 should be available to nearly all projects.
Using **Java 8**: ``` private static Comparator<String> nullSafeStringComparator = Comparator .nullsFirst(String::compareToIgnoreCase); private static Comparator<Metadata> metadataComparator = Comparator .comparing(Metadata::getName, nullSafeStringComparator) .thenComparing(Metadata::getValue, nullSafeStringComparator); public int compareTo(Metadata that) { return metadataComparator.compare(this, that); } ```
You can simply use [Apache Commons Lang](http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ObjectUtils.html#compare(T,%20T)): ``` result = ObjectUtils.compare(firstComparable, secondComparable) ```
How to simplify a null-safe compareTo() implementation?
[ "", "java", "refactoring", "comparison", "null", "compareto", "" ]
Given an instance of some class in Python, it would be useful to be able to determine which line of source code *defined* each method and property (e.g. to implement [1](https://stackoverflow.com/questions/465605/how-do-i-make-ipython-organize-tab-completion-possibilities-by-class)). For example, given a module ab.py ``` class A(object): z = 1 q = 2 def y(self): pass def x(self): pass class B(A): q = 4 def x(self): pass def w(self): pass ``` define a function whither(class\_, attribute) returning a tuple containing the filename, class, and line in the source code that defined or subclassed `attribute`. This means the definition in the class body, not the latest assignment due to overeager dynamism. It's fine if it returns 'unknown' for some attributes. ``` >>> a = A() >>> b = B() >>> b.spigot = 'brass' >>> whither(a, 'z') ("ab.py", <class 'a.A'>, [line] 2) >>> whither(b, 'q') ("ab.py", <class 'a.B'>, 8) >>> whither(b, 'x') ("ab.py", <class 'a.B'>, 9) >>> whither(b, 'spigot') ("Attribute 'spigot' is a data attribute") ``` I want to use this while introspecting Plone, where every object has hundreds of methods and it would be really useful to sort through them organized by class and not just alphabetically. Of course, in Python you can't always reasonably know, but it would be nice to get good answers in the common case of mostly-static code.
You are looking for the undocumented function `inspect.classify_class_attrs(cls)`. Pass it a class and it will return a list of tuples `('name', 'kind' e.g. 'method' or 'data', defining class, property)`. If you need information on absolutely everything in a specific instance you'll have to do additional work. Example: ``` >>> import inspect >>> import pprint >>> import calendar >>> >>> hc = calendar.HTMLCalendar() >>> hc.__class__.pathos = None >>> calendar.Calendar.phobos = None >>> pprint.pprint(inspect.classify_class_attrs(hc.__class__)) [... ('__doc__', 'data', <class 'calendar.HTMLCalendar'>, '\n This calendar returns complete HTML pages.\n '), ... ('__new__', 'data', <type 'object'>, <built-in method __new__ of type object at 0x814fac0>), ... ('cssclasses', 'data', <class 'calendar.HTMLCalendar'>, ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']), ('firstweekday', 'property', <class 'calendar.Calendar'>, <property object at 0x98b8c34>), ('formatday', 'method', <class 'calendar.HTMLCalendar'>, <function formatday at 0x98b7bc4>), ... ('pathos', 'data', <class 'calendar.HTMLCalendar'>, None), ('phobos', 'data', <class 'calendar.Calendar'>, None), ... ] ```
This is more-or-less impossible without static analysis, and even then, it won't always work. You can get the line where a function was defined and in which file by examining its code object, but beyond that, there's not much you can do. The `inspect` module can help with this. So: ``` import ab a = ab.A() meth = a.x # So, now we have the method. func = meth.im_func # And the function from the method. code = func.func_code # And the code from the function! print code.co_firstlineno, code.co_filename # Or: import inspect print inspect.getsource(meth), inspect.getfile(meth) ``` But consider: ``` def some_method(self): pass ab.A.some_method = some_method ab.A.some_class_attribute = None ``` Or worse: ``` some_cls = ab.A some_string_var = 'another_instance_attribute' setattr(some_cls, some_string_var, None) ``` Especially in the latter case, what do you want or expect to get?
How would you determine where each property and method of a Python class is defined?
[ "", "python", "introspection", "plone", "python-datamodel", "" ]
I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name. This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be worth it for them. Any ideas on how I can use a Perl/Python/Ruby type language without all the headaches of getting the interpreter on their computer? Thought about web for a second but it would not work for business reasons.
You can use [Perl Archive Toolkit](http://search.cpan.org/perldoc?PAR) to bring a minimal perl core + needed modules + your Perl program with you. And you can even convert it using [PAR Packer](http://search.cpan.org/perldoc?pp) to a windows exe file that will run just like any other program, from an end user's perspective.
You can get Windows executables in all three languages. * As usual with Perl, there's more than one way to do it: + [PAR Packer](http://search.cpan.org/perldoc?pp) (free/open-source) + [perl2exe](http://www.indigostar.com/perl2exe.htm) (shareware) + [PerlApp](http://community.activestate.com/products/PerlDevKit) (part of the Perl Dev Kit from ActiveState, commercial) * Python + [py2exe](http://www.py2exe.org/) + [PyInstaller](http://www.pyinstaller.org/) * Ruby + [RubyScript2Exe](http://www.erikveen.dds.nl/rubyscript2exe/) + [OCRA](http://ocra.rubyforge.org/)
How can I deploy a Perl/Python/Ruby script without installing an interpreter?
[ "", "python", "ruby", "perl", "" ]
When I design classes and have to choose between inheritance and composition, I usually use the rule of thumb: if the relationship is "is-a" - use inheritance, and if the relationship is "has-a" - use composition. Is it always right? Thank you.
No - "is a" does not always lead to inheritence. A well cited example is the relationship between a square and a rectangle. A square is a rectangle, but it will be bad to design code that inherits a Square class off a Rectangle class. My suggestion is to enhance your "is a / has a" heuristic with the [Liskov Substitution Principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle). To check whether an inheritence relationship complies with the Liskov Substitution Principle, ask whether clients of a base class can operate on the sub class without knowing that it is operating on a sub class. Of course, all the properties of the sub class must be preserved. In the square / rectangle example, we must ask whether a client of rectangle can operate on a square without knowing that it is a square. All that the client must know is that it is operating on a rectangle. The following function demonstrates a client that assumes that setting the width of a rectangle leaves the height unchanged. ``` void g(Rectangle& r) { r.SetWidth(5); r.SetHeight(4); assert(r.GetWidth() * r.GetHeight()) == 20); } ``` This assumption is true for a rectangle, but not for a square. So the function cannot operate on a square and therefore the inheritence relationship violates the Liskov Substitution principle. [Other examples](https://stackoverflow.com/q/56860/3681671)
Yes and no. The line can be blurred. This hasn't been helped by some pretty terrible examples of OO programming from the early days of OO like: Manager is an Employee is a Person. The thing you have to remember about inheritance is: inheritance breaks encapsulation. Inheritance is an implementation detail. There's all sorts written on this subject. The pithiest way to sum it up is: **Prefer composition.** That doesn't mean use it to the complete exclusion of inheritance. It just means inheritance is a fallback position.
Inheritance or composition: Rely on "is-a" and "has-a"?
[ "", "c++", "inheritance", "oop", "" ]
I have an application that uses simple sockets to pass some characters between two systems. I have my java application running as a server. I establish a connection fine, and even pass one message. However, after one message has been sent my connection closes. From what I can tell it appears as if on closing the `printWriter` and `bufferedReader` the socket itself is being closed?! This is bad, as I have multiple messages to send on the same connection. ``` printWriter = new PrintWriter(theServer.getClientSocket().getOutputStream()); bufferedReader = new BufferedReader(new InputStreamReader(theServer.getClientSocket().getInputStream())); printWriter.println("the line"); printWriter.close(); //Closing on these lines? bufferedReader.close(); //Closing on these lines? ``` Am I full of it? How do I maintain this connection in Java?
Yes, closing any Writer/Reader will close all other Writers and Readers that they wrap. Don't close it until you are ready to close the underlying socket.
As @Eddie [said](https://stackoverflow.com/questions/484925/does-closing-the-bufferedreader-printwriter-close-the-socket-connection#484939) (seconds before me! :) ), closing the writer and/or the reader will close the underlying socket streams [and the socket itself](http://docs.oracle.com/javase/8/docs/api/java/net/Socket.html#getInputStream--): ~~However, I believe the socket itself will not be closed~~. > Closing the returned InputStream will close the associated socket. You shouldn't close the writer nor the reader. Just flush the writer to make sure your messages will arrive in time. Closing the socket later on will close the respective streams, so you don't need to close them yourself. Just leave your reader/writer objects to the GC.
Does closing the BufferedReader/PrintWriter close the socket connection?
[ "", "java", "sockets", "" ]
Assume we have a method like this: ``` public IEnumerable<T> FirstMethod() { var entities = from t in context.Products where {some conditions} select t; foreach( var entity in entities ) { entity.SomeProperty = {SomeValue}; yield return entity; } } ``` where context is a DataContext that is generated by Linq to SQL designer. Does "FirstMethod" load the data into memory from database (because of the foreach loop) or will it still defer-load it until another foreach loop that doesn't have "yield return" is found in another method like the following? ``` public void SecondMethod() { foreach( var item in FirstMethod() ) { {Do Something} } } ```
The latter (deferred); `FirstMethod` is an iterator block (because of `yield return`); this means that you have a chain of iterators. Nothing is read until the **final caller** starts iterating the data; then each record is read in turn during the **final caller's** `foreach` (between which the connection/command is open). The `using` that surrounds `foreach` (under the bonnet) ensures that the connection is closed if the `foreach` is abandoned half-way-through. If you **want** to load the data earlier, use `.ToList()` or `.ToArray()` to buffer the data locally - but note that this breaks "composition" - i.e. the caller can no longer add extra `Where` etc clauses (which they can if it returns a raw `IQueryable<T>`). --- Re your question: ``` public IEnumerable<T> FirstMethod() { var entities = from t in context.Products where {some conditions} select t; foreach( var entity in entities.AsEnumerable() ) { entity.SomeProperty = {SomeValue}; yield return entity; } } ``` The `AsEnumerable` is the key here; it ends the composable `IQueryable<T>` chain, and uses LINQ-to-Objects for the rest.
In short, it doesn't load until SecondMethod performs the iteration... Read [here](http://rapidapplicationdevelopment.blogspot.com/2008/03/how-systemlinqwhere-really-works.html) for more...
Does it load the data from database?
[ "", "c#", ".net", "linq-to-sql", "" ]
I have a simple form on a view page, implemented as a user control, that looks something like this: ``` <%=Html.BeginForm("List", "Building", FormMethod.Post) %> //several fields go here <%Html.EndForm(); %> ``` There are two problems I would like resolved, the first is that I would like the controller method that receives this to take a type parameter of the user control. The goal is to avoid putting all of the fields of the form into the parameter list for the method. The controller method currently looks like this: ``` [AcceptVerbs("Post")] public ActionResult List(string capacityAmount) { ProfilerDataDataContext context = new ProfilerDataDataContext(); IEnumerable<Building> result = context.Buildings.OrderBy(p => p.SchoolName); ViewData["Boroughs"] = new SelectList(Boroughs.BoroughsDropDown()); return View(result); } ``` The rest of the fields in the form will be used to conduct a search against the buildings type. The form posts fine, I can search on the capacity the way you would expect, but I can smell ugliness ahead as I add parameters to the search. Second, smaller problem is that when the page renders the BeginForm tag renders the string "System.Web.Mvc.Form" to the page. How do I make that go away?
1) Use FormCollection as the argument: ``` public ActionResult List(FormCollection searchQuery) ``` Now you can iterate the FormCollection and get key/value search terms from your search form. 2) Remove the "=" from BeginForm: ``` <% Html.BeginForm("List", "Building", FormMethod.Post) %> ``` That said, you [should really be using](http://weblogs.asp.net/scottgu/archive/2008/10/16/asp-net-mvc-beta-released.aspx "ASP.NET MVC Beta Released"), um... using: ``` <% using (Html.BeginForm("List", "Building", FormMethod.Post)) { %> <% } %> ```
If I'm understanding your question properly, you use the html helper and create inputs named: ``` <%=Html.TextBox("building.FieldNumber1")%> <%=Html.TextBox("building.FieldNumber2")%> ``` You should be able to access the data using: ``` public ActionResult List(Building building) { ... var1 = building.FieldNumber1; var2 = building.FieldNumber2; ... } ``` and if your action is to do two different things depending on if form is submitted: ``` public ActionResult List() { //some code here } [AcceptVerbs(HttpVerbs.Post)] public ActionResult List(Building building) { ... var1 = building.FieldNumber1; var2 = building.FieldNumber2; ... } ```
Implementing Forms in ASP.net MVC
[ "", "c#", ".net", "asp.net-mvc", "forms", "view", "" ]
In C#/ASP.NET 3.5, I have a DataTable which pulls rows from the database. I want to dynamically apply a sort filter to the datatable (could be a dataview), and then do a loop through the "rows" of the sorted data to use each row for some metrics. I would greatly prefer not to hit the database each time to do custom sorting, but I'm not sure how to get a sorted datatable from an original datatable. I'm sure I'm forgetting/missing something simple, but I do not recall how to do this! I want to do this on the "sorted" list. It is currently doing it on the bound list from my query. ``` foreach (DataRow dr in dtTags.Rows) { LinkButton lbTag = new LinkButton(); lbTag.CssClass = "UserTagNoHover"; lbTag.ID = "hlUserTag" + dr["UserTagRID"].ToString(); lbTag.Text = dr["Name"].ToString(); //lbTag.Click += new System.EventHandler(this.Tag_OnClick); lbTag.CommandName = "User_Click"; lbTag.CommandArgument = "hlUserTag" + dr["UserTagRID"].ToString(); lbTag.ToolTip = "Total uses: " + dr["TotalCount"].ToString(); Boolean bAlreadyExists = false; foreach (LinkButton lbTest in pnlTags.Controls) { if (lbTest.ID == lbTag.ID) { bAlreadyExists = true; } } if (bAlreadyExists == false) { pnlTags.Controls.Add(lbTag); } } ```
The DataTable.Select() function does exactly what you seem to be wanting. Its second String parameter is a sorting string whose syntax is the same as SQL's: *[Column Name]* ASC, *[Other column name]* DESC, etc.
``` DataTable table = ... DataView view = table.DefaultView; view.Sort = ... view.RowFilter = ... ``` * MSDN: [DataView.Sort](http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx) * MSDN: [DataView.RowFilter](http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx)
.NET/C# - Sort DataTable, then manually process the rows
[ "", "c#", ".net", "" ]
I need to read some large files (from 50k to 100k lines), structured in groups separated by empty lines. Each group start at the same pattern "No.999999999 dd/mm/yyyy ZZZ". Here´s some sample data. > No.813829461 16/09/1987 270 > Tit.SUZANO PAPEL E CELULOSE S.A. (BR/BA) > C.N.P.J./C.I.C./N INPI : 16404287000155 > Procurador: MARCELLO DO NASCIMENTO > > No.815326777 28/12/1989 351 > Tit.SIGLA SISTEMA GLOBO DE GRAVACOES AUDIO VISUAIS LTDA (BR/RJ) > C.N.P.J./C.I.C./NºINPI : 34162651000108 > Apres.: Nominativa ; Nat.: De Produto > Marca: TRIO TROPICAL > Clas.Prod/Serv: 09.40 > \*DEFERIDO CONFORME RESOLUÇÃO 123 DE 06/01/2006, PUBLICADA NA RPI 1829, DE 24/01/2006. > Procurador: WALDEMAR RODRIGUES PEDRA > > No.900148764 11/01/2007 LD3 > Tit.TIARA BOLSAS E CALÇADOS LTDA > Procurador: Marcia Ferreira Gomes > \*Escritório: Marcas Marcantes e Patentes Ltda > \*Exigência Formal não respondida Satisfatoriamente, Pedido de Registro de Marca considerado inexistente, de acordo com Art. 157 da LPI > \*Protocolo da Petição de cumprimento de Exigência Formal: 810080140197 I wrote some code that´s parsing it accordingly. There´s anything that I can improve, to improve readability or performance? Here´s what I come so far: ``` import re, pprint class Despacho(object): """ Class to parse each line, applying the regexp and storing the results for future use """ regexp = { re.compile(r'No.([\d]{9}) ([\d]{2}/[\d]{2}/[\d]{4}) (.*)'): lambda self: self._processo, re.compile(r'Tit.(.*)'): lambda self: self._titular, re.compile(r'Procurador: (.*)'): lambda self: self._procurador, re.compile(r'C.N.P.J./C.I.C./N INPI :(.*)'): lambda self: self._documento, re.compile(r'Apres.: (.*) ; Nat.: (.*)'): lambda self: self._apresentacao, re.compile(r'Marca: (.*)'): lambda self: self._marca, re.compile(r'Clas.Prod/Serv: (.*)'): lambda self: self._classe, re.compile(r'\*(.*)'): lambda self: self._complemento, } def __init__(self): """ 'complemento' is the only field that can be multiple in a single registry """ self.complemento = [] def _processo(self, matches): self.processo, self.data, self.despacho = matches.groups() def _titular(self, matches): self.titular = matches.group(1) def _procurador(self, matches): self.procurador = matches.group(1) def _documento(self, matches): self.documento = matches.group(1) def _apresentacao(self, matches): self.apresentacao, self.natureza = matches.groups() def _marca(self, matches): self.marca = matches.group(1) def _classe(self, matches): self.classe = matches.group(1) def _complemento(self, matches): self.complemento.append(matches.group(1)) def read(self, line): for pattern in Despacho.regexp: m = pattern.match(line) if m: Despacho.regexp[pattern](self)(m) def process(rpi): """ read data and process each group """ rpi = (line for line in rpi) group = False for line in rpi: if line.startswith('No.'): group = True d = Despacho() if not line.strip() and group: # empty line - end of block yield d group = False d.read(line) arquivo = open('rm1972.txt') # file to process for desp in process(arquivo): pprint.pprint(desp.__dict__) print('--------------') ```
That is pretty good. Below some suggestions, let me know if you like'em: ``` import re import pprint import sys class Despacho(object): """ Class to parse each line, applying the regexp and storing the results for future use """ #used a dict with the keys instead of functions. regexp = { ('processo', 'data', 'despacho'): re.compile(r'No.([\d]{9}) ([\d]{2}/[\d]{2}/[\d]{4}) (.*)'), ('titular',): re.compile(r'Tit.(.*)'), ('procurador',): re.compile(r'Procurador: (.*)'), ('documento',): re.compile(r'C.N.P.J./C.I.C./N INPI :(.*)'), ('apresentacao', 'natureza'): re.compile(r'Apres.: (.*) ; Nat.: (.*)'), ('marca',): re.compile(r'Marca: (.*)'), ('classe',): re.compile(r'Clas.Prod/Serv: (.*)'), ('complemento',): re.compile(r'\*(.*)'), } def __init__(self): """ 'complemento' is the only field that can be multiple in a single registry """ self.complemento = [] def read(self, line): for attrs, pattern in Despacho.regexp.iteritems(): m = pattern.match(line) if m: for groupn, attr in enumerate(attrs): # special case complemento: if attr == 'complemento': self.complemento.append(m.group(groupn + 1)) else: # set the attribute on the object setattr(self, attr, m.group(groupn + 1)) def __repr__(self): # defines object printed representation d = {} for attrs in self.regexp: for attr in attrs: d[attr] = getattr(self, attr, None) return pprint.pformat(d) def process(rpi): """ read data and process each group """ #Useless line, since you're doing a for anyway #rpi = (line for line in rpi) group = False for line in rpi: if line.startswith('No.'): group = True d = Despacho() if not line.strip() and group: # empty line - end of block yield d group = False d.read(line) def main(): arquivo = open('rm1972.txt') # file to process for desp in process(arquivo): print desp # can print directly here. print('-' * 20) return 0 if __name__ == '__main__': main() ```
It would be easier to help if you had a specific concern. Performance will depend greatly on the efficiency of the particular regex engine you are using. 100K lines in a single file doesn't sound that big, but again it all depends on your environment. I use [Expresso](http://www.ultrapico.com/Expresso.htm) in my .NET development to test expressions for accuracy and performance. A Google search turned up [Kodos](http://kodos.sourceforge.net/about.html), a GUI Python regex authoring tool.
Extracting info from large structured text files
[ "", "python", "text-processing", "" ]
I want to write a regex that matches if a string contains XYZ but doesn't contain ABC somewhere before it. So "blah XYZ blah" should match, but "blah ABC blah XYZ blah " should not. Any ideas? In particular I'm writing the regex in c#, in case there's anything specific to that syntax. I guess I can use negative lookbehind but haven't used this before... thanks! UPDATE: I need a regex as I don't have the ability to modify the code, just some configuration. UPDATE: Changed as I actually only need to check that ABC doesn't appear *before* XYZ, I don't need to check if it comes after.
No need for lookbehind: ``` ^(?:(?!ABC).)*XYZ ```
``` ^(?:(?<!ABC).)*XYZ ``` was fine for my little testset.
How do i write a Regular Expression to match text containing XYZ but not ABC?
[ "", "c#", "regex", "" ]
Is it possible to determine the type of a local variable at runtime in TSQL? For example, say I wanted to do something along these lines: ``` IF ( @value IS INTEGER ) ``` Or ``` IF ( TYPEOF(@value) = <whatever> ) ``` Does anyone know of any way to accomplish this? EDIT: This is not for a specific task, this is more of a general knowledge question. I do appreciate answers that indicate that the type should be known since it is declared within the same batch, I am curious as to whether the type can be determined at runtime.
run this ``` declare @d int select @d = 500 if cast(sql_variant_property(@d,'BaseType') as varchar(20)) = 'int' print 'yes' else print 'no' ```
using SQL 2019 , below code still working ``` DECLARE @MyVar int;SET @MyVar = 99; DECLARE @MyVarDataType varchar(50); SET @MyVarDataType = cast(SQL_VARIANT_PROPERTY(@MyVar,'BaseType') AS varchar); PRINT @MyVarDataType ```
SQL Server 2005: Determine datatype of variable
[ "", "sql", "sql-server-2005", "t-sql", "" ]