Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a `VARCHAR` column in a `SQL Server 2000` database that can contain either letters or numbers. It depends on how the application is configured on the front-end for the customer. When it does contain numbers, I want it to be sorted numerically, e.g. as "1", "2", "10" instead of "1", "10", "2". Fields containing just letters, or letters and numbers (such as 'A1') can be sorted alphabetically as normal. For example, this would be an acceptable sort order. ``` 1 2 10 A B B1 ``` What is the best way to achieve this?
One possible solution is to pad the numeric values with a character in front so that all are of the same string length. Here is an example using that approach: ``` select MyColumn from MyTable order by case IsNumeric(MyColumn) when 1 then Replicate('0', 100 - Len(MyColumn)) + MyColumn else MyColumn end ``` The `100` should be replaced with the actual length of that column.
There are a few possible ways to do this. One would be ``` SELECT ... ORDER BY CASE WHEN ISNUMERIC(value) = 1 THEN CONVERT(INT, value) ELSE 9999999 -- or something huge END, value ``` the first part of the ORDER BY converts everything to an int (with a huge value for non-numerics, to sort last) then the last part takes care of alphabetics. Note that the performance of this query is probably at least moderately ghastly on large amounts of data.
How do I sort a VARCHAR column in SQL server that contains numbers?
[ "", "sql", "t-sql", "" ]
When calling a remote service (e.g. over RMI) to load a list of entities from a database using Hibernate, how do you manage it to initialize all the fields and references the client needs? Example: The client calls a remote method to load all customers. With each customer the client wants the reference to the customer's list of bought articles to be initialized. I can imagine the following solutions: 1. Write a remote method for each special query, which initializes the required fields (e.g. Hibernate.initialize()) and returns the domain objects to the client. 2. Like 1. but create DTOs 3. Split the query up into multiple queries, e.g. one for the customers, a second for the customers' articles, and let the client manage the results 4. The remote method takes a DetachedCriteria, which is created by the client and executed by the server 5. Develop a custom "Preload-Pattern", i.e. a way for the client to specify explicitly which properties to preload.
I have used 1 in the past and it worked well.
I think number 5 is why there is a "fetch" clause in HQL. Could you use that or is the problem more complex?
How to initialize Hibernate entities fetched by a remote method call?
[ "", "java", "hibernate", "remoting", "rmi", "" ]
I thought that there was some way in .net 3.0 to give an array list a type so that it didnt just return Object's but I'm having trouble doing so. Is it possible? If so, how?
`List<T>` was introduced with generics in .NET 2.0: ``` using System.Collections.Generic; var list = new List<int>(); list.Add(1); list.Add("string"); //compile-time error! int i = list[0]; ```
You're probably looking for List`<T>`, available since .NET 2.0, or for any other of the generic types available from System.Collections.Generic or System.Collections.ComponentModel.
Specifying the type of ArrayList's elements
[ "", "c#", ".net", "generics", "" ]
I'm looking for a really good dialog resizer class that will stretch and shrink individual items as needed as the screen is resized. Stephan Keil has a good one (DlgResizeHelper) which basically resizes everything by a set ratio, but I'm looking for something smarter. For example: * Icons should not resize * Single-line text boxes should not be stretched vertically * Buttons should probably stay the same size Basically I'm looking for something to look at all of the controls, figure out that a static text field is related to a control next/below it and anchor the two together, and resize large controls in a 'smart' way so it looks good. Are there such frameworks out there? I've been working on one but something ready-made would probably be better. FOLLOW UP: I'm looking at the suggested solutions. Many of them require you to go in an anchor each control on the dialog. I'm looking for something smart that will figure out what the anchors ought to be, with the ability to manually anchor if the guesses are wrong. Seems like it should be possible -- most humans would agree a static text field next to an edit field should be anchored together. Guess I'm almost looking for a little AI here :)
You can use wxWidgets. It completely replaces MFC, is multi-platform, and gives you a layout-based dialog mechanism.
I use [ResizableLib](http://www.codeproject.com/KB/tabs/resizableproperties.aspx?display=PrintAll&fid=913&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=51) (also does PropertySheets and Pages) off codeproject, IIRC. You set anchor points that determine how the dialog and controls resize or move as the dialog moves. You can set up to 2 anchors per control, (left, right) so you can move them as the dialog moves, or resize them as it moves. Its very easy to understand, if difficult to get perfectly right :)
Windows C++ dialog resizer class
[ "", "c++", "windows", "mfc", "dialog", "resize", "" ]
I have done some searches looking for information about how to do logging with the Spring Framework. We currently have an application that has no logging in it except for system.out statements (very bad way). What I would like to do, is add logging, but also want to be able to control the logging at run time, with say JMX. We are using Rad 7.0 / WebSphere 6.1 I am interesting to find out what is the best way(s) to accomplish this (I figure there may be several). Update: Thoughts on the following [Spring AOP Logging](http://www.devx.com/Java/Article/30799/0/page/1) Good ideal or not. This is in reference to a question posted here on logging: [Conditional Logging](https://stackoverflow.com/questions/105852/how-do-you-deal-with-conditional-logging-when-trying-to-respect-a-limited-cyclo). Does this improve things or just makes it more difficult in the area of logging?
I would use [Commons Logging](http://commons.apache.org/logging/) and [Log4j](http://logging.apache.org/log4j/1.2/index.html). This is not really a question for Spring, however the Springframework source does uses Commons Logging as well. If you create a log4j logger and appender in log4j, you can enable logging within the Springframework classes too. There are a few ways to control logging at runtime. The Log4j sandbox has a JSP, that you can drop into your webapp, that will allow you to control the log levels of all of the loggers within your application.
See the other answers for log4j. But also consider [JAMon](http://jamonapi.sourceforge.net/) for *application monitoring*. It's very easy to add to a spring application, e.g.: ``` <bean id="performanceMonitor" class="org.springframework.aop.interceptor.JamonPerformanceMonitorInterceptor"> <property name="useDynamicLogger" value="false"/> <property name="trackAllInvocations" value="true"/> </bean> <bean id="txRequired" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true"> <property name="transactionManager" ref="transactionManager"/> <property name="transactionAttributes" > <props> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> <property name="preInterceptors"> <list> <ref bean="performanceMonitor"/> </list> </property> </bean> ```
Preferred way to do logging in the SpringFrame work
[ "", "java", "spring", "logging", "" ]
If I'm running a signed Java applet. Can I load additional classes from remote sources, in the same domain or maybe even the same host, and run them? I'd like to do this without changing pages or even stopping the current applet. Of course, the total size of all classes is too large to load them all at once. Is there a way to do this? And is there a way to do this with signed applets and preserve their "confidence" status?
I think classes are lazy loaded in applets. being loaded on demand. Anyway, if the classes are outside of a jar you can simply use the applet classloader and load them by name. Ex: ``` ClassLoader loader = this.getClass().getClassLoader(); Class clazz = loader.loadClass("acme.AppletAddon"); ``` If you want to load classes from a jar I think you will need to create a new instance of URLClassLoader with the url(s) of the jar(s). ``` URL[] urls = new URL[]{new URL("http://localhost:8080/addon.jar")}; URLClassLoader loader = URLClassLoader.newInstance(urls,this.getClass().getClassLoader()); Class clazz = loader.loadClass("acme.AppletAddon"); ``` By default, applets are forbidden to create new classloaders. But if you sign your applet and include permission to create new classloaders you can do it.
Yes, you can open URL connections to the host you ran your applet from. You can either create a classloader with HTTP urls, or download the classes (as jars) to the user's machine and create a classloader with those jars in the classpath. The applet won't stop and you don't need to load another page. Regarding the second part of your question about confidence, once the user has granted access to your applet it can download anything, yes anything, it wants to the local machine. You can probably inform the user as to what it's doing, if your UI design permits this. Hope this helps.
Loading Java classes from a signed applet
[ "", "java", "applet", "signed", "download", "" ]
I've got an ASP.NET app using NHibernate to transactionally update a few tables upon a user action. There is a date range involved whereby only one entry to a table 'Booking' can be made such that exclusive dates are specified. My problem is how to prevent a race condition whereby two user actions occur almost simultaneously and cause mutliple entries into 'Booking' for >1 date. I can't check just prior to calling .Commit() because I think that will still leave be with a race condition? All I can see is to do a check AFTER the commit and roll the change back manually, but that leaves me with a very bad taste in my mouth! :) > booking\_ref (INT) PRIMARY\_KEY AUTOINCREMENT > > booking\_start (DATETIME) > > booking\_end (DATETIME)
* make the isolation level of your transaction SERIALIZABLE (`session.BeginTransaction(IsolationLevel.Serializable`) and check and insert in the same transaction. You should not in general set the isolationlevel to serializable, just in situations like this. or * lock the table before you check and eventually insert. You can do this by firing a SQL query through nhibernate: session.CreateSQLQuery("SELECT null as dummy FROM Booking WITH (tablockx, holdlock)").AddScalar("dummy", NHibernateUtil.Int32); This will lock only that table for selects / inserts for the duration of that transaction. Hope it helped
The above solutions can be used as an option. If I sent 100 request by using "Parallel.For" while transaction level is serializable, yess there is no duplicated reqeust id but 25 transaction is failed. It is not acceptable for my client. So we fixed the problem with only storing request id and adding an unique index on other table as temp.
NHibernate transaction and race condition
[ "", "sql", "sql-server", "nhibernate", "" ]
In IE, the dropdown-list takes the same width as the dropbox (I hope I am making sense) whereas in Firefox the dropdown-list's width varies according to the content. This basically means that I have to make sure that the dropbox is wide enough to display the longest selection possible. This makes my page look very ugly :( Is there any workaround for this problem? How can I use CSS to set different widths for dropbox and the dropdownlist?
Here's another [jQuery](http://jquery.com) based example. In contrary to all the other answers posted here, it takes all keyboard and mouse events into account, especially clicks: ``` if (!$.support.leadingWhitespace) { // if IE6/7/8 $('select.wide') .bind('focus mouseover', function() { $(this).addClass('expand').removeClass('clicked'); }) .bind('click', function() { $(this).toggleClass('clicked'); }) .bind('mouseout', function() { if (!$(this).hasClass('clicked')) { $(this).removeClass('expand'); }}) .bind('blur', function() { $(this).removeClass('expand clicked'); }); } ``` Use it in combination with this piece of CSS: ``` select { width: 150px; /* Or whatever width you want. */ } select.expand { width: auto; } ``` All you need to do is to add the class `wide` to the dropdown element(s) in question. ``` <select class="wide"> ... </select> ``` [Here is a jsfiddle example](http://jsfiddle.net/HnV9Q/).
Creating your own drop down list is more of a pain than it's worth. You can use some JavaScript to make the IE drop down work. It uses a bit of the YUI library and a special extension for fixing IE select boxes. You will need to include the following and wrap your `<select>` elements in a `<span class="select-box">` Put these before the body tag of your page: ``` <script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/yahoo_2.0.0-b3.js" type="text/javascript"> </script> <script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/event_2.0.0-b3.js" type="text/javascript"> </script> <script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/dom_2.0.2-b3.js" type="text/javascript"> </script> <script src="ie-select-width-fix.js" type="text/javascript"> </script> <script> // for each select box you want to affect, apply this: var s1 = new YAHOO.Hack.FixIESelectWidth( 's1' ); // s1 is the ID of the select box you want to affect </script> ``` Post acceptance edit: You can also do this without the YUI library and Hack control. All you really need to do is put an onmouseover="this.style.width='auto'" onmouseout="this.style.width='100px'" (or whatever you want) on the select element. The YUI control gives it that nice animation but it's not necessary. This task can also be accomplished with jquery and other libraries (although, I haven't found explicit documentation for this) -- amendment to the edit: IE has a problem with the onmouseout for select controls (it doesn't consider mouseover on options being a mouseover on the select). This makes using a mouseout very tricky. The first solution is the best I've found so far.
Dropdownlist width in IE
[ "", "javascript", "html", "internet-explorer", "drop-down-menu", "" ]
I am creating a downloading application and I wish to preallocate room on the harddrive for the files before they are actually downloaded as they could potentially be rather large, and noone likes to see "This drive is full, please delete some files and try again." So, in that light, I wrote this. ``` // Quick, and very dirty System.IO.File.WriteAllBytes(filename, new byte[f.Length]); ``` It works, atleast until you download a file that is several hundred MB's, or potentially even GB's and you throw Windows into a thrashing frenzy if not totally wipe out the pagefile and kill your systems memory altogether. Oops. So, with a little more enlightenment, I set out with the following algorithm. ``` using (FileStream outFile = System.IO.File.Create(filename)) { // 4194304 = 4MB; loops from 1 block in so that we leave the loop one // block short byte[] buff = new byte[4194304]; for (int i = buff.Length; i < f.Length; i += buff.Length) { outFile.Write(buff, 0, buff.Length); } outFile.Write(buff, 0, f.Length % buff.Length); } ``` This works, well even, and doesn't suffer the crippling memory problem of the last solution. It's still slow though, especially on older hardware since it writes out (potentially GB's worth of) data out to the disk. The question is this: Is there a better way of accomplishing the same thing? Is there a way of telling Windows to create a file of x size and simply allocate the space on the filesystem rather than actually write out a tonne of data. I don't care about initialising the data in the file at all (the protocol I'm using - bittorrent - provides hashes for the files it sends, hence worst case for random uninitialised data is I get a lucky coincidence and part of the file is correct).
[FileStream.SetLength](http://msdn.microsoft.com/en-us/library/system.io.filestream.setlength) is the one you want. The syntax: ``` public override void SetLength( long value ) ```
If you have to create the file, I think that you can probably do something like this: ``` using (FileStream outFile = System.IO.File.Create(filename)) { outFile.Seek(<length_to_write>-1, SeekOrigin.Begin); OutFile.WriteByte(0); } ``` Where length\_to\_write would be the size in bytes of the file to write. I'm not sure that I have the C# syntax correct (not on a computer to test), but I've done similar things in C++ in the past and it's worked.
Preallocating file space in C#?
[ "", "c#", "file", "file-io", "" ]
I have a huge ear that uses log4j and there is a single config file that is used to set it up. In this config file there is no mention of certain log files but, additional files apart from those specified in the config file get generated in the logs folder. I've searched for other combinations of (logger|log4j|log).(properties|xml) and haven't found anything promising in all of the jar files included in the ear. How do I track down which is the offending thread/class that is creating these extra files?
Try placing a breakpoint in the File class' constructors and the mkdir and createNewFile methods. Generally, code will use the File class to create its files or directories. You should have the Java source code for these classes included with your JVM.
Add `-Dlog4j.debug` to the command line and there will be extra info in standard output about how it is configured.
track down file handle
[ "", "java", "logging", "file", "jakarta-ee", "websphere", "" ]
How can i format currency related data in a manner that is culture aware in JavaScript?
There is the `Number.localeFormat()` function, but I'm not sure it's what you're after. <http://msdn.microsoft.com/en-gb/library/bb310813.aspx>
So I know this is an old question, but incase anyone else shows up looking for similar answers, in modern JavaScript you can use ``` new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number) ``` For more info here is the reference doc. <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat>
JavaScript culture sensitive currency formatting
[ "", "javascript", "localization", "currency", "" ]
I have a class that I wish to expose as a remote service using pythons SimpleXMLRPCServer. The server startup looks like this: ``` server = SimpleXMLRPCServer((serverSettings.LISTEN_IP,serverSettings.LISTEN_PORT)) service = Service() server.register_instance(service) server.serve_forever() ``` I then have a ServiceRemote class that looks like this: ``` def __init__(self,ip,port): self.rpcClient = xmlrpclib.Server('http://%s:%d' %(ip,port)) def __getattr__(self, name): # forward all calls to the rpc client return getattr(self.rpcClient, name) ``` So all calls on the ServiceRemote object will be forwarded to xmlrpclib.Server, which then forwards it to the remote server. The problem is a method in the service that takes named varargs: ``` @useDb def select(self, db, fields, **kwargs): pass ``` The @useDb decorator wraps the function, creating the db before the call and opening it, then closing it after the call is done before returning the result. When I call this method, I get the error "**call**() got an unexpected keyword argument 'name'". So, is it possible to call methods taking variable named arguments remotely? Or will I have to create an override for each method variation I need. --- Thanks for the responses. I changed my code around a bit so the question is no longer an issue. However now I know this for future reference if I indeed do need to implement positional arguments and support remote invocation. I think a combination of Thomas and praptaks approaches would be good. Turning kwargs into positional args on the client through xmlrpclient, and having a wrapper on methods serverside to unpack positional arguments.
You can't do this with plain xmlrpc since it has no notion of keyword arguments. However, you can superimpose this as a protocol on top of xmlrpc that would always pass a list as first argument, and a dictionary as a second, and then provide the proper support code so this becomes transparent for your usage, example below: ## Server ``` from SimpleXMLRPCServer import SimpleXMLRPCServer class Server(object): def __init__(self, hostport): self.server = SimpleXMLRPCServer(hostport) def register_function(self, function, name=None): def _function(args, kwargs): return function(*args, **kwargs) _function.__name__ = function.__name__ self.server.register_function(_function, name) def serve_forever(self): self.server.serve_forever() #example usage server = Server(('localhost', 8000)) def test(arg1, arg2): print 'arg1: %s arg2: %s' % (arg1, arg2) return 0 server.register_function(test) server.serve_forever() ``` ## Client ``` import xmlrpclib class ServerProxy(object): def __init__(self, url): self._xmlrpc_server_proxy = xmlrpclib.ServerProxy(url) def __getattr__(self, name): call_proxy = getattr(self._xmlrpc_server_proxy, name) def _call(*args, **kwargs): return call_proxy(args, kwargs) return _call #example usage server = ServerProxy('http://localhost:8000') server.test(1, 2) server.test(arg2=2, arg1=1) server.test(1, arg2=2) server.test(*[1,2]) server.test(**{'arg1':1, 'arg2':2}) ```
XML-RPC doesn't really have a concept of 'keyword arguments', so xmlrpclib doesn't try to support them. You would need to pick a convention, then modify xmlrpclib.\_Method to accept keyword arguments and pass them along using that convention. For instance, I used to work with an XML-RPC server that passed keyword arguments as two arguments, '-KEYWORD' followed by the actual argument, in a flat list. I no longer have access to the code I wrote to access that XML-RPC server from Python, but it was fairly simple, along the lines of: ``` import xmlrpclib _orig_Method = xmlrpclib._Method class KeywordArgMethod(_orig_Method): def __call__(self, *args, **kwargs): if args and kwargs: raise TypeError, "Can't pass both positional and keyword args" args = list(args) for key in kwargs: args.append('-%s' % key.upper()) args.append(kwargs[key]) return _orig_Method.__call__(self, *args) xmlrpclib._Method = KeywordArgMethod ``` It uses monkeypatching because that's by far the easiest method to do this, because of some clunky uses of module globals and name-mangled attributes (\_\_request, for instance) in the ServerProxy class.
Using **kwargs with SimpleXMLRPCServer in python
[ "", "python", "simplexmlrpcserver", "xmlrpclib", "" ]
I require a tree / directed acyclic graph implementation something like this: ``` public class TreeNode<K, V> { private K key; // 'key' for this node, always present private V value; // 'value' for this node, doesn't have to be set private TreeNode<K, V> parent; private Set<TreeNode<K, V>> children; } ``` * There is no sorting of any kind. * The `TreeNode` is just a wrapper around the key and a possible value (nodes don't have to have values set). * I require links to both the parent and the children. Is there anything out there in the standard APIs or Commons etc that will do this for me? I don't mind writing it myself (and I'm certainly **not** asking you folks to) I just don't want to re-invent the wheel.
There doesn't seem to be anything of the kind. I asked [a similar question](https://stackoverflow.com/questions/66893/tree-data-structure-in-c) last week and ended up implementing my own tree. My implementation was very similar to what you're proposing: ``` public class TreeNode<T> { private LinkedList<TreeNode<T>> children = new LinkedList<TreeNode<T>>(); public T value { get; set; } public TreeNode(T value) { this.value = value; } public LinkedList<TreeNode<T>> GetChildren() { return children; } } ``` You will have to add a link back to the parent(s).
There's also <http://www.jgrapht.org>, which has software licensed under the LGPL. I have to warn you though, implementing your own is fraught with danger. If you plan on using recursion on your structure (which is a graph), you'll have to ensure that it's acyclic, or you'll run into infinite loop problems. Better to use third party code where they've already dealt with the issues.
Tree (directed acyclic graph) implementation
[ "", "java", "data-structures", "tree", "graph-theory", "" ]
I'm in the process of moving one of our projects from VS6 to VS2008 and I've hit the following compile error with mshtml.h: ``` 1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5272) : error C2143: syntax error : missing '}' before 'constant' 1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5275) : error C2143: syntax error : missing ';' before '}' 1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5275) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2059: syntax error : '}' 1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2143: syntax error : missing ';' before '}' 1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2059: syntax error : '}' ``` Following the first error statement drops into this part of the mshtml.h code, pointing at the "True = 1" line: ``` EXTERN_C const GUID CLSID_CDocument; EXTERN_C const GUID CLSID_CScriptlet; typedef enum _BoolValue { True = 1, False = 0, BoolValue_Max = 2147483647L } BoolValue; EXTERN_C const GUID CLSID_CPluginSite; ``` It looks like someone on expert-sexchange also came across this error but I'd rather not dignify that site with a "7 day free trial". Any suggestions would be most welcome.
There is probably a #define changing something. Try running just the preprocessor on your .cpp and generating a .i file. The setting is in the project property pages. EDIT: Also, you can get the answer from that other expert site by scrolling to the bottom of the page. They have to do that or Google will take them out of their indexes.
you might already have the symbols True & False defined, try ``` #undef True #undef False ``` before including that file.
Compile errors in mshtml.h compiling with VS2008
[ "", "c++", "visual-studio-2008", "" ]
Which gets called first - the base constructor or "other stuff here"? ``` public class MyExceptionClass : Exception { public MyExceptionClass(string message, string extrainfo) : base(message) { //other stuff here } } ```
The base constructor will be called first. try it: ``` public class MyBase { public MyBase() { Console.WriteLine("MyBase"); } } public class MyDerived : MyBase { public MyDerived():base() { Console.WriteLine("MyDerived"); } } ```
Base class constructors get called before derived class constructors, but derived class initializers get called before base class initializers. E.g. in the following code: ``` public class BaseClass { private string sentenceOne = null; // A public BaseClass() { sentenceOne = "The quick brown fox"; // B } } public class SubClass : BaseClass { private string sentenceTwo = null; // C public SubClass() { sentenceTwo = "jumps over the lazy dog"; // D } } ``` Order of execution is: C, A, B, D. Check out these 2 msdn articles: * [Why do initializers run in the opposite order as constructors? Part One](http://blogs.msdn.com/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one.aspx) * [Why do initializers run in the opposite order as constructors? Part Two](http://blogs.msdn.com/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two.aspx)
Base constructor in C# - Which gets called first?
[ "", "c#", ".net", "asp.net", "" ]
I need to write a java script. This is supposed to validate if the checkbox is selected in the page or not. The problem here is that the check box is inside a grid and is generated dynamically. The reason being the number of check box that need to be rendered is not know at design time. So the id is know only at the server side.
Here is a thought: As indicated by Anonymous you can generate javascript, if you are in ASP.NET you have some help with the RegisterClientScriptBlock() method. [MSDN on Injecting Client Side Script](http://msdn.microsoft.com/en-us/library/aa478975.aspx) Also you could write, or generate, a javascript function that takes in a checkbox as a parameter and add an onClick attribute to your checkbox definition that calls your function and passes itself as the parameter ``` function TrackMyCheckbox(ck) { //keep track of state } <input type="checkbox" onClick="TrackMyCheckbox(this);".... /> ```
You have to generate your javascript too, or at least a javascript data structure (array) wich must contain the checkboxes you should control. Alternatively you can create a containing element, and cycle with js on every child input element of type checkbox.
Dynamic Client Script
[ "", "javascript", "scripting", "server-side-scripting", "" ]
I'm currently primarily a [D](https://en.wikipedia.org/wiki/D_(programming_language)) programmer and am looking to add another language to my toolbox, preferably one that supports the metaprogramming hacks that just can't be done in a statically compiled language like D. I've read up on Lisp a little and I would love to find a language that allows some of the cool stuff that Lisp does, but without the strange syntax, etc. of Lisp. I don't want to start a language flame war, and I'm sure both Ruby and Python have their tradeoffs, so I'll list what's important to me personally. Please tell me whether Ruby, Python, or some other language would be best for me. Important: 1. Good metaprogramming. Ability to create classes, methods, functions, etc. at runtime. Preferably, minimal distinction between code and data, Lisp style. 2. Nice, clean, sane syntax and consistent, intuitive semantics. Basically a well thought-out, fun to use, modern language. 3. Multiple paradigms. No one paradigm is right for every project, or even every small subproblem within a project. 4. An interesting language that actually affects the way one thinks about programming. Somewhat important: 1. Performance. It would be nice if performance was decent, but when performance is a real priority, I'll use D instead. 2. Well-documented. Not important: 1. Community size, library availability, etc. None of these are characteristics of the language itself, and all can change very quickly. 2. Job availability. I am not a full-time, professional programmer. I am a grad student and programming is tangentially relevant to my research. 3. Any features that are primarily designed with very large projects worked on by a million code monkeys in mind.
There's not really a huge difference between python and ruby at least at an ideological level. For the most part, they're just different flavors of the same thing. Thus, I would recommend seeing which one matches your programming style more.
> I've read up on Lisp a little and I would love to find a language that allows some of the cool stuff that Lisp does, but without the strange syntax, etc. of Lisp. Wouldn't we all. > minimal distinction between code and data, Lisp style Sadly, the minimal distinction between code and data and "strange" syntax are consequences of each other. If you want easy-to-read syntax, you have Python. However, the code is *not* represented in any of the commonly-used built-in data structures. It fails—as most languages do—in item #1 of your 'important' list. That makes it difficult to provide useful help. You can't have it all. Remember, you aren't the first to have this thought. If something like your ideal language existed, we'd all be using it. Since the real world falls short of your ideals, you'll have to re-prioritize your wish list. The "important" section has to be rearranged to identify what's *really* important to you.
Python vs. Ruby for metaprogramming
[ "", "python", "ruby", "lisp", "metaprogramming", "" ]
This question is related to (but perhaps not quite the same as): [Does Django have HTML helpers?](https://stackoverflow.com/questions/61451/does-django-have-html-helpers) My problem is this: In Django, I am constantly reproducing the basic formatting for low-level database objects. Here's an example: I have two classes, Person and Address. There are multiple Addresses for each Person, setup likeso (in their respective **models.py**) ``` class Person(models.Model): ... class Address(models.Model): contact = models.ForeignKey(Person) ``` Now, whenever I look at a Person, I want to see all their Addresses. So suppose **Persons/views.py** has something likeso: ``` def detail(request, person_id): person = get_object_or_404( Person, pk=person_id ) return render_to_response('persons/details.html', { 'title' : unicode(person), 'addresses': person.address_set.all() } ) ``` And, I have a template, **persons/details.html**, with code, for example, like-so: ``` {% extends "base.html" %} {% for address in addresses %} <b>{{ address.name }}</b> {{ address.type }} <br> {{ address.street_1 }}<br> {{ address.street_2 }}<br> {{ address.city }} {{ address.stateprov }} {{ address.postalcode }}<br> {{ address.country }} <hr> {{ endfor }} ``` I am repeating this code quite a bit, often with minor variations, such when it's in a table, and then < br > must be substituted by < /td >< td >. Other times, I don't want a street\_2 to display (or the < br > after it). All to say, there is fundamental logic that I want to express, that I am even more loath to tote around with block-and-copy! What I want is a **persons/details.html** with, for example, the following: ``` {% extends "base.html" %} {% for address in addresses %} {% address.as_html4 %} {% endfor %} ``` And if I want inline table, something likeso (I guess!): ``` {% extends "base.html" %} <table><tr> {% for address in addresses %} <tr><td> {% address.as_html4 </td><td> %} </td></tr> {% endfor %} </table> ``` The question is, then: Where is the best place to put the formatting? The logic? Django seem to have the following (plausible) options: 1. Put the formatting in models.py 2. Put the logic/formatting in views.py 3. Put the logic/formatting in some other sub-class of Person or Address (i.e. addresses/html4.py) 4. Create custom tags Help / insight much appreciated!
Sounds like an [inclusion tag](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags) is what you're looking for. You could have a template and tag for each major variation and use the tag's arguments to customise the context for each template as required. Basic tag definition: ``` @register.inclusion_tag('person/address.html') def display_address(address): return {'address': address} ``` Use in templates (assuming the templatetag module containing it has already been `{% load %}`-ed): ``` {% display_address address %} ```
I would use a template tag outputting data using a template html-file a k a [inclusion-tag](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags)
In Django, where is the best place to put short snippets of HTML-formatted data?
[ "", "python", "django", "model-view-controller", "design-patterns", "" ]
I would like to use javascript to develop general-purpose GUI applications. Initially these are to run on Windows, but I would like them to ultimately be cross-platform. Is there a way to do this without having to make the application run in a browser?
Check out [Adobe AIR](http://en.wikipedia.org/wiki/Adobe_AIR). From Wikipedia: *Adobe AIR is a cross-platform runtime environment for building rich Internet applications using Adobe Flash, Adobe Flex, HTML, or Ajax, that can be deployed as a desktop application.* Also check out [Mozilla Prism (in beta)](http://labs.mozilla.com/2007/10/prism/).
### JsLibs Today I came across this: <http://code.google.com/p/jslibs/> (from [DZone](http://www.dzone.com/links/rss/jslibs_standalone_javascript_development_runtime.html)) JS Libs seems to meet my requirement. I'll have a look, and if I find that it's interesting, I'll post back here.
GUI apps in javascript without a browser?
[ "", "javascript", "user-interface", "" ]
Our Java code (not the test code) reads files from the current directory, which means the working directory needs to be set properly whenever we run the code. When launching a JUnit test from within Eclipse, a launch configuration automatically gets created. The problem is, that the working directory in that launch configuration is always by default the root project directory which is always wrong, the test fails, I have to open the launch configuration dialog, change the working directory and relaunch the test. This is very annoying. The same thing happens when I run a single test method. I've already considered these: * Changing the current directory from the test code - not possible by design. * When opening a file, pass a parent directory parameter - too difficult, since this would affect lots of places. * Use the *Copy launch configuration* feature of Eclipse to create new launch configurations from existing ones that already have a correct working directory set. This doesn't really makes sense here, since I would like to launch a test or a test method quickly, just by invoking "run this test / method as JUnit test". All in all, it looks like it's responsibility of Eclipse, not the code. Is there a way to set the **default** working directory for **all future, newly created** JUnit launch configurations?
As far as I can tell, there's no way of changing the default working directory for future JUnit launch configurations in Eclipse 3.4. This issue has also been [reported as a bug](https://bugs.eclipse.org/bugs/show_bug.cgi?id=67585) in the Eclipse bug database. However, it is possible in IDEA. There's the *Edit Defaults* button for setting all kinds of defaults for each launch config type separately.
This is a subjective answer: I believe you're doing your tests wrong, you shouldn't be loading the files from the JUnit using relative or complete paths, but instead, have them as resources in the project (add them to the build path) and load them as resources in the JUnit tests. This way if something changes on the filesystem, someone uses a different filesystem or IDE but still has them in the build path (as source folders) you're not going to have a problem. I'm unsure if this is what you mean but if you really want to change it go to the Run Configuration options -> Your JUnit -> Arguments tab, at the bottom (Eclipse 3.4) you see Working Directory, click 'other' and change it from there.
How to default the working directory for JUnit launch configurations in Eclipse?
[ "", "java", "eclipse", "junit", "eclipse-3.4", "" ]
Please suggest some good resources to start writing Java Web services.
The standard way in Java to write a web service is to use Apache Axis. If you are generating a web service client, then you need the WSDL (.xsd, .wsdl, etc) of the foreign web service, and then you can use wsdl2java (or preferably, the ANT task provided by axis-ant) to simply generate the code to do the communications and a model. If you are generating a web service on the server side, then you can use Java2WSDL to turn a Java model into a web service implementation, although you will have to code the server side within the Impl class it generates. You can then easily deploy on Tomcat, etc, using the axis.war and the generated deploy.wsdd script. There's plenty of documentation out there that will help.
If you're using the Spring Framework, I suggest [Spring-WS](http://static.springframework.org/spring-ws/sites/1.5/). There is a very helpful [reference guide](http://static.springframework.org/spring-ws/sites/1.5/reference/html/index.html) which should get you started.
How to learn Java Webservices
[ "", "java", "web-services", "" ]
Python's convention is that variables are created by first assignment, and trying to read their value before one has been assigned raises an exception. PHP by contrast implicitly creates a variable when it is read, with a null value. This means it is easy to do this in PHP: ``` function mymodule_important_calculation() { $result = /* ... long and complex calculation ... */; return $resukt; } ``` This function always returns null, and if null is a valid value for the functuion then the bug might go undetected for some time. The Python equivalent would complain that the variable `resukt` is being used before it is assigned. So... is there a way to configure PHP to be stricter with variable assignments?
**PHP** doesn't do much forward checking of things at parse time. The best you can do is crank up the warning level to report your mistakes, but by the time you get an E\_NOTICE, its too late, and its not possible to force E\_NOTICES to occur in advance yet. A lot of people are toting the "error\_reporting E\_STRICT" flag, but its still retroactive warning, and won't protect you from bad code mistakes like you posted. This gem turned up on the php-dev mailing-list this week and I think its just the tool you want. Its more a lint-checker, but it adds scope to the current lint checking PHP does. [**PHP-Initialized Google Project**](http://code.google.com/p/php-initialized/wiki/Features) There's the hope that with a bit of attention we can get this behaviour implemented in PHP itself. So put your 2-cents on the PHP mailing list / bug system / feature requests and see if we can encourage its integration.
There is no way to make it fail as far as I know, but with E\_NOTICE in error\_reporting settings you can make it throw a warning (well, a notice :-) But still a string you can search for ).
PHP equivalent of Perl's 'use strict' (to require variables to be initialzied before use)
[ "", "php", "" ]
I think I might be missing the point of having a logging framework for your application. In all the small apps I've always written a small "Logging" class and just pass log messages to a method in it which is written to a file. What is the purpose of a 3rd party logging framework like log4net? Is it thread safety with logging write operations or am I missing something?
That's an excellent question. The first reason is "why not?" If you are using a logging framework, then you'll reap the maintainability benefits of using something already packaged. The second reason is that logging is subtle. Different threads, sessions, classes and object instances may all come into play in logging, and you don't want to have to figure this problem out on the fly. The third reason is that you may find a performance bottleneck in your code. Figuring out that your code is slow because you're writing to a file without buffering or your hard drive has run out of disk space because the logger doesn't rollover and compress old files can be a pain in the neck. The fourth reason is that you may want to append to syslog, or write to a database, or to a socket, or to different files. Frameworks have this functionality built in. But really, the first answer is the best one; there's very little benefit to writing your own, and a whole bunch of drawbacks.
you might want to switch to log to a db for some message, or an alerting system that pages the poor person on support More importantly though, most logging frameworks allow you to specify the loglevel of different classes so you dont need to cut a new binary each time you want more/less logging (that verbose logging for the bug you just spotted in production) [Log4Net's site](http://logging.apache.org/log4net/release/features.html "Log4Net's site") has more detail
What is the point of using a Logging framework?
[ "", "c#", ".net", "logging", "" ]
I am reading image files in Java using ``` java.awt.Image img = Toolkit.getDefaultToolkit().createImage(filePath); ``` On some systems this doesn't work, it instead throws an AWTError complaining about sun/awt/motif/MToolkit. How else can you create a java.awt.Image object from an image file?
I read images using [ImageIO](http://java.sun.com/javase/6/docs/api/javax/imageio/ImageIO.html). ``` Image i = ImageIO.read(InputStream in); ``` The javadoc will offer more info as well.
There is several static methods in ImageIO that allow to read images from different sources. The most interesting in your case are: ``` BufferedImage read(ImageInputStream stream) BufferedImage read(File input) BufferedImage read(InputStream input) ``` I checked inside in the code. It uses the ImageReader abstract class, and there is three implementors: JPEGReader. PNGReader and GIFReader. These classes and BufferedImage do not use any native methods apparently, so it should always work. It seems that the AWTError you have is because you are running java in a headless configuration, or that the windows toolkit has some kind of problem. Without looking at the specific error is hard to say though. This solution will allow you to read the image (probably), but depending on what you want to do with it, the AWTError might be thrown later as you try to display it.
How do you read an image in Java when Toolkit.getDefaultToolkit() throws an AWTError?
[ "", "java", "image", "awt", "" ]
Has anyone had good experiences with any Java libraries for Graph algorithms. I've tried [JGraph](http://www.jgraph.com/jgraph.html) and found it ok, and there are a lot of different ones in google. Are there any that people are actually using successfully in production code or would recommend? To clarify, I'm not looking for a library that produces graphs/charts, I'm looking for one that helps with Graph algorithms, eg minimum spanning tree, Kruskal's algorithm Nodes, Edges, etc. Ideally one with some good algorithms/data structures in a nice Java OO API.
If you were using JGraph, you should give a try to [JGraphT](http://jgrapht.org/) which is designed for algorithms. One of its features is visualization using the JGraph library. It's still developed, but pretty stable. I analyzed the complexity of JGraphT algorithms some time ago. Some of them aren't the quickest, but if you're going to implement them on your own and need to display your graph, then it might be the best choice. I really liked using its API, when I quickly had to write an app that was working on graph and displaying it later.
Summary: * [JGraphT](https://github.com/jgrapht/jgrapht/) if you are more interested in data structures and algorithms. * [JGraph](https://www.jgraph.com/jgraph.html) if your primary focus is visualization. * [Jung](http://jung.sourceforge.net/), [yWorks](http://www.yworks.com), and [BFG](http://bfo.com/products/graph/) are other things people tried using. * [Prefuse](https://github.com/prefuse/Prefuse) is a no no since one has to rewrite most of it. * [Google Guava](https://github.com/google/guava/wiki/GraphsExplained) if you need good datastructures only. * [Apache Commons Graph](http://commons.apache.org/sandbox/commons-graph/). Currently dormant, but provides implementations for many algorithms. See <https://issues.apache.org/jira/browse/SANDBOX-458> for a list of implemented algorithms, also compared with Jung, GraphT, Prefuse, [jBPT](https://github.com/jbpt/codebase)
Good Java graph algorithm library?
[ "", "java", "algorithm", "graph", "" ]
I am a C# developer. Still learning. I had not learn all the features of C# 2.0 and now the new version of c# is being released. how do we cope up with this.what is the best option to cope up with the latest programming skills.
As Steve M said: Read. But don't stop there. You also have to write. First: Write Code. Try out the stuff you read about. Look at open source software and how things are done by others. Try those new techniques out. Second: Write text. Write a blog post or whatever on how to do something. You had a problem and you solved it, now write down what the problem was, what ideas for solutions you had and what solution you picked for which reasons. Get people to comment, get peer review of your own thinking that way.
1. Read good quality code. Locate other projects (open source or proprietary projects within your organizations) and look for how other engineers have approached particular issues. Look for idioms, design patterns, styles that you find particularly good and adopt them in your coding practices. 2. Concentrate on the basics. Sure knowing how to perform a particular operation best in C# is good, but knowing how and when to abstract, avoiding duplication, following style rules, and giving your identifiers appropriate names are more important skills. These are also more valuable because you can apply them to any language. 3. Improve your code. When you find in code something complicated or suboptimal try to think of a better way to write it. For instance, if you write a lot of boilerplate code, examine how you can use abstraction mechanisms, like subroutines, methods, or classes, to avoid the code duplication. If an expression is particularly long, think whether putting some of it into a separate function can increase its readability. 4. Use tools. There are tools, like FindBugs, that can locate suboptimal or downright wrong code constructs. Make it a habit to have your code pass cleanly through these tools, and also from your compiler's highest warning setting. 5. Have your code reviewed. Find a mentor and have him or her review your code. Be ready to accept criticism and learn from this experience. Later repay this favor to the community by acting as a mentor.
How to improve the program coding
[ "", "c#", "" ]
I am writing a query in SQL server2005. This is returning me a duplicate rows in the result. Can i eliminate this duplication with a particular column as the key?
You can eliminate complete duplicate rows using the DISTINCT keyword. If there is some key column that is a duplicate but the rest of the columns are not, then you would have to use aggregate functions and a GROUP BY clause to explain to SQL Server what data you do want returned.
SELECT DISTINCT will eliminate duplicate rows.
Duplicate result
[ "", "sql", "sql-server", "" ]
Let's say I have the following class: ``` public class Test<E> { public boolean sameClassAs(Object o) { // TODO help! } } ``` How would I check that `o` is the same class as `E`? ``` Test<String> test = new Test<String>(); test.sameClassAs("a string"); // returns true; test.sameClassAs(4); // returns false; ``` I can't change the method signature from `(Object o)` as I'm overridding a superclass and so don't get to choose my method signature. I would also rather not go down the road of attempting a cast and then catching the resulting exception if it fails.
An instance of `Test` has no information as to what `E` is at runtime. So, you need to pass a `Class<E>` to the constructor of Test. ``` public class Test<E> { private final Class<E> clazz; public Test(Class<E> clazz) { if (clazz == null) { throw new NullPointerException(); } this.clazz = clazz; } // To make things easier on clients: public static <T> Test<T> create(Class<T> clazz) { return new Test<T>(clazz); } public boolean sameClassAs(Object o) { return o != null && o.getClass() == clazz; } } ``` If you want an "instanceof" relationship, use `Class.isAssignableFrom` instead of the `Class` comparison. Note, `E` will need to be a non-generic type, for the same reason `Test` needs the `Class` object. For examples in the Java API, see `java.util.Collections.checkedSet` and similar.
The method I've always used is below. It is a pain and a bit ugly, but I haven't found a better one. You have to pass the class type through on construction, as when Generics are compiled class information is lost. ``` public class Test<E> { private Class<E> clazz; public Test(Class<E> clazz) { this.clazz = clazz; } public boolean sameClassAs(Object o) { return this.clazz.isInstance(o); } } ```
Java Generics: Comparing the class of Object o to <E>
[ "", "java", "generics", "" ]
getEmployeeNameByBatchId(int batchID) getEmployeeNameBySSN(Object SSN) getEmployeeNameByEmailId(String emailID) getEmployeeNameBySalaryAccount(SalaryAccount salaryAccount) or getEmployeeName(int typeOfIdentifier, byte[] identifier) -> In this methods the typeOfIdentifier tells if identifier is batchID/SSN/emailID/salaryAccount Which one of the above is better way implement a get method? These methods would be in a Servlet and calls would be made from an API which would be provided to the customers.
Why not overload the getEmployeeName(??) method? getEmployeeName(int BatchID) getEmployeeName(object SSN)(bad idea) getEmployeeName(String Email) etc. Seems a good 'many' approach to me.
You could use something like that: ``` interface Employee{ public String getName(); int getBatchId(); } interface Filter{ boolean matches(Employee e); } public Filter byName(final String name){ return new Filter(){ public boolean matches(Employee e) { return e.getName().equals(name); } }; } public Filter byBatchId(final int id){ return new Filter(){ public boolean matches(Employee e) { return e.getBatchId() == id; } }; } public Employee findEmployee(Filter sel){ List<Employee> allEmployees = null; for (Employee e:allEmployees) if (sel.matches(e)) return e; return null; } public void usage(){ findEmployee(byName("Gustav")); findEmployee(byBatchId(5)); } ``` If you do the filtering by an SQL query you would use the `Filter` interface to compose a WHERE clause. The good thing with this approach is that you can combine two filters easily with: ``` public Filter and(final Filter f1,final Filter f2){ return new Filter(){ public boolean matches(Employee e) { return f1.matches(e) && f2.matches(e); } }; } ``` and use it like that: ``` findEmployee(and(byName("Gustav"),byBatchId(5))); ``` What you get is similar to the `Criteria` API in Hibernate.
Get Methods: One vs Many
[ "", "java", "oop", "jakarta-ee", "" ]
I've not used C++ very much in the past, and have recently been doing a lot of C#, and I'm really struggling to get back into the basics of C++ again. This is particularly tricky as work mandates that none of the most handy C++ constructs can be used, so all strings must be char \*'s, and there is no provision for STL lists. What I'm currently trying to do is to create a list of strings, something which would take me no time at all using STL or in C#. Basically I want to have a function such as: ``` char **registeredNames = new char*[numberOfNames]; ``` Then, ``` RegisterName(const * char const name, const int length) { //loop to see if name already registered snipped if(notFound) { registeredNames[lastIndex++] = name; } } ``` or, if it was C#... ``` if(!registeredNames.Contains(name)) { registeredNames.Add(name); } ``` and I realize that it doesn't work. I know the const nature of the passed variables (a const pointer and a const string) makes it rather difficult, but my basic problem is that I've always avoided this situation in the past by using STL lists etc. so I've never had to work around it!
You'll probably need to use strcmp to see if the string is already stored: ``` for (int index=0; index<=lastIndex; index++) { if (strcmp(registeredNames[index], name) == 0) { return; // Already registered } } ``` Then if you really need to store a copy of the string, then you'll need to allocate a buffer and copy the characters over. ``` char* nameCopy = malloc(length+1); strcpy(nameCopy, name); registeredNames[lastIndex++] = nameCopy; ``` You didn't mention whether your input is NULL terminated - if not, then extra care is needed, and strcmp/strcpy won't be suitable.
There are legitimate reasons that STL might be avoided. When working in fixed environments where memory or speed is a premium, it's sometimes difficult to tell what is going on under the hood with STL. Yes, you can write your own memory allocators, and yes, speed generally isn't a problem, but there are differences between STL implementations across platforms, and those differences mighe be subtle and potentially buggy. Memory is perhaps my biggest concern when thinking about using it. Memory is precious, and how we use it needs to be tightly controlled. Unless you've been down this road, this concept might not make sense, but it's true. We do allow for STL usage in tools (outside of game code), but it's prohibited inside of the actual game. One other related problem is code size. I am slightly unsure of how much STL can contribute to executable size, but we've seen marked increases in code size when using STL. Even if your executable is "only" 2M bigger, that's 2M less RAM for something else for your game. STL is nice for sure. But it can be abused by programmers who don't know what they are doing. It's not intentional, but it can provide nasty surprises when you don't want to see them (again, memory bloat and performance issues) I'm sure that you are close with your solution. ``` for ( i = 0; i < lastIndex; i++ ) { if ( !strcmp(&registeredNames[i], name ) { break; // name was found } } if ( i == lastIndex ) { // name was not found in the registeredNames list registeredNames[lastIndex++] = strdup(name); } ``` You might not want to use strdup. That's simply an example of how to to store the name given your example. You might want to make sure that you either don't want to allocate space for the new name yourself, or use some other memory construct that might already be available in your app. And please, don't write a string class. I have held up string classes as perhaps the worst example of how not to re-engineer a basic C construct in C++. Yes, the string class can hide lots of nifty details from you, but it's memory usage patterns are terrible, and those don't fit well into a console (i.e. ps3 or 360, etc) environment. About 8 years ago we did the same time. 200000+ memory allocations before we hit the main menu. Memory was terribly fragmented and we couldn't get the rest of the game to fit in the fixed environment. We wound up ripping it out. Class design is great for some things, but this isn't one of them. This is an opinion, but it's based on real world experience.
C++ strings without <string> and STL
[ "", "c++", "string", "list", "" ]
I want to create variables inside a function from a dictionary. Let's say I have a dictionary, `bar`: ``` bar = { 'a': 1, 'b': 2, 'c': 3 } ``` That goes to: ``` def foo(): a = 1 b = 2 c = 3 ``` I want to make new variables with the variable names as `bar`'s keys (`a, b, c`), then set the values of the variables to the value of the corresponding key. So, in the end, it should be similar to: ``` bar = { k: v } # ---> def foo(): k = v ``` Is it possible? And if so, how?
Your question is not clear. If you want to "set" said variables when foo is not running, no, you can't. There is no frame object yet to "set" the local variables in. If you want to do that in the function body, you shouldn't (check the [python documentation](http://docs.python.org/lib/built-in-funcs.html) for locals()). However, you *could* do a `foo.__dict__.update(bar)`, and then you could access those variables even from inside the function as foo.a, foo.b and foo.c. The question is: why do you want to do that, and why isn't a class more suitable for your purposes?
From your comment, perhaps what you're really looking for is something like a bunch object: ``` class Bunch(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) b=Bunch(**form.cleaned_data) print b.first_name, b.last_name ``` (The \*\* syntax is because Bunch-type objects are usually used like Bunch(foo=12, bar='blah') - not used in your case but I've left it for consistency with normal usage) This does require a "b." prefix to access your variables, but if you think about it, this is no bad thing. Consider what would happen if someone crafted a POST request to overwrite variables you *aren't* expecting to be overwritten - it makes it easy to produce crashes and DOS attacks, and could easily introduce more serious security vulnerabilities.
Dynamically create variables inside function
[ "", "python", "" ]
Are there any commonly used patterns in Javascript for storing the URL's of endpoints that will be requested in an AJAX application? For example would you create a "Service" class to abstract the URL's away?
I've used something like this (used in Rails): ``` NAMESPACE.categories.baseUri = '/categories'; NAMESPACE.categories.getUri = function(options) { options = options || {}; var uri = [NAMESPACE.categories.baseUri]; if(options.id) { uri.push(options.id); } if(options.action) { uri.push(options.action); } if(options.format) { uri.push('?format=' + options.format); } return uri.join('/'); } ```
You could create a collection of ValuePairs where you'd store each URL value and an identifier: ``` function ControlValuePair(Id, Value) { this.Id = Id; this.Value = Value; } function CreateCollection(ClassName) { var obj=new Array(); eval("var t=new "+ClassName+"()"); for(_item in t) { eval("obj."+_item+"=t."+_item); } return obj; } function ValuePairsCollection() { this.Container=""; this.Add=function(obj) { this.push(obj); } } ``` Later you can iterate through the collection or look up the id.
How do you store request URL's in Javascript to satisfy the DRY principal?
[ "", "javascript", "ajax", "web-services", "design-patterns", "" ]
I have this bit of javascript written with jQuery 1.2.5. It's contained inside the main function() of a plugin that I wrote. The plugin is a horizontal gallery scroller very similar to jCarousel. It does alot of auto calculating of widths and determines how many to scroll based on that and the size of the images, which is what all the calculations are that are going on. What my question is, how do I prevent this from firing off before a previous execution is finished. For instance, if I get a little click happy and just frantically mash down on `.digi_next`. Things don't go so well in the UI when that happens and I'd like to fix it :) I thought the answer might lie in `queue`, but all my attempts at using it haven't turned out anything worthwhile. ``` var self = this; $(".digi_next", this.container).click(function(){ var curLeft = $(".digi_container", self.container).css("left").split("px")[0]; var newLeft = (curLeft*1) - (self.containerPad + self.containerWidth) * self.show_photos; if (newLeft < ((self.digi_gal_width - (self.containerPad + self.containerWidth) * self.show_photos)) * -1) { newLeft = ((self.digi_gal_width - (self.containerPad + self.containerWidth) * self.show_photos)) * -1; } $(".digi_container", self.container).animate({ left: newLeft + "px" }, self.rotateSpeed); }); ```
Just use a global busy flag. When you enter your click handler, check it, and only proceed if it's false. Immediately set it to true, and then set it back to false when the animation ends. JavaScript is single-threaded, so there is no race condition to worry about. ``` var busy = false; $("...").onclick(function() { if (busy) return false; busy = true; $("...").animate(..., ..., ..., function() { busy= false; }); return false; }); ```
Take a look at [jQuery UI](http://ui.jquery.com/). Specifically [the effects-part](http://docs.jquery.com/UI/Effects/Slide) of the plug in. I use the slide-effect on [my personal website](http://roosteronacid.com/) (click on the arrows at the sides of the boxes). I prevent users triggering the effect more than once - before the effect has ended - with the [**one** event-handler](http://docs.jquery.com/Events/one#typedatafn) and a callback function. [Here's the source-code](http://roosteronacid.com/index.js)
jQuery onClick execution
[ "", "javascript", "jquery", "animation", "onclick", "" ]
In MS SQL 2000 and 2005, given a datetime such as '2008-09-25 12:34:56' what is the most efficient way to get a datetime containing only '2008-09-25'? Duplicated [here](https://stackoverflow.com/questions/2775/whats-the-best-way-to-remove-the-time-portion-of-a-datetime-value-sql-server).
I must admit I hadn't seen the floor-float conversion shown by Matt before. I had to test this out. I tested a pure select (which will return Date and Time, and is not what we want), the reigning solution here (floor-float), a common 'naive' one mentioned here (stringconvert) and the one mentioned here that I was using (as I thought it was the fastest). I tested the queries on a test-server MS SQL Server 2005 running on a Win 2003 SP2 Server with a Xeon 3GHz CPU running on max memory (32 bit, so that's about 3.5 Gb). It's night where I am so the machine is idling along at almost no load. I've got it all to myself. Here's the log from my test-run selecting from a large table containing timestamps varying down to the millisecond level. This particular dataset includes dates ranging over 2.5 years. The table itself has over 130 million rows, so that's why I restrict to the top million. ``` SELECT TOP 1000000 CRETS FROM tblMeasureLogv2 SELECT TOP 1000000 CAST(FLOOR(CAST(CRETS AS FLOAT)) AS DATETIME) FROM tblMeasureLogv2 SELECT TOP 1000000 CONVERT(DATETIME, CONVERT(VARCHAR(10), CRETS, 120) , 120) FROM tblMeasureLogv2 SELECT TOP 1000000 DATEADD(DAY, DATEDIFF(DAY, 0, CRETS), 0) FROM tblMeasureLogv2 ``` > SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 1 ms. > > (1000000 row(s) affected) Table 'tblMeasureLogv2'. Scan count 1, logical reads 4752, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. > > SQL Server Execution Times: CPU time = 422 ms, elapsed time = 33803 ms. > > (1000000 row(s) affected) Table 'tblMeasureLogv2'. Scan count 1, logical reads 4752, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. > > SQL Server Execution Times: CPU time = 625 ms, elapsed time = 33545 ms. > > (1000000 row(s) affected) Table 'tblMeasureLogv2'. Scan count 1, logical reads 4752, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. > > SQL Server Execution Times: CPU time = 1953 ms, elapsed time = 33843 ms. > > (1000000 row(s) affected) Table 'tblMeasureLogv2'. Scan count 1, logical reads 4752, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. > > SQL Server Execution Times: CPU time = 531 ms, elapsed time = 33440 ms. SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 1 ms. > > SQL Server Execution Times: CPU time = 0 ms, elapsed time = 1 ms. What are we seeing here? Let's focus on the CPU time (we're looking at conversion), and we can see that we have the following numbers: ``` Pure-Select: 422 Floor-cast: 625 String-conv: 1953 DateAdd: 531 ``` From this it looks to me like the DateAdd (at least in this particular case) is slightly faster than the floor-cast method. Before you go there, I ran this test several times, with the order of the queries changed, same-ish results. Is this something strange on my server, or what?
``` Select DateAdd(Day, DateDiff(Day, 0, GetDate()), 0) ``` DateDiff(Day, 0, GetDate()) is the same as DateDiff(Day, '1900-01-01', GetDate()) Since DateDiff returns an integer, you will get the number of days that have elapsed since Jan 1, 1900. You then add that integer number of days to Jan 1, 1900. The net effect is removing the time component. I should also mention that this method works for any date/time part (like year, quarter, month, day, hour, minute, and second). ``` Select DateAdd(Year, DateDiff(Year, 0, GetDate()), 0) Select DateAdd(Quarter, DateDiff(Quarter, 0, GetDate()), 0) Select DateAdd(Month, DateDiff(Month, 0, GetDate()), 0) Select DateAdd(Day, DateDiff(Day, 0, GetDate()), 0) Select DateAdd(Hour, DateDiff(Hour, 0, GetDate()), 0) Select DateAdd(Second, DateDiff(Second, '20000101', GetDate()), '20000101') ``` The last one, for seconds, requires special handling. If you use Jan 1, 1900 you will get an error. Difference of two datetime columns caused overflow at runtime. You can circumvent this error by using a different reference date (like Jan 1, 2000).
Most efficient way in SQL Server to get date from date+time?
[ "", "sql", "sql-server", "t-sql", "" ]
Is there a simple method of parsing XML files in C#? If so, what?
I'd use [LINQ to XML](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/linq-to-xml) if you're in .NET 3.5 or higher.
It's very simple. I know these are standard methods, but you can create your own library to deal with that much better. Here are some examples: ``` XmlDocument xmlDoc= new XmlDocument(); // Create an XML document object xmlDoc.Load("yourXMLFile.xml"); // Load the XML document from the specified file // Get elements XmlNodeList girlAddress = xmlDoc.GetElementsByTagName("gAddress"); XmlNodeList girlAge = xmlDoc.GetElementsByTagName("gAge"); XmlNodeList girlCellPhoneNumber = xmlDoc.GetElementsByTagName("gPhone"); // Display the results Console.WriteLine("Address: " + girlAddress[0].InnerText); Console.WriteLine("Age: " + girlAge[0].InnerText); Console.WriteLine("Phone Number: " + girlCellPhoneNumber[0].InnerText); ``` Also, there are some [other methods](http://www.google.lt/search?hl=lt&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&hs=pLz&q=parse+XML+C%23&btnG=Paie%C5%A1ka&meta=) to work with. For example, [here](http://support.microsoft.com/kb/307548). And I think there is no one best method to do this; you always need to choose it by yourself, what is most suitable for you.
How does one parse XML files?
[ "", "c#", "xml", "" ]
I'd like to line up items approximately like this: ``` item1 item2 i3 longitemname i4 longitemname2 anotheritem i5 ``` Basically items of varying length arranged in a table like structure. The tricky part is the container for these can vary in size and I'd like to fit as many as I can in each row - in other words, I won't know beforehand how many items fit in a line, and if the page is resized the items should re-flow themselves to accommodate. E.g. initially 10 items could fit on each line, but on resize it could be reduced to 5. I don't think I can use an html table since I don't know the number of columns (since I don't know how many will fit on a line). I can use css to float them, but since they're of varying size they won't line up. So far the only thing I can think of is to use javascript to get the size of largest item, set the size of all items to that size, and float everything left. Any better suggestions?
This can be done using floated div's, calculating the max width, and setting all widths to the max. Here's jquery code to do it: html: ``` <div class="item">something</div> <div class="item">something else</div> ``` css: ``` div.item { float: left; } ``` jquery: ``` var max_width=0; $('div.item').each( function() { if ($(this).width() > max_width) { max_width=$(this).width(); } } ).width(max_width); ``` Not too ugly but not too pretty either, I'm still open to better suggestions...
What happens when you get one item thats rediculously large and makes the rest look small? I would consider two solutions: 1. What you've already come up with involving a float:left; rule and jQuery, but with a max max\_width as well or 2. Just decide on a preset width for all items before hand, based on what values you expect to be in there Then add an overflow:hidden; rule so items that are longer don't scew the table-look. You could even change the jQuery function to trim items that are longer, adding an elipsis (...) to the end.
How to line up items of varied length in a resizable space in CSS?
[ "", "javascript", "jquery", "css", "css-tables", "" ]
With Hibernate, can you create a composite ID where one of the columns you are mapping to the ID can have null values? This is to deal with a legacy table that has a unique key which can have null values but no primary key. I realise that I could just add a new primary key column to the table, but I'm wondering if there's any way to avoid doing this.
No. Primary keys can not be null.
You wont get error but Hibernate wont be able to map those rows with NULL value for composite column to your Entity. That means you get entity with NULL values in result.
Hibernate mapping a composite key with null values
[ "", "java", "hibernate", "" ]
Is there a javascript function I can use to detect whether a specific silverlight version is installed in the current browser? I'm particularly interested in the Silverlight 2 Beta 2 version. I don't want to use the default method of having an image behind the silverlight control which is just shown if the Silverlight plugin doesn't load. **Edit:** From link provided in accepted answer: Include Silverlight.js (from Silverlight SDK) ``` Silverlight.isInstalled("2.0"); ```
Include Silverlight.js (from Silverlight SDK) `Silverlight.isInstalled("4.0")` --- **Resource:** [<http://msdn.microsoft.com/en-us/library/cc265155(vs.95).aspx>](http://msdn.microsoft.com/en-us/library/cc265155(vs.95).aspx)
Please actually use the latest script available at <http://code.msdn.microsoft.com/silverlightjs> for the latest updates. This has several fixes in it.
Detect via javascript whether Silverlight is installed
[ "", "javascript", "silverlight", "" ]
Is it possible to **dynamically create and modify images** on a **per pixel level** in JavaScript (on client side)? Or has this to be done with server based languaged, such as PHP? My use case is as follows: * The user opens webpage and loads locally stored image * A preview of the image is displayed * The user can modify the image with a set of sliders (pixel level operations) * In the end he can download the image to his local HDD When searching in the web I just found posts about using IE's filtering method, but didn't find anything about image editing functions in JavaScript.
This has to be done on the server side. One thing you might look at doing is allowing all the editing to go on client side, and then in the end POST the final image (via AJAX) to the server to allow it to return it to you as the correct MIME type, and correctly packed.
Some browsers support the canvas: <http://developer.mozilla.org/En/Drawing_Graphics_with_Canvas>
Creating/modifying images in JavaScript
[ "", "javascript", "image", "" ]
Deep down in WinDef.h there's this relic from the segmented memory era: ``` #define far #define near ``` This obviously causes problems if you attempt to use near or far as variable names. Any clean workarounds? Other then renaming my variables?
You can safely undefine them, contrary to claims from others. The reason is that they're just macros's. They only affect the preprocessor between their definition and their undefinition. In your case, that will be from early in windows.h to the last line of windows.h. If you need extra windows headers, you'd include them after windows.h and before the #undef. In your code, the preprocessor will simply leave the symbols unchanged, as intended. The comment about older code is irrelevant. That code will be in a separate library, compiled independently. Only at link time will these be connected, when macros are long gone.
Undefine any macros you don't want after including `windows.h`: ``` #include <windows.h> #undef near #undef far ```
Is there a clean way to prevent windows.h from creating a near & far macro?
[ "", "c++", "c", "winapi", "dos", "" ]
I have a query form that I would like to submit as a GET request so the result page may be bookmarked and otherwise RESTful. It's your classical text field with a submit button. How do I induce Seam/JSF to use GET and include the query expression as a parameter rather than POST, the default?
All you need to do is enable the SeamFilter in web.xml. See [Blog Example](http://docs.jboss.com/seam/2.0.2.SP1/reference/en-US/html_single/#blog) for an example RESTful application using Seam. The key is to use a Seam page parameter, defined in WEB-INF/pages.xml
you can use a PhaseListener to convert POST requests to GET requests or just to interpret GET requests so that they can be bookmarkable. This page should explain in more detail: <http://balusc.blogspot.com/2007/03/post-redirect-get-pattern.html>
Get Form request with Seam/JSF
[ "", "java", "rest", "jsf", "seam", "" ]
I am a .NET webdev using ASP.NET, C# etc... I "learned" javascript in college 5+ years ago and can do basic jobs with it. But I wonder if it is useful to become proficient in it. Why should I learn Javascript? Is it more advantageous then learning JQuery or a different [library](https://stackoverflow.com/questions/913/what-javascript-library-would-you-choose-for-a-new-project-and-why)?
Yes, definitely learn Javascript before you learn one of the libraries about. It's the whole walk-before-you-can-run thing.
Make sure you add these sites to your bookmarks: [Mozilla's developer site](http://developer.mozilla.org/En): This contains the reference to the Javascript API in Mozilla. This will help you make sure you're writing code that Firefox understands. [IE's site in Microsoft Developer Network](http://msdn.microsoft.com/en-us/ie/default.aspx): The same, for IE. [W3's reference of DOM for HTML](http://www.w3.org/TR/DOM-Level-2-HTML/html.html): In most web applications today, the Javascript code manipulates the DOM, which is an internal keeping track of the objects displayed on screen (but you already knew that, right ?) This is the reference to the DOM API. It is language neutral, which means it does not target Javascript, but these methods exist in Javascript too. [Douglas Crockford' site](http://javascript.crockford.com/): Doug Crockford is THE MAN when it comes down to Javascript. The articles in his page are a must read. Because Javascript has closures and first-class functions, he believes it is closer to Lisp and Scheme than to other languages. And he teaches you how to greatly improve your code with these language features. [Yahoo Developer network](http://developer.yahoo.com/): You may also want to check this. I'm not a regular visitor to this site, though, so I can't really say much about it.
Should I learn/become proficient in Javascript?
[ "", "javascript", "" ]
I want to have a `PHP script` send a `XML` formatted string to another `PHP script` that resides on a different server in a different part of town. Is there any nice, clean way of doing this? `(PHP5 and all the latest software available)`
check out [cURL](https://www.php.net/curl) for posting data between pages.
If it were me, I would just POST the xml data to the other script. You could use a socket from PHP, or use CURL. I think that's the cleanest solution, although SOAP is also viable if you don't mind the overhead of the SOAP request, as well as using a library.
Send data between two PHP scripts
[ "", "php", "xml", "" ]
What property in Netbeans to I need to change to set the name of my java swing app in the OS X menubar and dock? I found info.plist, but changing @PROJECTNAMEASIDENTIFIEER@ in multiple keys here had no effect. Thanks, hating netbeans.
The answer depends on how you run your application. If you run it from the command line, use '-Xdock:name=appname' in the JVM arguments. See the section "More tinkering with the menu bar" in the article linked to by Dan Dyer. If you are making a bundled, double-clickable application, however, you just need to set the standard CFBundle-related keys in your application's Info.plist (see the [documentation on Info.plist keys](http://developer.apple.com/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/PListKeys.html) for more details).
Check: ``` nbproject/project.properties nbproject/project.xml ``` in project.xml look for the name element... But... Why not just select the main project and right click and do rename?
<ProjectName.ProjectUI sucks as a name for my Netbeans java OS X app
[ "", "java", "macos", "netbeans", "menubar", "" ]
It's common knowledge that using System.Diagnostics.Process.Start is the way to launch a url from a C# applicaiton: System.Diagnostics.Process.Start("<http://www.mywebsite.com>"); However, if this url is invalid the application seems to have no way of knowing that the call failed or why. Is there a better way to launch a web browser? If not, what is my best option for url validation?
Try an approach as below. ``` try { var url = new Uri("http://www.example.com/"); Process.Start(url.AbsoluteUri); } catch (UriFormatException) { // URL is not parsable } ``` This does not ensure that the resource exist, but it does ensure the URL is wellformed. You might also want to check if the scheme is matching http or https.
If you need to verify that the URL exists, the only thing you can do is create a custom request in advance and verify that it works. I'd still use the Process.Start to shell out to the actual page, though.
What is the best way to launch a web browser with a custom url from a C# application?
[ "", "c#", ".net", "browser", "" ]
I have a problem with a string in C++ which has several words in Spanish. This means that I have a lot of words with accents and tildes. I want to replace them for their not accented counterparts. Example: I want to replace this word: "había" for habia. I tried replace it directly but with replace method of string class but I could not get that to work. I'm using this code: ``` for (it= dictionary.begin(); it != dictionary.end(); it++) { strMine=(it->first); found=toReplace.find_first_of(strMine); while (found!=std::string::npos) { strAux=(it->second); toReplace.erase(found,strMine.length()); toReplace.insert(found,strAux); found=toReplace.find_first_of(strMine,found+1); } } ``` Where `dictionary` is a map like this (with more entries): ``` dictionary.insert ( std::pair<std::string,std::string>("á","a") ); dictionary.insert ( std::pair<std::string,std::string>("é","e") ); dictionary.insert ( std::pair<std::string,std::string>("í","i") ); dictionary.insert ( std::pair<std::string,std::string>("ó","o") ); dictionary.insert ( std::pair<std::string,std::string>("ú","u") ); dictionary.insert ( std::pair<std::string,std::string>("ñ","n") ); ``` and `toReplace` strings is: ``` std::string toReplace="á-é-í-ó-ú-ñ-á-é-í-ó-ú-ñ"; ``` I obviously must be missing something. I can't figure it out. Is there any library I can use?. Thanks,
First, this is a really bad idea: you’re mangling somebody’s language by removing letters. Although the extra dots in words like “naïve” seem superfluous to people who only speak English, there are literally thousands of writing systems in the world in which such distinctions are very important. Writing software to mutilate someone’s speech puts you squarely on the wrong side of the tension between using computers as means to broaden the realm of human expression vs. tools of oppression. What is the reason you’re trying to do this? Is something further down the line choking on the accents? Many people would love to help you solve that. That said, libicu can do this for you. Open the [transform demo](http://www.icu-project.org/icu-bin/translit); copy and paste your Spanish text into the “Input” box; enter ``` NFD; [:M:] remove; NFC ``` as “Compound 1” and click transform. (With help from slide 9 of [Unicode Transforms in ICU](http://macchiato.com/slides/icu_transforms.pdf). Slides 29-30 show how to use the API.)
I disagree with the currently "approved" answer. The question makes perfect sense when you are indexing text. Like case-insensitive search, accent-insensitive search is a good idea. "naïve" matches "Naïve" matches "naive" matches "NAİVE" (you *do* know that an uppercase i is İ in Turkish? That's why you ignore accents) Now, the best algorithm is hinted at the approved answer: Use NKD (decomposition) to decompose accented letters into the base letter and a seperate accent, and then remove all accents. There is little point in the re-composition afterwards, though. You removed most sequences which would change, and the others are for all intents and purposes identical anyway. WHat's the difference between æ in NKC and æ in NKD?
How to remove accents and tilde in a C++ std::string
[ "", "c++", "string", "text", "str-replace", "" ]
I currently have a fairly robust server-side validation system in place, but I'm looking for some feedback to make sure I've covered all angles. Here is a brief outline of what I'm doing at the moment: * Ensure the input is not empty, or is too long * Escape query strings to prevent SQL injection * Using regular expressions to reject invalid characters (this depends on what's being submitted) * Encoding certain html tags, like <script> (all tags are encoded when stored in a database, with some being decoded when queried to render in the page) Is there anything I'm missing? Code samples or regular expressions welcome.
You shouldn't need to "Escape" query strings to prevent SQL injection - you should be using prepared statements instead. Ideally your input filtering will happen before any other processing, so you know it will always be used. Because otherwise you only need to miss one spot to be vulnerable to a problem. Don't forget to encode HTML entities on output - to prevent XSS attacks.
You should encode every html tag, not only 'invalid' ones. This is a hot debate, but basically it boils down to there will always be some invalid HTML combination that you will forget to handle correctly (nested tags, mismatched tags some browsers interpret 'correctly' and so on). So the safest option in my opinion is to store everything as htmlentities and then, on output, print a validated HTML-safe-subset tree (as entities) from the content.
Comprehensive server-side validation
[ "", "php", "regex", "validation", "sql-injection", "server-side", "" ]
Consider these classes. ``` class Base { ... }; class Derived : public Base { ... }; ``` this function ``` void BaseFoo( std::vector<Base*>vec ) { ... } ``` And finally my vector ``` std::vector<Derived*>derived; ``` I want to pass `derived` to function `BaseFoo`, but the compiler doesn't let me. How do I solve this, without copying the whole vector to a `std::vector<Base*>`?
`vector<Base*>` and `vector<Derived*>` are unrelated types, so you can't do this. This is explained in the C++ FAQ [here](https://isocpp.org/wiki/faq/proper-inheritance#parkinglot-of-car-vs-vehicle). You need to change your variable from a `vector<Derived*>` to a `vector<Base*>` and insert `Derived` objects into it. Also, to avoid copying the `vector` unnecessarily, you should pass it by const-reference, not by value: ``` void BaseFoo( const std::vector<Base*>& vec ) { ... } ``` Finally, to avoid memory leaks, and make your code exception-safe, consider using a container designed to handle heap-allocated objects, e.g: ``` #include <boost/ptr_container/ptr_vector.hpp> boost::ptr_vector<Base> vec; ``` Alternatively, change the vector to hold a smart pointer instead of using raw pointers: ``` #include <memory> std::vector< std::shared_ptr<Base*> > vec; ``` or ``` #include <boost/shared_ptr.hpp> std::vector< boost::shared_ptr<Base*> > vec; ``` In each case, you would need to modify your `BaseFoo` function accordingly.
Instead of passing the container object (`vector<>`), pass in `begin` and `end` iterators like the rest of the STL algorithms. The function that receives them will be templated, and it won't matter if you pass in Derived\* or Base\*.
Getting a vector<Derived*> into a function that expects a vector<Base*>
[ "", "c++", "stl", "vector", "covariance", "" ]
One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?
Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, [here](http://mail.python.org/pipermail/python-list/2000-March/048085.html "Tim Peters"). That's why you can't use something 'not hashable' as a dict key, like a list: ``` >>> a = {} >>> b = ['some', 'list'] >>> hash(b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list objects are unhashable >>> a[b] = 'some' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list objects are unhashable ``` You can [read more about hash tables](http://en.wikipedia.org/wiki/Hash_table "Hash table on wikipedia") or [check how it has been implemented in python](https://hg.python.org/cpython/file/10eea15880db/Objects/dictobject.c "Dict Object in Python source code") and [why it is implemented that way](https://hg.python.org/cpython/file/10eea15880db/Objects/dictnotes.txt "Notes on optimizing dictionaries in the CPython distribution").
There must be more to a Python dictionary than a table lookup on hash(). By brute experimentation I found this **hash collision**: ``` >>> hash(1.1) 2040142438 >>> hash(4504.1) 2040142438 ``` Yet it doesn't break the dictionary: ``` >>> d = { 1.1: 'a', 4504.1: 'b' } >>> d[1.1] 'a' >>> d[4504.1] 'b' ``` Sanity check: ``` >>> for k,v in d.items(): print(hash(k)) 2040142438 2040142438 ``` Possibly there's another lookup level beyond hash() that avoids collisions between dictionary keys. Or maybe dict() uses a different hash. (By the way, this in Python 2.7.10. Same story in Python 3.4.3 and 3.5.0 with a collision at `hash(1.1) == hash(214748749.8)`.) (I haven't found any collisions in Python 3.9.6. Since the hashes are bigger -- `hash(1.1) == 230584300921369601` -- I estimate it would take my desktop a thousand years to find one. So I'll get back to you on this.)
Is a Python dictionary an example of a hash table?
[ "", "python", "hash", "dictionary", "hashmap", "hashtable", "" ]
Is there any way to create the *query parameters* for doing a *GET request* in JavaScript? Just like in Python you have [`urllib.urlencode()`](http://web.archive.org/web/20080926234926/http://docs.python.org:80/lib/module-urllib.html), which takes in a dictionary (or list of two tuples) and creates a string like `'var1=value1&var2=value2'`.
Here you go: ``` function encodeQueryData(data) { const ret = []; for (let d in data) ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d])); return ret.join('&'); } ``` Usage: ``` const data = { 'first name': 'George', 'last name': 'Jetson', 'age': 110 }; const querystring = encodeQueryData(data); ```
[URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) has increasing browser support. ``` const data = { var1: 'value1', var2: 'value2' }; const searchParams = new URLSearchParams(data); // searchParams.toString() === 'var1=value1&var2=value2' ``` Node.js offers the [querystring](https://nodejs.org/api/querystring.html) module. ``` const querystring = require('querystring'); const data = { var1: 'value1', var2: 'value2' }; const searchParams = querystring.stringify(data); // searchParams === 'var1=value1&var2=value2' ```
How to create query parameters in Javascript?
[ "", "javascript", "url", "urlencode", "" ]
I'm sending mail from my C# Application, using the SmtpClient. Works great, but I have to decide if I want to send the mail as Plain Text or HTML. I wonder, is there a way to send both? I think that's called multipart. I googled a bit, but most examples essentially did not use SmtpClient but composed the whole SMTP-Body themselves, which is a bit "scary", so I wonder if something is built in the .net Framework 3.0? If not, is there any really well used/robust Third Party Library for sending e-Mails?
What you want to do is use the AlternateViews property on the MailMessage <http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews.aspx>
The MSDN Documentation seems to miss one thing though, I had to set the content type manually, but otherwise, it works like a charm :-) ``` MailMessage msg = new MailMessage(username, nu.email, subject, body); msg.BodyEncoding = Encoding.UTF8; msg.SubjectEncoding = Encoding.UTF8; AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlContent); htmlView.ContentType = new System.Net.Mime.ContentType("text/html"); msg.AlternateViews.Add(htmlView); ```
Sending a mail as both HTML and Plain Text in .net
[ "", "c#", ".net", "" ]
What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, `['a', 'b', 'c']` to `'a,b,c'`? (The cases `['s']` and `[]` should be mapped to `'s'` and `''`, respectively.) I usually end up using something like `''.join(map(lambda x: x+',',l))[:-1]`, but also feeling somewhat unsatisfied.
``` my_list = ['a', 'b', 'c', 'd'] my_string = ','.join(my_list) ``` ``` 'a,b,c,d' ``` This won't work if the list contains integers --- And if the list contains non-string types (such as integers, floats, bools, None) then do: ``` my_string = ','.join(map(str, my_list)) ```
Why the `map`/`lambda` magic? Doesn't this work? ``` >>> foo = ['a', 'b', 'c'] >>> print(','.join(foo)) a,b,c >>> print(','.join([])) >>> print(','.join(['a'])) a ``` In case if there are numbers in the list, you could use list comprehension: ``` >>> ','.join([str(x) for x in foo]) ``` or a generator expression: ``` >>> ','.join(str(x) for x in foo) ```
How would you make a comma-separated string from a list of strings?
[ "", "python", "string", "list", "" ]
Between Eclipse/SWT or Netbeans/Matisse, what does either Java GUI editor give you in terms of rapid development and maintainability?
You are really asking two different questions: SWT vs Swing, and Eclipse GUI Editor vs Netbeans GUI Editor (Matisse). First, the difference between SWT and Swing is that they are two fundamentally different GUI libraries. This akin to asking the difference between Tk and Win32, or Java Swing vs .NET Forms (not to say that SWT is .NET). There are a lot of discussions out there discussing SWT vs Swing--I don't know enough about SWT to summarize the differences. First, let me say my bias is in favor of Netbeans and I have spent 10 years learning the IDE from its days as Forte. As far as the GUI editor, Eclipse and Netbeans have functionally similar products, but implement the code in very different ways. My observation is that Matisse behaves, functions, and produces code that's reminiscent of Visual Studio .NET code. There are clear initialziation sections and custom behaviors for certain objects (such as the JTable). You can "Customize" an object and add your own arbitrary code via the GUI editor very easily for everything from initialization to setting individual properties. For event handling, it defaults to replicating "delegates" in .NET by using anonymous inner classes and invoking a stand-alone method. The GUI editor itself provides detailed access to the form object model and has a rich set of customizations. You also have the freedom to drop non-GUI beans into the form for use by GUI components, such as models (tablemodel, listmodel, etc), JPA-related objects, Workers, etc. What used to take a week to produce with hand-coded SWING takes a day with Matisse (though you have to really learn Matisse to do this). If you've been hand-coding swing for many years, then relearning to use a GUI editor ***effectively*** is going to be a long, hard lession. The code is highly maintainable from within Matisse; it is NOT intended to be edited outside of Matisse, but the code is suitable for editing if you needed to (many folks I know use Netbeans GUI and then copy the source into Eclipse). The Eclipse GUI editor is a very different creature. The GUI editor(s) are roughly the same in terms of overall capability, but I have found them to be less polished. The layout capabilities are about equal, though errors are a bit less forgiving at times. Some customizations required me to go to the source file and edit the file directly, rather than getting access to code customizations through the GUI. The code produced is very different than Matisse. GUI Components are added and initialized through "getters" and is scattered throughout the file; this good because each component is isolated/grouped into a single function, but troublesome when you need to diagnose bad interactions between component initialization. The same goes with the event handlers--very different than matisse. Eclipse also did not provide any protections from me editing/breaking/tampering with the produced GUI file where as Netbeans was almost obnoxious with its protections. As far as maintainability, the Eclipse code is probably a little closer to the way a human would produce Java code... personally, I find the code it produces harder to maintain, but I've been looking at Matisse generated code since the first beta so my opinion is hardly objective on this issue. Netbeans also has the capability of using the same editor for building Swing framework applications, Netbeans RCP, etc... I am unsure if Eclipse does the same.
This is definitely subjective -- we use both, Eclipse and Netbeans. I think it comes down to a matter of preference.
What does either Java GUI editor offer for rapid development and maintainability (i.e., Eclipse/SWT and Netbeans/Matisse)?
[ "", "java", "eclipse", "user-interface", "netbeans", "" ]
Is there a way to collect (e.g. in a List) multiple 'generic' objects that don't share a common super class? If so, how can I access their common properties? For example: ``` class MyObject<T> { public T Value { get; set; } public string Name { get; set; } public MyObject(string name, T value) { Name = name; Value = value; } } var fst = new MyObject<int>("fst", 42); var snd = new MyObject<bool>("snd", true); List<MyObject<?>> list = new List<MyObject<?>>(){fst, snd}; foreach (MyObject<?> o in list) Console.WriteLine(o.Name); ``` Obviously, this is pseudo code, this doesn't work. Also I don't need to access the .Value property (since that wouldn't be type-safe). **EDIT:** Now that I've been thinking about this, It would be possible to use sub-classes for this. However, I think that would mean I'd have to write a new subclass for every new type. --- @[Grzenio](https://stackoverflow.com/questions/51586/accessing-non-generic-members-of-a-generic-object#51621) Yes, that exactly answered my question. Of course, now I need to duplicate the entire shared interface, but that's not a big problem. I should have thought of that... @[aku](https://stackoverflow.com/questions/51586/accessing-non-generic-members-of-a-generic-object#51611) You are right about the duck typing. I wouldn't expect two completely random types of objects to be accessible. But I thought generic objects would share some kind of common interface, since they are exactly the same, apart from the type they are parametrized by. Apparently, this is not the case automatically.
I don't think it is possible in C#, because MyObject is not a baseclass of MyObject. What I usually do is to define an interface (a 'normal' one, not generic) and make MyObject implement that interface, e.g. ``` interface INamedObject { string Name {get;} } ``` and then you can use the interface: ``` List<INamedObject> list = new List<INamedObject>(){fst, snd}; foreach (INamedObject o in list) Console.WriteLine(o.Name); ``` Did it answer your question?
C# doesn't support duck typing. You have 2 choices: interfaces and inheritance, otherwise you can't access similar properties of different types of objects.
Accessing non-generic members of a generic object
[ "", "c#", ".net", "generics", "" ]
I assume that `char* = "string"` is the same to `char* = new char[6]`. I believe these strings are created on the heap instead of the stack. So do I need to destroy them or free their memory when I'm done using them or do they get destroyed by themselves?
No. You only need to manually free strings when you manually allocate the memory yourself using the `malloc` function (in C) or the `new` operator (in C++). If you do not use `malloc` or `new`, then the `char*` or string will be created on the stack or as a compile-time constant.
No. When you say: ``` const char* c = "Hello World!"; ``` You are assigning c to a "pre-existing" string constant which is NOT the same as: ``` char* c = new char[6]; ``` Only in the latter case are you allocating memory on the heap. So you'd call delete when you're done.
Is there a need to destroy char * = "string" or char * = new char[6]?
[ "", "c++", "memory", "" ]
I am a MFC programmer who is new to C# and am looking for a simple control that will allow number entry and range validation.
Look at the "NumericUpDown" control. It has range validation, the input will always be numeric, and it has those nifty increment/decrement buttons.
I had to implement a Control which only accepted numbers, integers or reals. I build the control as a specialization of (read: derived from) TextBox control, and using input control and a regular expresión for the validation. Adding range validation is terribly easy. This is the code for building the regex. \_numericSeparation is a string with characters accepted as decimal comma values (for example, a '.' or a ',': $10.50 10,50€ ``` private string ComputeRegexPattern() { StringBuilder builder = new StringBuilder(); if (this._forcePositives) { builder.Append("([+]|[-])?"); } builder.Append(@"[\d]*(("); if (!this._useIntegers) { for (int i = 0; i < this._numericSeparator.Length; i++) { builder.Append("[").Append(this._numericSeparator[i]).Append("]"); if ((this._numericSeparator.Length > 0) && (i != (this._numericSeparator.Length - 1))) { builder.Append("|"); } } } builder.Append(@")[\d]*)?"); return builder.ToString(); } ``` The regular expression matches any number (i.e. any string with numeric characters) with only one character as a numeric separation, and a '+' or a '-' optional character at the beginning of the string. Once you create the regex (when instanciating the Control), you check if the value is correct overriding the OnValidating method. CheckValidNumber() just applies the Regex to the introduced text. If the regex match fails, activates an error provider with an specified error (set with ValidationError public property) and raises a ValidationError event. Here you could do the verification to know if the number is in the requiered range. ``` private bool CheckValidNumber() { if (Regex.Match(this.Text, this.RegexPattern).Value != this.Text) { this._errorProvider.SetError(this, this.ValidationError); return false; } this._errorProvider.Clear(); return true; } protected override void OnValidating(CancelEventArgs e) { bool flag = this.CheckValidNumber(); if (!flag) { e.Cancel = true; this.Text = "0"; } base.OnValidating(e); if (!flag) { this.ValidationFail(this, EventArgs.Empty); } } ``` As I said, i also prevent the user from input data in the text box other than numeric characteres overriding the OnKeyPress methdod: ``` protected override void OnKeyPress(KeyPressEventArgs e) { if ((!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar)) && (!this._numberSymbols.Contains(e.KeyChar.ToString()) && !this._numericSeparator.Contains(e.KeyChar.ToString()))) { e.Handled = true; } if (this._numberSymbols.Contains(e.KeyChar.ToString()) && !this._forcePositives) { e.Handled = true; } if (this._numericSeparator.Contains(e.KeyChar.ToString()) && this._useIntegers) { e.Handled = true; } base.OnKeyPress(e); } ``` The elegant touch: I check if the number valid every time the user releases a key, so the user can get feedback as he/she types. (But remember that you must be carefull with the ValidationFail event ;)) ``` protected override void OnKeyUp(KeyEventArgs e) { this.CheckValidNumber(); base.OnKeyUp(e); } ```
Looking for a simple C# numeric edit control
[ "", "c#", "edit", "numeric", "" ]
I know that that is not a question... erm anyway HERE is the question. I have inherited a database that has 1(one) table in that looks much like this. Its aim is to record what species are found in the various (200 odd) countries. ``` ID Species Afghanistan Albania Algeria American Samoa Andorra Angola .... Western Sahara Yemen Zambia Zimbabwe ``` A sample of the data would be something like this ``` id Species Afghanistan Albania American Samoa 1 SP1 null null null 2 SP2 1 1 null 3 SP3 null null 1 ``` It seems to me this is a typical many to many situation and I want 3 tables. Species, Country, and SpeciesFoundInCountry The link table (SpeciesFoundInCountry) would have foreign keys in both the species and Country tables. (It is hard to draw the diagram!) ``` Species SpeciesID SpeciesName Country CountryID CountryName SpeciesFoundInCountry CountryID SpeciesID ``` Is there a magic way I can generate an insert statement that will get the CountryID from the new Country table based on the column name and the SpeciesID where there is a 1 in the original mega table? I can do it for one Country (this is a select to show what I want out) ``` SELECT Species.ID, Country.CountryID FROM Country, Species WHERE (((Species.Afghanistan)=1)) AND (((Country.Country)="Afghanistan")); ``` (the mega table is called species) But using this strategy I would need to do the query for each column in the original table. Is there a way of doing this in sql? I guess I can OR a load of my where clauses together and write a script to make the sql, seems inelegant though! Any thoughts (or clarification required)?
I would use a script to generate all the individual queries, since this is a one-off import process. Some programs such as Excel are good at mixing different dimensions of data (comparing column names to data inside rows) but relational databases rarely are. However, you might find that some systems (such as Microsoft Access, surprisingly) have convenient tools which you can use to normalise the data. Personally I'd find it quicker to write the script but your relative skills with Access and scripting might be different to mine.
Why do you want to do it in SQL? Just write a little script that does the conversion.
Mending bad BAD database design once data is in the system
[ "", "sql", "ms-access", "database-design", "" ]
Should each class in my C# project get its own file (in your opinion)?
While the one class per file policy is strictly enforced in Java, it's not required by C#. However, it's generally a good idea. I typically break this rule if I have a very small helper class that is only used by the main class, but I prefer to do that as a nested inner class for clarity's sake. You can however, split a single class into multiple files [using the `partial` keyword](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/partial-classes-and-methods). This is useful for separating your code from wizard-generated code.
Files are cheap, you aren't doing anyone a favor by consolidating many classes into single files. In Visual Studio, renaming the file in Solution Explorer will rename the class and all references to that class in your project. Even if you rarely use that feature, the cheapness of files and the ease of managing them mean the benefit is infinitely valuable, when divided by its cost.
C# classes in separate files?
[ "", "c#", "" ]
Say I have: ``` void Render(void(*Call)()) { D3dDevice->BeginScene(); Call(); D3dDevice->EndScene(); D3dDevice->Present(0,0,0,0); } ``` This is fine as long as the function I want to use to render is a function or a `static` member function: ``` Render(MainMenuRender); Render(MainMenu::Render); ``` However, I really want to be able to use a class method as well since in most cases the rendering function will want to access member variables, and Id rather not make the class instance global, e.g. ``` Render(MainMenu->Render); ``` However I really have no idea how to do this, and still allow functions and `static` member functions to be used.
There are a lot of ways to skin this cat, including templates. My favorite is [Boost.function](http://www.boost.org/doc/libs/1_36_0/doc/html/function.html) as I've found it to be the most flexible in the long run. Also read up on [Boost.bind](http://www.boost.org/doc/libs/1_36_0/libs/bind/bind.html) for binding to member functions as well as many other tricks. It would look like this: ``` #include <boost/bind.hpp> #include <boost/function.hpp> void Render(boost::function0<void> Call) { // as before... } Render(boost::bind(&MainMenu::Render, myMainMenuInstance)); ```
You can make a wrapper function `void Wrap(T *t)` that just calls `t->Call()` and have `Render` take such a function together with an object. That is: ``` void Wrap(T *t) { t->Call(); } void Render(void (*f)(T *), T *t) { ... f(t); ... } ```
C++ function pointers and classes
[ "", "c++", "oop", "class", "function-pointers", "" ]
I want to use the macports version of python instead of the one that comes with Leopard.
I have both installed: ``` $ which python /usr/bin/python $ which python2.5 /opt/local/bin/python2.5 ``` I also added the following line to my `.profile`: ``` export PATH=/opt/local/bin:/opt/local/sbin:$PATH ```
Don't. Apple ships various system utilities that rely on the system Python (and particularly the Python "framework" build); removing it will cause you problems. Instead, modify your PATH environ variable in your `~/.bash_profile` to put `/opt/local/bin` first.
How do I uninstall python from OSX Leopard so that I can use the MacPorts version?
[ "", "python", "macos", "osx-leopard", "macports", "" ]
I'm using [TinyXML](http://www.grinninglizard.com/tinyxml/) to parse/build XML files. Now, according to [the documentation](http://www.grinninglizard.com/tinyxmldocs/) this library supports multibyte character sets through UTF-8. So far so good I think. But, the only API that the library provides (for getting/setting element names, attribute names and values, ... everything where a string is used) is through `std::string` or `const char*`. This has me doubting my own understanding of multibyte character set support. How can a string that only supports 8-bit characters contain a 16 bit character (unless it uses a code page, which would negate the 'supports Unicode' claim)? I understand that you could theoretically take a 16-bit code point and split it over 2 chars in a `std::string`, but that wouldn't transform the `std::string` to a 'Unicode' string, it would make it invalid for most purposes and would maybe accidentally work when written to a file and read in by another program. So, can somebody explain to me how a library can offer an '8-bit interface' (`std::string` or `const char*`) and still support 'Unicode' strings? (I probably mixed up some Unicode terminology here; sorry about any confusion coming from that).
First, utf-8 is stored in const char \* strings, as @quinmars said. And it's not only a superset of 7-bit ASCII (code points <= 127 always encoded in a single byte as themselves), it's furthermore careful that bytes with those values are never used as part of the encoding of the multibyte values for code points >= 128. So if you see a byte == 44, it's a '<' character, etc. All of the metachars in XML are in 7-bit ASCII. So one can just parse the XML, breaking strings where the metachars say to, sticking the fragments (possibly including non-ASCII chars) into a char \* or std::string, and the returned fragments remain valid UTF-8 strings even though the parser didn't specifically know UTF-8. Further (not specific to XML, but rather clever), even more complex things genrally just work (tm). For example, if you sort UTF-8 lexicographically by bytes, you get the same answer as sorting it lexicographically by code points, despite the variation in # of bytes used, because the prefix bytes introducing the longer (and hence higher-valued) code points are numerically greater than those for lesser values).
UTF-8 is compatible to 7-bit ASCII code. If the value of a byte is larger then 127, it means a multibyte character starts. Depending on the value of the first byte you can see how many bytes the character will take, that can be 2-4 bytes including the first byte (technical also 5 or 6 are possible, but they are not valid utf-8). Here is a good resource about UTF-8: [UTF-8 and Unicode FAQ](http://www.cl.cam.ac.uk/~mgk25/unicode.html), also the wiki page for utf8 is very informative. Since UTF-8 is char based and 0-terminated, you can use the standard string functions for most things. The only important thing is that the character count can differ from the byte count. Functions like strlen() return the byte count but not necessarily the character count.
How does the UTF-8 support of TinyXML work?
[ "", "c++", "unicode", "utf-8", "tinyxml", "" ]
Is there a built-in editor for a multi-line string in a `PropertyGrid`.
I found that `System.Design.dll` has `System.ComponentModel.Design.MultilineStringEditor` which can be used as follows: ``` public class Stuff { [Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))] public string MultiLineProperty { get; set; } } ```
No, you will need to create what's called a modal UI type editor. You'll need to create a class that inherits from UITypeEditor. This is basically a form that gets shown when you click on the ellipsis button on the right side of the property you are editing. The only drawback I found, was that I needed to decorate the specific string property with a specific attribute. It's been a while since I had to do that. I got this information from a book by Chris Sells called "Windows Forms Programming in C#" There's a commercial propertygrid called [Smart PropertyGrid.NET](http://www.visualhint.com/index.php/propertygrid/) by VisualHint.
Multi-line string in a PropertyGrid
[ "", "c#", ".net", "winforms", "propertygrid", "" ]
In an AI application I am writing in C++, 1. there is not much numerical computation 2. there are lot of structures for which run-time polymorphism is needed 3. very often, several polymorphic structures interact during computation In such a situation, are there any optimization techniques? While I won't care to optimize the application just now, one aspect of selecting C++ over Java for the project was to enable more leverage to optimize and to be able to use non-object oriented methods (templates, procedures, overloading). In particular, what are the optimization techniques related to virtual functions? Virtual functions are implemented through virtual tables in memory. Is there some way to pre-fetch these virtual tables onto L2 cache (the cost of fetching from memory/L2 cache is increasing)? Apart from this, are there good references for data locality techniques in C++? These techniques would reduce the wait time for data fetch into L2 cache needed for computation. *Update*: Also see the following related forums: [Performance Penalty for Interface](https://stackoverflow.com/questions/113830/performance-penalty-for-working-with-interfaces-in-c#171549), [Several Levels of Base Classes](https://stackoverflow.com/questions/99510/does-several-levels-of-base-classes-slow-down-a-classstruct-in-c)
Virtual functions are very efficient. Assuming 32 bit pointers the memory layout is approximately: ``` classptr -> [vtable:4][classdata:x] vtable -> [first:4][second:4][third:4][fourth:4][...] first -> [code:x] second -> [code:x] ... ``` The classptr points to memory that is typically on the heap, occasionally on the stack, and starts with a four byte pointer to the vtable for that class. But the important thing to remember is the vtable itself is not allocated memory. It's a static resource and all objects of the same class type will point to the exactly the same memory location for their vtable array. Calling on different instances won't pull different memory locations into L2 cache. This [example from msdn](http://msdn.microsoft.com/en-us/magazine/cc301398.aspx) shows the vtable for class A with virtual func1, func2, and func3. Nothing more than 12 bytes. There is a good chance the vtables of different classes will also be physically adjacent in the compiled library (you'll want to verify this is you're especially concerned) which could increase cache efficiency microscopically. ``` CONST SEGMENT ??_7A@@6B@ DD FLAT:?func1@A@@UAEXXZ DD FLAT:?func2@A@@UAEXXZ DD FLAT:?func3@A@@UAEXXZ CONST ENDS ``` The other performance concern would be instruction overhead of calling through a vtable function. This is also very efficient. Nearly identical to calling a non-virtual function. Again from the [example from msdn](http://msdn.microsoft.com/en-us/magazine/cc301398.aspx): ``` ; A* pa; ; pa->func3(); mov eax, DWORD PTR _pa$[ebp] mov edx, DWORD PTR [eax] mov ecx, DWORD PTR _pa$[ebp] call DWORD PTR [edx+8] ``` In this example ebp, the stack frame base pointer, has the variable `A* pa` at zero offset. The register eax is loaded with the value at location [ebp], so it has the A\*, and edx is loaded with the value at location [eax], so it has class A vtable. Then ecx is loaded with [ebp], because ecx represents "this" it now holds the A\*, and finally the call is made to the value at location [edx+8] which is the third function address in the vtable. If this function call was not virtual the mov eax and mov edx would not be needed, but the difference in performance would be immeasurably small.
Section 5.3.3 of the [draft Technical Report on C++ Performance](http://www.open-std.org/jtc1/sc22/wg21/docs/TR18015.pdf) is entirely devoted to the overhead of virtual functions.
AI Applications in C++: How costly are virtual functions? What are the possible optimizations?
[ "", "c++", "optimization", "" ]
Is there a good reason why there is no `Pair<L,R>` in Java? What would be the equivalent of this C++ construct? I would rather avoid reimplementing my own. It seems that **1.6** is providing something similar (`AbstractMap.SimpleEntry<K,V>`), but this looks quite convoluted.
In [a thread on `comp.lang.java.help`](http://groups.google.com/group/comp.lang.java.help/browse_thread/thread/f8b63fc645c1b487/1d94be050cfc249b), Hunter Gratzner gives some arguments against the presence of a `Pair` construct in Java. The main argument is that a class `Pair` doesn't convey any semantics about the relationship between the two values (how do you know what "first" and "second" mean ?). A better practice is to write a very simple class, like the one Mike proposed, for each application you would have made of the `Pair` class. `Map.Entry` is an example of a pair that carry its meaning in its name. To sum up, in my opinion it is better to have a class `Position(x,y)`, a class `Range(begin,end)` and a class `Entry(key,value)` rather than a generic `Pair(first,second)` that doesn't tell me anything about what it's supposed to do.
This is Java. You have to make your own tailored Pair class with descriptive class and field names, and not to mind that you will reinvent the wheel by writing hashCode()/equals() or implementing Comparable again and again.
What is the equivalent of the C++ Pair<L,R> in Java?
[ "", "java", "tuples", "std-pair", "" ]
Yet again, my teacher was unable to answer my question. I knew who may be able to... So, I've never really learned C. In C++, I would, obviously, use a cout statement all of the time. In a recent assignment, my teacher told us to make sure to put ``` setbuf( stdout , NULL ); ``` at the top of main() in order to get an unbuffered output, thus allowing us to see the output properly. My question is this: will this statement affect a cout statement, or simply a printf() statement that I call? Thanks in advance!
By default, iostreams and stdio are synchronised. [Reference.](http://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio) This doesn't mean that manually adjusting the stdio buffering is a good idea, though! You may wish to utilise `std::endl` or `std::flush` (from `<ostream>`), which may help you. e.g., ``` std::cout << "Hello, world!" << std::endl; ``` or ``` std::cout << "Hello, world!\n" << std::flush; ``` Both of these do the same thing. ([`std::endl`](http://en.cppreference.com/w/cpp/io/manip/endl) = print endline, then flush.)
By default, if stdout or cout is printing to a console, the output is line buffered. This means that every newline that is printed will flush the output. You can explicitly call flush() whenever you want to override the behavior just in case say, the output is going to be redirected to a file and you want to use tail -f and need certain outputs in realtime. As Chris said, [sync\_with\_stdio](http://www.cplusplus.com/reference/iostream/ios_base/sync_with_stdio.html) should tie the unbuffered stdout with an unbuffered cout (by default), but if all you are doing is using cout, instead of using setbuf on stdout, a better option is to use [pubsetbuf](http://www.cplusplus.com/reference/iostream/streambuf/pubsetbuf.html) on the pointer returned by [rdbuf](http://www.cplusplus.com/reference/iostream/ios/rdbuf.html). ie: ``` // make cout unbuffered std::cout.rdbuf()->pubsetbuf(0, 0); ``` Another function that may be interesting to look at is [tie](http://www.cplusplus.com/reference/iostream/ios/tie.html).
Does setbuf() affect cout?
[ "", "c++", "class-library", "" ]
From [this post](https://stackoverflow.com/questions/60419/do-i-really-need-to-use-transactions-in-stored-procedures-mssql-2005). One obvious problem is scalability/performance. What are the other problems that transactions use will provoke? Could you say there are two sets of problems, one for long running transactions and one for short running ones? If yes, how would you define them? EDIT: Deadlock is another problem, but data inconsistency might be worse, depending on the application domain. Assuming a transaction-worthy domain (banking, to use the canonical example), deadlock possibility is more like a cost to pay for ensuring data consistency, rather than a problem with transactions use, or you would disagree? If so, what other solutions would you use to ensure data consistency which are deadlock free?
It depends a lot on the transactional implementation inside your database and may also depend on the transaction isolation level you use. I'm assuming "repeatable read" or higher here. Holding transactions open for a long time (even ones which haven't modified anything) forces the database to hold on to deleted or updated rows of frequently-changing tables (just in case you decide to read them) which could otherwise be thrown away. Also, rolling back transactions can be really expensive. I know that in MySQL's InnoDB engine, rolling back a big transaction can take FAR longer than committing it (we've seen a rollback take 30 minutes). Another problem is to do with database connection state. In a distributed, fault-tolerant application, you can't ever really know what state a database connection is in. Stateful database connections can't be maintained easily as they could fail at any moment (the application needs to remember what it was in the middle of doing it and redo it). Stateless ones can just be reconnected and have the (atomic) command re-issued without (in most cases) breaking state.
You can get deadlocks even without using explicit transactions. For one thing, most relational databases will apply an implicit transaction to each statement you execute. Deadlocks are fundamentally caused by acquiring multiple locks, and any activity that involves acquiring more than one lock can deadlock with any other activity that involves acquiring at least two of the same locks as the first activity. In a database transaction, some of the acquired locks may be held longer than they would otherwise be held -- to the end of the transaction, in fact. The longer locks are held, the greater the chance for a deadlock. This is why a longer-running transaction has a greater chance of deadlock than a shorter one.
What are the problems of using transactions in a database?
[ "", "sql", "transactions", "deadlock", "" ]
I'm using C# and i have written a locally installed application that dynamically generates files which need to be on an FTP server. Do i generate them to disk then upload them to the FTP server? or is there a way to open a stream to an FTP server and write the files directly?
Check the code sample I gave in this answer, doesn't rely on writing to files. It's not SQL specific and was just a suggestion on how to use SQL CLR integration assemblies to upload output from sql queries to an FTP server. The for loop in the method is just to demonstrate writing to the FTP stream. You should be able to rework to you needs: [How to write stored procedure output directly to a file on an FTP without using local or temp files?](https://stackoverflow.com/questions/20587/execute-stored-procedure-sql-2005-and-place-results-into-a-csv-file-on-a-ftp-lo#20689)
You should follow the class: ``` System.Net.FtpWebRequest ``` You will see that its arguments are streams and you can send data to them from any source. When seaching for .Net capabilities you should be aware of the object browser for visual studio acessible in: View > other windows > object browser Is supplies a search over all known assembly .Net objects.
How to correctly write dynamic files to an FTP server?
[ "", "c#", "ftp", "" ]
OK, this might sound a bit confusing and complicated, so bear with me. We've written a framework that allows us to define friendly URLs. If you surf to any arbitrary URL, IIS tries to display a 404 error (or, in some cases, 403;14 or 405). However, IIS is set up so that anything directed to those specific errors is sent to an .aspx file. This allows us to implement an HttpHandler to handle the request and do stuff, which involves finding the an associated template and then executing whatever's associated with it. Now, this all works in IIS 5 and 6 and, to an extent, on IIS7 - but for one catch, which happens when you post a form. See, when you post a form to a non-existent URL, IIS says "ah, but that url doesn't exist" and throws a 405 "method not allowed" error. Since we're telling IIS to redirect those errors to our .aspx page and therefore handling it with our HttpHandler, this normally isn't a problem. But as of IIS7, all POST information has gone missing after being redirected to the 405. And so you can no longer do the most trivial of things involving forms. To solve this we've tried using a HttpModule, which preserves POST data but appears to not have an initialized Session at the right time (when it's needed). We also tried using a HttpModule for all requests, not just the missing requests that hit 404/403;14/405, but that means stuff like images, css, js etc are being handled by .NET code, which is terribly inefficient. Which brings me to the actual question: has anyone ever encountered this, and does anyone have any advice or know what to do to get things working again? So far someone has suggested using Microsoft's own [URL Rewriting module](http://learn.iis.net/page.aspx/460/using-url-rewrite-module/). Would this help solve our problem? Thanks.
Microsoft released a hotfix for this : [<http://support.microsoft.com/default.aspx/kb/956578>](http://support.microsoft.com/default.aspx/kb/956578)
Since IIS7 uses .net from the top down there would not be any performance overhead of using an HttpModule, In fact there are several Managed HttpModules that are always used on every request. When the BeginRequest event is fired, the SessionStateModule may not have been added to the Modules collection, so if you try to handle the request during this event no session state info will be available. Setting the HttpContext.Handler property will initialize the session state if the requested handler needs it, so you can just set the handler to your fancy 404 page that implements IRequiresSessionState. The code below should do the trick, though you may need to write a different implementation for the IsMissing() method: ``` using System.Web; using System.Web.UI; class Smart404Module : IHttpModule { public void Dispose() {} public void Init(HttpApplication context) { context.BeginRequest += new System.EventHandler(DoMapping); } void DoMapping(object sender, System.EventArgs e) { HttpApplication app = (HttpApplication)sender; if (IsMissing(app.Context)) app.Context.Handler = PageParser.GetCompiledPageInstance( "~/404.aspx", app.Request.MapPath("~/404.aspx"), app.Context); } bool IsMissing(HttpContext context) { string path = context.Request.MapPath(context.Request.Url.AbsolutePath); if (System.IO.File.Exists(path) || (System.IO.Directory.Exists(path) && System.IO.File.Exists(System.IO.Path.Combine(path, "default.aspx")))) return true; return false; } } ``` Edit: I added an implementation of IsMissing() Note: On IIS7, The session state module does not run globally by default. There are two options: Enable the session state module for all requests (see my comment above regarding running managed modules for all request types), or you could use reflection to access internal members inside System.Web.dll.
Posting forms to a 404 + HttpHandler in IIS7: why has all POST data gone missing?
[ "", "c#", ".net", "iis-7", "httphandler", "" ]
In JavaScript, what is the best way to determine if a date provided falls within a valid range? An example of this might be checking to see if the user input `requestedDate` is part of the next valid work week. Note that this is not just checking to see if one date is larger than another as a valid date would be equal to or greater than the lower end of the range while less than or equal to the upper end of the range.
This is actually a problem that I have seen come up before a lot in my works and the following bit of code is my answer to the problem. ``` // checkDateRange - Checks to ensure that the values entered are dates and // are of a valid range. By this, the dates must be no more than the // built-in number of days appart. function checkDateRange(start, end) { // Parse the entries var startDate = Date.parse(start); var endDate = Date.parse(end); // Make sure they are valid if (isNaN(startDate)) { alert("The start date provided is not valid, please enter a valid date."); return false; } if (isNaN(endDate)) { alert("The end date provided is not valid, please enter a valid date."); return false; } // Check the date range, 86400000 is the number of milliseconds in one day var difference = (endDate - startDate) / (86400000 * 7); if (difference < 0) { alert("The start date must come before the end date."); return false; } if (difference <= 1) { alert("The range must be at least seven days apart."); return false; } return true; } ``` Now a couple things to note about this code, the `Date.parse` function should work for most input types, but has been known to have issues with some formats such as "YYYY MM DD" so you should test that before using it. However, I seem to recall that most browsers will interpret the date string given to Date.parse based upon the computers region settings. Also, the multiplier for 86400000 should be whatever the range of days you are looking for is. So if you are looking for dates that are at least one week apart then it should be seven.
So if i understand currenctly, you need to look if one date is bigger than the other. ``` function ValidRange(date1,date2) { return date2.getTime() > date1.getTime(); } ``` You then need to parse the strings you are getting from the UI, with Date.parse, like this: ``` ValidRange(Date.parse('10-10-2008'),Date.parse('11-11-2008')); ``` Does that help?
Using Javascript, how do I make sure a date range is valid?
[ "", "javascript", "validation", "date", "" ]
I mean, how does Java decide which protocols are available? I run some code from inside Eclipse, and it works just fine. Then I run the same code from outside Eclipse, and I get "unknown protocol" MalformedURLException. Probably it has to do with the code base, or something? Any hints would be helpful. Thanks!
The work of resolving the protocol is done by the [`URLStreamHandler`](http://java.sun.com/javase/6/docs/api/java/net/URLStreamHandler.html), which are stored in `URL.handlers` by protocol in lowercase. The handler, in turn, is created by the [`URLStreamHandlerFactory`](http://java.sun.com/javase/6/docs/api/java/net/URLStreamHandlerFactory.html) at `URL.factory`. Maybe eclipse is monkeying with that? Some of the [URL constructors](http://java.sun.com/javase/6/docs/api/java/net/URL.html#URL(java.lang.String,%20java.lang.String,%20int,%20java.lang.String,%20java.net.URLStreamHandler)) take stream handlers and you can set the factory with [URL.setURLStreamHandlerFactory](http://java.sun.com/javase/6/docs/api/java/net/URL.html#setURLStreamHandlerFactory(java.net.URLStreamHandlerFactory)). Here's a web post about [developing protocol handlers](http://www.webbasedprogramming.com/JAVA-Developers-Guide/ch29.htm).
The java standard way of defining protocol handlers is described here: <http://java.sun.com/developer/onlineTraining/protocolhandlers/> This relies on the protocol handler class being available on the boot (?) classloader. That doesn't work well with OSGi (and thus Eclipse). OSGi provides a wrapper around this mechanism to allow bundles/plugins to contribute protocol handlers. See: <http://www.osgi.org/javadoc/r4v41/org/osgi/service/url/URLStreamHandlerService.html> Eclipse also provides its own protocol: bundle-resource (iirc) which definitely won't work outside of Eclipse.
how is MalformedURLException thrown in Java
[ "", "java", "protocols", "malformedurlexception", "" ]
I have the following problem: I have an HTML textbox (`<input type="text">`) whose contents are modified by a script I cannot touch (it is my page, but i'm using external components). I want to be notified in my script every time the value of that textbox changes, so I can react to it. I've tried this: ``` txtStartDate.observe('change', function() { alert('change' + txtStartDate.value) }); ``` which (predictably) doesn't work. It only gets executed if I myself change the textbox value with the keyboard and then move the focus elsewhere, but it doesn't get executed if the script changes the value. Is there another event I can listen to, that i'm not aware of? I'm using the Prototype library, and in case it's relevant, the external component modifying the textbox value is Basic Date Picker (www.basicdatepicker.com)
As you've implied, change (and other events) only fire when the user takes some action. A script modifying things won't fire any events. Your only solution is to find some hook into the control that you can hook up to your listener. Here is how I would do it: ``` basicDatePicker.selectDate = basicDatePicker.selectDate.wrap(function(orig,year,month,day,hide) { myListener(year,month,day); return orig(year,month,day,hide); }); ``` That's based on a cursory look with Firebug (I'm not familiar with the component). If there are other ways of selecting a date, then you'll need to wrap those methods as well.
addEventListener("[DOMControlValueChanged](http://www.whatwg.org/specs/web-forms/current-work/#the-domcontrolvaluechanged)" will fire when a control's value changes, even if it's by a script. addEventListener("[input](http://www.whatwg.org/specs/web-forms/current-work/#the-change)" is a direct-user-initiated filtered version of DOMControlValueChanged. Unfortunately, DOMControlValueChanged is only supported by Opera currently and input event support is broken in webkit. The input event also has various bugs in Firefox and Opera. This stuff will probably be cleared up in HTML5 pretty soon, fwiw. Update: As of 9/8/2012, DOMControlValueChanged support has been dropped from Opera (because it was removed from HTML5) and 'input' event support is much better in browsers (including less bugs) now.
Javascript Events: Getting notified of changes in an <input> control value
[ "", "javascript", "html", "events", "" ]
I'm using C and sometimes I have to handle paths like * C:\Whatever * C:\Whatever\ * C:\Whatever\Somefile Is there a way to check if a given path is a directory or a given path is a file?
Call [GetFileAttributes](http://msdn.microsoft.com/en-us/library/aa364944(VS.85).aspx), and check for the FILE\_ATTRIBUTE\_DIRECTORY attribute.
stat() will tell you this. ``` struct stat s; if( stat(path,&s) == 0 ) { if( s.st_mode & S_IFDIR ) { // it's a directory } else if( s.st_mode & S_IFREG ) { // it's a file } else { // something else } } else { // error } ```
How can I tell if a given path is a directory or a file? (C/C++)
[ "", "c++", "c", "winapi", "" ]
I am working with a log of events where there are about 60 different "types" of events. Each event shares about 10 properties, and then there are subcategories of events that share various extra properties. How I work with these events does depend on their type or what categorical interfaces they implement. But it seems to be leading to code bloat. I have a lot of redundancy in the subclass methods because they implement some of the same interfaces. Is it more appropriate to use a single event class with a "type" property and write logic that checks type and maintain some organization of categories of types (e.g. a list of event types that are category a, a second list that are category b, etc)? Or is the subclass design more appropriate in this case? First Approach: ``` public interface Category1 {} public interface Category2 {} public abstract class Event { private base properties...; } public class EventType1 extends Event implements Category1, Category2 { private extra properties ...; } public class EventType2 extends Event implements Category3, Category4 { private extra properties ...; } ``` Second Approach: ``` public enum EventType {TYPE1, TYPE2, TYPE3, ...} public class Event { private union of all possible properties; private EventType type; } ``` My personal opinion is that it seems like a single event object is what is appropriate, because, if I am thinking about it correctly, there is no need for using inheritance to represent the model because it is really only the behavior and my conditions that alter based on the type. I need to have code that does stuff like: ``` if(event instanceof Category1) { ... } ``` This works well in the first approach in that instead of instanceof I can just call the method on the event and implement "the same code" in each of the appropriate subclasses. But the second approach is so much more concise. Then I write stuff like: ``` if(CATEGORY1_TYPES.contains(event.getEventType()) { ... } ``` And all my "processing logic" can be organized into a single class and none of it is redundantly spread out among the subclasses. So is this a case where although OO appears more appropriate, it would be better not too?
It depends on if each type of event inherently has different behavior that the event itself can execute. Do your Event objects need methods that behave differently per type? If so, use inheritance. If not, use an enum to classify the event type.
I would go with the object per event type solution, but I would instead group commonly used combinations of interfaces under (probably abstract) classes providing their **skeletal implementations**. This greatly reduces the code bloat generated by having many interfaces, but, on the other hand, increases the number of classes. But, if used properly and reasonably, it leads to cleaner code.
Should I not subclass by type of object if there are many types?
[ "", "java", "design-patterns", "inheritance", "" ]
I have a table `UserAliases` (`UserId, Alias`) with multiple aliases per user. I need to query it and return all aliases for a given user, the trick is to return them all in one column. Example: ``` UserId/Alias 1/MrX 1/MrY 1/MrA 2/Abc 2/Xyz ``` I want the query result in the following format: ``` UserId/Alias 1/ MrX, MrY, MrA 2/ Abc, Xyz ``` Thank you. I'm using SQL Server 2005. p.s. actual T-SQL query would be appreciated :)
You can use a function with COALESCE. ``` CREATE FUNCTION [dbo].[GetAliasesById] ( @userID int ) RETURNS varchar(max) AS BEGIN declare @output varchar(max) select @output = COALESCE(@output + ', ', '') + alias from UserAliases where userid = @userID return @output END GO SELECT UserID, dbo.GetAliasesByID(UserID) FROM UserAliases GROUP BY UserID GO ```
Well... I see that an answer was already accepted... but I think you should see another solutions anyway: ``` /* EXAMPLE */ DECLARE @UserAliases TABLE(UserId INT , Alias VARCHAR(10)) INSERT INTO @UserAliases (UserId,Alias) SELECT 1,'MrX' UNION ALL SELECT 1,'MrY' UNION ALL SELECT 1,'MrA' UNION ALL SELECT 2,'Abc' UNION ALL SELECT 2,'Xyz' /* QUERY */ ;WITH tmp AS ( SELECT DISTINCT UserId FROM @UserAliases ) SELECT LEFT(tmp.UserId, 10) + '/ ' + STUFF( ( SELECT ', '+Alias FROM @UserAliases WHERE UserId = tmp.UserId FOR XML PATH('') ) , 1, 2, '' ) AS [UserId/Alias] FROM tmp /* -- OUTPUT UserId/Alias 1/ MrX, MrY, MrA 2/ Abc, Xyz */ ```
How to return multiple values in one column (T-SQL)?
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
I'm just trying to time a piece of code. The pseudocode looks like: ``` start = get_ticks() do_long_code() print "It took " + (get_ticks() - start) + " seconds." ``` How does this look in Python? More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?
In the `time` module, there are two timing functions: `time` and `clock`. `time` gives you "wall" time, if this is what you care about. However, the python [docs](http://docs.python.org/lib/module-time.html) say that `clock` should be used for benchmarking. Note that `clock` behaves different in separate systems: * on MS Windows, it uses the Win32 function QueryPerformanceCounter(), with "resolution typically better than a microsecond". It has no special meaning, it's just a number (it starts counting the first time you call `clock` in your process). ``` # ms windows t0= time.clock() do_something() t= time.clock() - t0 # t is wall seconds elapsed (floating point) ``` * on \*nix, `clock` reports CPU time. Now, this is different, and most probably the value you want, since your program hardly ever is the only process requesting CPU time (even if you have no other processes, the kernel uses CPU time now and then). So, this number, which typically is smaller¹ than the wall time (i.e. time.time() - t0), is more meaningful when benchmarking code: ``` # linux t0= time.clock() do_something() t= time.clock() - t0 # t is CPU seconds elapsed (floating point) ``` Apart from all that, the [timeit](http://docs.python.org/lib/module-timeit.html) module has the `Timer` class that is supposed to use what's best for benchmarking from the available functionality. ¹ unless threading gets in the way… ² Python ≥3.3: there are [`time.perf_counter()` and `time.process_time()`](http://www.python.org/dev/peps/pep-0418/#id18). `perf_counter` is being used by the `timeit` module.
What you need is `time()` function from `time` module: ``` import time start = time.time() do_long_code() print "it took", time.time() - start, "seconds." ``` You can use [timeit](http://docs.python.org/lib/module-timeit.html) module for more options though.
Get timer ticks in Python
[ "", "python", "timer", "" ]
How can I set the protected `DoubleBuffered` property of the controls on a form that are suffering from flicker?
Here's a more generic version of [Dummy's solution](https://stackoverflow.com/questions/76993/how-to-double-buffer-net-controls-on-a-form#77041). We can use reflection to get at the protected [DoubleBuffered](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.doublebuffered.aspx) property, and then it can be set to **true**. **Note**: You should [pay your developer taxes](https://devblogs.microsoft.com/oldnewthing/20050822-11/?p=34483) and not [use double-buffering if the user is running in a terminal services session](https://devblogs.microsoft.com/oldnewthing/20060103-12/?p=32793) (e.g. Remote Desktop) This helper method will not turn on double buffering if the person is running in remote desktop. ``` public static void SetDoubleBuffered(System.Windows.Forms.Control c) { //Taxes: Remote Desktop Connection and painting //http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx if (System.Windows.Forms.SystemInformation.TerminalServerSession) return; System.Reflection.PropertyInfo aProp = typeof(System.Windows.Forms.Control).GetProperty( "DoubleBuffered", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); aProp.SetValue(c, true, null); } ```
Check [this thread](http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/aaed00ce-4bc9-424e-8c05-c30213171c2c) Repeating the core of that answer, you can turn on the WS\_EX\_COMPOSITED style flag on the window to get both the form and all of its controls double-buffered. The style flag is available since XP. It doesn't make painting faster but the entire window is drawn in an off-screen buffer and blitted to the screen in one whack. Making it look instant to the user's eyes without visible painting artifacts. It is not entirely trouble-free, some visual styles renderers can glitch on it, particularly TabControl when its has too many tabs. YMMV. Paste this code into your form class: ``` protected override CreateParams CreateParams { get { var cp = base.CreateParams; cp.ExStyle |= 0x02000000; // Turn on WS_EX_COMPOSITED return cp; } } ``` The big difference between this technique and Winform's double-buffering support is that Winform's version only works on one control at at time. You will still see each individual control paint itself. Which can look like a flicker effect as well, particularly if the unpainted control rectangle contrasts badly with the window's background.
How to double buffer .NET controls on a form?
[ "", "c#", "winforms", "flicker", "doublebuffered", "" ]
What's the best way to implement a SQL script that will grant select, references, insert, update, and delete permissions to a database role on all the user tables in a database? Ideally, this script could be run multiple times, as new tables were added to the database. SQL Server Management Studio generates scripts for individual database objects, but I'm looking for more of a "fire-and-forget" script.
Dr Zimmerman is on the right track here. I'd be looking to write a stored procedure that has a cursor looping through user objects using execute immediate to affect the grant. Something like this: ``` IF EXISTS ( SELECT 1 FROM sysobjects WHERE name = 'sp_grantastic' AND type = 'P' ) DROP PROCEDURE sp_grantastic GO CREATE PROCEDURE sp_grantastic AS DECLARE @object_name VARCHAR(30) ,@time VARCHAR(8) ,@rights VARCHAR(20) ,@role VARCHAR(20) DECLARE c_objects CURSOR FOR SELECT name FROM sysobjects WHERE type IN ('P', 'U', 'V') FOR READ ONLY BEGIN SELECT @rights = 'ALL' ,@role = 'PUBLIC' OPEN c_objects WHILE (1=1) BEGIN FETCH c_objects INTO @object_name IF @@SQLSTATUS <> 0 BREAK SELECT @time = CONVERT(VARCHAR, GetDate(), 108) PRINT '[%1!] hitting up object %2!', @time, @object_name EXECUTE('GRANT '+ @rights +' ON '+ @object_name+' TO '+@role) END PRINT '[%1!] fin!', @time CLOSE c_objects DEALLOCATE CURSOR c_objects END GO GRANT ALL ON sp_grantastic TO PUBLIC GO ``` Then you can fire and forget: ``` EXEC sp_grantastic ```
I'm sure there is an easier way, but you could loop through the sysobjects table in the database and grant permissions to any user table objects that exist. You could then run that multiple times whenever new tables are added.
What's the best way to implement a SQL script that will grant permissions to a database role on all the user tables in a database?
[ "", "sql", "sql-server", "t-sql", "permissions", "" ]
Scenario: You have an ASP.Net webpage that should display the next image in a series of images. If 1.jpg is currently loaded, the refresh should load 2.jpg. Assuming I would use this code, where do you get the current images name. ``` string currImage = MainPic.ImageUrl.Replace(".jpg", ""); currImage = currImage.Replace("~/Images/", ""); int num = (Convert.ToInt32(currImage) + 1) % 3; MainPic.ImageUrl = "~/Images/" + num.ToString() + ".jpg"; ``` The problem with the above code is that the webpage used is the default site with the image set to 1.jpg, so the loaded image is always 2.jpg. So in the process of loading the page, is it possible to pull the last image used from the pages properties?
``` int num = 1; if(Session["ImageNumber"] != null) { num = Convert.ToInt32(Session["ImageNumber"]) + 1; } Session["ImageNumber"] = num; ```
You can store data in your page's [`ViewState`](http://msdn.microsoft.com/en-us/library/4yfdwycw(VS.71).aspx) dictionary So in your Page\_Load you could write something like... ``` var lastPicNum = (int)ViewState["lastPic"]; lastPicNum++; MainPic.ImageUrl = string.Format("~/Images/{0}.jpg", lastPicNum); ViewState["lastPic"] = lastPicNum; ``` you should get the idea. And if you're programming ASP.NET and still does not understands how ViewState and web forms work, you should read [this MSDN article](http://msdn.microsoft.com/en-us/library/ms972976.aspx) Understanding ViewState from the beginning will help with a lot of ASP.NET gotchas as well.
How do you get the current image name from an ASP.Net website?
[ "", "c#", "asp.net", "" ]
I am currently using Linq to NHibernate (although that is not an issue with regards to this question) to execute queries against my database and I want to be able to test whether the current `IQueryable` result instance has been executed or not. The debugger knows that my `IQueryable` has not been *'invoked'* because it tells me that expanding the Results property will *'enumerate'* it. Is there a way for me to programmatically identify that as well. I hope that makes sense :)
How about writing an IQueryable wrapper like this: ``` class QueryableWrapper<T> : IQueryable<T> { private IQueryable<T> _InnerQueryable; private bool _HasExecuted; public QueryableWrapper(IQueryable<T> innerQueryable) { _InnerQueryable = innerQueryable; } public bool HasExecuted { get { return _HasExecuted; } } public IEnumerator<T> GetEnumerator() { _HasExecuted = true; return _InnerQueryable.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public Type ElementType { get { return _InnerQueryable.ElementType; } } public System.Linq.Expressions.Expression Expression { get { return _InnerQueryable.Expression; } } public IQueryProvider Provider { get { return _InnerQueryable.Provider; } } } ``` Then you can use it like this: ``` var query = new QueryableWrapper<string>( from str in myDataSource select str); Debug.WriteLine("HasExecuted: " + query.HasExecuted.ToString()); foreach (string str in query) { Debug.WriteLine(str); } Debug.WriteLine("HasExecuted: " + query.HasExecuted.ToString()); ``` Output is: False String0 String1 ... True
Assuming you're using Visual Studio, you can insert `DataContext.Log = Console.Out` into your code. You can then watch the SQL as it's executed, in the output window. I'm not sure whether it's possible to programatically test whether the query has been executed. You can force it to execute, for example by calling `.ToList` on the query.
How can I test that my Linq IQueryable has executed
[ "", "c#", "linq", "" ]
We're in the process of setting up a new framework and way of doing business for our new internal apps. Our current design dictates that all security logic should be handled by our database, and all information (and I mean all) will be going in and out of the database via stored procedures. The theory is, the data access layer requests info from a stored procedure and passes over authentication to the database. The database determines the user's role/permissions and decides whether or not to perform the task (whether that be retrieving data or making an update). I guess this means fewer database transactions. One call to the database. If the security was in our data access layer, this would require 1 database call to determine if the user had proper permissions, and then 1 separate database call to perform the action. I, for one, find the SQL Management studio completely lacking as an IDE. My main concern is we will end up having to maintain some nasty amount of business logic in our stored procedures for some very minimal performance gains. Right now, we're using LINQ for our ORM. It seems light and fast, but best of all, its really easy to rapidly develop in. Is the maintenance cost worth the performance gain? Are we fooling ourselves into thinking there will even be a noticeable performance gain? Or are we just making a nightmare for ourselves? Our environment: * Internal, non-mission critical business apps * C#/ASP.NET 3.5 * Windows 2003 * MS SQL Server 2005 * 35 Medium sized web apps with approx 500 users
**Don't do that**. We recently had a **VERY BAD** experience when the "database guru" decided to go to another company. The maintenance of all the logic in the procedures are just horrible!! Yes, you're going to have some performance improvement, but that's not worth it. In fact, performance is not even a big concern in internal application. Invest more money in good servers. It'll pay off.
Unfortunately there is no "one true answer". The choice you must make depends on multiple factors, like: * The familiarity of the team with the given solutions (ie if a majority of them is comfortable writing SQL, it can be in the database, however if a majority of them is more comfortable with C#, it should be in the code) * The "political power" of each party * etc There is no decisive advantage in any direction (as you said performance gains are minimal), the one thing to keep in mind is the DRY (Don't Repeat Yourself) principle: don't reimplement the functionality twice (in the code and in the DB), because keeping them in synch will be a nightmare. Pick one solution and stick to it.
Should data security be performed on the database side?
[ "", "sql", "security", "stored-procedures", "" ]
This is something simple I came up with for [this question](https://stackoverflow.com/questions/146795/how-to-read-config-file-entries-from-an-ini-file). I'm not entirely happy with it and I saw it as a chance to help improve my use of STL and streams based programming. ``` std::wifstream file(L"\\Windows\\myini.ini"); if (file) { bool section=false; while (!file.eof()) { std::wstring line; std::getline(file, line); if (line.empty()) continue; switch (line[0]) { // new header case L'[': { std::wstring header; size_t pos=line.find(L']'); if (pos!=std::wstring::npos) { header=line.substr(1, pos); if (header==L"Section") section=true; else section=false; } } break; // comments case ';': case ' ': case '#': break; // var=value default: { if (!section) continue; // what if the name = value does not have white space? // what if the value is enclosed in quotes? std::wstring name, dummy, value; lineStm >> name >> dummy; ws(lineStm); WCHAR _value[256]; lineStm.getline(_value, ELEMENTS(_value)); value=_value; } } } } ``` How would you improve this? Please do not recommend alternative libraries - I just want a simple method for parsing out some config strings from an INI file.
> // what if the name = value does not have white space? > // what if the value is enclosed in quotes? I would use boost::regex to match for every different type of element, something like: ``` boost::smatch matches; boost::regex name_value("(\S+)\s*=\s*(\S+)"); if(boost::regex_match(line, matches, name_value)) { name = matches[1]; value = matches[2]; } ``` the regular expressions might need some tweaking. I would also replace de stream.getline with std::getline, getting rid of the static char array.
This: ``` for (size_t i=1; i<line.length(); i++) { if (line[i]!=L']') header.push_back(line[i]); else break; } ``` should be simplified by a call to wstrchr, wcschr, WSTRCHR, or something else, depending on what platform you are on.
Help improve this INI parsing code
[ "", "c++", "stl", "stream", "ini", "" ]
I have one thread that writes results into a Queue. In another thread (GUI), I periodically (in the IDLE event) check if there are results in the queue, like this: ``` def queue_get_all(q): items = [] while 1: try: items.append(q.get_nowait()) except Empty, e: break return items ``` Is this a good way to do it ? **Edit:** > I'm asking because sometimes the > waiting thread gets stuck for a few > seconds without taking out new > results. The "stuck" problem turned out to be because I was doing the processing in the idle event handler, without making sure that such events are actually generated by calling `wx.WakeUpIdle`, as is recommended.
I'd be very surprised if the `get_nowait()` call caused the pause by not returning if the list was empty. Could it be that you're posting a large number of (maybe big?) items between checks which means the receiving thread has a large amount of data to pull out of the `Queue`? You could try limiting the number you retrieve in one batch: ``` def queue_get_all(q): items = [] maxItemsToRetrieve = 10 for numOfItemsRetrieved in range(0, maxItemsToRetrieve): try: if numOfItemsRetrieved == maxItemsToRetrieve: break items.append(q.get_nowait()) except Empty, e: break return items ``` This would limit the receiving thread to pulling up to 10 items at a time.
If you're always pulling all available items off the queue, is there any real point in using a queue, rather than just a list with a lock? ie: ``` from __future__ import with_statement import threading class ItemStore(object): def __init__(self): self.lock = threading.Lock() self.items = [] def add(self, item): with self.lock: self.items.append(item) def getAll(self): with self.lock: items, self.items = self.items, [] return items ``` If you're also pulling them individually, and making use of the blocking behaviour for empty queues, then you should use Queue, but your use case looks much simpler, and might be better served by the above approach. **[Edit2]** I'd missed the fact that you're polling the queue from an idle loop, and from your update, I see that the problem isn't related to contention, so the below approach isn't really relevant to your problem. I've left it in in case anyone finds a blocking variant of this useful: For cases where you do want to block until you get at least one result, you can modify the above code to wait for data to become available through being signalled by the producer thread. Eg. ``` class ItemStore(object): def __init__(self): self.cond = threading.Condition() self.items = [] def add(self, item): with self.cond: self.items.append(item) self.cond.notify() # Wake 1 thread waiting on cond (if any) def getAll(self, blocking=False): with self.cond: # If blocking is true, always return at least 1 item while blocking and len(self.items) == 0: self.cond.wait() items, self.items = self.items, [] return items ```
Get all items from thread Queue
[ "", "python", "multithreading", "queue", "" ]
I'm creating an ORM in PHP, and I've got a class 'ORM' which basically creates an object corresponding to a database table (I'm aiming for similar to/same functionality as an ActiveRecord pattern.) ORM itself extends 'Database', which sets up the database connection. So, I can call: ```` ``` $c = new Customer(); $c->name = 'John Smith'; $c->save(); ``` ```` The ORM class provides this functionality (sets up the class properties, provides save(), find(), findAll() etc. methods), and Customer extends ORM. However, in the future I may be wanting to add extra public methods to Customer (or any other model I create), so should this be extending ORM or not? I know I haven't provided much information here, but hopefully this is understandable on a vague explanation, as opposed to posting up 300+ lines of code.
I agree with the other answers here - put the additional methods into a descendant class. I'd also add an asterisk to that though: each time you extend the class with extra methods, think about what you are trying to achieve with the extension, and think about whether or not it can be generalised and worked back into the parent class. For example: ``` // Customer.class.php function getByName($name) { // SELECT * FROM `customer` WHERE `name` = $name } // ** this could instead be written as: ** // ORM.class.php function getByField($field, $value) { // SELECT * FROM `$this->table` WHERE `$field` = $value } ```
You're certainly thinking correctly to put your business logic in a new class outside your 'ORM'. For me, instead simply extending the ORM-class, I'd rather encapsulate it with a new, value object class to provide an additional degree of freedom from your database design to free you up to think of the class as a pure business object.
Should I be extending this class? (PHP)
[ "", "php", "oop", "orm", "activerecord", "" ]
How can I setup a shared ccache without falling into a permissions problem? I would like to run a nightly or CI build with latest changes and share all created binaries throughout the R&D using a large ccache repository.
The easiest solution: create a new group (e.g. "devel"), and make all developers members of it. Give read/write permissions to that group on the directory hierarchy where the cache is maintained. The developers will also need to fix their umask.
See the newly written [Sharing a cache](https://ccache.dev/manual/3.7.11.html#_sharing_a_cache) section in ccache's manual. In essence, use the same `CCACHE_DIR` setting, set `CCACHE_UMASK` appropriately and consider using `CCACHE_BASEDIR`.
How to setup a shared ccache
[ "", "c++", "c", "compiler-construction", "build-process", "" ]
I have the following XML structure: ``` <?xml version="1.0" ?> <course xml:lang="nl"> <body> <item id="787900813228567" view="12000" title="0x|Beschrijving" engtitle="0x|Description"><![CDATA[Dit college leert studenten hoe ze een onderzoek kunn$ <item id="5453116633894965" view="12000" title="0x|Onderwijsvorm" engtitle="0x|Method of instruction"><![CDATA[instructiecollege]]></item> <item id="7433550075448316" view="12000" title="0x|Toetsing" engtitle="0x|Examination"><![CDATA[Opdrachten/werkstuk]]></item> <item id="015071401858970545" view="12000" title="0x|Literatuur" engtitle="0x|Required reading"><![CDATA[Wayne C. Booth, Gregory G. Colomb, Joseph M. Wi$ <item id="5960589172957031" view="12000" title="0x|Uitbreiding" engtitle="0x|Expansion"><![CDATA[]]></item> <item id="3610066867901779" view="12000" title="0x|Aansluiting" engtitle="0x|Place in study program"><![CDATA[]]></item> <item id="19232369892482925" view="12000" title="0x|Toegangseisen" engtitle="0x|Course requirements"><![CDATA[]]></item> <item id="3332396346891524" view="12000" title="0x|Doelgroep" engtitle="0x|Target audience"><![CDATA[]]></item> <item id="6606851872934866" view="12000" title="0x|Aanmelden bij" engtitle="0x|Enrollment at"><![CDATA[]]></item> <item id="1478643580820973" view="12000" title="0x|Informatie bij" engtitle="0x|Information at"><![CDATA[Docent]]></item> <item id="9710608434763993" view="12000" title="0x|Rooster" engtitle="0x|Schedule"><![CDATA[1e semester, maandag 15.00-17.00, zaal 1175/030]]></item> </body> </course> ``` I want to get the data from one of the item tags. To get to this tag, I use the following xpath: ``` $description = $xml->xpath("//item[@title='0x|Beschrijving']"); ``` This does indeed return an array in the form of: ``` Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 787900813228567 [view] => 12000 [title] => 0x|Beschrijving [engtitle] => 0x|Description ) ) ) ``` But where is the actual information (that is stored between the item tags) located? I must be doing something wrong, but I can't figure out what that might be... Probably something really simple... Help would be appreciated.
When you load the XML file, you'll need to handle the CDATA.. This example works: ``` <?php $xml = simplexml_load_file('file.xml', NULL, LIBXML_NOCDATA); $description = $xml->xpath("//item[@title='0x|Beschrijving']"); var_dump($description); ?> ``` Here's the output: ``` array(1) { [0]=> object(SimpleXMLElement)#2 (2) { ["@attributes"]=> array(4) { ["id"]=> string(15) "787900813228567" ["view"]=> string(5) "12000" ["title"]=> string(15) "0x|Beschrijving" ["engtitle"]=> string(14) "0x|Description" } [0]=> string(41) "Dit college leert studenten hoe ze een on" } } ```
I believe its equivalent to the \_\_toString() method on the object, so ``` echo $description[0]; ``` Should display it, or you can cast it; ``` $str = (string) $description[0]; ```
Retrieving CDATA contents from XML using PHP and simplexml
[ "", "php", "xpath", "simplexml", "" ]
See title: what does it mean for a C++ function to be inline?
The function is placed in the code, rather than being called, similar to using macros (conceptually). This can improve speed (no function call), but causes code bloat (if the function is used 100 times, you now have 100 copies). You should note this does not force the compiler to make the function inline, and it will ignore you if it thinks its a bad idea. Similarly the compiler may decide to make normal functions inline for you. This also allows you to place the entire function in a header file, rather than implementing it in a cpp file (which you can't anyways, since then you get an unresolved external if it was declared inline, unless of course only that cpp file used it).
It means one thing and one thing only: that the compiler will elide multiple definitions of the function. A function normally cannot be defined multiple times (i.e. if you place a non-inline function definition into a header and then #include it into multiple compilation units you will receive a linker error). Marking the function definition as "inline" suppresses this error (the linker ensures that the Right Thing happens). IT DOES NOT MEAN ANYTHING MORE! Most significantly, it does NOT mean that the compiler will embed the compiled function into each call site. Whether that occurs is entirely up to the whims of the compiler, and typically the inline modifier does little or nothing to change the compiler's mind. The compiler can--and does--inline functions that *aren't* marked inline, and it can make function calls to functions that *are* marked inline. Eliding multiple definitions is the thing to remember.
What Does It Mean For a C++ Function To Be Inline?
[ "", "c++", "inline-functions", "" ]
I am working on Linux with the GCC compiler. When my C++ program crashes I would like it to automatically generate a stacktrace. My program is being run by many different users and it also runs on Linux, Windows and Macintosh (all versions are compiled using `gcc`). I would like my program to be able to generate a stack trace when it crashes and the next time the user runs it, it will ask them if it is ok to send the stack trace to me so I can track down the problem. I can handle the sending the info to me but I don't know how to generate the trace string. Any ideas?
For Linux and I believe Mac OS X, if you're using gcc, or any compiler that uses glibc, you can use the backtrace() functions in `execinfo.h` to print a stacktrace and exit gracefully when you get a segmentation fault. Documentation can be found [in the libc manual](http://www.gnu.org/software/libc/manual/html_node/Backtraces.html). Here's an example program that installs a `SIGSEGV` handler and prints a stacktrace to `stderr` when it segfaults. The `baz()` function here causes the segfault that triggers the handler: ``` #include <stdio.h> #include <execinfo.h> #include <signal.h> #include <stdlib.h> #include <unistd.h> void handler(int sig) { void *array[10]; size_t size; // get void*'s for all entries on the stack size = backtrace(array, 10); // print out all the frames to stderr fprintf(stderr, "Error: signal %d:\n", sig); backtrace_symbols_fd(array, size, STDERR_FILENO); exit(1); } void baz() { int *foo = (int*)-1; // make a bad pointer printf("%d\n", *foo); // causes segfault } void bar() { baz(); } void foo() { bar(); } int main(int argc, char **argv) { signal(SIGSEGV, handler); // install our handler foo(); // this will call foo, bar, and baz. baz segfaults. } ``` Compiling with `-g -rdynamic` gets you symbol info in your output, which glibc can use to make a nice stacktrace: ``` $ gcc -g -rdynamic ./test.c -o test ``` Executing this gets you this output: ``` $ ./test Error: signal 11: ./test(handler+0x19)[0x400911] /lib64/tls/libc.so.6[0x3a9b92e380] ./test(baz+0x14)[0x400962] ./test(bar+0xe)[0x400983] ./test(foo+0xe)[0x400993] ./test(main+0x28)[0x4009bd] /lib64/tls/libc.so.6(__libc_start_main+0xdb)[0x3a9b91c4bb] ./test[0x40086a] ``` This shows the load module, offset, and function that each frame in the stack came from. Here you can see the signal handler on top of the stack, and the libc functions before `main` in addition to `main`, `foo`, `bar`, and `baz`.
It's even easier than "man backtrace", there's a little-documented library (GNU specific) distributed with glibc as libSegFault.so, which was I believe was written by Ulrich Drepper to support the program catchsegv (see "man catchsegv"). This gives us 3 possibilities. Instead of running "program -o hai": 1. Run within catchsegv: ``` $ catchsegv program -o hai ``` 2. Link with libSegFault at runtime: ``` $ LD_PRELOAD=/lib/libSegFault.so program -o hai ``` 3. Link with libSegFault at compile time: ``` $ gcc -g1 -lSegFault -o program program.cc $ program -o hai ``` In all 3 cases, you will get clearer backtraces with less optimization (gcc -O0 or -O1) and debugging symbols (gcc -g). Otherwise, you may just end up with a pile of memory addresses. You can also catch more signals for stack traces with something like: ``` $ export SEGFAULT_SIGNALS="all" # "all" signals $ export SEGFAULT_SIGNALS="bus abrt" # SIGBUS and SIGABRT ``` The output will look something like this (notice the backtrace at the bottom): ``` *** Segmentation fault Register dump: EAX: 0000000c EBX: 00000080 ECX: 00000000 EDX: 0000000c ESI: bfdbf080 EDI: 080497e0 EBP: bfdbee38 ESP: bfdbee20 EIP: 0805640f EFLAGS: 00010282 CS: 0073 DS: 007b ES: 007b FS: 0000 GS: 0033 SS: 007b Trap: 0000000e Error: 00000004 OldMask: 00000000 ESP/signal: bfdbee20 CR2: 00000024 FPUCW: ffff037f FPUSW: ffff0000 TAG: ffffffff IPOFF: 00000000 CSSEL: 0000 DATAOFF: 00000000 DATASEL: 0000 ST(0) 0000 0000000000000000 ST(1) 0000 0000000000000000 ST(2) 0000 0000000000000000 ST(3) 0000 0000000000000000 ST(4) 0000 0000000000000000 ST(5) 0000 0000000000000000 ST(6) 0000 0000000000000000 ST(7) 0000 0000000000000000 Backtrace: /lib/libSegFault.so[0xb7f9e100] ??:0(??)[0xb7fa3400] /usr/include/c++/4.3/bits/stl_queue.h:226(_ZNSt5queueISsSt5dequeISsSaISsEEE4pushERKSs)[0x805647a] /home/dbingham/src/middle-earth-mud/alpha6/src/engine/player.cpp:73(_ZN6Player5inputESs)[0x805377c] /home/dbingham/src/middle-earth-mud/alpha6/src/engine/socket.cpp:159(_ZN6Socket4ReadEv)[0x8050698] /home/dbingham/src/middle-earth-mud/alpha6/src/engine/socket.cpp:413(_ZN12ServerSocket4ReadEv)[0x80507ad] /home/dbingham/src/middle-earth-mud/alpha6/src/engine/socket.cpp:300(_ZN12ServerSocket4pollEv)[0x8050b44] /home/dbingham/src/middle-earth-mud/alpha6/src/engine/main.cpp:34(main)[0x8049a72] /lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe5)[0xb7d1b775] /build/buildd/glibc-2.9/csu/../sysdeps/i386/elf/start.S:122(_start)[0x8049801] ``` If you want to know the gory details, the best source is unfortunately the source: See <http://sourceware.org/git/?p=glibc.git;a=blob;f=debug/segfault.c> and its parent directory <http://sourceware.org/git/?p=glibc.git;a=tree;f=debug>
How to automatically generate a stacktrace when my program crashes
[ "", "c++", "gcc", "crash", "stack-trace", "assert", "" ]
Can there be buffer overflow/overrun vulnerabilities in completely managed asp.net web portal.If yes how can this be tested.
Not unless you exploit the webserver or .NET/ASP.NET stack itself.
In the general case, you don't need to worry about buffer overruns. This is one of the major advantages of managed code, garbage collection being perhaps the other major advantage. There are a few edge cases that you should be aware of - any time your managed code interacts with unmanaged code (Win32 API calls, COM interop, P/Invoke, etc) there is a potential for buffer overruns in the unmanaged code, based on parameters passed in from managed code. Also code marked as "unsafe" can directly manipulate memory addresses in such a way as to cause buffer overflow. Most C# code is written without using the "unsafe" keyword, though.
Is buffer overflow/overrun possible in completely managed asp.net c# web application
[ "", "c#", "asp.net", "buffer-overflow", "buffer-overrun", "" ]
In C++, it's not possible to initialize array members in the initialization list, thus member objects should have default constructors and they should be properly initialized in the constructor. Is there any (reasonable) workaround for this apart from not using arrays? [Anything that can be initialized using only the initialization list is in our application far preferable to using the constructor, as that data can be allocated and initialized by the compiler and linker, and every CPU clock cycle counts, even before `main`. However, it is not always possible to have a default constructor for every class, and besides, reinitializing the data again in the constructor rather defeats the purpose anyway.] E.g. I'd like to have something like this (but this one doesn't work): ``` class OtherClass { private: int data; public: OtherClass(int i) : data(i) {}; // No default constructor! }; class Foo { private: OtherClass inst[3]; // Array size fixed and known ahead of time. public: Foo(...) : inst[0](0), inst[1](1), inst[2](2) {}; }; ``` The only workaround I'm aware of is the non-array one: ``` class Foo { private: OtherClass inst0; OtherClass inst1; OtherClass inst2; OtherClass *inst[3]; public: Foo(...) : inst0(0), inst1(1), inst2(2) { inst[0]=&inst0; inst[1]=&inst1; inst[2]=&inst2; }; }; ``` **Edit**: It should be stressed that `OtherClass` has no default constructor, and that it is very desirable to have the linker be able to allocate any memory needed (one or more static instances of `Foo` will be created), using the heap is essentially *verboten*. I've updated the examples above to highlight the first point.
One possible workaround is to avoid the compiler calling the OtherClass constructor at all, and to call it on your own using placement new to initialize it whichever way you need. Example: ``` class Foo { private: char inst[3*sizeof(OtherClass)]; // Array size fixed. OtherClass has no default ctor. // use Inst to access, not inst OtherClass &Inst(int i) {return (OtherClass *)inst+i;} const OtherClass &Inst(int i) const {return (const OtherClass *)inst+i;} public: Foo(...) { new (Inst(0)) OtherClass(...); new (Inst(1)) OtherClass(...); new (Inst(2)) OtherClass(...); } ~Foo() { Inst(0)->~OtherClass(); Inst(1)->~OtherClass(); Inst(2)->~OtherClass(); } }; ``` To cater for possible alignment requirements of the OtherClass, you may need to use \_\_declspec(align(x)) if working in VisualC++, or to use a type other than char like: ``` Type inst[3*(sizeof(OtherClass)+sizeof(Type)-1)/sizeof(Type)]; ``` ... where Type is int, double, long long, or whatever describes the alignment requirements.
What data members are in OtherClass? Will value-initialization be enough for that class? If value-initialization is enough, then you can value-initialize an array in the member initialization list: ``` class A { public: A () : m_a() // All elements are value-initialized (which for int means zero'd) { } private: int m_a[3]; }; ``` If your array element types are class types, then the default constructor will be called. **EDIT:** Just to clarify the comment from Drealmer. Where the element type is non-POD, then it should have an "accessible default constructor" (as was stated above). If the compiler cannot call the default constructor, then this solution will not work. The following example, would not work with this approach: ``` class Elem { public: Elem (int); // User declared ctor stops generation of implicit default ctor }; class A { public: A () : m_a () // Compile error: No default constructor {} private: Elem m_a[10]; }; ```
Any workarounds for non-static member array initialization?
[ "", "c++", "" ]
I've been looking at F# recently, and while I'm not likely to leap the fence any time soon, it definitely highlights some areas where C# (or library support) could make life easier. In particular, I'm thinking about the pattern matching capability of F#, which allows a very rich syntax - much more expressive than the current switch/conditional C# equivalents. I won't try to give a direct example (my F# isn't up to it), but in short it allows: * match by type (with full-coverage checking for discriminated unions) [note this also infers the type for the bound variable, giving member access etc] * match by predicate * combinations of the above (and possibly some other scenarios I'm not aware of) While it would be lovely for C# to eventually borrow [ahem] some of this richness, in the interim I've been looking at what can be done at runtime - for example, it is fairly easy to knock together some objects to allow: ``` var getRentPrice = new Switch<Vehicle, int>() .Case<Motorcycle>(bike => 100 + bike.Cylinders * 10) // "bike" here is typed as Motorcycle .Case<Bicycle>(30) // returns a constant .Case<Car>(car => car.EngineType == EngineType.Diesel, car => 220 + car.Doors * 20) .Case<Car>(car => car.EngineType == EngineType.Gasoline, car => 200 + car.Doors * 20) .ElseThrow(); // or could use a Default(...) terminator ``` where getRentPrice is a Func<Vehicle,int>. [note - maybe Switch/Case here is the wrong terms... but it shows the idea] To me, this is a lot clearer than the equivalent using repeated if/else, or a composite ternary conditional (which gets very messy for non-trivial expressions - brackets galore). It also avoids a *lot* of casting, and allows for simple extension (either directly or via extension methods) to more-specific matches, for example an InRange(...) match comparable to the VB Select...Case "x To y" usage. **I'm just trying to gauge if people think there is much benefit from constructs like the above (in the absence of language support)?** Note additionally that I've been playing with 3 variants of the above: * a Func<TSource,TValue> version for evaluation - comparable to composite ternary conditional statements * an Action<TSource> version - comparable to if/else if/else if/else if/else * an Expression<Func<TSource,TValue>> version - as the first, but usable by arbitrary LINQ providers Additionally, using the Expression-based version enables Expression-tree re-writing, essentially inlining all the branches into a single composite conditional Expression, rather than using repeated invocation. I haven't checked recently, but in some early Entity Framework builds I seem to recall this being necessary, as it didn't like InvocationExpression very much. It also allows more efficient usage with LINQ-to-Objects, since it avoids repeated delegate invocations - tests show a match like the above (using the Expression form) performing at the same speed [marginally quicker, in fact] compared to the equivalent C# composite conditional statement. For completeness, the Func<...> based-version took 4 times as long as the C# conditional statement, but is still very quick and is unlikely to be a major bottleneck in most use-cases. I welcome any thoughts / input / critique / etc on the above (or on the possibilities of richer C# language support... here's hoping ;-p).
In C# 7, you can do: ``` switch(shape) { case Circle c: WriteLine($"circle with radius {c.Radius}"); break; case Rectangle s when (s.Length == s.Height): WriteLine($"{s.Length} x {s.Height} square"); break; case Rectangle r: WriteLine($"{r.Length} x {r.Height} rectangle"); break; default: WriteLine("<unknown shape>"); break; case null: throw new ArgumentNullException(nameof(shape)); } ```
After trying to do such "functional" things in C# (and even attempting a book on it), I've come to the conclusion that no, with a few exceptions, such things don't help too much. The main reason is that languages such as F# get a lot of their power from truly supporting these features. Not "you can do it", but "it's simple, it's clear, it's expected". For instance, in pattern matching, you get the compiler telling you if there's an incomplete match or when another match will never be hit. This is less useful with open ended types, but when matching a discriminated union or tuples, it's very nifty. In F#, you expect people to pattern match, and it instantly makes sense. The "problem" is that once you start using some functional concepts, it's natural to want to continue. However, leveraging tuples, functions, partial method application and currying, pattern matching, nested functions, generics, monad support, etc. in C# gets *very* ugly, very quickly. It's fun, and some very smart people have done some very cool things in C#, but actually *using* it feels heavy. What I have ended up using often (across-projects) in C#: * Sequence functions, via extension methods for IEnumerable. Things like ForEach or Process ("Apply"? -- do an action on a sequence item as it's enumerated) fit in because C# syntax supports it well. * Abstracting common statement patterns. Complicated try/catch/finally blocks or other involved (often heavily generic) code blocks. Extending LINQ-to-SQL fits in here too. * Tuples, to some extent. \*\* But do note: The lack of automatic generalization and type inference really hinder the use of even these features. \*\* All this said, as someone else mentioned, on a small team, for a specific purpose, yes, perhaps they can help if you're stuck with C#. But in my experience, they usually felt like more hassle than they were worth - YMMV. Some other links: * [Mono.Rocks playground](http://anonsvn.mono-project.com/viewvc/branches/rocks-playground/) has many similar things (as well as non-functional-programming-but-useful additions). * [Luca Bolognese's functional C# library](http://blogs.msdn.com/lucabol/archive/2008/04/01/a-c-library-to-write-functional-code-part-i-background.aspx) * [Matthew Podwysocki's functional C# on MSDN](http://code.msdn.microsoft.com/FunctionalCSharp)
Is there any benefit to this switch / pattern matching idea?
[ "", "c#", "switch-statement", "" ]
I'm not happy with the rendering of HTML by Swing's JEditorPane. In particular bullets for unordered lists are hideous. Customising the rendering seems extremely difficult. Therefore I'm looking for a replacement with better HTML rendering. Does this exist? (I asked Google, and found nothing except a promising dead link).
Something that I looked at extensively a while back - and there are many options - however I nearly ended up using <http://lobobrowser.org/cobra.jsp>, but then the project was cancelled so I can't tell you how it all turned out...
<http://today.java.net/pub/a/today/2004/05/24/html-pt1.html>
Is there a good drop-in replacement for Java's JEditorPane?
[ "", "java", "swing", "jeditorpane", "" ]
We have redesigned the structure to a website which has several business units. Now I want to redirect (301) to the new page. IE: was www.example.com/abc now www.example.com/default.aspx?article=abc I have tried to use Global.asax to do this, and it works properly when I debug through it. ``` if (Request.RawUrl.Contains("abc")) { Response.RedirectLocation = "/default.aspx?article=abc"; Response.StatusCode = 301; Response.StatusDescription = "Moved"; Response.End(); } ``` So <http://localhost:1234/example/abc> redirects properly, but (where 1234 is the port for the debugging server) <http://localhost/example/abc> does not redirect, it gives me a 404. Any ideas? --- Additional info: If I go to <http://localhost/example/abc/default.aspx> then it redirects properly.
Well, if the port indicates you are using the built-in web server (the one that comes with VS), this probably works because that *always* routes requests through the ASP.NET framework. Requests ending with /abc will not automatically route through the ASP.NET framework because IIS may not "know" you want them to. You need to check your IIS settings to make sure such requests are routed to the aspnet\_isapi.dll --- **EDIT:** To accomplish this, you need to add a [**wildcard mapping**](http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5c5ae5e0-f4f9-44b0-a743-f4c3a5ff68ec.mspx): 1. In IIS Manager, expand the local computer, expand the Web Sites folder, right-click the Web site or virtual directory that you want, and then click Properties. 2. Click the appropriate tab: Home Directory, Virtual Directory, or Directory. 3. In the Application settings area, click Configuration, and then click the Mappings tab. 4. To install a wildcard application map, do the following: * On the Mappings tab, click Add or Insert. * Type the path to the DLL in the Executable text box or click Browse to navigate to it (for example, the ASP.NET 2.0 dll is at c:\windows\microsoft.net\framework\v2.0.50727\aspnet\_isapi.dll on my machine) * For extension, use ".\*" without quotes, of course * Select which verbs you want to look for (GET,HEAD,POST,DEBUG are the usual for ASP.NET, you decide) * Make sure "Script engine" or "Application engine" is selected * Uncheck "Check that file exists" * Click okay. I may be off on this, but if I am, hopefully someone will correct me. :)
You should use the IIS wild card redirection, you will need something like this; ``` *; www.example.com/*; www.example.com/default.aspx?article=$0 ``` There is a reasonable reference at [Microsoft](http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/41c238b2-1188-488f-bf2d-464383b1bb08.mspx?mfr=true) If you're using Apache I think you'll need to modify the htaccess file.
How can I redirect and modify extension-less URLs via ASP.NET?
[ "", "c#", ".net", "iis", "configuration", "routes", "" ]
I need to set the text within a DIV element dynamically. What is the best, browser safe approach? I have prototypejs and scriptaculous available. ``` <div id="panel"> <div id="field_name">TEXT GOES HERE</div> </div> ``` Here's what the function will look like: ``` function showPanel(fieldName) { var fieldNameElement = document.getElementById('field_name'); //Make replacement here } ```
I would use Prototype's `update` method which supports plain text, an HTML snippet or any JavaScript object that defines a `toString` method. ``` $("field_name").update("New text"); ``` * [Element.update documentation](http://www.prototypejs.org/api/element/update)
You can simply use: ``` fieldNameElement.innerHTML = "My new text!"; ```
How do I replace text inside a div element?
[ "", "javascript", "html", "dom", "" ]
I am creating an SQL view for a file that strips out the spaces in a particular field. My question is if there is a why to set a key on that new view so a person can still CHAIN the file. We are on V5R3.
Okay found the answer at <http://archive.midrange.com/midrange-l/200809/msg01062.html>. It is not possible at V5R3. Supposedly at V6R1 this is possible.
Could you accomplish the same thing using a logical file or with an `OPNQRYF` statement? Both of those allow you to set key fields and may be able to strip out the spaces in a file.
Setting a key field on a view
[ "", "sql", "view", "ibm-midrange", "" ]
I try to fetch a Wikipedia article with Python's urllib: ``` f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes") s = f.read() f.close() ``` However instead of the html page I get the following response: Error - Wikimedia Foundation: ``` Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to () Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT ``` Wikipedia seems to block request which are not from a standard browser. Anybody know how to work around this?
You need to use the [urllib2](http://docs.python.org/lib/module-urllib2.html) that superseedes [urllib](http://docs.python.org/lib/module-urllib.html) in the [python std library](http://docs.python.org/lib/) in order to change the user agent. Straight from the [examples](http://web.archive.org/web/20070202031348/http://docs.python.org/lib/urllib2-examples.html) ``` import urllib2 opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] infile = opener.open('http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes') page = infile.read() ```
It is not a solution to the specific problem. But it might be intersting for you to use the mwclient library (<http://botwiki.sno.cc/wiki/Python:Mwclient>) instead. That would be so much easier. Especially since you will directly get the article contents which removes the need for you to parse the html. I have used it myself for two projects, and it works very well.
Fetch a Wikipedia article with Python
[ "", "python", "urllib2", "user-agent", "wikipedia", "http-status-code-403", "" ]
python's time module seems a little haphazard. For example, here is a list of methods in there, from the docstring: ``` time() -- return current time in seconds since the Epoch as a float clock() -- return CPU time since process start as a float sleep() -- delay for a number of seconds given as a float gmtime() -- convert seconds since Epoch to UTC tuple localtime() -- convert seconds since Epoch to local time tuple asctime() -- convert time tuple to string ctime() -- convert time in seconds to string mktime() -- convert local time tuple to seconds since Epoch strftime() -- convert time tuple to string according to format specification strptime() -- parse string to time tuple according to format specification tzset() -- change the local timezone ``` Looking at localtime() and its inverse mktime(), why is there no inverse for gmtime() ? Bonus questions: what would you name the method ? How would you implement it ?
There is actually an inverse function, but for some bizarre reason, it's in the [calendar](https://docs.python.org/2/library/calendar.html) module: calendar.timegm(). I listed the functions in this [answer](https://stackoverflow.com/questions/79797/how-do-i-convert-local-time-to-utc-in-python#79913).
I always thought the time and datetime modules were a little incoherent. Anyways, here's the inverse of mktime ``` import time def mkgmtime(t): """Convert UTC tuple to seconds since Epoch""" return time.mktime(t)-time.timezone ```
Is there an inverse function for time.gmtime() that parses a UTC tuple to seconds since the epoch?
[ "", "python", "" ]
In C++, I'm trying to catch all types of exceptions in one catch (like `catch(Exception)` in C#). How is it done? And what's more, how can one catch divide-by-zero exceptions?
``` catch (...) { // Handle exceptions not covered. } ``` Important considerations: * A better approach is to catch specific types of exception that you can actually recover from as opposed to all possible exceptions. * `catch(...)` will also catch certain serious system level exceptions (varies depending on compiler) that you are not going to be able to recover reliably from. Catching them in this way and then swallowing them and continuing could cause further serious problems in your program. * Depending on your context it can be acceptable to use `catch(...)`, providing the exception is re-thrown. In this case, you log all useful local state information and then re-throw the exception to allow it to propagate up. However you should read up on the [RAII pattern](http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization) if you choose this route.
You **don't** want to be using `catch (...)` (i.e. catch with the ellipsis) unless you really, definitely, most provable have a need for it. The reason for this is that some compilers (Visual C++ 6 to name the most common) also turn errors like segmentation faults and other really bad conditions into exceptions that you can gladly handle using `catch (...)`. This is very bad, because you don't see the crashes anymore. And technically, yes, you can also catch division by zero (you'll have to "StackOverflow" for that), but you really should be avoiding making such divisions in the first place. Instead, do the following: * If you actually know what kind of exception(s) to expect, catch those types and no more, and * If you need to throw exceptions yourself, and need to catch all the exceptions you will throw, make these exceptions derive from `std::exception` (as Adam Pierce suggested) and catch that.
How can I catch all types of exceptions in one catch block?
[ "", "c++", "exception", "try-catch", "" ]
How can I use JUnit idiomatically to test that some code throws an exception? While I can certainly do something like this: ``` @Test public void testFooThrowsIndexOutOfBoundsException() { boolean thrown = false; try { foo.doStuff(); } catch (IndexOutOfBoundsException e) { thrown = true; } assertTrue(thrown); } ``` I recall that there is an annotation or an Assert.xyz or *something* that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.
It depends on the JUnit version and what assert libraries you use. * For JUnit5 and 4.13 [see answer](https://stackoverflow.com/a/2935935/2986984) * If you use AssertJ or google-truth, [see answer](https://stackoverflow.com/a/41019785/2986984) The original answer for `JUnit <= 4.12` was: ``` @Test(expected = IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); Object o = emptyList.get(0); } ``` Though [answer](https://stackoverflow.com/a/31826781/2986984) has more options for JUnit <= 4.12. Reference: * [JUnit Test-FAQ](https://junit.org/junit4/faq.html#atests_7)
**Edit:** Now that JUnit 5 and JUnit 4.13 have been released, the best option would be to use [`Assertions.assertThrows()`](https://junit.org/junit5/docs/current/user-guide/#extensions-exception-handling) (for JUnit 5) and [`Assert.assertThrows()`](https://junit.org/junit4/javadoc/latest/org/junit/Assert.html#assertThrows(java.lang.Class,%20org.junit.function.ThrowingRunnable)) (for JUnit 4.13+): ``` @Test void exceptionTesting() { Exception exception = assertThrows(ArithmeticException.class, () -> calculator.divide(1, 0)); assertEquals("/ by zero", exception.getMessage()); } ``` See [my other answer](https://stackoverflow.com/a/46514550/95725) for details. If you haven't migrated to JUnit 5, but can use JUnit 4.7, you can use the [`ExpectedException`](http://junit.org/javadoc/latest/org/junit/rules/ExpectedException.html) Rule: ``` public class FooTest { @Rule public final ExpectedException exception = ExpectedException.none(); @Test public void doStuffThrowsIndexOutOfBoundsException() { Foo foo = new Foo(); exception.expect(IndexOutOfBoundsException.class); foo.doStuff(); } } ``` This is much better than `@Test(expected=IndexOutOfBoundsException.class)` because the test will fail if `IndexOutOfBoundsException` is thrown before `foo.doStuff()` See [this article](http://www.infoq.com/news/2009/07/junit-4.7-rules) for details.
How do you assert that a certain exception is thrown in JUnit tests?
[ "", "java", "exception", "junit", "junit4", "assert", "" ]
I'm trying to insert some import lines into a python source file, but i would ideally like to place them right after the initial docstring. Let's say I load the file into the lines variable like this: ``` lines = open('filename.py').readlines() ``` How to find the line number, where the docstring ends?
If you're using the standard docstring format, you can do something like this: ``` count = 0 for line in lines: if line.startswith ('"""'): count += 1 if count < 3: # Before or during end of the docstring continue # Line is after docstring ``` Might need some adaptation for files with no docstrings, but if your files are formatted consistently it should be easy enough.
Rather than using a regex, or relying on specific formatting you could use python's tokenize module. ``` import tokenize f=open(filename) insert_index = None for tok, text, (srow, scol), (erow,ecol), l in tokenize.generate_tokens(f.readline): if tok == tokenize.COMMENT: continue elif tok == tokenize.STRING: insert_index = erow, ecol break else: break # No docstring found ``` This way you can even handle pathological cases like: ``` # Comment # """Not the real docstring""" ' this is the module\'s \ docstring, containing:\ """ and having code on the same line following it:'; this_is_code=42 ``` excactly as python would handle them.
How to skip the docstring using regex
[ "", "python", "" ]
Alright, I have been doing the following (variable names have been changed): ``` FileInputStream fis = null; try { fis = new FileInputStream(file); ... process ... } catch (IOException e) { ... handle error ... } finally { if (fis != null) fis.close(); } ``` Recently, I started using FindBugs, which suggests that I am not properly closing streams. I decide to see if there's anything that can be done with a finally{} block, and then I see, oh yeah, close() can throw IOException. What are people supposed to do here? The Java libraries throw too many checked exceptions.
For Java 7 and above [try-with-resources](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) should be used: ``` try (InputStream in = new FileInputStream(file)) { // TODO: work } catch (IOException e) { // TODO: handle error } ``` If you're stuck on Java 6 or below... This pattern avoids mucking around with **null**: ``` try { InputStream in = new FileInputStream(file); try { // TODO: work } finally { in.close(); } } catch (IOException e) { // TODO: error handling } ``` --- For a more detail on how to effectively deal with *close*, read this blog post: [Java: how not to make a mess of stream handling](http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html). It has more sample code, more depth and covers the pitfalls of wrapping *close* in a *catch* block.
Something like the following should do it, up to you whether you throw or swallow the IOException on attempting to close the stream. ``` FileInputStream fis = null; try { fis = new FileInputStream(file); ... process ... } catch (IOException e) { ... blah blah blah ... } finally { try { if (fis != null) fis.close(); } catch (IOException e) { } } ```
Closing a Java FileInputStream
[ "", "java", "exception", "stream", "" ]