Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm trying to fix single quote bug in the code: ``` std::string Index; connection->Open(); String^ sTableName = gcnew String(TableName.c_str()); String^ insertstring = String::Format("INSERT INTO {0} (idx, rec, date) VALUES (@idx, @rec, getdate())", sTableName); SqlCommand^ command = gcnew SqlCommand(insertstring, connection); String^ idx = gcnew String(Index.c_str()); command->Parameters->Add("@idx", SqlDbType::VarChar)->Value = idx; ``` The bug is that if idx="that's", the SQL fails saying that there is a syntax error. Obviously, the problem is in the quote. But some googling shows that using parameters is the way to work with quotes. And SqlParameter works well, if type is TEXT and not VARCHAR. There are any solutions other than manually doubling number of quote symbols in the string? Update: I tried to manually edit this field in SQL Management Studio and it didn't allow single quotes in VARCHAR field. It this normal in SQL?
I suspect the problem is either a quote getting in your table name, or that idx sounds more like the name of a number type than a character type. --- Based on your update, I suggest you check for extra constraints on the table in management studio.
To be honest I have never had a problem with SqlParameters. But try the following: <http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx> ``` command->Parameters->AddWithValue("@idx", idx); ``` This should work and encode correctly for you.
False Alarm: SqlCommand, SqlParameter and single quotes
[ "", ".net", "c++", "sql-server", "managed-c++", "" ]
I want to print the input value in flex to PHP. **My Flex Code...** ``` <mx:HTTPService id="sendReq" result="google(event)" showBusyCursor="true" method="POST" url="http://localhost/search/index.php" useProxy="false"> <mx:request xmlns=""> <keyword> {keyword.text} </keyword> </mx:request> </mx:HTTPService> <mx:TextInput text="" id="keyword" left="130.5" top="89" right="228.5" height="40" fontSize="20" fontWeight="bold" borderStyle="outset" focusThickness="0"/> <mx:Button click="sendReq.send();" id="search" label="search" right="133.5" top="91" height="40" width="75" alpha="1.0" fillAlphas="[1.0, 1.0]"/> ``` **My PHP code,** ``` $keyword = $_POST['keyword']; echo $keyword; ``` But i am not able to receive the keyword from Flex. Can anyone find the error down here which i am not able to get.
I don't have time to solve this problem, but here is some advice in debugging it: First, I would trace everything in the opening tag for your HTTPRequest. ``` <mx:HTTPService id = "sendReq" result = "trace( event )" fault = "trace( event )" showBusyCursor = "true" method = "POST" url = "http://localhost/search/index.php" useProxy = "false"> ``` If there is something wrong with your request, you have absolutely no way of knowing that -- your request has no fault handler! On the PHP side, the best way to debug an application like this is with some logging system. Here is a pretty generic logging function: ``` define( 'PATH_TO_LOG_FOLDER', "../Logs" ); public function log( $message ){ $logFileName = "log"; if(!$fp = @fopen(PATH_TO_LOG_FOLDER. DIRECTORY_SEPARATOR . $logFileName .date('Y-m-d').".log", 'a+')){ return FALSE; } flock( $fp, LOCK_EX ); fwrite( $fp, $message ); flock( $fp, LOCK_UN ); fclose( $fp ); } ``` On <http://localhost/search/index.php> call ``` $message = ""; for( $_REQUEST as $key => $val ) { $message .= "$key = $val\n"; } log( $message ); ```
Have you tried using FireBug? it's a firefox extension that can show you exactly what's coming and going on the connection between the flex client and the server.
Flex input and output in PHP
[ "", "php", "apache-flex", "" ]
I'm building a small abstract class that's supposed to make certain tasks easier. For example: $var = class::get('id'); would run check if there's pointer id in the $\_GET, returning a string or array according to parameters. This should also work for post and request and maby more. I'm doing it in the way there's function for all the superglobals. I'm using get as example: get function gets a pointer as parameter, it calls fetchdata function and uses the pointer and "$\_GET" as the parameters. fetchdata is supposed to just blindly use the string it got as superglobal and point to it with the other param. Then check if it exists there and return either the value or false to get function, that returns the value/false to caller. Only problem is to get the string work as superglobal when you don't know what it is. I did this before with a switch that checked the param and in case it was "get", it set $\_GET to value of another variable. However I don't want to do it like that, I want it to be easy to add more functions without having to touch the fetchdata. I tried $method = eval($method), but it didn't work. ($method = "$\_GET"), any suggestions? EDIT: Sorry if I didn't put it clear enough. I have a variable X with string value "$\_GET", how can I make it so X gets values from the source described in the string? So simply it's $X = $\_GET if X has value "$\_GET" $X = $\_POST if X has value "$\_POST" I just don't know what value X has, but it needs to get data from superglobal with the same name than its value.
According to [this page in the manual](http://uk.php.net/manual/en/language.variables.superglobals.php): > **Note: Variable variables** > > Superglobals cannot be used as variable variables inside functions or class methods. This means you **can't** do this inside a function or method (which you would be able to do with other variables) : ``` $var = '_GET'; ${$var}[$key] ``` Instead of passing a string to `fetchdata()`, could you not pass `$_GET` itself? I think PHP will not copy a variable unless you modify it ('copy on write'), so this shouldn't use memory unnecessarily. Otherwise there are only nine superglobals, so a switch-case as you have suggested isn't unreasonable. You could do this with `eval()` if you really had to, something like: ``` eval('return $_GET;'); ``` I think that would be unnecessary and a bad idea though; it is slow and you need to be extremely careful about letting untrusted strings anywhere near it.
Don't use eval. Just use reference. ``` //test value for cli $_GET['test'] = 'test'; /** * @link http://php.net/manual/en/filter.constants.php reuse the filter constants */ function superglobalValue($key, $input = null) { if ($input === INPUT_POST) $X = &$_POST; else $X = &$_GET; return (isset($X[$key]) ? $X[$key] : false); } function getArrayValue(&$array, $key) { return (array_key_exists($key, $array) ? $array[$key] : false); } //test dump var_dump( superglobalValue('test', INPUT_GET), superglobalValue('test', INPUT_POST), getArrayValue($_GET, 'test'), getArrayValue($_POST, 'test') ); ``` $\_GET, $\_POST and $\_REQUEST dont have any null values by default, only string or array. So I used isset there instead of array\_key\_exists. Param order: I always put required params before optional when I can, and the data objects before the manipulation/subjective params. Thats why key is first param for superglobalValue and second param for getArrayValue.
PHP how to use string as superglobal
[ "", "php", "string", "superglobals", "" ]
I am looking to design a database for a website where users will be able to gain points (reputation) for performing certain activities and am struggling with the database design. I am planning to keep records of the things a user does so they may have 25 points for an item they have submitted, 1 point each for 30 comments they have made and another 10 bonus points for being awesome! Clearly all the data will be there, but it seems like a lot or querying to get the total score for each user which I would like to display next to their username (in the form of a level). For example, a query to the submitted items table to get the scores for each item from that user, a query to the comments table etc. If all this needs to be done for every user mentioned on a page.... LOTS of queries! I had considered keeping a score in the user table, which would seem a lot quicker to look up, but I've had it drummed into me that storing data that can be calculated from other data is **BAD!** I've seen a lot of sites that do similar things (even stack overflow does similar) so I figure there must be a "best practice" to follow. Can anyone suggest what it may be? Any suggestions or comments would be great. Thanks!
I think that this is definitely a great question. I've had to build systems that have similar behavior to this--especially when the table with the scores in it is accessed pretty often (like in your scenario). Here's my suggestion to you: First, create some tables like the following (I'm using SQL Server best practices, but name them however you see fit): ``` UserAccount UserAchievement -Guid (PK) -Guid (PK) -FirstName -UserAccountGuid (FK) -LastName -Name -EmailAddress -Score ``` Once you've done this, go ahead and create a view that looks something like the following (no, I haven't verified this SQL, but it should be a good start): ``` SELECT [UserAccount].[FirstName] AS FirstName, [UserAccount].[LastName] AS LastName, SUM([UserAchievement].[Score]) AS TotalPoints FROM [UserAccount] INNER JOIN [UserAchievement] ON [UserAccount].[Guid] = [UserAchievement].[UserAccountGuid] GROUP BY [UserAccount].[FirstName], [UserAccount].[LastName] ORDER BY [UserAccount].[LastName] ASC ``` I know you've mentioned some concern about performance and a lot of queries, but if you build out a view like this, you won't ever need more than one. I recommend not making this a materialized view; instead, just index your tables so that the lookups that you need (essentially, UserAccountGuid) will enable fast summation across the table. I will add one more point--if your UserAccount table gets huge, you may consider a slightly more intelligent query that would incorporate the names of the accounts you need to get roll-ups for. This will make it possible not to return huge data sets to your web site when you're only showing, you know, 3-10 users' information on the page. I'd have to think a bit more about how to do this elegantly, but I'd suggest staying away from "IN" statements since this will invoke a linear search of the table.
For very high read/write ratios, denormalizing is a very valid option. You can use an indexed view and the data will be kept in sync declaratively (so you never have to worry about there being bad score data). The downside is that it IS kept in sync.. so the updates to the store total are a synchronous aspect of committing the score action. This would normally be quite fast, but it is a design decision. If you denormalize yourself, you can choose if you want to have some kind of delayed update system. Personally I would go with an indexed view for starting, and then later you can replace it fairly seamlessly with a concrete table if your needs dictate.
What's the best way to store/calculate user scores?
[ "", "sql", "mysql", "database", "database-design", "" ]
Is there any way to check if a variable (class member or standalone) with specified name is defined? Example: ``` if "myVar" in myObject.__dict__ : # not an easy way print myObject.myVar else print "not defined" ```
A compact way: ``` print myObject.myVar if hasattr(myObject, 'myVar') else 'not defined' ``` htw's way is more Pythonic, though. `hasattr()` is different from `x in y.__dict__`, though: `hasattr()` takes inherited class attributes into account, as well as dynamic ones returned from `__getattr__`, whereas `y.__dict__` only contains those objects that are attributes of the `y` instance.
``` try: print myObject.myVar except NameError: print "not defined" ```
Easy way to check that a variable is defined in python?
[ "", "python", "" ]
I am part of a software development company looking for a good way to update my SQL Server tables when I put out a new version of the software. I know the answer is to probably use scripts in one form or another. I am considering writing my own .NET program that runs the scripts to make it a bit easier and more user-friendly. I was wondering if there are any tools out there along those lines. Any input would be appreciated.
Suggest you look at Red\_gate's SQlCompare
What kind of product are you using for your software installation? Products like InstallShield often now include SQL steps as an option for part of your install script. Otherwise, you could look at using isql/osql to run your script from the command line through a batch file. One of the developers where I'm currently consulting wrote a rather nifty SQL installer. I'll ask him when he gets in how he went about it.
SQL Server Version Updating Tables
[ "", "sql", "sql-server", "database", "sql-server-2008", "" ]
How do I set some group policy rule or mechanism to make sure that every developer commits their code to the source control? I use visualsvn server with Ankhsvn client btw. Thanks
Our basic policy is "**If it's not in the source code repository it doesn't exist.**" * Developers only get to mark tasks as "development completed" when they check in the code. * Build your deliverable(s) only from a tagged set of source code (not some joker's workstation copy.) * **NOTHING** that's not in source control goes into QA or Production. Checking in broken code is considered bad form but is not punished (outside a little ribbing from those inconvenienced.) I'd like to use continuous integration and configure broken builds to automatically back out the broken changes but I don't expect to be able to any time soon where I'm at. Edit: We also require artifact numbers in the comment for each checkin. This prevents gratuitous changes that are unassociated with a requirement.
These sort of policies are best enforced using peer pressure. Create an environment where it is the accepted practice to commit the code. Otherwise, it will become a drudgery and developers will find ways around it.
Enforcing source control
[ "", "c#", "svn", "version-control", "visualsvn-server", "ankhsvn", "" ]
`&` has `&&`. `|` has `||`. Why doesn't `^` have `^^`? I understand that it wouldn't be short-circuiting, but it would have different semantics. In C, `true` is really any non-zero value. Bitwise XOR is not always the same thing as logical XOR: ``` int a=strcmp(str1,str2);// evaluates to 1, which is "true" int b=strcmp(str1,str3);// evaluates to 2, which is also "true" int c=a ^^ b; // this would be false, since true ^ true = false int d=a ^ b; //oops, this is true again, it is 3 (^ is bitwise) ``` Since you can't always rely on a true value being `1` or `-1`, wouldn't a `^^` operator be very helpful? I often have to do strange things like this: ``` if(!!a ^ !!b) // looks strange ```
[Dennis Ritchie answers](https://web.archive.org/web/20100213061432/http://www.it.usyd.edu.au/%7Edasymond/mirror/c-faq/misc/xor.dmr.html) > There are both historical and practical reasons why there is no `^^` operator. > > The practical is: there's not much use for the operator. The main point of `&&` and `||` is to take advantage of their short-circuit evaluation not only for efficiency reasons, but more often for expressiveness and correctness. > [...] > By contrast, an `^^` operator would always force evaluation of both arms of the expression, so there's no efficiency gain. Furthermore, situations in which `^^` is really called for are pretty rare, though examples can be created. These situations get rarer and stranger as you stack up the operator-- > > ``` > if (cond1() ^^ cond2() ^^ cond3() ^^ ...) ... > ``` > > does the consequent exactly when an odd number of the `condx()`s are true. By contrast, the `&&` and `||` analogs remain fairly plausible and useful.
Technically, one already exists: ``` a != b ``` since this will evaluate to true if the truth value of the operands differ. ### Edit: [Volte](https://stackoverflow.com/users/89709/volte)'s comment: ``` (!a) != (!b) ``` is correct because my answer above does not work for `int` types. I will delete mine if he adds his answer. ### Edit again: Maybe I'm forgetting something from C++, but the more I think about this, the more I wonder why you would ever write `if (1 ^ 2)` in the first place. The purpose for `^` is to exclusive-or two numbers together (which evaluates to another number), not convert them to boolean values and compare their truth values. This seems like it would be an odd assumption for a language designer to make.
Why is there no ^^ operator in C/C++?
[ "", "c++", "c", "operators", "language-design", "xor", "" ]
I am working on an application that uses Oracle's built in authentication mechanisms to manage user accounts and passwords. The application also uses row level security. Basically every user that registers through the application gets an Oracle username and password instead of the typical entry in a "USERS" table. The users also receive labels on certain tables. This type of functionality requires that the execution of DML and DDL statements be combined in many instances, but this poses a problem because the DDL statements perform implicit commits. If an error occurs after a DDL statement has executed, the transaction management will not roll everything back. For example, when a new user registers with the system the following might take place: 1. Start transaction 2. Insert person details into a table. (i.e. first name, last name, etc.) -DML 3. Create an oracle account (create user testuser identified by password;) -DDL implicit commit. Transaction ends. 4. New transaction begins. 5. Perform more DML statments (inserts,updates,etc). 6. Error occurs, transaction only rolls back to step 4. I understand that the above logic is working as designed, but I'm finding it difficult to unit test this type of functionality and manage it in data access layer. I have had the database go down or errors occur during the unit tests that caused the test schema to be contaminated with test data that should have been rolled back. It's easy enough to wipe the test schema when this happens, but I'm worried about database failures in a production environment. I'm looking for strategies to manage this. This is a Java/Spring application. Spring is providing the transaction management.
You should use Oracle proxy authentication in combination with row level security. Read this: <http://www.oracle.com/technology/pub/articles/dikmans-toplink-security.html>
First off I have to say: bad idea doing it this way. For two reasons: 1. Connections are based on user. That means you largely lose the benefits of connection pooling. It also doesn't scale terribly well. If you have 10,000 users on at once, you're going to be continually opening and closing hard connections (rather than soft connection pools); and 2. As you've discovered, creating and removing users is DDL not DML and thus you lose "transactionality". Not sure why you've chosen to do it this but I would **strongly** recommend you implement users at the application and not the database layer. As for how to solve your problem, basically you can't. Same as if you were creating a table or an index in the middle of your sequence.
Unit testing DDL statements that need to be in a transaction
[ "", "java", "oracle", "unit-testing", "ddl", "dml", "" ]
I'm very excited about the dynamic features in C# ([C#4 dynamic keyword - why not?](https://stackoverflow.com/questions/245318/c4-dynamic-keyword-why-not)), especially because in certain Library parts of my code I use a lot of reflection. My question is twofold: **1. does "dynamic" replace Generics, as in the case below?** Generics method: ``` public static void Do_Something_If_Object_Not_Null<SomeType>(SomeType ObjToTest) { //test object is not null, regardless of its Type if (!EqualityComparer<SomeType>.Default.Equals(ObjToTest, default(SomeType))) { //do something } } ``` dynamic method(??): ``` public static void Do_Something_If_Object_Not_Null(dynamic ObjToTest) { //test object is not null, regardless of its Type?? but how? if (ObjToTest != null) { //do something } } ``` **2. does "dynamic" now allow for methods to return Anonymous types, as in the case below?:** ``` public static List<dynamic> ReturnAnonymousType() { return MyDataContext.SomeEntities.Entity.Select(e => e.Property1, e.Property2).ToList(); } ``` cool, cheers **EDIT:** Having thought through my question a little more, and in light of the answers, I see I completely messed up the main generic/dynamic question. They are indeed completely different. So yeah, thanks for all the info. What about point 2 though?
`dynamic` might simplify a limited number of reflection scenarios (where you know the member-name up front, but there is no interface) - in particular, it might help with generic operators ([although other answers exist](http://www.yoda.arachsys.com/csharp/genericoperators.html)) - but other than the generic operators trick, there is little crossover with generics. Generics allow you to know (at compile time) about the type you are working with - conversely, `dynamic` doesn't *care* about the type. In particular - generics allow you to specify and prove a number of conditions *about* a type - i.e. it might implement some interface, or have a public parameterless constructor. `dynamic` doesn't help with either: it doesn't support interfaces, and worse than simply not caring about interfaces, it means that we can't even **see** explicit interface implementations with `dynamic`. Additionally, `dynamic` is really a special case of `object`, so boxing comes into play, but with a vengence. In reality, you should limit your use of `dynamic` to a few cases: * COM interop * DLR interop * *maybe* some light duck typing * *maybe* some generic operators For all other cases, generics and regular C# are the way to go.
To answer your question. **No.** * Generics gives you "**algorithm reuse**" - you write code independent of a data Type. the dynamic keyword doesn't do anything related to this. I define `List<T>` and then i can use it for List of strings, ints, etc... * **Type safety**: The whole compile time checking debate. Dynamic variables will not alert you with compile time warnings/errors in case you make a mistake they will just blow up at runtime if the method you attempt to invoke is missing. Static vs Dynamic typing debate * **Performance** : Generics improves the performance for algorithms/code using Value types by a significant order of magnitude. It prevents the whole boxing-unboxing cycle that cost us pre-Generics. Dynamic doesn't do anything for this too. What the `dynamic` keyword would give you is * simpler code (when you are interoperating with Excel lets say..) You don't need to specify the name of the classes or the object model. If you invoke the right methods, the runtime will take care of invoking that method if it exists in the object at that time. The compiler lets you get away even if the method is not defined. However it implies that this will be slower than making a compiler-verified/static-typed method call since the CLR would have to perform checks before making a dynamic var field/method invoke. * The dynamic variable can hold different types of objects at different points of time - You're not bound to a specific family or type of objects.
Does the C# 4.0 "dynamic" keyword make Generics redundant?
[ "", "c#", ".net", "generics", "reflection", "dynamic", "" ]
A project I was working on has finished, so I've been moved on to some new tasking at my employer. The previous work was very agile, small team, progress over procedure, etc etc. So anyway, the new project I'm on - I find myself confused on how to deal with management. They have no real understanding of object oriented programing , current technologies or methodologies. They seem to fear change and just recently we moved to the latest JRE We do these code reviews and I have to listen to "gray beards" saying how much better it is in ADA or how they used to do things in C. But then when they try to code review - they lack even the most basic understanding of OOP design and dev. They focus more on the style of the code; spacing; method names; etc. One of the senior level people say we should be writing our own logger instead of using log4j because of one negative review of log4j in an academic PDF written ages ago. How do I deal with this? How can I explain to them that their design is faulty or that they are really behind the times, without coming across as a jerk. I've only been with this organization for about a year - so I don't know how much credibility I will have.
Regarding the code review, I would say make them happy. Name and space things the way they like. Focus your time on better design, of course, and enjoy the ADA reminiscing, it still can give you some background of where things are today and how they got there. In other words, don't take that part too seriously. Worry about what is important to getting the job done. The job in this case is making those that matter feel you made a positive contribution to the project. Regarding Log4j, I would just suggest a different framework. Either the built in JDK logging (can't complain about that, it is a built in API) or something like SLF, which lets you plug in whatever you want (including your own, I guess, which you can then throw away and replace with something real when they realize it was a mistake, and you only have to change the classpath). Now there will be times where it is important. In that case, make it sound as much as possible that it is their idea. For example, on the logging, state that there are many logging frameworks out there that represent a lot of lines of code, and you were wondering if there are other ways to leverage that work for this project, and then let them "figure out" the solution. There will be times when you have to push something as your idea - there will be no other way. In that case stick to the evidence, martial allies as much as possible by keeping relationships with those that do have influence in good standing, and realize that every battle you fight, you lose position, even if you win (perhaps especially if you win).
I'd recommend approaching your concerns as 'suggestions'. Make a suggestion and ask for their opinion on it, that way they feel as if they are still in control even though you've planted the seed and are directing the conversation. Regardless of how long you have been with an organization, you are there and you are there for a reason (they hired you for your input). Find your voice and how to best approach your team members with suggestions and/or concerns. This is a crucial part of being a team member and will increase your value.
How to deal with inept management
[ "", "java", "oop", "" ]
How do I generate circular image thumbnails using PIL? The space outside the circle should be transparent. Snippets would be highly appreciated, thank you in advance.
The easiest way to do it is by using masks. Create a black and white mask with any shape you want. And use `putalpha` to put that shape as an alpha layer: ``` from PIL import Image, ImageOps mask = Image.open('mask.png').convert('L') im = Image.open('image.png') output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5)) output.putalpha(mask) output.save('output.png') ``` Here is the mask I used: ![alt text](https://i.stack.imgur.com/tlWXo.png) --- If you want the thumbnail size to be variable you can use `ImageDraw` and draw the mask: ``` from PIL import Image, ImageOps, ImageDraw size = (128, 128) mask = Image.new('L', size, 0) draw = ImageDraw.Draw(mask) draw.ellipse((0, 0) + size, fill=255) im = Image.open('image.jpg') output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5)) output.putalpha(mask) output.save('output.png') ``` --- If you want the output in GIF then you need to use the paste function instead of `putalpha`: ``` from PIL import Image, ImageOps, ImageDraw size = (128, 128) mask = Image.new('L', size, 255) draw = ImageDraw.Draw(mask) draw.ellipse((0, 0) + size, fill=0) im = Image.open('image.jpg') output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5)) output.paste(0, mask=mask) output.convert('P', palette=Image.ADAPTIVE) output.save('output.gif', transparency=0) ``` Note that I did the following changes: * The mask is now inverted. The white was replaced with black and vice versa. * I'm converting into 'P' with an 'adaptive' palette. Otherwise, PIL will only use web-safe colors and the result will look bad. * I'm adding transparency info to the image. **Please note**: There is a big issue with this approach. If the GIF image contained black parts, all of them will become transparent as well. You can work around this by choosing another color for the transparency. I would strongly advise you to use PNG format for this. But if you can't then that is the best you could do.
I would like to add to the already accepted answer a solution to antialias the resulting circle, the trick is to produce a bigger mask and then scale it down using an ANTIALIAS filter: here is the code ``` from PIL import Image, ImageOps, ImageDraw im = Image.open('image.jpg') bigsize = (im.size[0] * 3, im.size[1] * 3) mask = Image.new('L', bigsize, 0) draw = ImageDraw.Draw(mask) draw.ellipse((0, 0) + bigsize, fill=255) mask = mask.resize(im.size, Image.ANTIALIAS) im.putalpha(mask) ``` this produces a far better result in my opinion.
How do I generate circular thumbnails with PIL?
[ "", "python", "thumbnails", "python-imaging-library", "geometry", "" ]
What is the simplest way to call a program from with a piece of Java code? (The program I want to run is aiSee and it can be run from command line or from Windows GUI; and I am on Vista but the code will also be run on Linux systems).
Take a look at [Process](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Process.html) and [Runtime](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html) classes. Keep in mind that what you are trying to accomplish is probably not platform independent. Here is a little piece of code that might be helpful: ``` public class YourClass { public static void main(String args[]) throws Exception { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("name_of_your_application.exe"); int exitVal = proc.exitValue(); System.out.println("Process exitValue: " + exitVal); } } ``` [One](https://stackoverflow.com/questions/506154/runtime-class-in-java) question in S.O. discussing similiar issues. [Another](https://stackoverflow.com/questions/480433/launch-jvm-process-from-a-java-application-use-runtime-exec) one. [And](https://stackoverflow.com/questions/636367/java-executing-a-java-application-in-a-separate-process) another one.
You can get a runtime instance using `Runtime.getRuntime()` and call the runtime's `exec` method, with the command to execute the program as an argument. For example: ``` Runtime runTime = Runtime.getRuntime (); Process proc = rt.exec("iSee.exe"); ``` You can also capture the output of the program by using getting the InputStream from the process.
Running a program from within Java code
[ "", "java", "runtime.exec", "external-process", "" ]
I am curious to know why this is happening. Please read the code example below and the corresponding IL that was emitted in comments below each section: ``` using System; class Program { static void Main() { Object o = new Object(); o.GetType(); // L_0001: newobj instance void [mscorlib]System.Object::.ctor() // L_0006: stloc.0 // L_0007: ldloc.0 // L_0008: callvirt instance class [mscorlib]System.Type [mscorlib]System.Object::GetType() new Object().GetType(); // L_000e: newobj instance void [mscorlib]System.Object::.ctor() // L_0013: call instance class [mscorlib]System.Type [mscorlib]System.Object::GetType() } } ``` Why did the compiler emit a `callvirt` for the first section but a `call` for the second section? Is there any reason that the compiler would ever emit a `callvirt` instruction for a non-virtual method? And if there are cases in which the compiler will emit a `callvirt` for a non-virtual method does this create problems for type-safety?
**Just playing safe.** Technically C# compiler doesn't **always** use `callvirt` For static methods & methods defined on value types, it uses `call`. The majority is provided via the `callvirt` IL instruction. The difference that swung the vote between the two is the fact that `call` assumes the "object being used to make the call" is not null. `callvirt` on the other hand checks for not null and throws a NullReferenceException if required. * For static methods, the object is a type object and cannot be null. Ditto for value types. Hence `call` is used for them - better performance. * For the others, the language designers decided to go with `callvirt` so the JIT compiler verifies that the object being used to make the call is not null. Even for non-virtual instance methods.. they valued safety over performance. *See Also: Jeff Richter does a better job at this - in his 'Designing Types' chapter in CLR via C# 2nd Ed*
See [this](http://blogs.msdn.com/ericgu/archive/2008/07/02/why-does-c-always-use-callvirt.aspx) old blog post by Eric Gunnerson. Here's the text of the post: **Why does C# always use callvirt?** This question came up on an internal C# alias, and I thought the answer would be of general interest. That's assuming that the answer is correct - it's been quite a while. The .NET IL language provides both a call and callvirt instruction, with the callvirt being used to call virtual functions. But if you look through the code that C# generates, you will see that it generates a "callvirt" even in cases where there is no virtual function involved. Why does it do that? I went back through the language design notes that I have, and they state quite clearly that we decided to use callvirt on 12/13/1999. Unfortunately, they don't capture our rationale for doing that, so I'm going to have to go from my memory. We had gotten a report from somebody (likely one of the .NET groups using C# (thought it wasn't yet named C# at that time)) who had written code that called a method on a null pointer, but they didn’t get an exception because the method didn’t access any fields (ie “this” was null, but nothing in the method used it). That method then called another method which did use the this point and threw an exception, and a bit of head-scratching ensued. After they figured it out, they sent us a note about it. We thought that being able to call a method on a null instance was a bit weird. Peter Golde did some testing to see what the perf impact was of always using callvirt, and it was small enough that we decided to make the change.
Why is the C# compiler emitting a callvirt instruction for a GetType() method call?
[ "", "c#", "compiler-construction", "il", "type-safety", "" ]
I am using pyodbc, via Microsoft Jet, to access the data in a Microsoft Access 2003 database from a Python program. The Microsoft Access database comes from a third-party; I am only reading the data. I have generally been having success in extracting the data I need, but I recently noticed some discrepancies. I have boiled it down to a simple query, of the form: ``` SELECT field1 FROM table WHERE field1 = 601 AND field2 = 9067 ``` I've obfuscated the field names and values but really, it doesn't get much more trivial than that! When I run the query in Access, it returns one record. Then I run it over pyodbc, with code that looks like this: ``` connection = pyodbc.connect(connectionString) rows = connection.execute(queryString).fetchall() ``` (Again, it doesn't get much more trivial than that!) The value of queryString is cut-and-pasted from the working query in Access, but it returns *no* records. I expected it to return the same record. When I change the query to search for a different value for field2, bingo, it works. It is only some values it rejects. So, please help me out. Where should I be looking next to explain this discrepancy? If I can't trust the results of trivial queries, I don't have a chance on this project! *Update*: It gets even simpler! The following query gives different numbers... SELECT COUNT(\*) FROM table I ponder if it is related to some form of caching and/or improper transaction management by another application that occasionally to populates the data.
Problem was resolved somewhere between an upgrade to Access 2007 and downloading a fresh copy of the database from the source. Still don't know what the root cause was, but suspect some form of index corruption.
can you give us an obfuscated database that shows this problem? I've never experienced this. At least give the table definitions -- are any of the columns floats or decimal?
PyODBC and Microsoft Access: Inconsistent results from simple query
[ "", "python", "ms-access", "odbc", "jet", "pyodbc", "" ]
Does anyone know of a jQuery plugin that has 'helpers' or extensions like those found in the [YAHOO.lang namespace](http://developer.yahoo.com/yui/yahoo/#lang)? I have in mind functions such as: ``` isNull isDefined isString isFunction ``` I would also appreciate the same kind of thing for strings and arrays, such as Contains, StartsWith (I know these are easy to write, I'm just looking for a plugin that encompasses them all). It's not in the YAHOO.lang namespace but also form related extensions- determining a radiobox's value (from the one checked), a form element's type in a friendly name. Specifically a plugin with fluent API rather than selector based such as ``` $("input[@type=radio][@checked]") ``` Again I'm aware they're easy to implement but I don't want to reinvent the wheel.
I decided to write two new plugins myself. Here's the two projects: # [Form extensions](http://www.bitbucket.org/mrshrinkray/jquery-extensions/) **Example:** ``` // elementExists is also added if ($("#someid").elementExists()) alert("found it"); // Select box related $("#mydropdown").isDropDownList(); // Can be any of the items from a list of radio boxes - it will use the name $("#randomradioboxitem").isRadioBox("myvalue"); $("#radioboxitem").isSelected("myvalue"); ``` # [General extensions](http://www.bitbucket.org/mrshrinkray/jquery-extensions/) These are modelled on Prototype/Mochikit functions such as isNull. **Example:** ``` $.isNumber(42); var x; $.isUndefined(x); $.isNullOrUndefined(x); $.isString(false); $.emptyString("the quick brown fox"); $.startsWith("the quick brown fox","the"); $.formatString("Here is the {0} and {2}","first","second"); ``` Both have over 50 unit tests that come as part of the download. Hopefully they'll be useful to people finding this page.
[jQuery 1.3.2](http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js) has `isFunction` and `isArray` built in (see snippet below). The code for isString is staightforward (`typeof obj === "string"`), as is isNull (`obj === null`) and isDefined (`obj !== undefined`) - so I would just code that inline instead of using a function. ``` // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return toString.call(obj) === "[object Function]"; }, isArray: function( obj ) { return toString.call(obj) === "[object Array]"; }, ```
jQuery version of YAHOO.lang (isUndefined, isNull, isString etc.)
[ "", "javascript", "jquery", "yui", "" ]
Using the javascript function ``` function squareIt(number) { return number * number; } ``` When given the number 4294967296 the function returns 18446744073709552000 is returned Everyone knows the real answer is 18446744073709551616 :-) I guess this is to to with rounding on my 32-bit machine. However, would this script give the right answer on a 64 bit machine? Has anyone tried this?
ChrisV- [see this post](https://stackoverflow.com/questions/307179/what-is-javascripts-max-int-whats-the-highest-integer-value-a-number-can-go-to). Also it easier for people to evaluate your question by typing the following JavaScript directly into the browser URL textbox: ``` javascript:4294967296*4294967296 ```
what about this ``` function squareIt(number){ return Math.pow(number,2) } ```
Javascript - How to squared a number?
[ "", "javascript", "32-bit", "" ]
Simple question here: is there any way to convert from a jagged array to a double pointer? e.g. Convert a `double[][]` to `double**` This can't be done just by casting unfortunately (as it can in plain old C), unfortunately. Using a `fixed` statement doesn't seem to resolve the problem either. Is there any (preferably as efficient as possible) way to accomplish this in C#? I suspect the solution may not be very obvious at all, though I'm hoping for a straightforward one nonetheless.
A double[][] is an array of double[], not of double\* , so to get a double\*\* , we first need a double\*[] ``` double[][] array = //whatever //initialize as necessary fixed (double* junk = &array[0][0]){ double*[] arrayofptr = new double*[array.Length]; for (int i = 0; i < array.Length; i++) fixed (double* ptr = &array[i][0]) { arrayofptr[i] = ptr; } fixed (double** ptrptr = &arrayofptr[0]) { //whatever } } ``` I can't help but wonder what this is for and if there is a better solution than requiring a double-pointer.
A little bit of safety. As mentioned in comments to the first solution, nested arrays could be moved, so they should be pinned too. ``` unsafe { double[][] array = new double[3][]; array[0] = new double[] { 1.25, 2.28, 3, 4 }; array[1] = new double[] { 5, 6.24, 7.42, 8 }; array[2] = new double[] { 9, 10.15, 11, 12.14 }; GCHandle[] pinnedArray = new GCHandle[array.Length]; double*[] ptrArray = new double*[array.Length]; for (int i = 0; i < array.Length; i++) { pinnedArray[i] = GCHandle.Alloc(array[i], GCHandleType.Pinned); } for (int i = 0; i < array.Length; ++i) { // as you can see, this pointer will point to the first element of each array ptrArray[i] = (double*)pinnedArray[i].AddrOfPinnedObject(); } // here is your double** fixed(double** doublePtr = &ptrArray[0]) { Console.WriteLine(**doublePtr); } // unpin all the pinned objects, // otherwise they will live in memory till assembly unloading // even if they will went out of scope for (int i = 0; i < pinnedArray.Length; ++i) pinnedArray[i].Free(); } ``` A brief explanation of the problem: When we allocate some objects on the heap, they could be moved to another location on garbage collecting. So, imagine next situation: you have allocated some object and your inner arrays, they are all placed in zero generation on the heap. [![enter image description here](https://i.stack.imgur.com/WbCAD.png)](https://i.stack.imgur.com/WbCAD.png) Now, some object has gone from scope and became garbage, some objects just been allocated. Garbage collector will move old objects out of heap and move other objects closer to the beginning or even to the next generation, compacting heap. The result will looks like: [![enter image description here](https://i.stack.imgur.com/IM01A.png)](https://i.stack.imgur.com/IM01A.png) So, our goal is to “pin” some objects in heap, so they would not move. What we have to achieve this goal? We have [fixed](https://msdn.microsoft.com/en-us/library/f58wzh21.aspx) statement and [GCHandle.Allocate](https://msdn.microsoft.com/en-us/library/a95009h1(v=vs.110).aspx) method. First, what `GCHandle.Allocate` does? It creates new entry in inner system table that have a reference to the object that passed to method as a parameter. So, when garbage collector will examine heap, he will check inner table for entries and if he will find one, he will mark object as alive and will not move it out of heap. Then, he will look on how this object is pinned and will not move the object in memory in compacting stage. `fixed` statement does almost the same, except it “unpins” object automatically when you leave scope. Summarizing: each object that has been pinned with `fixed` will be automatically “unpinned” once he left a scope. In our case, it will be on next iteration of loop. How to check that your objects will not be moved or garbage collected: just consume all the heap's budget for zero generation and force GC to compact heap. In other words: create a lot of objects on the heap. And do it after you pinned your objects or “fixed” them. ``` for(int i = 0; i < 1000000; ++i) { MemoryStream stream = new MemoryStream(10); //make sure that JIT will not optimize anything, make some work stream.Write(new Byte[]{1,2,3}, 1, 2); } GC.Collect(); ``` Small notice: there are two types of heaps — for large objects and for small ones. If your object is large, you should create large objects to check your code, otherwise small objects will not force GC to start garbage collection and compacting. Lastly, here's some sample code, demonstrating the dangers of accessing the underlying arrays with unpinned/unfixed pointers - for anybody who is interested. ``` namespace DangerousNamespace { // WARNING! // This code includes possible memory access errors with unfixed/unpinned pointers! public class DangerousClass { public static void Main() { unsafe { double[][] array = new double[3][]; array[0] = new double[] { 1.25, 2.28, 3, 4 }; array[1] = new double[] { 5, 6.24, 7.42, 8 }; array[2] = new double[] { 9, 10.15, 11, 12.14 }; fixed (double* junk = &array[0][0]) { double*[] arrayofptr = new double*[array.Length]; for (int i = 0; i < array.Length; i++) fixed (double* ptr = &array[i][0]) { arrayofptr[i] = ptr; } for (int i = 0; i < 10000000; ++i) { Object z = new Object(); } GC.Collect(); fixed (double** ptrptr = &arrayofptr[0]) { for (int i = 0; i < 1000000; ++i) { using (MemoryStream z = new MemoryStream(200)) { z.Write(new byte[] { 1, 2, 3 }, 1, 2); } } GC.Collect(); // should print 1.25 Console.WriteLine(*(double*)(*(double**)ptrptr)); } } } } } } ```
Converting from a jagged array to double pointer in C#
[ "", "c#", "arrays", "pointers", "jagged-arrays", "double-pointer", "" ]
my application needs multiple jars to work. Since it is a desktop application i can not hold the user responsible of installing. So in my build script i unzip the jars content in to my build directory delete manifest files, compile my software and jar it again. Everything works as it should my question is are there any long term side effects to this process?
In the past, there were JARs with weird content (like the DB2 driver which contains `com.ibm` and `com.IBM`; after decompressing in a Windows filesystem, those two packages would be merged). The only issue you need to be aware of are signed jars and other files in META-INF which might have the same name in multiple source JARs. A simple solution for all these issues is to use [One-JAR](http://one-jar.sourceforge.net/). It allows to wrap several JARs into one without unpacking them, first. And read this answer: [Easiest way to merge a release into one JAR file](https://stackoverflow.com/questions/81260/java-easiest-way-to-merge-a-release-into-one-jar-file)
A simpler solution (IMO) is using [Maven's assembly plugin](http://maven.apache.org/plugins/maven-assembly-plugin/usage.html), which is also described in one of the answers to another question which was linked to in a [previous Q&A](https://stackoverflow.com/questions/81260/java-easiest-way-to-merge-a-release-into-one-jar-file). This is provided you are using Maven (which is a recommended tool by its own right) as a build tool.
Merging Multiple Jars in to a Single Jar
[ "", "java", "jar", "" ]
I've been trying to understand what's the optimal way to do [Ajax](http://en.wikipedia.org/wiki/Ajax_%28programming%29) in [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29). By reading stuff here and there I gathered that the common process is: 1. formulate your Ajax call using some [JavaScript](http://en.wikipedia.org/wiki/JavaScript) library (e.g., [jQuery](http://en.wikipedia.org/wiki/JQuery)), set up a URL pattern in Django that catches the call and passes it to a view function 2. in the [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) view function retrieve the objects you are interested in and send them back to the client in JSON format or similar (by using the built in serializer module, or [simplejson](http://code.google.com/p/simplejson/)) 3. define a callback function in JavaScript that receives the JSON data and parses them, so to create whatever HTML is needed to be displayed. Finally, the JavaScript script puts the HTML wherever it should stay. Now, what I still don't get is *how are Django templates related to all of this?* Apparently, we're not making use of the power of templates at all. Ideally, I thought it'd be nice to pass back a JSON object and a template name, so that the data could be iterated over and an HTML block is created. But maybe I'm totally wrong here... The only resource I found that goes in this direction is [this snippet (769)](http://www.djangosnippets.org/snippets/769/) but I haven't tried it yet. Obviously, what's going to happen in this case is that all the resulting HTML is created on the server side, then passed to the client. The JavaScript-callback function only has to display it in the right place. Does this cause performance problems? If not, even without using the snippet above, why not formatting the HTML directly in the backend using Python instead of the front-end? Many thanks! **UPDATE: please use [snippet 942](http://www.djangosnippets.org/snippets/942/) because it is an enhanced version of the one above!** I found that the inheritance support works much better this way..
Hey thanks vikingosegundo! I like using decorators too :-). But in the meanwhile I've been following the approach suggested by the snippet I was mentioning above. Only thing, use instead [the snippet n. 942](http://www.djangosnippets.org/snippets/942/) cause it's an improved version of the original one. Here's how it works: Imagine you have a template (e.g., 'subtemplate.html') of whatever size that contains a useful block you can reuse: ``` ........ <div id="results"> {% block results %} {% for el in items %} <li>{{el|capfirst}}</li> {% endfor %} {% endblock %} </div><br /> ........ ``` By importing in your view file the snippet above you can easily reference to any block in your templates. A cool feature is that the inheritance relations among templates are taken into consideration, so if you reference to a block that includes another block and so on, everything should work just fine. So, the ajax-view looks like this: ``` from django.template import loader # downloaded from djangosnippets.com[942] from my_project.snippets.template import render_block_to_string def ajax_view(request): # some random context context = Context({'items': range(100)}) # passing the template_name + block_name + context return_str = render_block_to_string('standard/subtemplate.html', 'results', context) return HttpResponse(return_str) ```
Here is how I use the same template for traditional rendering and Ajax-response rendering. Template: ``` <div id="sortable"> {% include "admin/app/model/subtemplate.html" %} </div> ``` Included template (aka: subtemplate): ``` <div id="results_listing"> {% if results %} {% for c in results %} ..... {% endfor %} {% else %} ``` The Ajax-view: ``` @login_required @render_to('admin/app/model/subtemplate.html')#annoying-decorator def ajax_view(request): ..... return { "results":Model.objects.all(), } ``` Of course you can use render\_to\_response. But I like those annoying decorators :D
Rendering JSON objects using a Django template after an Ajax call
[ "", "python", "ajax", "django", "json", "templates", "" ]
I was just made aware of a bug I introduced, the thing that surprised me is that it compiled, is it legal to switch on a constant? Visual Studio 8 and [Comeau](http://www.comeaucomputing.com/tryitout/) both accept it (with no warnings). ``` switch(42) { // simplified version, this wasn't a literal in real life case 1: std::cout << "This is of course, imposible" << std::endl; } ```
It's not impossible that switching on a constant makes sense. Consider: ``` void f( const int x ) { switch( x ) { ... } } ``` Switching on a literal constant would rarely make sense, however. But it is legal. **Edit:** Thinking about it, there is case where switching on a literal makes perfect sense: ``` int main() { switch( CONFIG ) { ... } } ``` where the program was compiled with: ``` g++ -DCONFIG=42 foo.cpp ```
Not everything that makes sense to the compiler makes sense! The following will also compile but makes no sense: ``` if (false) { std::cout << "This is of course, imposible" << std::endl; } ``` It's up to us as developers to spot these.
Is it legal to switch on a constant in C++?
[ "", "c++", "switch-statement", "" ]
I need to make a div layer so that when you click on it you will have your cursor there blinking and you can insert/delete text just like `<input type="text">` does, except that I do not want to use it as it is slightly too limited to my case. I can definitely use JavaScript.
DIV element has (other elements as well) `contentEditable` property that you can set in Javascript to true. ``` getElementById('YourDiv').contentEditable = true; ```
You can make the div editable by setting its `contentEditable` attribute / property to `true`. However, for anything that is slightly more powerful or flexible then very basic editing, you might want to look at existing solutions such as: * [TinyMCE](http://tinymce.moxiecode.com/) * [Kevin Roth's RTE](http://kevinroth.com/rte/) * [The YUI editor](http://developer.yahoo.com/yui/editor/)
How to make a div with a blinking cursor and editable text without using <input>?
[ "", "javascript", "css", "html", "input", "" ]
Right now I have ``` double numba = 5212.6312 String.Format("{0:C}", Convert.ToInt32(numba) ) ``` This will give me ``` $5,213.00 ``` but I don't want the ".00". I know I can just drop the last three characters of the string every time to achieve the effect, but seems like there should be an easier way.
First - don't keep currency in a `double` - use a `decimal` instead. Every time. Then use "C0" as the format specifier: ``` decimal numba = 5212.6312M; string s = numba.ToString("C0"); ```
This should do the job: ``` String.Format("{0:C0}", Convert.ToInt32(numba)) ``` The number after the `C` specifies the number of decimal places to include. I suspect you really want to be using the [`decimal`](http://msdn.microsoft.com/en-us/library/364x0z75(VS.80).aspx) type for storing such numbers however.
How do I format a double to currency rounded to the nearest dollar?
[ "", "c#", "formatting", "rounding", "currency", "" ]
With the upcoming rise of AJAX applications on the web, I wrote some own pieces of code to understand what it is about. I know there must be easier ways than directly dealing with the XMLHttpRequest object and thought this is why all the AJAX frameworks were created. However, when I had a look at some of them, I mostly found documentation on how to create visual effects and how to manipulate the DOM tree easily. I don't understand why they call themselves AJAX frameworks then, as I consider a AJAX framework as something which helps me to manage sending HTTP requests and processing the responses. Am I missing the point? What is about those frameworks?
Once you've got data back from the server you'll want to display it somehow. The sensible way to do this is through DOM manipulation. And most people using AJAX are doing so because they want to turn a static web page into a dynamic visual application. Hence the focus on visual effect.
YUI says: > The YUI Library is a set of utilities and controls, written in JavaScript, for building richly interactive web applications using techniques such as DOM scripting, DHTML and AJAX. jQuery says: > jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. MooTools says: > MooTools is a compact, modular, Object-Oriented JavaScript framework designed for the intermediate to advanced JavaScript developer. Prototype.js says: > Prototype is a JavaScript Framework that aims to ease development of dynamic web applications. So, none of the first four frameworks that I thought of describe themselves as being an "Ajax framework". It sounds like the Chinese Whisper effect has just caused ignorant third parties to misdescribe them to you. The term Ajax, like DHTML, has gained a substantial number of people who use it to mean "JavaScript" rather then its actual meaning.
What have all the AJAX frameworks to do with AJAX?
[ "", "javascript", "xml", "ajax", "frameworks", "xmlhttprequest", "" ]
In my Java code, I occasionally run into situations where I have to catch a checked exception from a library function that I'm *pretty sure* can't occur in my use case. Also, when coding, I sometimes notice that I'm relying on certain inputs from other modules (my own) to have or not have particular features. For example, I might expect a string to be in a certain format etc. In these situations, I would often put in a verification step, although I control the code that send the input myself. At the moment, I'm working on a quite complex product that I want to be very reliable. Among other things, I want it to collect information from caught exceptions and automatically file bug reports. **For the above two scenarios, I therefore defined an (unchecked) "ProbableBugException", that tells me I made a mistake in the code delivering the input data.** Is that a) stupid, b) paranoid or c) good practice? This is going to be subjective, I'll put up three wiki answers so we can vote away without rep warping. **ETA**: *Thanks to Svend for pointing out that Java has assertions, I didn't realize that. Assertions are actuall pretty much what my question was about, but I only knew them from C and have never used them there.*
I'm thinking that using an [assert](https://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html) is what you really want there ("probably bug").
It's stupid, because: * the exception should be much more specific, like InvalidInputException * you should think harder about the input side, it's likely that it's shaky if you feel you need that kind of exception
Is defining a "ProbableBugException" code smell, paranoia or good practice?
[ "", "java", "" ]
What is the easiest way to do the equivalent of `rm -rf` in Python?
``` import shutil shutil.rmtree("dir-you-want-to-remove") ```
While useful, rmtree isn't equivalent: it errors out if you try to remove a single file, which `rm -f` does not (see example below). To get around this, you'll need to check whether your path is a file or a directory, and act accordingly. Something like this should do the trick: ``` import os import shutil def rm_r(path): if os.path.isdir(path) and not os.path.islink(path): shutil.rmtree(path) elif os.path.exists(path): os.remove(path) ``` Note: this function will not handle character or block devices (that would require using the `stat` module). Example in difference of between `rm -f` and Python's `shutils.rmtree` ``` $ mkdir rmtest $ cd rmtest/ $ echo "stuff" > myfile $ ls myfile $ rm -rf myfile $ ls $ echo "stuff" > myfile $ ls myfile $ python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import shutil >>> shutil.rmtree('myfile') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/shutil.py", line 236, in rmtree onerror(os.listdir, path, sys.exc_info()) File "/usr/lib/python2.7/shutil.py", line 234, in rmtree names = os.listdir(path) OSError: [Errno 20] Not a directory: 'myfile' ``` *Edit:* handle symlinks; note limitations as per @pevik's comment
Easiest way to rm -rf in Python
[ "", "python", "" ]
Referring to the [first answer](https://stackoverflow.com/questions/114214/class-method-differences-in-python-bound-unbound-and-static/114267#114267) about python's bound and unbound methods here, I have a question: ``` class Test: def method_one(self): print "Called method_one" @staticmethod def method_two(): print "Called method_two" @staticmethod def method_three(): Test.method_two() class T2(Test): @staticmethod def method_two(): print "T2" a_test = Test() a_test.method_one() a_test.method_two() a_test.method_three() b_test = T2() b_test.method_three() ``` produces output: ``` Called method_one Called method_two Called method_two Called method_two ``` Is there a way to override a static method in python? I expected `b_test.method_three()` to print "T2", but it doesn't (prints "Called method\_two" instead).
In the form that you are using there, you are explicitly specifying what class's static `method_two` to call. If `method_three` was a classmethod, and you called `cls.method_two`, you would get the results that you wanted: ``` class Test: def method_one(self): print "Called method_one" @staticmethod def method_two(): print "Called method_two" @classmethod def method_three(cls): cls.method_two() class T2(Test): @staticmethod def method_two(): print "T2" a_test = Test() a_test.method_one() # -> Called method_one a_test.method_two() # -> Called method_two a_test.method_three() # -> Called method_two b_test = T2() b_test.method_three() # -> T2 Test.method_two() # -> Called method_two T2.method_three() # -> T2 ```
The behavior you see is the expected behavior. Static methods are... static. When you call `method_three()` defined in `Test` it will certainly call `method_two()` defined by `Test`. As for how to "get around" this proper behavior... The very best way is to make methods virtual when you want virtual behavior. If you're stuck with some library code with a static method that you wish were virtual then you might look deeper to see if there's a reason or if it's just an oversight. Otherwise, you can define a new `method_three()` in `T2` that calls `T2.method_two()`.
Overriding a static method in python
[ "", "python", "static", "overriding", "" ]
This question is related with one of my earlier questions.. [Previous Post](https://stackoverflow.com/questions/827831/what-are-the-advantages-of-blocking-queue-in-java) In there the blocking nature is mentioned as an advantage. I tried to develop some simple code to demonstrate the blocking nature but I got stuck. I just tried to make a `BlockingQueue` of size 4 and tried to add 5 elements and ended up with a `java.lang.IllegalStateException`. Can someone show me a code example for blocking nature of `BlockingQueue`? --- ``` public static void main(String[] args) { BlockingQueue<String> bq = new LinkedBlockingQueue<String>(4); try { bq.offer("A"); bq.offer("B"); bq.offer("C"); bq.offer("D"); bq.offer("E"); System.out.println("1 = " + bq.take()); System.out.println("2 = " + bq.take()); System.out.println("3 = " + bq.take()); System.out.println("4 = " + bq.take()); System.out.println("5 = " + bq.take()); System.out.println("6 = " + bq.take()); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } ``` I used this code segment. In this case I am trying to put 5 elements to a queue with size 4. In this case 4 elements (A,B,C,D) should be added to queue. Then I am calling `take()` method while printing. Shouldn't "E" be inserted automatically to the queue when I call **`System.out.println("1 = " + bq.take());`** ? Because it gets one free slot?
Were you adding with [`add`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html#add(E)), [`offer`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html#offer(E)), or [`put`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html#put(E))? I assume you were using `add`, since it is the only one that can throw an `IllegalStateException`; but if you read the [table](http://java.sun.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html), you'll see that if you want blocking semantics, you should be using [`put`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html#put(E)) (and [`take`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html#take()) to remove). **Edit:** There are a couple of problems with your example. First I'll answer the question "Why doesn't E get inserted when I call `take()` the first time?" The answer is that by the time you call `take()`, you have already tried *and failed* to insert E. There is then nothing to insert once the space has been freed. Now if you changed `offer()` to `put()`, `put("E")` will never return. Why? Because it's waiting for *some other thread* to remove an element from the queue. Remember, `BlockingQueues` are designed for multiple threads to access. Blocking is useless (actually worse than useless) if you have a single-threaded application. Here is an improved example: ``` public static void main(String[] args) { final BlockingQueue<String> bq = new LinkedBlockingQueue<String>(4); Runnable producer = new Runnable() { public void run() { try { bq.put("A"); bq.put("B"); bq.put("C"); bq.put("D"); bq.put("E"); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } }; Runnable consumer = new Runnable() { public void run() { try { System.out.println("1 = " + bq.take()); System.out.println("2 = " + bq.take()); System.out.println("3 = " + bq.take()); System.out.println("4 = " + bq.take()); System.out.println("5 = " + bq.take()); System.out.println("6 = " + bq.take()); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } }; new Thread(producer).start(); new Thread(consumer).start(); } ``` Now the `put("E")` call will actually succeed, since it can now wait until the consumer thread removes "A" from the queue. The last `take()` will still block infinitely, since there is no sixth element to remove.
mmyers beat me to it :P (+1) that should be what you need, good luck! **NOTE:** put() will fail in your example because put() will block until space is available. Since space is never available, the program never continues execution. ==== old answer====== a BlockingQueue is an interface, you'll have to use one of the implementating classes. The "Blocking Nature" simply states that you can request something from your queue, and if it is empty, the thread it is in will *block* (wait) until something gets added to the queue and then continue processing. `ArrayBlockingQueue DelayQueue LinkedBlockingQueue PriorityBlockingQueue SynchronousQueue` <http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html> ``` //your main collection LinkedBlockingQueue<Integer> lbq = new LinkedBlockingQueue<Integer>(); //Add your values lbq.put(100); lbq.put(200); //take() will actually remove the first value from the collection, //or block if no value exists yet. //you will either have to interrupt the blocking, //or insert something into the queue for the program execution to continue int currVal = 0; try { currVal = lbq.take(); } catch (InterruptedException e) { e.printStackTrace(); } ```
Blocking Queue - Need more information
[ "", "java", "data-structures", "concurrency", "queue", "" ]
I'm recieving the following error when trying to do inserts: > java.lang.NoSuchMethodError : org.hibernate.event.PreInsertEvent.getSource()Lorg/hibernate/event/EventSource; I've seen [other](http://drglennn.blogspot.com/2008/10/hibernate-preinserteventgetsource.html) people with the same problem due to incompatibility in hibernate jars, but I believe I've got it right (according to the [compatibility matrix](https://www.hibernate.org/6.html#A3)) Here's the relevant section from my pom.xml: ``` <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.4.0.GA</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-commons-annotations</artifactId> <version>3.3.0.ga</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.3.1.GA</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>3.1.0.GA</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.4.0.GA</version> </dependency> ``` Can anyone advise? Regards Marty
I found a solution, but I'm not sure it's correct -- anyone with a better, please advise: Added a reference to cglib, and explicity excluded hibernate (was including 3.2) ``` <dependencies> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.4.0.GA</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-commons-annotations</artifactId> <version>3.3.0.ga</version> <exclusions> <exclusion> <groupId>org.hibernate</groupId> <artifactId>hibernate</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.3.1.GA</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>3.1.0.GA</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.4.0.GA</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> </dependencies> ```
This is a known bug : <https://hibernate.onjira.com/browse/HVAL-81> . It occurs when you reference an older version of hibernate validator than core.
Hibernate "PreInsertEvent.getSource()" NoSuchMethodError
[ "", "java", "hibernate", "maven-2", "" ]
With ``` include('basemodel.php'); ``` I get > Fatal error: Class 'BaseModel' not found in C:\xampp\htdocs\allsides\account\model.php on line 2 Without ``` include('basemodel.php'); ``` I get > Fatal error: Cannot redeclare class BaseModel in C:\xampp\htdocs\allsides\others\basemodel.php on line 2
Never, never, ever use include or require. Use include\_once or require\_once. There are a few small exceptions to this rule. But for the most part where ever your code says include or require, change it to include\_once or require\_once. (Template engines and similar code within code oddities and workarounds for eval sometimes need the non-\_once versions. But this not what you are doing.)
Try: require\_once ("basemodel.php"); === Edit: wait -- what other files are you including?
Problem including a file in php gives an error whether I include the file or not
[ "", "class", "php", "" ]
I have a table with hierarchical data. A column "ParentId" that holds the Id ("ID" - key column) of it's parent. When deleting a row, I want to delete all children (all levels of nesting). How to do it? Thanks
When the number of rows is not too large, erikkallen's recursive approach works. Here's an alternative that uses a temporary table to collect all children: ``` create table #nodes (id int primary key) insert into #nodes (id) values (@delete_id) while @@rowcount > 0 insert into #nodes select distinct child.id from table child inner join #nodes parent on child.parentid = parent.id where child.id not in (select id from #nodes) delete from table where id in (select id from #nodes) ``` It starts with the row with @delete\_id and descends from there. The where statement is to protect from recursion; if you are sure there is none, you can leave it out.
On SQL Server: Use a recursive query. Given CREATE TABLE tmp(Id int, Parent int), use ``` WITH x(Id) AS ( SELECT @Id UNION ALL SELECT tmp.Id FROM tmp JOIN x ON tmp.Parent = x.Id ) DELETE tmp FROM x JOIN tmp ON tmp.Id = x.Id ```
Deleting hierarchical data in SQL table
[ "", "sql", "sql-server-2005", "" ]
I'm working on a project in C++ and QT, and I want to open a new QWidget window, have the user interact with it, etc, then have execution return to the method that opened the window. Example (MyClass inherits QWidiget): ``` void doStuff(){ MyClass newWindow = new Myclass(); /* I don't want the code down here to execute until newWindow has been closed */ } ``` I feel like there is most likely a really easy way to do this, but for some reason I can't figure it out. How can I do this?
Have `MyClass` inherit `QDialog`. Then open it as a modal dialog with `exec()`. ``` void MainWindow::createMyDialog() { MyClass dialog(this); dialog.exec(); } ``` Check out <http://qt-project.org/doc/qt-4.8/qdialog.html>
An other way is to use a loop which waits on the closing event : ``` #include <QEventLoop> void doStuff() { // Creating an instance of myClass MyClass myInstance; // (optional) myInstance.setAttribute(Qt::WA_DeleteOnClose); myInstance.show(); // This loop will wait for the window is destroyed QEventLoop loop; connect(this, SIGNAL(destroyed()), & loop, SLOT(quit())); loop.exec(); } ```
Wait until QWidget closes
[ "", "c++", "qt", "" ]
I'm looking for a way to rotate a string in c++. I spend all of my time in python, so my c++ is *very* rusty. Here is what I want it to do: if I have a string 'abcde' I want it changed to 'bcdea' (first character moved to the end). Here is how I did it in python: ``` def rotate(s): return s[1:] + s[:1] ``` I'm not sure how to do it in cpp. Maybe use an array of chars?
I recommend [`std::rotate`](http://en.cppreference.com/w/cpp/algorithm/rotate): ``` std::rotate(s.begin(), s.begin() + 1, s.end()); ```
Here's a solution that "floats" the first character to the end of the string, kind of like a single iteration of bubble sort. ``` #include <algorithm> string rotate(string s) { for (int i = 1; i < s.size(); i++) swap(s[i-1], s[i]); return s; } ``` if you want the function to rotate the string in-place: ``` #include <algorithm> void rotate(string &s) { for (int i = 1; i < s.size(); i++) swap(s[i-1], s[i]); } ```
Rotate a string in c++?
[ "", "c++", "string", "" ]
For example the following cast can be found littered throughout the MSDN documentation: ``` (LPTSTR)&lpMsgBuf ``` Should I bother converting that to: ``` static_cast<LPTSTR>(&lpMsgBuf); ``` Or should I just leave all the idiomatic C-esque Win32 portions as they are typically found in the docs, and save the more idiomatic C++ style/usage for the rest of my code?
New style casts were introduced for a reason: they're safer, more explanatory/self-commenting, easier to see, and easier to grep for. So use them. By more explanatory, we mean that you can't just cast to something, you have to say *why* you're casting (I'm casting in an inheritance hierarchy (dynamic\_cast), my cast is implementation defined and possibly not portable (reinterpret\_cast), I'm casting away constness (const\_cast), etc.). They're purposefully long and ugly so that the cast jumps out at the reader (and to discourage a programming style that employs too much casting). They're safer because, e.g., you can't cast away constness without explicitly doing that.
Rather than sprinkling my code with either old-style casts or new-style casts, I'd take advantage of C++'s operator overloading to add inline overloaded versions of the Windows API functions that take parameters of the proper types. (As long as this is documented for new developers, it hopefully won't be too confusing.) For example, `FormatMessage`'s fifth parameter is normally an `LPTSTR`, but if you pass the `FORMAT_MESSAGE_ALLOCATE_BUFFER` flag, the fifth parameter is a pointer to an LPTSTR. So I'd define a function like this: ``` inline DWORD WINAPI FormatMessage( __in DWORD dwFlags, __in_opt LPCVOID lpSource, __in DWORD dwMessageId, __in DWORD dwLanguageId, __out LPTSTR *lpBuffer, __in DWORD nSize, __in_opt va_list *Arguments ) { assert(dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER); return FormatMessage(dwFlags, lpSource, dwMessageId, dwLanguageId, static_cast<LPTSTR>(&lpBuffer), nSize, Arguments); } ```
When using Win32 code in your modern C++ app, should you use proper casting?
[ "", "c++", "winapi", "visual-c++", "" ]
> **Possible Duplicate:** > [Where do the Python unit tests go?](https://stackoverflow.com/questions/61151/where-do-the-python-unit-tests-go) Are unit tests kept in the same file as the code, a separate file in the same directory, or in an entirely different directory?
I always place my unit tests in a subdirectory to the related code called test. For example: */libs/authentication*, the tests would be placed in */libs/authentication/tests*
I prefer to keep them in a seperate directory, usually called either "unittests" or just "tests". I then play games in the Makefile to have to automatically handle this directory, if it exists. It's a little bit of a pain to set up, but I personally prefer not to have the unit tests cluttering up the functional code. This way they are "close" enough to be obvious, but not in your face all the time.
Where to keep Python unit tests?
[ "", "python", "unit-testing", "code-organization", "" ]
I ran across some code recently at work (recreated to be similar to what I am dealing with) similar to the code below Is there a way I can rework the code below to use one data structure (with performance in mind)? Here is some code to illustrate what I mean: ``` public class ObjectMapper { private Map<UUID,Integer> uuidMap; private Map<Integer,UUID> indexMap; public ObjectMapper(){ uuidMap = new HashMap<UUID,Integer>(); indexMap = new HashMap<Integer,UUID>(); } public void addMapping(int index, UUID uuid){ uuidMap.put(uuid, index); indexMap.put(index, uuid); } . . . public Integer getIndexByUUID(UUID uuid){ return uuidMap.get(uuid); } public UUID getUUIDByIndex(Integer index){ return indexMap.get(index); } } ```
This is answered [here](https://stackoverflow.com/questions/711618/java-collection-unique-key-and-unique-value) with the recommendation to use BiMap from [Google Collections](http://code.google.com/p/google-collections/)
Apache collections supports a [BidiMap](http://commons.apache.org/collections/api-3.1/org/apache/commons/collections/BidiMap.html) interface and a variety of fairly effective implementations.
Two Way Mapping using single Data Structure
[ "", "java", "oop", "jakarta-ee", "uuid", "" ]
I want to convert `String` to `Date` in different formats. For example, I am getting from user, ``` String fromDate = "19/05/2009"; // i.e. (dd/MM/yyyy) format ``` I want to convert this `fromDate` as a Date object of `"yyyy-MM-dd"` format How can I do this?
Take a look at [`SimpleDateFormat`](http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html). The code goes something like this: ``` SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd"); try { String reformattedStr = myFormat.format(fromUser.parse(inputString)); } catch (ParseException e) { e.printStackTrace(); } ```
# tl;dr ``` LocalDate.parse( "19/05/2009" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ``` # Details The other Answers with `java.util.Date`, `java.sql.Date`, and `SimpleDateFormat` are now outdated. # `LocalDate` The modern way to do date-time is work with the java.time classes, specifically `LocalDate`. The [`LocalDate`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html) class represents a date-only value without time-of-day and without time zone. # `DateTimeFormatter` To parse, or generate, a String representing a date-time value, use the [`DateTimeFormatter`](http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) class. ``` DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ); LocalDate ld = LocalDate.parse( "19/05/2009" , f ); ``` Do not conflate a date-time object with a String representing its value. A date-time object **has *no* format**, while a String does. A date-time object, such as `LocalDate`, can *generate* a String to represent its internal value, but the date-time object and the String are separate distinct objects. You can specify any custom format to generate a String. Or let java.time do the work of automatically localizing. ``` DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL ) .withLocale( Locale.CANADA_FRENCH ) ; String output = ld.format( f ); ``` Dump to console. ``` System.out.println( "ld: " + ld + " | output: " + output ); ``` > ld: 2009-05-19 | output: mardi 19 mai 2009 [See in action in IdeOne.com](http://ideone.com/4xOyiS). --- # About *java.time* The [*java.time*](http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) framework is built into Java 8 and later. These classes supplant the troublesome old [legacy](https://en.wikipedia.org/wiki/Legacy_system) date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), & [`SimpleDateFormat`](http://docs.oracle.com/javase/9/docs/api/java/text/SimpleDateFormat.html). The [*Joda-Time*](http://www.joda.org/joda-time/) project, now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advises migration to the [java.time](http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. To learn more, see the [*Oracle Tutorial*](http://docs.oracle.com/javase/tutorial/datetime/TOC.html). And search Stack Overflow for many examples and explanations. Specification is [JSR 310](https://jcp.org/en/jsr/detail?id=310). You may exchange *java.time* objects directly with your database. Use a [JDBC driver](https://en.wikipedia.org/wiki/JDBC_driver) compliant with [JDBC 4.2](http://openjdk.java.net/jeps/170) or later. No need for strings, no need for `java.sql.*` classes. Where to obtain the java.time classes? * [**Java SE 8**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8), [**Java SE 9**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9), and later + Built-in. + Part of the standard Java API with a bundled implementation. + Java 9 adds some minor features and fixes. * [**Java SE 6**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6) and [**Java SE 7**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7) + Much of the java.time functionality is back-ported to Java 6 & 7 in [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/). * [**Android**](https://en.wikipedia.org/wiki/Android_(operating_system)) + Later versions of Android bundle implementations of the java.time classes. + For earlier Android (<26), the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project adapts *ThreeTen-Backport* (mentioned above). See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). The [**ThreeTen-Extra**](http://www.threeten.org/threeten-extra/) project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as [`Interval`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html), [`YearWeek`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html), [`YearQuarter`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html), and [more](http://www.threeten.org/threeten-extra/apidocs/index.html).
Parse String to Date with Different Format in Java
[ "", "java", "string", "date", "" ]
I'm currently writing a sitemap generator that scrapes a site for urls and builds an xml sitemap. As most of the waiting is spent on requests to uri's I'm using threading, specifically the build in ThreadPool object. In order to let the main thread wait for the unknown amount of threads to complete I have implemented the following setup. I don't feel this is a good solution though, can any threading gurus advise me of any problems this solution has, or suggest a better way to implement it? The EventWaitHandle is set to EventResetMode.ManualReset Here is the thread method ``` protected void CrawlUri(object o) { try { Interlocked.Increment(ref _threadCount); Uri uri = (Uri)o; foreach (Match match in _regex.Matches(GetWebResponse(uri))) { Uri newUri = new Uri(uri, match.Value); if (!_uriCollection.Contains(newUri)) { _uriCollection.Add(newUri); ThreadPool.QueueUserWorkItem(_waitCallback, newUri); } } } catch { // Handle exceptions } finally { Interlocked.Decrement(ref _threadCount); } // If there are no more threads running then signal the waithandle if (_threadCount == 0) _eventWaitHandle.Set(); } ``` Here is the main thread method ``` // Request first page (based on host) Uri root = new Uri(context.Request.Url.GetLeftPart(UriPartial.Authority)); // Begin threaded crawling of the Uri ThreadPool.QueueUserWorkItem(_waitCallback, root); Thread.Sleep(5000); // TEMP SOLUTION: Sleep for 5 seconds _eventWaitHandle.WaitOne(); // Server the Xml Sitemap context.Response.ContentType = "text/xml"; context.Response.Write(GetXml().OuterXml); ``` Any ideas are much appreciated :)
Well, first off you can create a ManualResetEvent that starts unset, so you don't have to sleep before waiting on it. Secondly you're going to need to put thread synchronization around your Uri collection. You could get a race condition where one two threads pass the "this Uri does not exist yet" check and they add duplicates. Another race condition is that two threads could pass the `if (_threadCount == 0)` check and they could both set the event. Last, you can make the whole thing much more efficient by using the asynchronous BeginGetRequest. Your solution right now keeps a thread around to wait for every request. If you use async methods and callbacks, your program will use less memory (1MB per thread) and won't need to do context switches of threads nearly as much. Here's an example that should illustrate what I'm talking about. Out of curiosity, I did test it out (with a depth limit) and it does work. ``` public class CrawlUriTool { private Regex regex; private int pendingRequests; private List<Uri> uriCollection; private object uriCollectionSync = new object(); private ManualResetEvent crawlCompletedEvent; public List<Uri> CrawlUri(Uri uri) { this.pendingRequests = 0; this.uriCollection = new List<Uri>(); this.crawlCompletedEvent = new ManualResetEvent(false); this.StartUriCrawl(uri); this.crawlCompletedEvent.WaitOne(); return this.uriCollection; } private void StartUriCrawl(Uri uri) { Interlocked.Increment(ref this.pendingRequests); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.BeginGetResponse(this.UriCrawlCallback, request); } private void UriCrawlCallback(IAsyncResult asyncResult) { HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest; try { HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); string responseText = this.GetTextFromResponse(response); // not included foreach (Match match in this.regex.Matches(responseText)) { Uri newUri = new Uri(response.ResponseUri, match.Value); lock (this.uriCollectionSync) { if (!this.uriCollection.Contains(newUri)) { this.uriCollection.Add(newUri); this.StartUriCrawl(newUri); } } } } catch (WebException exception) { // handle exception } finally { if (Interlocked.Decrement(ref this.pendingRequests) == 0) { this.crawlCompletedEvent.Set(); } } } } ```
When doing this kind of logic I generally try to make an object representing each asynchronous task and the data it needs to run. I would typically add this object to the collection of tasks to be done. The thread pool gets these tasks secheduled, and I would let the object itself remove itself from the "to be done" collection when the task finishes, possibly signalling on the collection itself. So you're finished when the "to be done" collection is empty; the main thread is probably awoken once by each task that finishes.
Threading an unkown amount of threads in C#
[ "", "c#", "asp.net", "multithreading", "" ]
I'm very curious of the stack memory organization after I experiment what's going on in the background and obviously saw it's matching with tiny knowledge I acquired from books. Just wanted to check if what I've understood is correct. I have a fundamental program -- has 2 functions, first one is foo and the other is main (the entry point). ``` void foo(){ // do something here or dont } int main(){ int i = 0; printf("%p %p %p\n",foo, &i, main); system("PAUSE"); return EXIT_SUCCESS; }; ``` The output of the program is shown below, main's local variable i is located totally in a unrelated position. integer is a value type but checked it again with a char \* pointer local to main and obtain similar results. ``` 00401390 0022FF44 00401396 Press any key to continue . . . ``` I mainly understand that code and variables are allocated into different segments of memory (code segment/data segment). So basically is it right to say call stack collapses basic information about the execution of functions (their local variables, parameters, returning points) and keep them in the data segment?
A little caveat at the start: all of these answers are somewhat affected by the operating system and hardware architecture. Windows does things fairly radically differently from UNIX-like languages, real-time operating systems and old small-system UNIX. But the basic answer as @Richie and @Paul have said, is "yes." When your compiler and linker get through with the code, it's broken up into what are known as "text" and "data" segments in UNIX. A *text segment* contains instructions and some kinds of static data; a data segment contains, well, data. A big chunk of the data segment is then allocated for stack and heap space. Other chunks can be allocated to things like static or extern data structures. So yes, when the program runs, the program counter is busily fetching instructions from a different segment than the data. Now we get into some architecture dependencies, but in general if you have segmented memory your instructions are constructed in such a way that fetching a byte from the segments is as efficient as possible, In the old 360 architecture, they had *base registers*, in x86 have a bunch of hair that grew as the address space went to the old 8080's to modern processors, but all of the instructions are very carefully optimized because, as you can imagine, fetching instructions and their operands are very intensively used. Now we et to more modern architectures with virtual memory and *memory management unit*s. Now the machine has specific hardware that let's the program treat the address space as a big flat range of addresses; the various segments simply get placed in that bit virtual address space. The MMU's job is to take a virtual address and translate it to a physical address, including what to do if that virtual address doesn't happen to be in physical memory at all at the moment. Again, the MMU hardware is very heavily optimized, but that doesn't mean there is **no** performance cost associated. But as processors have gotten faster and programs have goten bigger, it's become less and less important.
Yes, that's exactly right. Code and data live in different parts of memory, with different permissions. The stack holds parameters, return addresses and local ("automatic") variables, and lives with the data.
Is runtime stack kept in data segment of memory?
[ "", "c++", "c", "memory", "stack", "segments", "" ]
Brand new to web design, using python. Got Apache up and running, test python script working in cgi-bin directory. Get valid results when I type in the URL explicitly: ".../cgi-bin/showenv.py" But I don't want the URL to look that way. Here at stackoverflow, for example, the URLs that display in my address bar never have the messy details showing the script that was used to run them. They're clean of cgi-bin, .py, etc. extensions. How do I do that? EDIT: Thanks for responses, every single one helpful, lots to learn. I'm going with URL Rewriting for now; example in the docs looks extremely close to what I actually want to do. But I'm committed to python, so will have to look at WSGI down the road.
The python way of writing web applications is not cgi-bin. It is by using [WSGI](http://wsgi.org). WSGI is a standard interface between web servers and Python web applications or frameworks. The [PEP 0333](http://www.python.org/dev/peps/pep-0333/) defines it. There are no disadvantages in using it instead of CGI. And you'll gain a lot. Beautiful URLs is just one of the neat things you can do easily. Also, writing a WSGI application means you can deploy on any web server that supports the WSGI interface. Apache does so by using [mod\_wsgi](http://code.google.com/p/modwsgi/). You can configure it in apache like that: ``` WSGIScriptAlias /myapp /usr/local/www/wsgi-scripts/myapp.py ``` Then all requests on `http://myserver.domain/myapp` will go to myapp.py's `application` callable, including `http://myserver.domain/myapp/something/here`. example `myapp.py`: ``` def application(environ, start_response): start_response('200 OK', [('Content-type', 'text/plain')]) return ['Hello World!'] ```
I think you can do this by rewriting URL through Apache configuration. You can see the Apache documentation for rewriting [here](http://httpd.apache.org/docs/2.0/misc/rewriteguide.html).
How to hide "cgi-bin", ".py", etc from my URLs?
[ "", "python", "cgi", "" ]
I have a very simple ASP.Net MVC Application that I have produced from an online tutorial. I've followed it exactly, step by step and have tried multiple times but keep getting the same error when I execute the code. The program just displays an index page which lists a series of data from an sql server database using linq to sql. This is the error: Could not load type 'MvcApplication1.Views.Home.Index'. Any ideas what the problem could be?
Possible answer here: <http://www.jondavis.net/techblog/post/2009/04/29/Set-Up-IIS-For-An-MVC-App-When-All-Else-Fails-Check-View-Config.aspx> Basically, add the Views directory's web.config to your target Views directory. Although, it doesn't sound like you're using a strongly typed view, or aren't deploying your code. Also, I have seen this problem also appear if the compile settings are removed from web.config. In an ASP.NET MVC project created in Visual Studio 2008, those settings are included in web.config, and they should remain or else this error will occur.
Are you running the current version of MVC? There was a big update in the Release Candidate that removed the code-behinds on views. I ran into the same issue. Uninstalling MVC, then reinstalling fixed the problem for me. This can be done in Control Panel --> Add/Remove Programs. Hope this helps, Adam
ASP.Net MVC "Could Not Load Type" when executing
[ "", "c#", "asp.net", "asp.net-mvc", "" ]
I'm trying to figure out Python lambdas. Is `lambda` one of those "interesting" language items that in real life should be forgotten? I'm sure there are some edge cases where it might be needed, but given the obscurity of it, the potential of it being redefined in future releases (my assumption based on the various definitions of it) and the reduced coding clarity - should it be avoided? This reminds me of overflowing (buffer overflow) of C types - pointing to the top variable and overloading to set the other field values. It feels like sort of a techie showmanship but maintenance coder nightmare.
Are you talking about [lambda expressions](https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions)? Like ``` lambda x: x**2 + 2*x - 5 ``` Those things are actually quite useful. Python supports a style of programming called *functional programming* where you can pass functions to other functions to do stuff. Example: ``` mult3 = filter(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9]) ``` sets `mult3` to `[3, 6, 9]`, those elements of the original list that are multiples of 3. This is shorter (and, one could argue, clearer) than ``` def filterfunc(x): return x % 3 == 0 mult3 = filter(filterfunc, [1, 2, 3, 4, 5, 6, 7, 8, 9]) ``` Of course, in this particular case, you could do the same thing as a list comprehension: ``` mult3 = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9] if x % 3 == 0] ``` (or even as `range(3,10,3)`), but there are many other, more sophisticated use cases where you can't use a list comprehension and a lambda function may be the shortest way to write something out. * Returning a function from another function ``` >>> def transform(n): ... return lambda x: x + n ... >>> f = transform(3) >>> f(4) 7 ``` This is often used to create function wrappers, such as Python's decorators. * Combining elements of an iterable sequence with `reduce()` ``` >>> reduce(lambda a, b: '{}, {}'.format(a, b), [1, 2, 3, 4, 5, 6, 7, 8, 9]) '1, 2, 3, 4, 5, 6, 7, 8, 9' ``` * Sorting by an alternate key ``` >>> sorted([1, 2, 3, 4, 5, 6, 7, 8, 9], key=lambda x: abs(5-x)) [5, 4, 6, 3, 7, 2, 8, 1, 9] ``` I use lambda functions on a regular basis. It took me a while to get used to them, but eventually I came to understand that they're a very valuable part of the language.
`lambda` is just a fancy way of saying `function`. Other than its name, there is nothing obscure, intimidating or cryptic about it. When you read the following line, replace `lambda` by `function` in your mind: ``` >>> f = lambda x: x + 1 >>> f(3) 4 ``` It just defines a function of `x`. Some other languages, like `R`, say it explicitly: ``` > f = function(x) { x + 1 } > f(3) 4 ``` You see? It's one of the most natural things to do in programming.
How are lambdas useful?
[ "", "python", "function", "lambda", "closures", "" ]
I am working on a mobile application in .NET. This is a windows mobile application. I am facing a problem in this application that I wanna upload an image/file to given url/server. Many upload classes is not using like `Webclient,WebRequest,WebResponse`. I used `HttpWebReques`, That is not connecting with server. Can anyone help me on how to upload the images on given url in windows mobile 6 in .NET?
Not sure what you mean exactly with uploading images to a given URL. Surely you need some listener or something on your server to be able to receive the image data. You could create a .NET web service, with a function that takes a byte[] input parameter to upload your image data, on your server and reference that in your Windows Mobile application.
Can you modify the server code as well? If so there are a couple of other options. You could store the images in a database (SQL Server Compact Edition) and then use Synchronization Services. You could use WCF to transfer the data (for mobile you have two WCF options, web service and message...you might want message for this).
Upload images in windows mobile 6 in .net
[ "", "c#", "windows-mobile", "" ]
Is there a way to execute "internal" code via reflection? Here is an example program: ``` using System; using System.Reflection; namespace ReflectionInternalTest { class Program { static void Main(string[] args) { Assembly asm = Assembly.GetExecutingAssembly(); // Call normally new TestClass(); // Call with Reflection asm.CreateInstance("ReflectionInternalTest.TestClass", false, BindingFlags.Default | BindingFlags.CreateInstance, null, null, null, null); // Pause Console.ReadLine(); } } class TestClass { internal TestClass() { Console.WriteLine("Test class instantiated"); } } } ``` Creating a testclass normally works perfectly, however when i try to create an instance via reflection, I get a missingMethodException error saying it can't find the Constructor (which is what would happen if you tried calling it from outside the assembly). Is this impossible, or is there some workaround i can do?
Based on Preets direction to an alternate post: ``` using System; using System.Reflection; using System.Runtime.CompilerServices; namespace ReflectionInternalTest { class Program { static void Main(string[] args) { Assembly asm = Assembly.GetExecutingAssembly(); // Call normally new TestClass(1234); // Call with Reflection asm.CreateInstance("ReflectionInternalTest.TestClass", false, BindingFlags.Default | BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.NonPublic, null, new Object[] {9876}, null, null); // Pause Console.ReadLine(); } } class TestClass { internal TestClass(Int32 id) { Console.WriteLine("Test class instantiated with id: " + id); } } } ``` This works. (Added an argument to prove it was a new instance). turns out i just needed the instance and nonpublic BindingFlags.
Here is an example ... ``` class Program { static void Main(string[] args) { var tr = typeof(TestReflection); var ctr = tr.GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null); var obj = ctr.Invoke(null); ((TestReflection)obj).DoThatThang(); Console.ReadLine(); } } class TestReflection { internal TestReflection( ) { } public void DoThatThang() { Console.WriteLine("Done!") ; } } ```
c#, Internal, and Reflection
[ "", "c#", "reflection", "internal", "" ]
I have just created a report in Report Manager using a Stored Procedure which uses a temporary table. I'm getting the error "Could not generate a list of fields for the query. Invalid object name '#xxxx'" I read this is because when Report Manager tries to PrepareQuery it runs into difficulty because the temporary table doesn't exist yet, is this correct? If so do you have any workarounds?
I ran into this one once...exact same thing, actually. I fixed it by dropping this line into my SP before creating any temp tables: ``` SET FMTONLY OFF ``` That should do the trick for it.
The only way is an obvious one, make your temp table a permanent one and do the management of it yourself (deleting rows after use etc). This could be faster as well as indexable and you can add keys as needed to ensure integrity. It can also act as a cache for long running queries. If you are certain that there will only ever be one user calling the sp then you can dump the data from the table using truncate rather than delete. Not much help, but I never found any other way of doing it.
Temporary table issue in Reporting Services 2000
[ "", "sql", "sql-server", "report", "" ]
I have a TreeSet, which will be full of integers. To make a long story short, I'm trying to loop starting after the last (greatest) value stored in the list. What I'm doing now to get the starting variable is: ``` Object lastObj = primes.last(); Integer last = new Integer(lastObj.toString()); int start = 1 + last.intValue(); // the added 1 is just for program logic ``` I'm sure that there must be a better way to cast an object (which I know will always be an int) into the int 'start'. Anyone know of a better way of doing this?
Are you using Java version 1.6? In that case you can take advantage of autoboxing and generics to clean up the code. First, the TreeSet can be declared as containing only Integer objects ``` TreeSet<Integer> primes; ``` Now to get the object from the set you can ``` Integer last = primes.last(); ``` and using the autoboxing feature you get ``` int start = 1 + last; ```
In J2SE 5 or later it happens automatically, with the "autoboxing" feature. ``` int start = 1 + last; ``` <http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html> Also, if you know they're all going to be Integer objects, use the parameterized type: ``` List<Integer> obj = new ArrayList<Integer>()... ``` Then combine it with the autoboxing feature: ``` int start = 1 + obj.last(); ```
Java object to int: a better way?
[ "", "java", "generics", "" ]
I am new to programming. I have been trying to write a function in C++ that explodes the contents of a string into a string array at a given parameter, example: ``` string str = "___this_ is__ th_e str__ing we__ will use__"; ``` should return string array: ``` cout << stringArray[0]; // 'this' cout << stringArray[1]; // ' is' cout << stringArray[2]; // ' th' cout << stringArray[3]; // 'e str' cout << stringArray[4]; // 'ing we' cout << stringArray[5]; // ' will use' ``` I can tokenize the string just fine, but the hardest part for me is how can i specify the number of elements in stringArray before assigning it the current string toke and also how to return stringArray from the function. Would someone show me how to write the function? **Edit1:** I don't necessarily need the results to been in string array just any container that i can call as a regular variable with some sort of indexing.
Here's my first attempt at this using vectors and strings: ``` vector<string> explode(const string& str, const char& ch) { string next; vector<string> result; // For each character in the string for (string::const_iterator it = str.begin(); it != str.end(); it++) { // If we've hit the terminal character if (*it == ch) { // If we have some characters accumulated if (!next.empty()) { // Add them to the result vector result.push_back(next); next.clear(); } } else { // Accumulate the next character into the sequence next += *it; } } if (!next.empty()) result.push_back(next); return result; } ``` Hopefully this gives you some sort of idea of how to go about this. On your example string it returns the correct results with this test code: ``` int main (int, char const **) { std::string blah = "___this_ is__ th_e str__ing we__ will use__"; std::vector<std::string> result = explode(blah, '_'); for (size_t i = 0; i < result.size(); i++) { cout << "\"" << result[i] << "\"" << endl; } return 0; } ```
Using STL (sorry no compiler not tested) ``` #include <vector> #include <string> #include <sstream> int main() { std::vector<std::string> result; std::string str = "___this_ is__ th_e str__ing we__ will use__"; std::stringstream data(str); std::string line; while(std::getline(data,line,'_')) { result.push_back(line); // Note: You may get a couple of blank lines // When multiple underscores are beside each other. } } ``` // or define a token ``` #include <vector> #include <string> #include <iterator> #include <algorithm> #include <sstream> struct Token: public std::string // Yes I know this is nasty. { // But it is just to demosntrate the principle. }; std::istream& operator>>(std::istream& s,Token& t) { std::getline(s,t,'_'); // *** // Remove extra '_' characters from the stream. char c; while(s && ((c = s.get()) != '_')) {/*Do Nothing*/} if (s) { s.unget(); // Put back the last char as it is not '_' } return s; } int main() { std::string str = "___this_ is__ th_e str__ing we__ will use__"; std::stringstream data(str); std::vector<std::string> result(std::istream_iterator<Token>(data), std::istream_iterator<Token>()); } ```
How can I split a string by a delimiter into an array?
[ "", "c++", "function", "string", "" ]
I have a game that currently runs under Windows and Mac OS X and I'd like to make it available under Linux. The porting should be fairly easy since it's a Java based game and uses portable libraries that are available on all 3 platforms. The hard part and the reason for this question is packaging it so that it works on as many modern Linux distributions as possible. The primary target will be Ubuntu 9. Webstart is not an acceptable way, .tar.gz is the last resort. I would stronly prefer a package that has correctly defined dependencies (such as Java) and installs easily. I also need to be able to build the package under a Windows environment since some tools in my build chain are Windows-only.
Start by looking at how a similar project has achieved this. One that springs to mind is [Freecol](http://www.freecol.org), a cross-platform Java-based game. Their [download page](http://www.freecol.org/download.html) has fairly clear information on installing it on a number of platforms. They also have packages available at sites such as [GetDEB](http://www.getdeb.net/app/FreeCol) for Ubuntu and [PackMan](http://packman.links2linux.org/package/freecol) for OpenSuse. Generally, if you want to hit as many distributions as possible, the formats you should consider are (in rough order of importance): 1. Ubuntu .deb (also create a repository if you can) 2. OpenSUSE .rpm or .ypm (1 click install) 3. Fedora .rpm 4. .tar.gz pre-compiled package Then a build from source option, or a best-effort binary installer. Finally, look at other popular distros such as Debian, Mandriva, and BSDs Once a package exists for a specific platform, you may wish to consider getting it accepted into that distribution. This will make it easier for users to find and acquire. Information on the process for ubuntu can be found here: * <https://wiki.ubuntu.com/UbuntuDevelopment/NewPackages> (EDIT: Better list, thanks to Jonik's suggestion.)
Have a look at Zero Install (<http://0install.net/>). * Anyone can install software You don't have to be the administrator just to install a word-processor [ more ] * Anyone can distribute software You don't need to be blessed by a distribution (or anyone else) to be part of Zero Install; The system is completely decentralised [ more ] * Automatic updates When updates are available, Zero Install will notify you[ more ] * Security If one user downloads a malicious program, other users aren't affected; Users can share downloads without having to trust each other; Installation does not execute any of the downloaded code; Digital signatures are always checked before new software is r
How to package a game for Linux?
[ "", "java", "linux", "software-distribution", "rpm", "deb", "" ]
I have a ListBox containing a group of 'Expander' items, and what I would like to do is make the `IsExpanded` property for each of them exclusive. For example, if I have 10 Expanders in the `ListBox`, I'd like only one to be open at a time. Here is what I have so far: ``` <Window> <Window.Resources> <DataTemplate x:Key="NormalTemplate"> <Expander Margin="0" IsExpanded="True" Header="{Binding Model.Name}" Background="Green"> <Grid> <StackPanel HorizontalAlignment="Stretch"> <TextBlock Text="{Binding Model.Description}" TextWrapping="Wrap" HorizontalAlignment="Stretch" Margin="0"/> </StackPanel> </Grid> </Expander> </DataTemplate> </Window.Resources> <Grid> <ListBox ItemsSource="{Binding Groups}" ItemTemplate="{DynamicResource NormalTemplate}" /> </Grid> </Window> ``` Is there any way to do this? I'm not tied to a `ListBox` or indeed Expanders, heck - I'm not tied to any of it if it needs to change.
What determines whether an `Expander` is expanded? If it's selection, you could bind the `IsExpanded` property to the `IsSelected` property of the `ListBoxItem`: ``` <Expander IsExpanded="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}" ...> ```
Since Kent Boogaart's answer did not work for me, I did like this: Note: I am using XAML Material Design and maybe it is the reason it does not work ``` <Style TargetType="{x:Type Expander}"> <EventSetter Event="Loaded" Handler="Expander_Loaded" /> <EventSetter Event="Expanded" Handler="Expander_Expanded" /> </Style> ``` ``` private readonly List<Expander> allExpanders = new(); private void Expander_Loaded(object sender, System.Windows.RoutedEventArgs e) { allExpanders.Add(sender as Expander); } private void Expander_Expanded(object sender, System.Windows.RoutedEventArgs e) { foreach (Expander exp in allExpanders.Where(exp => exp != sender)) { exp.IsExpanded = false; } } ```
Making a collection of WPF Expanders 'expand' exclusively, i.e. only one expanded at a time
[ "", "c#", "wpf", "data-binding", "listbox", "expander", "" ]
How can I read the value of a system environment variable in a T-SQL script? This is to run on SQL Server 2005.
This should give you a list (provided you allow people to execute xp\_cmdshell) exec master..xp\_cmdshell 'set' Note: xp\_cmdshell is a security hazard ... You could also do this with a managed stored proc an extended stored proc or via a com component.
To "read the value of a system environment variable in a T-SQL script" you can set SQL Management Studio to use "sqlcmd Mode". Then you can use like this: ``` Print '$(TEMP)' :r $(Temp)\Member.sql go ``` I'm not sure how this is done outside of "SQL Management Studio" but it should be hard to find out.
Using Environment variables in T-SQL
[ "", "sql", "sql-server-2005", "environment-variables", "" ]
> There is a list of numbers. > The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed. > > ``` > #Example: > >>>que = [2,3,10,5,8,9,7,3,5,2] > >>>make_teams(que) > 27 27 > ``` Is there an error in the following code algorithm for some case? How do I optimize and/or pythonize this? ``` def make_teams(que): que.sort() if len(que)%2: que.insert(0,0) t1,t2 = [],[] while que: val = (que.pop(), que.pop()) if sum(t1)>sum(t2): t2.append(val[0]) t1.append(val[1]) else: t1.append(val[0]) t2.append(val[1]) print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n" ``` Question is from <http://www.codechef.com/problems/TEAMSEL/>
**New Solution** This is a breadth-first search with heuristics culling. The tree is limited to a depth of players/2. The player sum limit is totalscores/2. With a player pool of 100, it took approximately 10 seconds to solve. ``` def team(t): iterations = range(2, len(t)/2+1) totalscore = sum(t) halftotalscore = totalscore/2.0 oldmoves = {} for p in t: people_left = t[:] people_left.remove(p) oldmoves[p] = people_left if iterations == []: solution = min(map(lambda i: (abs(float(i)-halftotalscore), i), oldmoves.keys())) return (solution[1], sum(oldmoves[solution[1]]), oldmoves[solution[1]]) for n in iterations: newmoves = {} for total, roster in oldmoves.iteritems(): for p in roster: people_left = roster[:] people_left.remove(p) newtotal = total+p if newtotal > halftotalscore: continue newmoves[newtotal] = people_left oldmoves = newmoves solution = min(map(lambda i: (abs(float(i)-halftotalscore), i), oldmoves.keys())) return (solution[1], sum(oldmoves[solution[1]]), oldmoves[solution[1]]) print team([90,200,100]) print team([2,3,10,5,8,9,7,3,5,2]) print team([1,1,1,1,1,1,1,1,1,9]) print team([87,100,28,67,68,41,67,1]) print team([1, 1, 50, 50, 50, 1000]) #output #(200, 190, [90, 100]) #(27, 27, [3, 9, 7, 3, 5]) #(5, 13, [1, 1, 1, 1, 9]) #(229, 230, [28, 67, 68, 67]) #(150, 1002, [1, 1, 1000]) ``` Also note that I attempted to solve this using GS's description, but it is impossible to get enough information simply by storing the running totals. And if you stored **both** the number of items and totals, then it would be the same as this solution except you kept needless data. Because you only need to keep the n-1 and n iterations up to numplayers/2. I had an old exhaustive one based on binomial coefficients (look in history). It solved the example problems of length 10 just fine, but then I saw that the competition had people of up to length 100.
[Dynamic programming](http://en.wikipedia.org/wiki/Dynamic_programming) is the solution you're looking for. Example with [4, 3, 10, 3, 2, 5]: ``` X-Axis: Reachable sum of group. max = sum(all numbers) / 2 (rounded up) Y-Axis: Count elements in group. max = count numbers / 2 (rounded up) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 | | | | 4| | | | | | | | | | | // 4 2 | | | | | | | | | | | | | | | 3 | | | | | | | | | | | | | | | ``` ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 | | | 3| 4| | | | | | | | | | | // 3 2 | | | | | | | 3| | | | | | | | 3 | | | | | | | | | | | | | | | ``` ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 | | | 3| 4| | | | | |10| | | | | // 10 2 | | | | | | | 3| | | | | |10|10| 3 | | | | | | | | | | | | | | | ``` ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 | | | 3| 4| | | | | |10| | | | | // 3 2 | | | | | | 3| 3| | | | | |10|10| 3 | | | | | | | | | | 3| | | | | ``` ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 | | 2| 3| 4| | | | | |10| | | | | // 2 2 | | | | | 2| 3| 3| | | | | 2|10|10| 3 | | | | | | | | 2| 2| 3| | | | | ``` ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 | | 2| 3| 4| 5| | | | |10| | | | | // 5 2 | | | | | 2| 3| 3| 5| 5| | | 2|10|10| 3 | | | | | | | | 2| 2| 3| 5| 5| | | ^ ``` 12 is our lucky number! Backtracing to get the group: ``` 12 - 5 = 7 {5} 7 - 3 = 4 {5, 3} 4 - 4 = 0 {5, 3, 4} ``` The other set can then be calculated: {4,3,10,3,2,5} - {5,3,4} = {10,3,2} All fields with a number are possible solutions for one bag. Choose the one that is furthest in the bottom right corner. BTW: It's called the [knapsack-problem](http://en.wikipedia.org/wiki/Knapsack_problem). > If all weights (w1, ..., wn and W) are > nonnegative integers, the knapsack > problem can be solved in > pseudo-polynomial time using dynamic > programming.
Algorithm to Divide a list of numbers into 2 equal sum lists
[ "", "python", "algorithm", "dynamic-programming", "np-complete", "knapsack-problem", "" ]
When should the Windows Registry be used for per-user state, and when should we use the filesystem, particularly the user's AppData folder? (eg, C:\Users\USERNAME\AppData). Where does Isolated Storage come in? Is there a pretty firm rule, or is it just a fuzzy thing, like "use the registry until it becomes too much data to store in the registry". or "use whatever you feel like using." Are there Windows logo requirements that affect the decision? If I use the AppData directory, how do I choose between Local, Roaming and LocalLow ? edit: I just noticed these similar questions: * [When and why should you store data in the Registry?](https://stackoverflow.com/questions/268424/when-and-why-should-you-store-data-in-the-windows-registry) * [Registry vs Ini file for storing user-configurable app settings](https://stackoverflow.com/questions/6607/registry-vs-ini-file-for-storing-user-configurable-application-settings). I will summarize replies.
If you have a small number of key/value pairs and the values aren't big the registry is great - and you don't care about xcopy deployment - then use the registry (I know this isn't exact, but it's usually obvious when working with the registry becomes a pain). If you want xcopy deployment the data must be in the same folder as the program obviously - but the program can be somewhere under the AppData folder, it doesn't have to be under "program files". Use isolated storage only when you need it or have to use it - for example ClickOnce. Otherwise use AppData\Roaming, use Local or LocalLow only if you have a good reason. EDIT: Here is the difference between Roaming, Local and LocalLow: Windows has a little known feature called "roaming profiles", the general idea is that in a corporate environment with this feature enabled any user can use any computer. When a user logs in his private settings are downloaded from the server and when he logs out his settings are uploaded back to the server (the actual process is more complicated, obviously). Files in the User's "Roaming" folder in Vista or "Application Data" in XP move around with the user - so any settings and data should be stored there. Files under "Local" and "LocalLow" in vista and "Local Settings" in XP do not, so it's a good place for temp files, things that are tied to the specific computer or data that can be recalculated. In Vista, as part of the new security features we all know and love, you can have programs running in "low integrity mode" (for example IE in protected mode), those programs are running with reduced privileges and can't access files in the user's profile - except for files under the "LocalLow" folder. So, in conclusion, files stored in "LocalLow" are inherently insecure and files in "Local"/"Local Settings" are likely to be unavailable in some large companies - so unless you have good reason and know exactly what you are doing go with "Roaming"/"Application Data".
Don't clutter up my Registry thank you. Use isolated storage, thats what it's for. See [Was The Windows Registry a Good Idea?](http://www.codinghorror.com/blog/archives/000939.html) On Jeffs Blog...
How to decide where to store per-user state? Registry? AppData? Isolated Storage?
[ "", "c#", "wpf", "windows", "winforms", "registry", "" ]
Simply put I want to call *public static* methods decorated with *WebMethod* attribute inside my code-behind C# file from *jquery.ajax* to get some json and other simple stuff (in different functions). But instead I'm getting whole page :'( I'm not using asp.net AJAX though I'm developing for .NET 3.5 framework and using VS 2008. (There are some restrictions from client) Please let me know if I can use page-methods with using asp.net ajax or If not what is other simple solution?
After much deliberations I found the problem. I was using [jquery's editable plugin](http://www.appelsiini.net/projects/jeditable). This was source of the problem. When jeditable calls jquery's ajax it sets ajax options like this: ``` var ajaxoptions = { type: 'POST', data: submitdata, url: settings.target, success: function(result, status) { if (ajaxoptions.dataType == 'html') { $(self).html(result); } self.editing = false; callback.apply(self, [result, settings]); if (!$.trim($(self).html())) { $(self).html(settings.placeholder); } }, error: function(xhr, status, error) { onerror.apply(form, [settings, self, xhr]); } }; ``` so it was sending the things as simple *html* and to use this with page methods we need to setup the things so that it sends as *json*. So we need to add something to the settings like this: ``` var ajaxoptions = { type: 'POST', data: submitdata, url: settings.target, dataType: 'json', //Data Type contentType: 'application/json; charset=utf-8', //Content Type //....other settings }; ``` So I put two new properties in settings **dataType** and **contentType** and changed above to this: ``` var ajaxoptions = { type: 'POST', data: submitdata, url: settings.target, dataType: settings.dataType, contentType: settings.contentType, //....other settings }; ``` Now another problem arised :( it was sending data (from **submitdata** property) as normal query-string which asp.net does not accept with *json* requests. So I had to use [jquery's json plugin](http://plugins.jquery.com/project/LABSJSON) and change the way data is sent in ajax using following test on dataType: ``` if (settings.dataType == "json") { if ($.toJSON) { submitdata = $.toJSON(submitdata); } } ``` and it works like breeze!!!
I am not sure but i think WebMethods are accessible only through asp.net AJAX. I may be wrong though, because we dont use it that way at all. We do it in a slightly different way. We have built a aspx page which accepts all our AJAX requests and passes them to the subsequent methods. **Server side code** ``` If Not (Request("method") Is Nothing) Then method = Request("method") username = HttpContext.Current.User.Identity.Name.ToString Select Case UCase(method) Case "GETPROJECTS" Response.ContentType = "text/json" Response.Write(GetProjects(Request("cid"), Request("status"))) Exit Select end select end if ``` **Client Side code [using jquery]** ``` $.ajaxSetup({ error: function(xhr, msg) { alert(xhr, msg) }, type: "POST", url: "Ajax.aspx", beforeSend: function() { showLoader(el); }, data: { method: 'GetProjects', cid: "2", status:"open"}, success: function(msg) { var data = JSON.parse(msg); alert(data.Message); }, complete: function() { hideLoader(el); } }); ``` Hope this helps.
Using PageMethods with jQuery
[ "", "c#", "asp.net", "asp.net-ajax", "jquery", "pagemethods", "" ]
Does anyone know of a Webmail Contact List Importer scripts (ColdFusion, PHP etc) like those used on Twitter and LinkedIn ? I've found some but they are paid for and I want some more bespoke & open. To clarify a little more I'm not looking for a way to process .csv files :) I'm looking for a bit of code that can logging into gmail, yahoo mail, hotmail, aol and pull out the users address book.
Are you actually after a method where a user enters their webmail username and password into your site and then your site goes off and grabs contact details from that account? If so, then it sounds like a can of worms to me, and is something that our very own Mr Atwood [blogged about](http://www.codinghorror.com/blog/archives/000953.html) a while back. I'd go with something along the lines of Evgeniy's answer. *(I would have just commented on the question but my woeful rep prevents me...)* (Edited to include the link to Jeff's blog now that I'm allowed)
You will likely need to use a library that can log into all of those services, and access their contact lists in their format, and extract them in one format. In other news, The [PHP/Curl book](http://curl.phptrack.com/get_page.php?fuseaction=downloads) seems to have it all done for $25 cost of the book. I would suspect whatever the code is in PHP, it would be about half with Coldfusion.
Webmail Contact List Importer
[ "", "php", "open-source", "coldfusion", "scripting", "webmail", "" ]
I'm looking for a library that will disassemble x86 code into some sort of object model that I can then use to write routines that analyze the code. I'm not interested in a library that converts x86 code to text disassembly--I've found more than a few of those, but they're not that useful since I want to do some work on top of the code that I disassemble. Oh, and I'd like it to be .Net code (VB or C# preferable).
Reflector doesn't do x86 as far as I know. Your best bet is using the scripting or COM interface to [OllyDbg](http://www.ollydbg.de/) or [IDA Pro](http://www.hex-rays.com/idapro/). I would recommend IDA Pro if you can afford it. IDA has a very rich API, active development and lots of documentation. You can run it in autonomous mode, I believe using the '-AS' switch. See <http://www.hex-rays.com/idapro/idadoc/417.htm> for more info on the command line arguments. I also ran into [libdasm](http://bastard.sourceforge.net/libdisasm.html), but never used it, so not sure how good it is. libdasm looks like C/C++ so it should be simple to write an API wrapper in C#.
An old question, but if someone else comes along and you are after a 100% C# .NET implementation rather than using interop, [SharpDisasm](https://sharpdisasm.codeplex.com) provides an x86/x86-64 disassembler to both Intel and AT&T syntax. It decodes each instruction to an object that provides access to low-level information about the instruction (e.g. instruction size, operand number and types etc). SharpDisasm is a full C# port of the [libudis86](https://github.com/vmt/udis86) C-library disassembler. The disassembler is exposed through the `SharpDisam.Disassembler` class. Output from the provided example console app: ``` C:\>echo a1 c9 fd ff ff a1 37 02 00 00 b8 37 02 00 00 b4 09 8a 25 09 00 00 00 8b 04 6d 85 ff ff ff 89 45 f0| disasmcli 32 00000000 a1 c9 fd ff ff mov eax, [0xfffffdc9] 00000005 a1 37 02 00 00 mov eax, [0x237] 0000000a b8 37 02 00 00 mov eax, 0x237 0000000f b4 09 mov ah, 0x9 00000011 8a 25 09 00 00 00 mov ah, [0x9] 00000017 8b 04 6d 85 ff ff ff mov eax, [ebp*2-0x7b] 0000001e 89 45 f0 mov [ebp-0x10], eax C:\>echo 488b05f7ffffff67668b40f06766035e1048030425ffff 000067660344bef04c0384980000008048a10000000000800000 | disasmcli 64 0000000000000000 48 8b 05 f7 ff ff ff mov rax, [rip-0x9] 0000000000000007 67 66 8b 40 f0 mov ax, [eax-0x10] 000000000000000c 67 66 03 5e 10 add bx, [esi+0x10] 0000000000000011 48 03 04 25 ff ff 00 00 add rax, [0xffff] 0000000000000019 67 66 03 44 be f0 add ax, [esi+edi*4-0x10] 000000000000001f 4c 03 84 98 00 00 00 80 add r8, [rax+rbx*4-0x80000000] 0000000000000027 48 a1 00 00 00 00 00 80 00 00 mov rax, [0x800000000000] ```
Are there any good VB/C# x86 disassembler libraries?
[ "", "c#", "vb.net", "x86", "disassembly", "" ]
Is it possible to add a list to a struct? ``` public struct test { public string x; list<string> y = new list<string>(); } ``` something like that? ive been trying but im just not getting it
Yes you can have a list in struct but you cannot initialise it with a field initialiser and instead you must use the constructor. ``` struct MyStruct { public List<string> MyList; public int MyInt; public MyStruct(int myInt) { MyInt = myInt; MyList = new List<string>(); } } ```
struct can have a constructor and you can instantiate the list in the constructor.
is it possible to add a list to a structure?
[ "", "c#", "list", "data-structures", "" ]
Referring to [this question](https://stackoverflow.com/questions/889319/how-to-calculate-approximately-the-connection-speed-of-a-website-using-javascript) , how can i get the current page size in kb, this size i will use to know the connection speed for this page.
Unless your page has size in megabytes, the result will be meaningless. This is because time needed to connect, send request, and wait for server to send reply back is [quite large](http://webkit.org/blog/166/optimizing-page-loading-in-web-browser/) compared to time required to download the page, and in addition to that TCP/IP has [slow start](http://en.wikipedia.org/wiki/Slow-start). You also have to take into account caches, proxies and number of parallel connections that browser will make (e.g. may prioritize download of scripts and styles, making page download time appear slow).
if you mean just the html then you can use jQuery to do get the number of characters (bytes in most cases, depending on the encoding) ``` $(document).ready( function() { var pagebytes = $('html').html().length; var kbytes = pagebytes / 1024; } ); ``` this basically counts number of characters contained within (including) tag. that will exclude any Doctype specified, but since that would be static always you can add length of doctype to pagebytes. **//Edit** looks like doctype in the end may not be static. but without it, it still should be accurate enough.
How to get current page size in KB using just javascript?
[ "", "javascript", "html", "widget", "" ]
Is it possible to pull a bunch of .jpg pictures form a local file and throw them into a list? *Sorry, I was very vague* Pulling from a directory (relitive to the index) like. I want to list them in an image tag, sequentially.
You could use the following to dynamically create an image and append it to a list. ``` $('<img />') .attr('src', 'FOLDER LOCATION HERE') .appendTo('#mylist') ``` some quick searching led me to find a FileSystemObject ( ActiveX =( ) to search a folder for files. here is a link: <http://www.codeproject.com/KB/scripting/search_in_files.aspx> but if you are doing any server side processing (.net, php, whatever) that would be the best way to figure out what images are available to you to display on the page. (so if you could clarify)
Are you saying you have a local text file filled with the locations of images? ``` <?php $handle = fopen("localfile.txt", 'r'); echo '<ul>'; while ($line = gets($handle)) { echo '<li><img src="' . $line . '"/></li>'; } echo '</ul>'; fclose($handle); ?> ```
jQuery pull images from directory
[ "", "javascript", "jquery", "directory", "image", "" ]
How to serialize Multiple Objects of the same Class into a single file and Deserialze into Those objects in c#
Serialize and deserialize an array of those objects.
Try something like this: ``` using (FileStream output = new FileStream("C:\\peoplearray.dat", FileMode.CreateNew)) { BinaryFormatter bformatter = new BinaryFormatter(); bformatter.Serialize(output, new Person[] { new Person{Firstname="Alex"} }); } using (FileStream input = new FileStream("C:\\peoplearray.dat", FileMode.Open)) { BinaryFormatter bformatter = new BinaryFormatter(); var results = bformatter.Deserialize(input) as Person[]; foreach (Person p in results) { Console.WriteLine(p.Firstname); } } ``` So long as person is [Serializable] this will work
How to Serialize Multiple Objects of the SAme Class into a single file and Deseialze into Those objects in c#
[ "", "c#", "serialization", "" ]
**Edit:** I've retitled this to an example as the code works as expected. I am trying to copy a file, get a MD5 hash, then delete the copy. I am doing this to avoid process locks on the original file, which another app writes to. However, I am getting a lock on the file I've copied. ``` File.Copy(pathSrc, pathDest, true); String md5Result; StringBuilder sb = new StringBuilder(); MD5 md5Hasher = MD5.Create(); using (FileStream fs = File.OpenRead(pathDest)) { foreach(Byte b in md5Hasher.ComputeHash(fs)) sb.Append(b.ToString("x2").ToLower()); } md5Result = sb.ToString(); File.Delete(pathDest); ``` I am then getting a 'process cannot access the file' exception on `File.Delete()`'. I would expect that with the `using` statement, the filestream would be closed nicely. I have also tried declaring the filestream separately, removing `using`, and putting `fs.Close()` and `fs.Dispose()` after the read. After this, I commented out the actually md5 computation, and the code excutes, with the file being deleted, so it looks like it's something to do with `ComputeHash(fs)`.
I took your code put it in a console app and ran it with no errors, got the hash and the test file is deleted at the end of execution? I just used the .pdb from my test app as the file. What version of .NET are you running? I am putting the code that I have that works here, and if you put this in a console app in VS2008 .NET 3.5 sp1 it runs with no errors (at least for me). ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.IO; namespace lockTest { class Program { static void Main(string[] args) { string hash = GetHash("lockTest.pdb"); Console.WriteLine("Hash: {0}", hash); Console.ReadKey(); } public static string GetHash(string pathSrc) { string pathDest = "copy_" + pathSrc; File.Copy(pathSrc, pathDest, true); String md5Result; StringBuilder sb = new StringBuilder(); MD5 md5Hasher = MD5.Create(); using (FileStream fs = File.OpenRead(pathDest)) { foreach (Byte b in md5Hasher.ComputeHash(fs)) sb.Append(b.ToString("x2").ToLower()); } md5Result = sb.ToString(); File.Delete(pathDest); return md5Result; } } } ```
Import the name space ``` using System.Security.Cryptography; ``` Here is the function that returns you md5 hash code. You need to pass the string as parameter. ``` public static string GetMd5Hash(string input) { MD5 md5Hash = MD5.Create(); // Convert the input string to a byte array and compute the hash. byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); // Create a new Stringbuilder to collect the bytes // and create a string. StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } // Return the hexadecimal string. return sBuilder.ToString(); } ```
C# MD5 hasher example
[ "", "c#", "hash", "md5", "" ]
I'm trying to perform barcode recognition on a multipage tiff file. But the tiff file is coming to me from a fax server (which I don't have control over) that saves the tiff with a non-square pixel aspect ratio. This is causing the image to be badly squashed due to the aspect ratio. I need to convert the tiff to a square pixel aspect ratio, but have no idea how to do that in C#. I'll also need to stretch the image so that changing the aspect ratio still makes the image legible. Has anyone done this in C#? Or has anyone used an image library that will perform such a procedure?
In case anyone else out there runs into the same issue, here is the super simple way I ended up fixing this annoying issue. ``` using System.Drawing; using System.Drawing.Imaging; // The memoryStream contains multi-page TIFF with different // variable pixel aspect ratios. using (Image img = Image.FromStream(memoryStream)) { Guid id = img.FrameDimensionsList[0]; FrameDimension dimension = new FrameDimension(id); int totalFrame = img.GetFrameCount(dimension); for (int i = 0; i < totalFrame; i++) { img.SelectActiveFrame(dimension, i); // Faxed documents will have an non-square pixel aspect ratio. // If this is the case,adjust the height so that the // resulting pixels are square. int width = img.Width; int height = img.Height; if (img.VerticalResolution < img.HorizontalResolution) { height = (int)(height * img.HorizontalResolution / img.VerticalResolution); } bitmaps.Add(new Bitmap(img, new Size(width, height))); } } ```
Oh, I forgot to mention. `Bitmap.SetResolution` may help with the aspect ratio issues. The below stuff is just about resizing. Check out [This page](http://www.codeproject.com/KB/GDI-plus/imageprocessing4.aspx). It discusses two mechanisms for resizing. I suspect in your case bilinear filtering is actually a bad idea, since you probably want things nice and monochrome. Below is a copy of the naive resize algorithm (written by Christian Graus, from the page linked above), which should be what you want. ``` public static Bitmap Resize(Bitmap b, int nWidth, int nHeight) { Bitmap bTemp = (Bitmap)b.Clone(); b = new Bitmap(nWidth, nHeight, bTemp.PixelFormat); double nXFactor = (double)bTemp.Width/(double)nWidth; double nYFactor = (double)bTemp.Height/(double)nHeight; for (int x = 0; x < b.Width; ++x) for (int y = 0; y < b.Height; ++y) b.SetPixel(x, y, bTemp.GetPixel((int)(Math.Floor(x * nXFactor)), (int)(Math.Floor(y * nYFactor)))); return b; } ``` An alternative mechanism is to abuse the `GetThumbNailImage` function like [this](http://snippets.dzone.com/posts/show/4336). That code maintains aspect ratio, but removing the code that does that should be simple.
Change tiff pixel aspect ratio to square
[ "", "c#", "tiff", "barcode", "aspect-ratio", "" ]
I'm looking for a Log4J Layout/Formatter that helps me prune stack-traces in exceptions a little better than the defaults. That the stack-execution is somewhere below main() is quite obvious and unnecessary for me to know, and that the exception occurred deeply within some other library is really nothing I can do too much about. What I would like is a Layout that trims the stack-trace to, say the last 5 method-calls of method within my own code, identified by containing jar-file, package or something else. Is there something along these lines, or do I have to write some magic myself?
I tried looking for this as well but didn't find anything satisfactory so I wrote up a custom ThrowableRenderer which prunes out extraneous stack frames. I've open sourced the code for others to use. Check out my [blog post](http://blog.delphix.com/zubair/log4j-stack-trace-pruning/) on it; you can find a link to the code there.
I asked a [similar question (about completely suppressing the stack trace](https://stackoverflow.com/questions/348582/how-can-i-configure-log4j-to-not-print-the-exception-stacktrace) a while back. Unfortunately, there is no setting for that, you need to subclass PatternLayout to do it.
Is there a Log4J Layout/Formatter that prunes Stack Traces for exceptions?
[ "", "java", "exception", "log4j", "" ]
Other than reading the `GetFileName()` file and reading to line `GetFileLineNumber()` of a stackframe from ``` new StackTrace(exception).GetFrame(x) ``` is there a way to get the actual line of code (as a string) which caused an exception? Thanks
Post moretem debugging is difficult, but not impossible. There are tools you can use ([here](http://www.microsoft.com/downloads/details.aspx?FamilyID=28bd5941-c458-46f1-b24d-f60151d875a3&displaylang=en) and [here](http://www.microsoft.com/whdc/devtools/debugging/default.mspx) for example) as well as [techniques](http://blogs.msdn.com/tess/archive/2009/03/20/debugging-a-net-crash-with-rules-in-debug-diag.aspx).
I don't think so. The code is compiled, therefore it is no longer available. However, if you *also* have the source code available, there may be a few workarounds.
Can I get the line of code that caused an exception?
[ "", "c#", "exception", "" ]
Here is a simple sorting program of an ArrayList: ``` ArrayList<String> list = new ArrayList<String>(); list.add("1_Update"); list.add("11_Add"); list.add("12_Delete"); list.add("2_Create"); Collections.sort(list); for (String str : list) { System.out.println(str.toString()); } ``` I was expecting the output of this program as: ``` 1_Update 2_Create 11_Add 12_Delete ``` But when I run this program I am getting output as: ``` 11_Add 12_Delete 1_Update 2_Create ``` Why is this and how do I get the ArrayList to sort as shown in the expected output?
You could write a custom comparator: ``` Collections.sort(list, new Comparator<String>() { public int compare(String a, String b) { return Integer.signum(fixString(a) - fixString(b)); } private int fixString(String in) { return Integer.parseInt(in.substring(0, in.indexOf('_'))); } }); ```
When you sort this type of data as a string, it is comparing the characters themselves, including the digits. All of the string that begin with "1", for example, will end up together. So the order ends up similar to this... 1 10 100 2 20 200 At no point does the sort "realize" that you are assigning meaning to subsets of the string, such as the variable length numbers at the front of the string. When sorting numbers as strings, padding to the left with zeros as much as required to cover the largest number can help, but it does not really solve the problem when you don't control the data, as in your example. In that case, the sort would be... 001 002 010 020 100 200
How can I sort this ArrayList the way that I want?
[ "", "java", "sorting", "arraylist", "" ]
I need some help with a textbox: The textbox is only allowed to contain letters. how do I do this?
You could do this with javascript to filter out which charaters you accept, but if you can use Asp.net AJAX then you can add a FilteredTextBoxExtender to the textbox and only allow upper case and/or lower case letters. To add a FilteredTextBoxExtender in Visual Studio 2008 you can do the following: * view the page in design mode and find the textbox * click the arrow on the right side of the textbox to open the TextBox Tasks menu and select Add Extender. * Then select the FilteredTextBoxExtender and click OK * Now your textbox should have a new property available in the designer. Make sure the textbox is selected and click F4 to open the properties designer. * Find the new property in the property designer. It should be named YOURTEXTBOXNAME\_FilteredTextBoxExtender. Find the FilterType property and select UppercaseLetters or LowercaseLetters. * If you want both upper case and lower case letters you must edit the markup directly and set its value to "UppercaseLetters, LowercaseLetters"
Check here : [How to make Textbox only accept alphabetic characters](https://stackoverflow.com/questions/790378/how-do-i-make-textbox-to-only-accept-alphabets-appear-error-if-is-not-an-alphabet/), there are some different approached to choose from. Edit: I see on the tags that we are talking asp.net, which the question I mentioned discusses the problem from a WinForms perspective. Might be that you want to do something similar using the onKeyPress event in JavaScript instead. [This article on w3schools.com](http://www.w3schools.com/jsref/jsref_onkeypress.asp) contains an example code that may do exactly what you are looking for.
textbox allow only letters
[ "", "c#", "asp.net", "" ]
I need the JavaScript code to iterate through the filled attributes in an HTML element. This [Element.attributes](http://reference.sitepoint.com/javascript/Node/attributes) ref says I can access it via index, but does not specify whether it is well supported and can be used (cross-browser). Or any other ways? (without using any frameworks, like jQuery / Prototype)
This would work in IE, Firefox and Chrome (can somebody test the others please? — Thanks, @Bryan): ``` for (var i = 0; i < elem.attributes.length; i++) { var attrib = elem.attributes[i]; console.log(attrib.name + " = " + attrib.value); } ``` EDIT: IE iterates *all* attributes the DOM object in question supports, no matter whether they have actually been defined in HTML or not. You must look at the `attrib.specified` Boolean property to find out if the attribute actually exists. Firefox and Chrome seem to support this property as well: ``` for (var i = 0; i < elem.attributes.length; i++) { var attrib = elem.attributes[i]; if (attrib.specified) { console.log(attrib.name + " = " + attrib.value); } } ```
Another method is to convert the attribute collection to an array using [`Array.from`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from): ``` Array.from(element.attributes).forEach(attr => { console.log(`${attr.nodeName}=${attr.nodeValue}`); }) ```
How to iterate through all attributes in an HTML element?
[ "", "javascript", "html", "dom", "" ]
My app is expanding, but the reqs dictate that there should be only one window open at all times, think of Nodepad where there is a menu, with each menu item different functionality but only one window open at all times as opposed to Excel where a user may have few windows open at once. So in terms of Windows forms, I was thinking of placing a form within a main form. Then i could load an embedded form needed depending on the user menu choice. OR I could be adding controls to the main form (and their events dynamically depending on the user menu choice). I would use a presenter class for that. That's just two solution I would use. Do you guys have any tips/experience on how to do it better? I realize now that I would have to re-write parts of my app, but let's pretend i am starting from scratch.
Don't embed Forms, it's not what Forms are for. And it's not necessary. Put the UI of your modules/sections on UserControls. That keeps it nice and modular and you keep your options open: those UserControls can be directly embedded (1 at a time) in the MainForm or in MDI ChildWindows or in TabPages or ... Use a Base UserControl (Visual Inheritance) and/or a Interface to implement common functionality.
It sounds like what you are describing is [Multiple-Document Interface (MDI) Applications](http://msdn.microsoft.com/en-us/library/aa983667(VS.71).aspx). Fortunately, there is great support for MDI in WinForms. Here's a quick [intro](http://www.dotnetjunkies.com/quickstart/winforms/doc/WinFormsMDI.aspx).
Design pattern for a single form Windows Forms application
[ "", "c#", "winforms", "design-patterns", "" ]
Duplicate of: [There is a function to use pattern matching (using regular expressions) in C++?](https://stackoverflow.com/questions/329517/there-is-a-function-to-use-pattern-matching-using-regular-expressions-in-c) I'm not sure where one would use it... are there any parser-type functions that take some regex as an argument or something? I just found out that my editor will highlight a line after / as "regex" for C/C++ syntax which I thought was weird...
In the vanilla C++ language there is no support for regular expressions. However there are several libraries available that support Regex's. Boost is a popular one. Check out Boost's Regex implementation. * <http://www.onlamp.com/pub/a/onlamp/2006/04/06/boostregex.html> * <http://www.boost.org/doc/libs/1_39_0/libs/regex/doc/html/boost_regex/syntax.html>
[PCRE](http://www.pcre.org/) is the de-facto standard regex library for C (and it also works in C++). (What your editor is doing I don't know. Using a library like PCRE or any of the others suggested doesn't change the syntax of C - your regex definitions will always be held in strings.)
is it possible to use regex in c++?
[ "", "c++", "c", "regex", "" ]
I have the following statement: ``` SELECT CASE WHEN (1 = 1) THEN 10 ELSE dbo.at_Test_Function(5) END AS Result ``` I just want to confirm that in this case the function wont be executed? My reason for asking is that the function is particularly slow and if the critiria is true I want to avoid calling the function... Cheers Anthony
Do not make this assumption, it is **WRONG**. The Query Optimizer is completely free to choose the evaluation order it pleases and SQL as a language does NOT offer operator short-circuit. Even if you may find in testing that the function is never evaluated, in production you may hit every now and then conditions that cause the server to choose a different execution plan and first evaluate the function, then the rest of the expression. A typical example would be when the server notices that the function return is deterministic and not depending on the row data, in which case it would first evaluate the function to get the value, and *after* that start scanning the table and evaluate the WHERE inclusion criteria using the function value determined beforehand.
Your assumpion is correct - it won't be executed. I understand your concern, but the CASE construct is "smart" in that way - it doesn't evaluate any conditions after the first valid condition. Here's an example to prove it. If both branches of this case statement were to execute, you would get a "divide by zero" error: ``` SELECT CASE WHEN 1=1 THEN 1 WHEN 2=2 THEN 1/0 END AS ProofOfConcept ``` Does this make sense?
Calling a function from within a select statement - SQL
[ "", "sql", "sql-server", "performance", "user-defined-functions", "" ]
While rendering the view page, based on some condition in the controller action I want to disable all the controls (textbox, checkbox, button etc) present in the form in a MVC view page. Is there any way to do that? Please help.
you can pass a flag to the view to indcate that it must disable all the controls. here is an example: ``` public ActionResult MyAction() { ViewData["disablecontrols"] = false; if (condition) { ViewData["disablecontrols"] = true; } return View(); } ``` In the view(using jQuery): ``` <script type="text/javascript"> $(document).ready(function() { var disabled = <%=ViewData["disablecontrols"].ToString()%>; if (disabled) { $('input,select').attr('disabled',disabled); } }) </script> ```
That really depends on how your controls are being rendered. We do something similar in practice, except we set controls to read only. This is to allow us to re-use show (read-only) and edit views. The way I would personally recommend to do it is to have a read-only flag that is set in the view using a value in ViewData. From there, write some helper methods to distinguish between disabled and non-disabled markup. You can build this markup yourself, or wrap the existing HtmlHelper methods ASP.NET MVC provides. ``` // In your controller ViewData["DisableControls"] = true; <%-- In your view --%> <% bool disabled = ViewData["DisableControls"] as bool; %> ... <%= Html.TextBox("fieldname", value, disabled) %> <%= Html.CheckBox("anotherone", value, disabled) %> // In a helper class public static string TextBox(this HtmlHelper Html, string fieldname, object value, bool disabled) { var attributes = new Dictionary<string, string>(); if (disabled) attributes.Add("disabled", "disabled"); return Html.TextBox(fieldname, value, attributes); } ``` The way we do it is to use the Page\_Load(), as you would in WebForms, to disable server controls. We built some custom server controls to handle our form fields. This was in ASP.NET MVC's infancy, and I wouldn't recommend doing this, but it's an alternative.
Disable all controls (textbox, checkbox, button etc) in a View (ASP.NET MVC)
[ "", "c#", "asp.net", "asp.net-mvc", "" ]
Is there something equivalent to OmniCppComplete for java in vim ? I know of eclim but I think it is overkill for such a simple feature.
See <http://www.vim.org/scripts/script.php?script_id=1785>
Also found VJDE - <http://www.vim.org/scripts/script.php?script_id=1213> - Need to evaluate which one is better/more up-to-date
Vim Java code completion?
[ "", "java", "vim", "" ]
I have a common comms library that i have written to communicate with our hardware over TCP/IP The common library allows both the clients application and our engineer tool to share common code. The common library runs threads that need to return data back to forms. I have some working code but I feel that there must be an easier way to do it. This is a simplified version of what i have... ``` namespace EngineerTool { public delegate void DelegateSearchFinished(); public partial class MainForm : Form { public DelegateSearchFinished d_SearchFinished; Discover discovery; public MainForm() { InitializeComponent(); discovery = new Discover(this.FinishedSearchInvoke); d_SearchFinished = new DelegateSearchFinished(this.FinishedSearch); discovery.Start(); } public void FinishedSearchInvoke() { this.Invoke(this.d_SearchFinished, new Object[] {}); } public void FinishedSearch() { // Search has finished here! } } } namespace DiscoveryTool { public delegate void DelegateSearchFinished(); public class Discover { DelegateSearchFinished _callFinished; public Discover(DelegateSearchFinished callFinished) { _callFinished = callFinished; } public void Start() { // starts thread and stuff } public void ThreadWorker() { _callFinished(); } } } ```
What about creating an event on the Discover class and the Form subscribes to the event, instead of passing delegates around.
Take a look at the BackgroundWorker class: [BackgroundWorker Component Overview](http://msdn.microsoft.com/en-us/library/8xs8549b.aspx)
Passing data back from external dll with threads
[ "", "c#", "multithreading", "dll", "delegates", "" ]
I wanted to check whether the variable is defined or not. For example, the following throws a not-defined error ``` alert( x ); ``` How can I catch this error?
In JavaScript, `null` is an object. There's another value for things that don't exist, `undefined`. The DOM returns `null` for almost all cases where it fails to find some structure in the document, but in JavaScript itself `undefined` is the value used. Second, no, there is not a direct equivalent. If you really want to check for specifically for `null`, do: ``` if (yourvar === null) // Does not execute if yourvar is `undefined` ``` If you want to check if a variable exists, that can only be done with `try`/`catch`, since `typeof` will treat an undeclared variable and a variable declared with the value of `undefined` as equivalent. But, to check if a variable is declared *and* is not `undefined`: ``` if (yourvar !== undefined) // Any scope ``` Previously, it was necessary to use the `typeof` operator to check for undefined safely, because it was possible to reassign `undefined` just like a variable. The old way looked like this: ``` if (typeof yourvar !== 'undefined') // Any scope ``` The issue of `undefined` being re-assignable was fixed in ECMAScript 5, which was released in 2009. You can now safely use `===` and `!==` to test for `undefined` without using `typeof` as `undefined` has been read-only for some time. If you want to know if a member exists independent but don't care what its value is: ``` if ('membername' in object) // With inheritance if (object.hasOwnProperty('membername')) // Without inheritance ``` If you want to to know whether a variable is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy): ``` if (yourvar) ``` [Source](http://lists.evolt.org/archive/Week-of-Mon-20050214/099714.html)
The only way to truly test if a variable is `undefined` is to do the following. Remember, undefined is an object in JavaScript. ``` if (typeof someVar === 'undefined') { // Your variable is undefined } ``` Some of the other solutions in this thread will lead you to believe a variable is undefined even though it has been defined (with a value of NULL or 0, for instance).
How to check a not-defined variable in JavaScript
[ "", "javascript", "variables", "undefined", "" ]
Sorry if this is a dup; I haven't found any questions that pose quite this same problem. The issue is illustrated by this screenshot, ironically taken from [a CSS blog site](http://nettuts.com/html-css-techniques/solving-5-common-css-headaches/) (it's immediately below the text "In order to set a positioning context".) I've been hitting the same issue in my own code. About halfway down this image, there's a line with a long comment that forces the enclosing `div` to provide a horizontal scrollbar (via the `overflow: auto` setting.) As shown in the screenshot, the surrounding lines with gray backgrounds don't stretch to fill the entire width of the parent's canvas. Instead, they remain fixed at the width of the parent's **viewport**. (Those backgrounds belong to `div`s that enclose individual lines of text.) I see this in Firefox 3.1 and IE8 (regardless of IE7 compatibility mode.) Is there any cross-browser method to force those child `div`s to stretch to the full width of the canvas (or put another way, to set their widths to the max width of their peers)? My guess is "no", or the site's author would be using it. [![alt text](https://i.stack.imgur.com/NafHA.jpg)](https://i.stack.imgur.com/NafHA.jpg) (source: [outofwhatbox.com](http://outofwhatbox.com/images/nettuts-css.jpg)) **EDIT**: Here is a bare-bones example. For some reason, the scrollbar doesn't show in IE, but it does show in Firefox 3.1 (and with the same behavior that I'm seeing elsewhere.) ``` Note: The CSS shown here is derived from SyntaxHighlighter (http://alexgorbatchev.com/), released under GPL 3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>sample</title> <style type="text/css"> .syntaxhighlighter .line.alt1 .content { background-color:#FFFFFF !important; } .syntaxhighlighter .line .content { color:#000000 !important; display:block !important; font-family: "Consolas","Monaco","Bitstream Vera Sans Mono","Courier New",Courier,monospace; font-size: 12pt; font-weight: 400; color: #000000; white-space: nowrap; } .syntaxhighlighter .line.alt2 .content { background-color:#F0F0F0 !important; } .syntaxhighlighter { background-color:#E7E5DC !important; margin:1em 0 !important; padding:1px !important; width:497px !important; height: auto !important; } .line { overflow:visible !important; } .lines { overflow-x:auto !important; } </style> </head> <body> <div class="syntaxhighlighter" > <div class="lines"> <div class="line alt1"> <span class="content"> <span style="margin-left: 0px ! important;" class="block"> <code class="plain">this is line 1 </code> </span> </span> </div> <div class="line alt2"> <span class="content"> <span style="margin-left: 20px ! important;" class="block"> <code class="plain">this is line 2</code> </span> </span> </div> <div class="line alt1"> <span class="content"> <span style="margin-left: 40px ! important;" class="block"> <code class="plain">this is a very very very very very very long line number 3</code> </span> </span> </div> <div class="line alt2"> <span class="content"> <span style="margin-left: 0px ! important;" class="block"> <code class="keyword">this is line 4</code> </span> </span> </div> <div class="line alt1"> <span class="content"> <span style="margin-left: 20px ! important;" class="block"> <code class="plain">and this is line 5.</code> </span> </span> </div> </div> </div> ``` **UPDATE** 2009/05/14: Here's the script that I've deployed, based on [brianpeiris's answer](https://stackoverflow.com/questions/815443/expand-div-children-to-width-of-the-canvas-not-just-the-viewport/815549#815549) below. In case anyone's interested, here's a [more detailed description](http://www.outofwhatbox.com/blog/2009/05/fixing-a-scroll-where-the-grays-came-in/) of the changes that were needed. ``` // Ensure that each content <span> is sized to fit the width of the scrolling region. // (When there is no horizontal scrollbar, use the width of the parent.) fixContentSpans : function() { jQuery('.syntaxhighlighter > div.lines').each(function(){ var container = jQuery(this); var scrollWidth = this.scrollWidth; var width = jQuery(this).width(); var contents = container.find('.content'); jQuery(contents).each(function(){ var child = jQuery(this); var widthAvail = scrollWidth - parseFloat(child.css("margin-left")) - parseFloat(child.css("padding-left")) - parseFloat(child.css("padding-right")); var borderLeft = parseFloat(child.css("border-left-width")); // IE uses names (e.g. "medium") for border widths, resulting in NaN // when we parse the value. Rather than trying to get the numeric // value, we'll treat it as 0. This may add a few additional pixels // in the scrolling region, but probably not enough to worry about. if (!isNaN(borderLeft)) { widthAvail -= borderLeft; } child.width(widthAvail); }); }); }, ```
If you don't mind a bit of jQuery, run the following code in Firebug on the nettuts+ website to fix the problem. ``` $('.dp-highlighter').each(function(){ var container = $(this); if(this.scrollWidth !== $(this).width()) { container.children().each(function(){ var child = $(this); var childPaddingLeft = parseInt(child.css('paddingLeft').slice(0, -2)); child.width(container.get(0).scrollWidth - childPaddingLeft); }); } }); ``` **Edit:** Seems to work in IE7/8 as well. **Further Edit:** Here's the JavaScript necessary to fix the code you provided: ``` $('.syntaxhighlighter > div').each(function(){ var container = $(this); if(this.scrollWidth !== $(this).width()) { container.find('.content').each(function(){ var child = $(this); child.width(container.get(0).scrollWidth); }); } }); ``` ## Demo I've hosted your code on JS Bin with the JavaScript fix: <http://jsbin.com/axeso>
I don't think there is a way to stretch the divs to be the whole width. The problem is that the text isn't really inside of the div. It is overflowing outside of the div of the line (that contains the shading) One solution is to use a table. Use a table row to hold each row of the source code. Following is a code sample. The first container uses divs, and the second uses a table. ``` <style> .container { width: 300px; overflow: auto; } .lineA { height: 20px; overflow: visible; } .lineB { height: 20px; background-color: #888888; overflow: visible; } </style> <div class="container"> <div class="lineA">Hello World</div> <div class="lineB">Hello World</div> <div class="lineA">Hello World</div> <div class="lineB">Hello World</div> <div class="lineA">Really&nbsp;Long&nbsp;Line.&nbsp;Really&nbsp;Long&nbsp;Line.&nbsp;Really&nbsp;Long&nbsp;Line.&nbsp;Really&nbsp;Long&nbsp;Line.&nbsp;Really&nbsp;Long&nbsp;Line.&nbsp;Really&nbsp;Long&nbsp;Line.</div> <div class="lineB">Hello World</div> </div> <div class="container"> <table> <tr><td class="lineA">Hello World</td></tr> <tr><td class="lineB">Hello World</td></tr> <tr><td class="lineA">Hello World</td></tr> <tr><td class="lineB">Hello World</td></tr> <tr><td class="lineA">Really&nbsp;Long&nbsp;Line.&nbsp;Really&nbsp;Long&nbsp;Line.&nbsp;Really&nbsp;Long&nbsp;Line.&nbsp;Really&nbsp;Long&nbsp;Line.&nbsp;Really&nbsp;Long&nbsp;Line.&nbsp;Really&nbsp;Long&nbsp;Line.</td></tr> <tr><td class="lineB">Hello World</td></tr> </table> </div> ``` Here is a screenshot: [alt text http://img354.imageshack.us/img354/9418/csstest.png](http://img354.imageshack.us/img354/9418/csstest.png)
Expand div children to width of the canvas, not just the viewport?
[ "", "javascript", "html", "css", "" ]
So, as the title says, when GWT compiles Java into JavaScript, is the result just minified, or is it obfuscated also?
According to the [GWT FAQ](http://code.google.com/support/bin/answer.py?answer=55203&topic=10212) the code is obfuscated, but they state that "This is partly done to protect the intellectual property of the application you develop, but also because obfuscation reduces the size of the generated JavaScript files". I'm not sure if this is true obfuscation or just variable/method renaming and stripping of whitespaces. A "true" obfuscation might actually make the code larger than the original code.
I'd also like to say that the GWT compiler minifies Js because of its optimization. It will, for example, inline method calls where possible and rename variables to shorter names.
Is GWT compiled JavaScript obfuscated or only minified?
[ "", "javascript", "gwt", "" ]
How do you update this environment variable at runtime so that ctypes can load a library wherever? I've tried the following and neither seem to work. ``` from ctypes import * os.environ['LD_LIBRARY_PATH'] = "/home/starlon/Projects/pyCFA635/lib" os.putenv('LD_LIBRARY_PATH', "/home/starlon/Projects/pyCFA635/lib") lib = CDLL("libevaluator.so") ```
By the time a program such as Python is running, the dynamic loader (ld.so.1 or something similar) has already read LD\_LIBRARY\_PATH and won't notice any changes thereafter. So, unless the Python software itself evaluates LD\_LIBRARY\_PATH and uses it to build the possible path name of the library for `dlopen()` or an equivalent function to use, setting the variable in the script will have no effect. Given that you say it doesn't work, it seems plausible to suppose that Python does not build and try all the possible library names; it probably relies on LD\_LIBRARY\_PATH alone.
Even if you give a fully qualified path to CDLL or cdll.LoadLibrary(), you may still need to set LD\_LIBRARY\_PATH before invoking Python. If the shared library you load explicitly refers to another shared library and no "rpath" is set in the .so for that library, then it won't be found, even if it has already been loaded. An rpath in a library specifies a search path to be used to search for other libraries needed by that library For example, I have a case of a set of interdependent third-party libraries not produced by me. b.so references a.so. Even if I load a.so in advance: ``` ctypes.cdll.LoadLibrary('/abs/path/to/a.so') ctypes.cdll.LoadLibrary('/abs/path/to/b.so') ``` I get an error on the second load, because b.so refers to simply 'a.so', without an rpath, and so b.so doesn't know that's the correct a.so. So I have to set LD\_LIBRARY\_PATH in advance to include '/abs/path/to'. To avoid having to set LD\_LIBRARY\_PATH, you modify the rpath entry in the .so files. On Linux, there are two utilities I found that do this: chrpath, and [patchelf](http://nixos.org/patchelf.html). chrpath is available from the Ubuntu repositories. It cannot change rpath on .so's that never had one. patchelf is more flexible.
Changing LD_LIBRARY_PATH at runtime for ctypes
[ "", "python", "ctypes", "" ]
Short best practice question: If an object A is injected into another object B, should then object B implement IDisposable and dispose A when B is disposed?
I would generally say no; the nature of dependency injection means that the injected object does not know much about the lifecycle of what it was injected with; to some extent, this is the definition of injection. As such, I do not think the injected object should dispose whatever it was injected with; the injecting code should take the responsibility for knowing the complete lifecycle of all the objects it is injecting, and should be able to properly dispose of them when all operations on them are complete, and not before.
If you're referring to the [dependency injection](http://www.martinfowler.com/articles/injection.html) pattern, I think it depends on the knowledge in Object B about the implementation of Object A. The reason for doing dependency injection like this is usually because you do not know on beforehand how Object A will be implemented and whether it requires IDisposable. The only thing you know is the interface. Adding this behavior would result in tighter coupling between the two classes, IMO.
Should injected properties be disposed?
[ "", "c#", "" ]
Currently ASP.NET MVC's OutputCache attribute has a huge downfall. If you want to cache parts of your site you have to use a workaround due to the limitation of ASP.NET's pipeline that MVC relies on. Say you have a page that has a statistics module that you surface through RenderAction you can't cache just that part of the page out of the box. My question is, what ways have you found to get around this limitation that are elegant and easy to use? I've personally found 2 of them neither I'm particularly happy with. Though they work they seem to just feel wrong when building an app around them. Solution 1 - Sub Controllers <http://mhinze.com/subcontrollers-in-aspnet-mvc/> Solution 2 - Partial requests <http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/> So if you have another solution or maybe even a way you've used one of these solutions elegantly I'd love some ideas on design and/or usage.
I've done this with option 2 (using Html.RenderAction) with pretty good success. I also created different base classes for my controllers, one that caches and one that doesn't so that I put all of my cached actions in one place. I don't do this very often so it's not too bad to isolate these actions. With a combination of caching and a GZip compression filter I wrote I get pretty blazing performance out of MVC.
In some cases it's better not to use ASP.NET OutputCache feature at all. Instead use Caching in your business/service layer with optional gzip compression. Sometimes this combination is even faster than full output caching.
Ways to workaround whole page caching in ASP.NET MVC
[ "", "c#", "asp.net-mvc", "" ]
I'm looking for a C++ library that implements or enables the implementation of a HTTP client. It should handle cookies as well. What would you propose?
[Curl++](http://www.curlpp.org/): is an option, particularly if you want things in more of a C++ style. [cpp-netlib](http://cpp-netlib.org/#): very good and simple to use, available on ubuntu ``` sudo apt-get install libcppnetlib-dev ``` example: ``` using namespace boost::network; using namespace boost::network::http; client::request request_("http://127.0.0.1:8000/"); request_ << header("Connection", "close"); client client_; client::response response_ = client_.get(request_); std::string body_ = body(response_); ```
Take a look at [Poco Libraries](http://pocoproject.org/). I started using them as they are portable and it's a joy to work with. Simple and clean - though I haven't dived in anything fancy for the moment.
What C++ library should I use to implement a HTTP client?
[ "", "c++", "http", "client", "" ]
I'm trying to implement OpenID on my site. I've got Google, Yahoo! and ClaimID working so far, but AOL tells me "Invalid devId or Site not registered.". So how do I register my site and/or get a devID and pass it along? I'm using JanRain/PHP OpenID. AOL's dev blog is just a mess.
This may not be related, but it looks like AOL's OpenID may be having issues right now, I had to switch to another provider to log into SO.
AOL is only an OpenID 1.x Provider, whereas the others you mentioned are 2.0 providers (I'm not sure about ClaimID). I think Janrain's PHP library can handle interop with either version, but in your investigation just be aware of the potential difference there.
AOL OpenID?
[ "", "php", "openid", "aol", "" ]
I have a `JPanel` with two labels with pictures. I need to print these content of the `JPanel`. Please help me out. How can I print only this `JPanel`'s contents, as I also have different components on my `JFrame` but I just need to print **this** `JPanel`. Thanks.
Here is an example to print any Swing component. ``` public void printComponenet(Component component){ PrinterJob pj = PrinterJob.getPrinterJob(); pj.setJobName(" Print Component "); pj.setPrintable (new Printable() { public int print(Graphics pg, PageFormat pf, int pageNum){ if (pageNum > 0){ return Printable.NO_SUCH_PAGE; } Graphics2D g2 = (Graphics2D) pg; g2.translate(pf.getImageableX(), pf.getImageableY()); component.paint(g2); return Printable.PAGE_EXISTS; } }); if (pj.printDialog() == false) return; try { pj.print(); } catch (PrinterException ex) { // handle exception } } ```
A simple way to do it would be implementing the `Printable` interface (in `java.awt.print`) and adding the specified `print` method (it works similar to `paint`—in here, you could specify what components you would want to draw onto the printed page). And when you want to actually print the contents of the panel, obtain a `PrinterJob` instance and call its `setPrintable` method, passing the object that implemented `Printable`. That's just a quick overview, though. I'd recommend taking a look at [Sun's tutorial on printing](http://java.sun.com/docs/books/tutorial/2d/printing/index.html) for further information.
How can I print a single JPanel's contents?
[ "", "java", "swing", "printing", "" ]
I have a list of addresses in two separate tables that are slightly off that I need to be able to match. For example, the same address can be entered in multiple ways: * 110 Test St * 110 Test St. * 110 Test Street Although simple, you can imagine the situation in more complex scenerios. I am trying to develop a simple algorithm that will be able to match the above addresses as a key. For example. the key might be "11TEST" - first two of 110, first two of Test and first two of street variant. A full match key would also include first 5 of the zipcode as well so in the above example, the full key might look like "11TEST44680". I am looking for ideas for an effective algorithm or resources I can look at for considerations when developing this. Any ideas can be pseudo code or in your language of choice. We are only concerned with US addresses. In fact, we are only looking at addresses from 250 zip codes from Ohio and Michigan. We also do not have access to any postal software although would be open to ideas for cost effective solutions (it would essentially be a one time use). Please be mindful that this is an initial dump of data from a government source so suggestions of how users can clean it are helpful as I build out the application but I would love to have the best initial I possibly can by being able to match addresses as best as possible.
I'm working on a similar algorithm as we speak, it should handle addresses in Canada, USA, Mexico and the UK by the time I'm done. The problem I'm facing is that they're in our database in a 3 field plaintext format [whoever thought *that* was a good idea should be shot IMHO], so trying to handle rural routes, general deliveries, large volume receivers, multiple countries, province vs. state vs. county, postal codes vs. zip codes, spelling mistakes is no small or simple task. Spelling mistakes alone was no small feat - especially when you get to countries that use French names - matching Saint, Sainte, St, Ste, Saints, Saintes, Sts, Stes, Grand, Grande, Grands, Grandes with or without period or hyphenation to the larger part of a name cause no end of performance issues - especially when St could mean saint *or* street and may or may not have been entered in the correct context (i.e. feminine vs. masculine). What if the address has largely been entered correctly but has an incorrect province or postal code? One place to start your search is the [**Levenstein Distance Algorithm**](http://en.wikipedia.org/wiki/Levenstein_Distance) which I've found to be really useful for eliminating a large portion of spelling mistakes. After that, it's mostly a case of searching for keywords and comparing against a postal database. I would be really interested in collaborating with anyone that is currently developing tools to do this, perhaps we can assist each other to a common solution. I'm already part of the way there and have overcome all the issues I've mentioned so far, having someone else working on the same problem would be really helpful to bounce ideas off. Cheers - [ben at afsinc dot ca]
If you would prefer tonot develop one and rather use an off-the-shelf product that uses many of the technologies mentioned here, see: <http://www.melissadata.com/dqt/matchup-api.htm> *Disclaimer: I had a role in its development and work for the company.*
Address Match Key Algorithm
[ "", "c#", "algorithm", "t-sql", "join", "street-address", "" ]
I have two entity classes annotated in the following way ``` @Entity class A { @ManyToMany(mappedBy="A", cascade=CascadeType.ALL) private List<B> b; .. } @Entity class B { @ManyToMany(cascade=CascadeType.ALL) private List<A> a; .. } ``` If I store an instance of the class 'B', the relations are stored in the database and the getter in class 'A' will return the correct subset of B's. However, if I make changes to the list of Bs in 'A', the changes are not stored in the database? My question is, how can I make it so that changes in either class are "cascaded" to the other class? EDIT: I've tried different variations of removing the mappedBy-parameter and defining a JoinTable (and columns), but I've been unable to find the correct combination.
The shortest answer seems to be you cannot and it makes sense. In a bidirectional many-to-many association one side must be master and is used to persist changes to the underlying join table. As JPA will not maintain both side of the association, you could end up with a memory situation that could not be reloaded once stored in the database. Example: ``` A a1 = new A(); A a2 = new A(); B b = new B(); a1.getB().add(b); b.getA().add(a2); ``` If this state could be persisted, you would end up with the following entries in the join table: ``` a1_id, b_id a2_id, b_id ``` But upon loading, how would JPA know that you intended to only let b know about a2 and not a1 ? and what about a2 that should not know about b ? This is why you have to maintain the bidirectional association yourself (and make the above example impossible to get to, even in memory) and JPA will only persist based on the state of one side of it.
Have you specified the inverse join columns? ``` @Entity class A { @ManyToMany(mappedBy="A", cascade=CascadeType.ALL) private List <B> b; .. } @Entity class B { @ManyToMany @JoinTable ( name="A_B", joinColumns = {@JoinColumn(name="A_ID")}, inverseJoinColumns = {@JoinColumn(name="B_ID")} ) private List<A> a; .. } ``` That's assuming a join table called A\_B with columns A\_ID and B\_ID.
Saving bidirectional ManyToMany
[ "", "java", "jpa", "" ]
> **Possible Duplicates:** > [What is the best approach for a Java developer to learn C++](https://stackoverflow.com/questions/789659/what-is-the-best-approach-for-a-java-developer-to-learn-c) How would you go about learning C++ if you were "Stuck in your ways" with newer languages like Java or C#? I've been working as a developer for 3 years, I've got both a Bachellors and a masters in computing science from a Reputable UK University... I've written millions of lines of C# thousands of lines of Java and a few hundred lines of C... But I don't know C++, I feel a little like I've cheated the profession by not knowing a what I think is a key language. I've written Code in C++ files, mainly for bug fixes, but it was really just C in disguise. What is the best way to go about learning C++, if you are more used to the nice abstractions that higher level languages give you to get away from the nitty grittyness of C++. Has anyone on SO gone from being an experienced Java, C# (or some other language) developor to a C++ programmer? if so how did you do it, was it difficult and do you have any pointers?
By reading Stroustroup's C++ Programming Language. Switched from Common Lisp.
I have an idea: try looking up all those "Java for C++ Programmers" articles, because there are so many of them. They're written for those who took the historical path (like I did), but it seems like there ought to be an awful lot of useful information, examples, etc., of what the parallels are and how they're different. That, and spend a lot of time developing in C++ :-)
How to Learn C++ When you are stuck in your ways with newer Languages?
[ "", "c++", "" ]
I want to record what various sources have to say about a historical figure. i.e. * The website Wikipedia says that Susan B. Anthony was born February 15, 1820 and her favorite color was blue * The book *Century of Struggle* says that Susan B. Anthony was born on February 12, 1820 and her favorite color was red * The book *History of Woman's Suffrage* says that Susan B. Anthony was born on February 15, 1820 and her favorite color was red and she was the second cousin of Abraham Lincoln I also want researchers to be able to express their confidence, for instance with a percentage, in the individual claims that these sources are making. i.e. * User A is 90% confident that Susan B. Anthony was born on February 15, 1820; 75% confident that her favorite color was blue, and 30% confident that she was second cousins with Abraham Lincoln * User B is 30% confident that Susan B. Anthony was born on February 12, 1820; 60% confident that her favorite color was blue, and 10% confident that she was second cousins with Abraham Lincoln I then want each user to have a view of Susan B. Anthony that shows her birthday, favorite color, and relationships that the users thinks are most likely to be true. I'm also want to use a relational database datastore, and the way that I can think to do this is to create a separate table for every individual type of atomic fact that I want the users to be able to express their confidence in. So for this example there would be eight tables in total, and three separate table for the three separate atomic facts. ``` Source(id) Person(id) Claim(claim_id, source, FOREIGN KEY(source) REFERENCES Source(id) ) Alleged_birth_date(claim_id, person, birth_date, FOREIGN KEY(claim_id) REFERENCES Claim(id), FOREIGN KEY(person) REFERENCES person(id)) Alleged_favorite_color(claim_id, person, color, FOREIGN KEY(claim_id) REFERENCES Claim(id), FOREIGN KEY(person) REFERENCES person(id)) Alleged_kinship(claim_id, person, relationship type, kin, FOREIGN KEY(claim_id) REFERENCES Claim(id), FOREIGN KEY(person) REFERENCES Person(id)) User(id) Confidence_in_claim(user, claim, confidence, FOREIGN KEY(user) REFERENCES User(id), FOREIGN KEY(claim) REFERENCES claim(id)) ``` This feels like it gets very complicated very quickly, as actually want to record a lot of types of atomic facts. Are there better ways to do this? This is, I think, the same issue that Martin Fowler calls [Contradictory Observations](http://www.martinfowler.com/bliki/ContradictoryObservations.html).
[RDF](http://en.wikipedia.org/wiki/Resource_Description_Framework) is great for this. It's usually described as a format for metadata; but in fact it's a graph model of 'assertions' on triplets. The whole 'semantic web' idea is to publish lots of facts on RDF, and search engines would be inference engines that traverse the unified graph to find relationships. There's also some mechanisms to refer to a triplet, so you can say something about an assertion, like it's origin (who says this?), or when it was asserted (when did he said that?), or how much you beleive it to be true, etc. As a big example, the whole [OpenCyc](http://www.cyc.com/cyc/opencyc/overview) 'commonsense knowledge base' is queryable in RDF
You should try a Star Schema model, centered around a "Fact" table and several "Dimension" tables. This is a well-explored model, and there are many database optimizations for it. claim\_fact(source\_id, person\_id, user\_id, details\_id, weight) Source\_dimension(id, name) Person\_dimension(id, name) User\_dimension(id, name) details\_dimension(id, name NOT NULL, color NULLABLE, kinship NULLABLE, birthday NULLABLE) Every claim would have a source, person, user, and details. NAME values for details would be values such as "kinship", "birthday". Keep in mind that this is an OLAP schema (rather than an OLTP structure), and being so it is not fully normalized. The benefits to this outweigh any problems you may come across due to redundancy, as queries to star schemas are highly optimized by DBMSs configured for Data Warehousing. RECOMMENDED READING: The Data Warehouse Toolkit (Kimball, et al.)
Modeling atomic facts in a relational database
[ "", "sql", "database", "database-design", "data-modeling", "relational", "" ]
Suppose I have IRepository interface and its implementation SqlRepository that takes as an argument LINQ to SQL DataContext. Suppose as well that I have IService interface and its implementation Services that takes three IRepository, IRepository and IRepository. Demo code is below: ``` public interface IRepository<T> { } public class SqlRepository<T> : IRepository<T> { public SqlRepository(DataContext dc) { ... } } public interface IService<T> { } public class Service<T,T1,T2,T3> : IService<T> { public Service(IRepository<T1> r1, IRepository<T2>, IRepository<T3>) { ... } } ``` Is it any way while creating Service class to inject all three repositories with the same DataContext?
All you need to do is make sure when you register the `Datacontext` with your Unity container use the `PerResolveLifetimeManager` either in config: ``` <type type="<namespace>.DataContext, <assembly>"> <lifetime type="Microsoft.Practices.Unity.PerResolveLifetimeManager, Microsoft.Practices.Unity" /> </type> ``` or in code: ``` container.RegisterType<DataContext>(new PerResolveLifetimeManager()); ``` then whenever the container resolves the `Service` any dependencies which also require a `DataContext` will be provided with exactly the same one. But the next request to resolve `Service` will create a new `DataContext`.
I think I know what you want to do. I'm in the same boat and am trying to come up with a solution. My Service layer performs operations on in coming requests, and what it does depends on the contents. It passes it to a series of chain of responsibility classes. I want the same context passed to all classes within the lifetime of the service method called You can Specify PerResolveLifetimeManager. So far, it seems to be working with my test cases: Service Class: ``` public interface IServiceClass { void DoService(); } class ServiceClass : IServiceClass { private IHandler Handler { get; set; } public ServiceClass(IHandler handler) { Handler = handler; } public void DoService() { Handler.HandleRequest(); } } ``` IHandler is implemented by two classes, and performs Chain of Responsibility pattern: ``` public interface IHandler { void HandleRequest(); } class Handler : IHandler { private IDataContext DataContext { get; set; } public Handler(IDataContext dataContext) { DataContext = dataContext; } public void HandleRequest() { DataContext.Save("From Handler 1"); } } class Handler2 : IHandler { private IDataContext DataContext { get; set; } private IHandler NextHandler { get; set; } public Handler2(IDataContext dataContext, IHandler handler) { DataContext = dataContext; NextHandler = handler; } public void HandleRequest() { if (NextHandler != null) NextHandler.HandleRequest(); DataContext.Save("From Handler 2"); } } ``` As you can see, both handlers accept an instance of IDataContext, which I want to be the same in both of them. Handler2 also accepts an instance of IHandler to pass control to (it does both here to demonstrate, but actually, only one would handle the request...) IDataContext. In the constructor I initialize a Guid, and during its operation, output it so I can see if both times its called is using the same instance: ``` public interface IDataContext { void Save(string fromHandler); } class DataContext : IDataContext { private readonly Guid _guid; public DataContext() { _guid = Guid.NewGuid(); } public void Save(string fromHandler) { Console.Out.WriteLine("GUI: [{0}] {1}", _guid, fromHandler); } } ``` Finally, registration and calling of service: ``` private IUnityContainer container; private void InitializeUnity() { container = new UnityContainer(); container.RegisterType<IHandler, Handler2>("Handler2", new InjectionConstructor(new ResolvedParameter<IDataContext>(), new ResolvedParameter<IHandler>("Handler1"))); container.RegisterType<IHandler, Handler>("Handler1"); container.RegisterType<IDataContext, DataContext>(new PerResolveLifetimeManager()); container.RegisterType<IServiceClass, ServiceClass>("MyClass", new InjectionConstructor(new ResolvedParameter<IHandler>("Handler2"))); } private void CallService() { var service = container.Resolve<ServiceClass>("MyClass"); service.DoService(); // Resolving and calling again to simulate multiple resolves: service = container.Resolve<ServiceClass>("MyClass"); service.DoService(); } ``` This is the output I get: ``` GUI: [f2250055-8a5f-4f80-a1b6-bcc5574138cf] From Handler 1 GUI: [f2250055-8a5f-4f80-a1b6-bcc5574138cf] From Handler 2 GUI: [22a5c0a3-3c5c-4683-807d-bf2b43f3cd0a] From Handler 1 GUI: [22a5c0a3-3c5c-4683-807d-bf2b43f3cd0a] From Handler 2 ``` Hope this wall of text answered your question... If not sorry, it did inspire a solution I needed to implement...
Inject same DataContext instance across several types with Unity
[ "", "c#", "dependency-injection", "unity-container", "datacontext", "" ]
If I do not care about a thrown Exception. Can I code in a way as not to create it? In other words, can an Exception be thrown but no Exception object be created? An example - Simple example using a System.Net.Sockets.Socket ``` Socket acceptingSocket; acceptingSocket.Blocking = false; while(condition) { try { Socket acceptedSocket = acceptingSocket.Accept(); //(i) doWork(acceptedSocket); } catch{} } ``` because the socket is in non-blocking mode if there is no connection to accept a SocketException is thrown at point (i) and the conditional loop continues. using this code implementation - will the SocketException object be created? AND if it is created - is there a way to NOT create it?
You can't suppress exceptions, you can only ignore them. In any case, it's not the creating of the Exception object that's expensive -- it's the stack walk that happens when the exception is thrown. Also, ``` catch(SocketException) {} ``` not ``` catch { } or catch(Exception) { } ``` :)
Yes, it will be created. No, there is no way to avoid this.
How to supress the creation of an (.net) Exception object?
[ "", "c#", ".net", "exception", "memory", "garbage-collection", "" ]
I am new to the C# XmlSerializer so I might be missing something basic here. The problem I am running into is that I have one class that has a `List<T>` of another class. When I serialize the main class the XML looks beautiful and all the data is intact. When I deserialize the XML, the data in the `List<T>` disappears and I am left with an empty `List<T>`. I am not receiving any errors and the serialization portion works like charm. What am I missing with the deserialization process? **EDIT:** Note that the code shown below does not reproduce the problem - it works. This was a simplified version of the real code, which did *not* work. Unfortunately, the code below was simplified enough to not reproduce the problem! ``` public class User { public User() { this.Characters = new List<Character>(); } public string Username { get; set; } public List<Character> Characters { get; set; } } public class Character { public Character() { this.Skills = new List<Skill>(); } public string Name { get; set; } public List<Skill> Skills { get; set; } } public enum Skill { TreeClimber, ForkliftOperator } public static void Save(User user) { using (var textWriter = new StreamWriter("data.xml")) { var xmlSerializer = new XmlSerializer(typeof(User)); xmlSerializer.Serialize(textWriter, user); } } public static User Restore() { if (!File.Exists("data.xml")) throw new FileNotFoundException("data.xml"); using (var textReader = new StreamReader("data.xml")) { var xmlSerializer = new XmlSerializer(typeof(User)); return (User)xmlSerializer.Deserialize(textReader); } } public void CreateAndSave() { var character = new Character(); character.Name = "Tranzor Z"; character.Skills.Add(Skill.TreeClimber); var user = new User(); user.Username = "Somebody"; user.Characters.Add(character); Save(user); } public void RestoreAndPrint() { var user = Restore(); Console.WriteLine("Username: {0}", user.Username); Console.WriteLine("Characters: {0}", user.Characters.Count); } ``` The XML generated by executing CreateAndSave() looks like so: ``` <User> <Username>Somebody</Username> <Characters> <Character> <Name>Tranzor Z</Name> <Skills> <Skill>TreeClimber</Skill> </Skills> </Character> <Characters> </User> ``` Perfect! That's the way it should look. If I then execute `RestoreAndPrint()` I get a User object with the Username property set properly but the Characters property is an empty list: ``` Username: Somebody Characters: 0 ``` Can anybody explain to me why the Characters property is serialized properly but won't deserialize?
After futzing around with the code for a long time I finally gave up on the idea of using the default behaviour of the XmlSerializer. All of the relevant classes now inherit IXmlSerializer and implement the ReadXml() and WriteXml() functions. I was really hoping to take the lazy route but now that I've played with IXmlSerializer I realize that it really isn't difficult at all and the added flexibility is really nice.
Cannot reproduce; I get (after fixing the more immediate bugs): ``` Username: Somebody Characters: 1 ``` Changes: * `WriteLine` instead of `WriteFormat` (which prevented it compiling) * init the lists in the default constructors (which prevented `CreateAndSave` from working): + `public User() { Characters = new List<Character>(); }` + `public Character() { Skills = new List<Skill>(); }`
XmlSerializer.Deserialize() isn't deserializing a List<T> correctly
[ "", "c#", ".net", "xml-serialization", "" ]
I have a .NET console application that needs to generate some HTML files. I could just construct the HTML in a StringBuilder and write the contents out to a file, but I was thinking it would be nicer to use some kind of template file with placeholders for where the data goes and then process my data through it at runtime. I'm guessing there are ways to use aspx, or T4, or some of the alternative view engines that you can use with ASP.NET MVC, but I don't know what would be easiest to integrate into a console application (or how I would go about integrating them). I want to end up able to call something of the form: ``` GenerateHtml(htmlPath, template, customDataObject); ```
As Matt mentioned, spark is nice but it could be overkill for some simple templates and gets complicated if you are not using it in MVC. I have personally had a lot of success with NVelocity and I also publish a simple example/wrapper on using it: <http://simpable.com/code/simpletemplate/> In addition, GraffitiCMS's entire theming system run on NVelocity (although I would have used spark if it were available for this task). -Scott
One way you could do this is create a XSL file as the template, serialise your `customDataObject` as XML then perform a transform to generate the required HTML. **Update:** Whilst I like (and do use) the string replacement method advocated by other folks here, there is a certain flexibility to using XML/XSL. Say your object has a property that is a list, for example an order object with a list of line item objects, you pretty much have to burn into your code the logic that has to render the line items. With XSL all you do is pass the serialised order object XML to the XSL and let the XSL handle whatever HTML it needs to generate. This means you can often edit the XSL in place or have variants (order summary, detailed order etc) without adding extra code to your app with all the extra hassle of rebuild/deploy. But then it all depends on the complexity of what you need to render, for some jobs string replacement is more obvious, for others XSL is the way. As I said, we use both.
Generating HTML using a template from a .NET application
[ "", "c#", ".net", "html", "template-engine", "" ]
I want to produce a desktop application with a very simple GUI (a background graphic, a cancel button and a progress bar). My main targets are Mac and Windows. Is this possible using Visual C++ 2008? Can anyone point to any examples using Visual C++? Or is there a better way to create the GUI separately?
Use Qt4. <http://qt-project.org/> This is a self containing framework which contains developers tools, GUI builders, String/IO/XML/Thread classes, Audio/Video controls, HTML widgets and many, many more features. It's built to be completely multi-platform, one code for all systems. In contrary to wxWidgets, it feels more object-oriented, and has by far better documentation and its better maintained. See it online: <http://qt-project.org/doc/qt-4.8/> EDIT- 6 years since the original Answer. I should point to Qt5 - <http://www.qt.io/>
I would recommend [wxWidgets](http://www.wxwidgets.org/). It's crossplatform and works with Visual C++. There's also Qt (see Colins post) which is what KDE (Linux desktop manager) uses. It has a more restrictive license though.
What is the best way to make a simple cross platform GUI in C++?
[ "", "c++", "visual-studio", "user-interface", "cross-platform", "" ]
The recursion is sort of a 'divide and conquer' style, it splits up while getting smaller (Tree data structure), and I want it to break completely if a violation is found, meaning break all the recursive paths, and return true. Is this possible?
You could return an error code, or modify some global variable so that each recursive instance knows to "kill itself". Something of the sort. ``` int foo(bar){ int to_the_next; if (go_recursive){ to_the_next = foo(whisky_bar); if (to_the_next ==DIE) return DIE; } if (something_unexpected_happened) return DIE; process;//may include some other recursive calls, etc etc } ```
No matter what you do, you are going to have to unwind the stack. This leaves two options: 1. Magic return value (as described by one of the Toms) 2. Throw an exception (as mentioned by thaggie) If the case where you want things to die is rare, this may be one of those situations where throwing an exception might be a viable choice. And before everyone jumps down my throat on this, remember that one of the most important rules of programming is knowing when it's appropriate to break the rule. As it turns out, I spent today evaluating the zxing library from google code. They actually use exception throws for a lot of control structures. My first impression when I saw it was horror. They were literally calling methods tens of thousands of times with different parameters until the method doesn't throw an exception. This certainly looked like a performance problem, so I made some adjustments to change things over to using a magic return value. And you know what? The code was 40% faster when running in a debugger. But when I switched to non-debugging, the code was less than 1% faster. I'm still not crazy about the decision to use exceptions for flow control in this case (I mean, the exceptions get thrown *all* the time). But it's certainly not worth my time to re-implement it given the almost immeasurable performance difference. If your condition that triggers death of the iteration is not a fundamental part of the algorithm, using an exception may make your code a lot cleaner. For me, the point where I'd make this decision is if the entire recursion needs to be unwound, then I'd use an exception. IF only part of the recursion needs to be unwound, use a magic return value.
Breaking out of a recursion in java
[ "", "java", "recursion", "" ]
I remember that at one point, [it was said that Python is less object oriented than Ruby](http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html), since in Ruby, everything is an object. Has this changed for Python as well? Is the latest Python more object oriented than the previous version?
Jian Lin — the answer is "Yes", Python is more object-oriented than when Matz decided he wanted to create Ruby, and both languages now feature "everything is an object". Back when Python was younger, "types" like strings and numbers lacked methods, whereas "objects" were built with the "class" statement (or by deliberately building a class in a C extension module) and were a bit less efficient but did support methods and inheritance. For the very early 1990s, when a fast 386 was a pretty nice machine, this compromise made sense. But types and classes were unified in Python 2.2 (released in 2001), and strings got methods and, in more recent Python versions, users can even subclass from them. So: Python was certainly less object oriented at one time; but, so far as I know, every one of those old barriers is now gone. Here's the guide to the unification that took place: <http://www.python.org/download/releases/2.2/descrintro/> **Clarification:** perhaps I can put it even more simply: in Python, everything has *always* been an object; but some basic kinds of object (ints, strings) once played by "different rules" that prevent OO programming methods (like inheritance) from being used with them. That has now been fixed. The len() method, described in another response here, is probably the only thing left that I wish Guido had changed in the upgrade to Python 3.0. But at least he gave me dictionary comprehensions, so I won't complain too loudly. :-)
I'm not sure that I buy the argument that Ruby is more object-oriented than Python. There's more to being object-oriented than just using objects and dot syntax. A common argument that I see is that in Python to get the length of a list, you do something like this: ``` len(some_list) ``` I see this as a [bikeshed argument](http://en.wikipedia.org/wiki/Color_of_the_bikeshed). What this really translates to (almost directly) is this: ``` some_list.__len__() ``` which is perfectly object oriented. I think Rubyists may get a bit confused because typically being object-oriented involves using the dot syntax (for example `object.method()`). However, if I misunderstand Rubyists' arguments, feel free to let me know. Regardless of the object-orientation of this, there is one advantage to using len this way. One thing that's always annoyed me about some languages is having to remember whether to use `some_list.size()` or `some_list.length()` or `some_list.len` for a particular object. Python's way means just one function to remember
Has Python changed to more object oriented?
[ "", "python", "ruby", "oop", "" ]
I'm getting this error when I run or debug my GA/AI from MyEclipse: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space eclipse.ini looks like this: ``` -showsplash com.genuitec.myeclipse.product --launcher.XXMaxPermSize 256m -vmargs -Xms128m -Xmx512m -Duser.language=en -XX:PermSize=128M -XX:MaxPermSize=256M ``` MyEclipse is called like this: ``` "C:\Program Files\MyEclipse 6.0\eclipse\eclipse.exe" -vm "C:\Program Files\MyEclipse 6.0\jre\bin\javaw.exe" -vmargs -Xms1448M -Xmx1448M ``` bumping the vm settings up from this: ``` "C:\Program Files\MyEclipse 6.0\eclipse\eclipse.exe" -vm "C:\Program Files\MyEclipse 6.0\jre\bin\javaw.exe" -vmargs -Xms80M -Xmx1024M ``` has had no effect. So I'm trying to get it to dump the heap to a file, but placing these: ``` -XX:+HeapDumpOnCtrlBreak -XX:+HeapDumpOnOutOfMemoryError ``` in the Program arguments has had no effect. How do I get something to work with more memory usage analysis? jstack, for instance, is not currently available on Windows platforms. And using SendSignal has no effect that I can see. ![a screen shot](https://imgur.com/KV4d.jpg)
There are a number of ways to get heap dumps. Here are some I've used: 1. `-XX:+HeapDumpOnOutOfMemoryError` *should* get you dump if you hit your OOM. 2. Connect with [VisualVM](https://visualvm.dev.java.net/) (free) and use its GUI to force a heap dump 3. Use one of the many good commercial profilers (JProfiler, YourKit, ...) 4. Use jmap (see below) to force a dump from a running process If you're running Java 6, [jmap](http://java.sun.com/javase/6/docs/technotes/tools/share/jmap.html) should work on Windows. This might be useful if you want to dump the heap and you haven't hit your OOM. Use Windows Task Manager to find the pid of your Java app, and in a console run this: ``` jmap -dump:format=b,file=c:\heap.bin <pid> ``` In addition to VisualVM, the [Eclipse Memory Analyzer](http://www.eclipse.org/mat/) (also free) can help you analyze what's eating up all the space once you've got the dump.
`-XX:+HeapDumpOnOutOfMemoryError` should be put in "`VM Arguments`" not "`Program Arguments`"
How do I Save the Heap (Dump to a File) in Eclipse?
[ "", "java", "memory-leaks", "heap-memory", "" ]
I have a class that maps incoming messages to matching readers based on the message's class. All message types implement the interface message. A reader registers at the mapper class, stating which message types it will be able to handle. This information needs to be stored in the message reader in some way and my approach was to set a `private final` array from the constructor. Now, it seems I have some misunderstanding about generics and / or arrays, that I can't seem to figure out, see the code below. What is it? ``` public class HttpGetMessageReader implements IMessageReader { // gives a warning because the type parameter is missing // also, I actually want to be more restrictive than that // // private final Class[] _rgAccepted; // works here, but see below private final Class<? extends IMessage>[] _rgAccepted; public HttpGetMessageReader() { // works here, but see above // this._rgAccepted = new Class[1]; // gives the error "Can't create a generic array of Class<? extends IMessage>" this._rgAccepted = new Class<? extends IMessage>[1]; this._rgAccepted[0] = HttpGetMessage.class; } } ``` **ETA**: *As cletus correctly pointed out, the most basic googling shows that Java does not permit generic arrays. I definitely understand this for the examples given (like `E[] arr = new E[8]`, where `E` is a type parameter of the surrounding class). But why is `new Class[n]` allowed? And what then is the "proper" (or at least, common) way to do this?*
Java does not permit [generic arrays](http://www.google.com.au/search?hl=en-GB&q=java+generics+arrays&sourceid=navclient-ff&rlz=1B3GGGL_en-GBAU319AU319&ie=UTF-8). More information in the [Java Generics FAQ](http://www.angelikalanger.com/Articles/Papers/JavaGenerics/ArraysInJavaGenerics.htm). To answer your question, just use a [List](http://java.sun.com/javase/6/docs/api/java/util/List.html) (probably [ArrayList](http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html)) instead of an array. Some more explanation can be found in [Java theory and practice: Generics gotchas](http://www.ibm.com/developerworks/java/library/j-jtp01255.html): > ## Generics are not covariant > > While you might find it helpful to > think of collections as being an > abstraction of arrays, they have some > special properties that collections do > not. Arrays in the Java language are > covariant -- which means that if > Integer extends Number (which it > does), then not only is an `Integer` > also a Number, but an `Integer[]` is > also a `Number[]`, and you are free to > pass or assign an `Integer[]` where a > `Number[]` is called for. (More > formally, if `Number` is a supertype > of `Integer`, then `Number[]` is a > supertype of `Integer[]`.) You might > think the same is true of generic > types as well -- that `List<Number>` > is a supertype of `List<Integer>`, and > that you can pass a `List<Integer>` > where a `List<Number>` is expected. > Unfortunately, it doesn't work that > way. > > It turns out there's a good reason it > doesn't work that way: It would break > the type safety generics were supposed > to provide. Imagine you could assign a > `List<Integer>` to a `List<Number>`. > Then the following code would allow > you to put something that wasn't an > `Integer` into a `List<Integer>`: > > ``` > List<Integer> li = new ArrayList<Integer>(); > List<Number> ln = li; // illegal > ln.add(new Float(3.1415)); > ``` > > Because ln is a `List<Number>`, adding > a `Float` to it seems perfectly legal. > But if ln were aliased with li, then > it would break the type-safety promise > implicit in the definition of li -- > that it is a list of integers, which > is why generic types cannot be > covariant.
> And what then is the "proper" (or at least, common) way to do this? ``` @SuppressWarnings(value="unchecked") public <T> T[] of(Class<T> componentType, int size) { return (T[]) Array.newInstance(componentType, size); } public demo() { Integer[] a = of(Integer.class, 10); System.out.println(Arrays.toString(a)); } ```
How do I use arrays of generic types correctly?
[ "", "java", "generics", "" ]
I'm a developer and I suck at SQL:) Please help me out here. I'd like to create my own Stored Procedure that creates a Tenant in my SaaS database. In order to do this I need to create a new SQL Login for the Tenant and then add it to a predefined SQL Role. I'm already stumped just trying to create the Login. Here is what I've tried... ``` CREATE PROCEDURE [MyScheme].[Tenants_InsertTenant] @username nvarchar(2048), @password nvarchar(2048) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; CREATE LOGIN @username WITH PASSWORD = @password END ``` > Msg 102, Level 15, State 1, Procedure Tenants\_InsertTenant, Line 16 > Incorrect syntax near '@username'. > > Msg 319, Level 15, State 1, Procedure Tenants\_InsertTenant, Line 16 > Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon. I realize this should be straightforward but when your new to SQL and the SQL manager errors are as cryptic as they seem to be to me its better just to ask for help:) Thanks, Justin
Apparently CREATE LOGIN only accepts literals. You could try wrapping it in an exec and building it as a string: Add `quotename` for safety from sql injection attacks ``` DECLARE @sql nvarchar(max) = 'CREATE LOGIN ' + quotename(@username) + ' WITH PASSWORD = ' + quotename(@password, ''''); EXEC(@sql) ```
Posible solution: ``` sp_addlogin @loginame = 'test', @passwd = 'test', @defdb = 'test' ```
CREATE LOGIN - can't use @parameter as username
[ "", "sql", "sql-server", "authentication", "t-sql", "" ]
Suppose I have a method which changes the state of an object, and fires an event to notify listeners of this state change: ``` public class Example { public int Counter { get; private set; } public void IncreaseCounter() { this.Counter = this.Counter + 1; OnCounterChanged(EventArgs.Empty); } protected virtual void OnCounterChanged(EventArgs args) { if (CounterChanged != null) CounterChanged(this,args); } public event EventHandler CounterChanged; } ``` The event handlers may throw an exception even if `IncreaseCounter` successfully completed the state change. So we do not have strong [exception safety](http://www.boost.org/community/exception_safety.html) here: > The strong guarantee: that the > operation has either completed > successfully or thrown an exception, > leaving the program state exactly as > it was before the operation started. Is it possible to have strong exception safety when you need to raise events?
To prevent an exception in a handler from propagating to the event generator, the answer is to manually invoke each item in the MultiCast Delegate (i.e. the event handler) inside of a try-catch All handlers will get called, and the exception won't propagate. ``` public EventHandler<EventArgs> SomeEvent; protected void OnSomeEvent(EventArgs args) { var handler = SomeEvent; if (handler != null) { foreach (EventHandler<EventArgs> item in handler.GetInvocationList()) { try { item(this, args); } catch (Exception e) { // handle / report / ignore exception } } } } ``` What remains is for you to implement the logic for what do do when one or more event recipients throws and the others don't. The catch() could catch a specific exception as well and roll back any changes if that is what makes sense, allowing the event recipient to signal the event source that an exceptional situation has occurred. As others point out, using exceptions as control flow isn't recommended. If it's truly an exceptional circumstance, then by all means use an exception. If you're getting a lot of exceptions you probably want to use something else.
The general pattern you will see for frameworks is: ``` public class Example { public int Counter { get; private set; } public void IncreaseCounter() { OnCounterChanging(EventArgs.Empty); this.Counter = this.Counter + 1; OnCounterChanged(EventArgs.Empty); } protected virtual void OnCounterChanged(EventArgs args) { if (CounterChanged != null) CounterChanged(this, args); } protected virtual void OnCounterChanging(EventArgs args) { if (CounterChanging != null) CounterChanging(this, args); } public event EventHandler<EventArgs> CounterChanging; public event EventHandler<EventArgs> CounterChanged; } ``` If a user would like to throw an exception to prevent the changing of the value then they should be doing it in the OnCounterChanging() event instead of the OnCounterChanged(). By definition of the name (past tense, suffix of -ed) that implies the value has been changed. **Edit:** Note that you generally want to stay away from copious amounts of extra try..catch/finally blocks as exception handlers (including try..finally) are expensive depending on the language implementation. i.e. The win32 stack framed model or the PC-mapped exception model both have their pros and cons, however if there are too many of these frames they will both be costly (either in space or execution speed). Just another thing to keep in mind when creating a framework.
Can I have strong exception safety and events?
[ "", "c#", "exception", "events", "" ]
Would following the table below be the best way of determining the access type of member variables of a class that I'm creating (sorry if this table is hard to see; it's the same table shown <http://www.cplusplus.com/doc/tutorial/inheritance/>)? ``` Access public protected private members of the same class yes yes yes members of derived classes yes yes no not members yes no no ```
The table is correct, if that's what you're asking. What it's saying in words is that you can always access member variables of the class your method is in. If the member variable is defined in a parent class then you can only access it if the member variable is protected or public. If you're outside the class then you can only access public member variables. There is no "best way" -- these are the rules presented in a reasonable fashion.
You should add friend classes/methods there, but friendship is clear: in C++ *friends can touch your private parts*.
determing access type of member variables of a class
[ "", "c++", "" ]
I know you can ALTER the column order in MySQL with FIRST and AFTER, but why would you want to bother? Since good queries explicitly name columns when inserting data, is there really any reason to care what order your columns are in in the table?
Column order had a big performance impact on some of the databases I've tuned, spanning Sql Server, Oracle, and MySQL. This post has [good rules of thumb](http://forums11.itrc.hp.com/service/forums/questionanswer.do?threadId=143188): * Primary key columns first * Foreign key columns next. * Frequently searched columns next * Frequently updated columns later * Nullable columns last. * Least used nullable columns after more frequently used nullable columns An example for difference in performance is an Index lookup. The database engine finds a row based on some conditions in the index, and gets back a row address. Now say you are looking for SomeValue, and it's in this table: ``` SomeId int, SomeString varchar(100), SomeValue int ``` The engine has to guess where SomeValue starts, because SomeString has an unknown length. However, if you change the order to: ``` SomeId int, SomeValue int, SomeString varchar(100) ``` Now the engine knows that SomeValue can be found 4 bytes after the start of the row. So column order can have a considerable performance impact. EDIT: Sql Server 2005 stores fixed-length fields at the start of the row. And each row has a reference to the start of a varchar. This completely negates the effect I've listed above. So for recent databases, column order no longer has any impact.
**Update:** In `MySQL`, there may be a reason to do this. Since variable datatypes (like `VARCHAR`) are stored with variable lengths in `InnoDB`, the database engine should traverse all previous columns in each row to find out the offset of the given one. The impact may be as big as **17%** for `20` columns. See this entry in my blog for more detail: * [**Choosing column order**](http://explainextended.com/2009/05/21/choosing-column-order/) In `Oracle`, trailing `NULL` columns consume no space, that's why you should always put them to the end of the table. Also in `Oracle` and in `SQL Server`, in case of a large row, a `ROW CHAINING` may occur. `ROW CHANING` is splitting a row that doesn't fit into one block and spanning it over the multiple blocks, connected with a linked list. Reading trailing columns that didn't fit into the first block will require traversing the linked list, which will result in an extra `I/O` operation. See [**this page**](http://www.akadia.com/services/ora_chained_rows.html) for illustration of `ROW CHAINING` in `Oracle`: That's why you should put columns you often use to the beginning of the table, and columns you don't use often, or columns that tend to be `NULL`, to the end of the table. **Important note:** If you like this answer and want to vote for it, please also vote for [`@Andomar`'s answer](https://stackoverflow.com/questions/894522/is-there-any-reason-to-worry-about-the-column-order-in-a-table/894545#894545). He answered the same thing, but seems to be downvoted for no reason.
Is there any reason to worry about the column order in a table?
[ "", "mysql", "sql", "database-table", "" ]
sometimes i use debug code to alert something in javascript (for example, matching something in regular expression), but forget a modifier and and the alert is in an infinite loop (or if the loop matches the pattern 300 times). If using Firefox, the alert keeps on coming out, and there is no way to even close the tab, the window, or the app. If I force exit, it will close all the tabs and even other windows of Firefox... is there actually a way to stop the loop more gracefully?
The short answer is: No. This is one good reason to use Firebug and the console.log function. Which, ironically, will cause the "stop script because it's running away dialog" to not display in some cases, meaning you are right back where you are now. Chrome and Opera have this feature. IE doesn't, Apple Safari doesn't either. Not a native solution but you could try this grease-monkey script: <http://www.tumuski.com/2008/05/javascript-alert-cancel-button/> Also, you *could* simply override the alert function to use a confirm dialog instead and stop showing alerts if the confirm is canceled: ``` var displayAlerts = true; ``` And then: ``` function alert(msg) { if (displayAlerts) { if (!confirm(msg)) { displayAlerts = false; } } } ```
Looks like you can in firefox: 1. Hold Ctrl 2. Hold Enter 3. Press F4 once According to the blog post, it doesn't work in all cases, more information here: [puremango.co.uk](http://www.puremango.co.uk/2010/02/break-out-of-infinite-alert-popups/)
if i make a mistake in code and cause an infinite loop in javascript and it keeps on calling alert(), is there a way out to stop the loop?
[ "", "javascript", "firefox", "alert", "" ]
I'm looking for an two-way encryption algorithm to encode an array as a string, so that I can securely store some data in a cookie. The algorithm shouldn't just implode the array, I want it to be obfuscated too. My data contains all printable characters. A link to something would be sufficient, I just can't seem to dig anything up on Google. Maybe I should just implode the array with some obscure character, and then encrypt it somehow? I'm not sure what method to encrypt it with though... it doesn't have too secure, the cookie data isn't *that* sensitive. Oh... yeah, the encryption algorithm should let me use a key/salt. mcrypt\_encrypt seems to be giving back messy long results, but perhaps I'm not using the right cipher. Which is the simplest cipher (produces short clean strings)?
[serialize()](http://us.php.net/serialize) will get your information from an array to a string - and you could pass it through [base64\_encode()](http://us.php.net/base64_encode) if you just want obfuscation - but not security. If you want some security - look into mcrypt and blowfish: [blowfish example](http://www.chilkatsoft.com/p/php_blowfish.asp) Regarding [`mcrypt`](http://php.net/manual/en/function.mcrypt-encrypt.php) > Warning This function has been DEPRECATED as of PHP 7.1.0. Relying on > this function is highly discouraged.
Based on gnarf's answer, this should do the trick: ``` function encode_arr($data) { return base64_encode(serialize($data)); } function decode_arr($data) { return unserialize(base64_decode($data)); } ``` Just in case anyone else wants a copy-and-paste solution.
Encrypt array as string
[ "", "php", "encryption", "" ]