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 ...
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 MyCol...
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...
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...
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-l...
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. ...
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 sa...
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...
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="u...
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...
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 c...
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 sec...
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 simulta...
* 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....
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...
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 ugl...
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('...
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">` ...
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 ve...
[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...
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).(pr...
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/JavaScr...
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 Service...
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 be...
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 argu...
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 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>...
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 u...
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\msht...
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...
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"; ...
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 se...
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 ta...
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 ...
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 c...
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 clas...
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...
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....
### 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 co...
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 Default...
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 f...
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...
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(...
**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"...
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...
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...
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 f...
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 c...
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 loo...
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...
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...
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 so...
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 bas...
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...
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(); } ...
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.cla...
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/email...
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)...
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 ...
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 an...
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 bet...
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 ...
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(...
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...
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.ac...
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) ...
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...
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() { ...
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 - ...
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 usin...
``` 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 ...
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 ...
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 ...
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()...
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 y...
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 th...
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...
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 m...
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 th...
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...
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...
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 ...
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 laun...
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 ...
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 clas...
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 mut...
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)...
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 expre...
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 forge...
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 ...
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 d...
`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. ...
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 = ...
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...
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 `'var...
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 = encodeQueryDa...
[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](h...
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-Bo...
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 = AlternateVie...
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 ...
``` 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: ...
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 ...
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) { Na...
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<INamed...
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. \_numericS...
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 ...
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 Microsof...
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, spli...
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 me...
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); ``` ...
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 memb...
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 e...
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....
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 val...
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...
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 opti...
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...
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 rela...
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 ...
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::...
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 -...
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 transactio...
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 upda...
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 ot...
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 ...
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 ...
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 se...
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...
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...
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 day...
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.pars...
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/UR...
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 mechani...
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: ``` txtStart...
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.selectDat...
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 ...
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 se...
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 ...
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/...
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.G...
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,'A...
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: * o...
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 i...
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. ...
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 fo...
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_gran...
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.R...
``` 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["...
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 ...
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 ...
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 `.To...
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 acc...
**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 ...
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...
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")...
> // 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)) { ...
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 ...
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 ret...
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 = [] d...
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->n...
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 t...
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 b...
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|Onderwijsvo...
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)...
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...
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...
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 st...
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/Bac...
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 withi...
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 in...
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 ...
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. // u...
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) { } priv...
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 ...
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} rectan...
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 s...
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 li...
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 (Reque...
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 ...
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?mf...
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 fieldNameEle...
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.wiki...
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:...
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...
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() -- con...
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 compi...
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 y...
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;...
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 = Ind...
**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#assertThr...
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...
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.ST...
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 FindBug...
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 patter...
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 { i...
Closing a Java FileInputStream
[ "", "java", "exception", "stream", "" ]