Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am working with an order system that has two tables Order and OrderLine pretty standard stuff. I want to work out an order line number for the order lines with respect to the order e.g. Orderid Orderlineid linenumber 1          1              1 2          2              1 2          3              2 3       ...
You can use something like this: ``` select ol1.orderId, ol1.orderLineId, count(*) as lineNumber from orderLine ol1 inner join orderLine ol2 on ol1.orderId = ol2.orderId and ol1.orderLineId >= ol2.orderLineId group by ol1.orderId, ol1.orderLineId ```
IMHO, calculating it every time you need it may end up being more of a headache than it's worth. And while it may be a pain to update the historical line numbers and save it to the database, you'd only be doing that once... and then would just need to write code to automate it later. To handle the deletes, you'd just ...
How do I Compute an Order Line Number in SQL 2000
[ "", "sql", "" ]
In `SQL Server`, I can do something like this: ``` UPDATE tbl1 SET col2 = tbl2.col2 FROM table1 tbl1 INNER JOIN table2 tbl2 ON tbl1.col1 = tbl2.col1 ``` I haven't bothered to look whether this is part of any SQL standard or not, and I'm sure there are other ways to do it, but it is *astoundingly* useful...
This works for sqlite: ``` UPDATE tbl1 SET col2 = (SELECT col2 FROM tbl2 WHERE tbl2.col1 = tbl1.col1) ```
Just to emphasize Geogory Higley's post: I have had problems with `UPDATE tbl1 SET col2 = (SELECT col2 FROM tbl2 WHERE tbl2.col1 = tbl1.col1)` where it updates columns in tbl1 that do not exist in tbl2. see cheetah post at <http://sqlite.phxsoftware.com/forums/p/1708/7238.aspx> which points to: <http://www.mail-arch...
Cross-table UPDATE in SQLITE3
[ "", "sql", "sqlite", "sql-update", "" ]
In `java.util.Calendar`, January is defined as month 0, not month 1. Is there any specific reason to that ? I have seen many people getting confused about that...
It's just part of the horrendous mess which is the Java date/time API. Listing what's wrong with it would take a very long time (and I'm sure I don't know half of the problems). Admittedly working with dates and times is tricky, but aaargh anyway. Do yourself a favour and use [Joda Time](http://joda-time.sourceforge.n...
Because doing math with months is much easier. 1 month after December is January, but to figure this out normally you would have to take the month number and do math ``` 12 + 1 = 13 // What month is 13? ``` I know! I can fix this quickly by using a modulus of 12. ``` (12 + 1) % 12 = 1 ``` This works just fine for ...
Why is January month 0 in Java Calendar?
[ "", "java", "calendar", "" ]
I had a discussion with a colleague at work, it was about SQL queries and sorting. He has the opinion that you should let the server do any sorting before returning the rows to the client. I on the other hand thinks that the server is probably busy enough as it is, and it must be better for performance to let the clien...
In general, you should let the database do the sorting; if it doesn't have the resources to handle this effectively, you need to upgrade your database server. First off, the database may already have indexes on the fields you want so it may be trivial for it to retrieve data in sorted order. Secondly, the client can't...
It depends... Is there paging involved? What's the max size of the data set? Is the entire dataset need to be sorted the same one way all the time? or according to user selection? Or, (if paging is involved), is it only the records in the single page on client screen need to be sorted? (not normally acceptable) or does...
Sorting on the server or on the client?
[ "", "sql", "database", "performance", "sorting", "" ]
How can I draw something in JPanel that will stay the same and not be repainted, I am doing a traffic simulation program and I want the road to be drawn once because It will not change. Thanks
I'm not sure you actually want your road to never be repainted - repaint events fire (for example) when your window is resized, or when it becomes visible following another window obstructing it. If your panel never repaints then it'll look peculiar. As far as I remember, Swing will only fire appropriate paint events ...
To my knowledge, no, unless there is a trick with transparent overlays. Most graphical applications I saw (and did) just re-draw the whole panel on each repaint. Now, you can do that once, in a graphic buffer, and then just paint the whole background at once, quickly, by copying the graphic buffer to the JPanel. It sh...
How can I draw something on a jPanel that will not be repainted?
[ "", "java", "jpanel", "" ]
I typically use extension methods very sparingly. When I do feel compelled to write an extension method, I sometimes want to overload the method. My question is, what are your thoughts on extension methods calling other extension methods? Bad practice? It feels wrong, but I can't really define why. For example, the se...
I would have to say that DRY controls here. Personally, I see nothing wrong with an extension method calling another extension method, especially if that other extension is contained within the same assembly. All-in-all, the method calls are just translated by the compiler from: ``` extended.ExtensionMethod(foo); ``` ...
I personally don't see a problem with it, the second scenario I think feels more wrong....
C# Extensions
[ "", "c#", "extension-methods", "" ]
Suppose that I have a Java class with a static method, like so: ``` class A { static void foo() { // Which class invoked me? } } ``` And suppose further that class A has an arbitrary number of subclasses: ``` class B extends A { } class C extends A { } class D extends A { } ... ``` Now consider ...
It can't, and that's part of the problem with static methods. As far as the compiler is concerned `A.foo()` and `B.foo()` are exactly the same thing. In fact, they compile down to the same bytecode. You can't get more similar than that. If you really need this sort of information, use a singleton and turn `foo()` into...
Although you can't find out which class the static method was *invoked on*, it is possible to find out which class actually *invoked* the method at runtime: ``` static void foo() { Throwable t = new Throwable(); StackTraceElement[] trace = t.getStackTrace(); String className = trace[1].getClassName(); Clas...
Which class invoked my static method?
[ "", "java", "reflection", "" ]
In HTML, I can find a file starting from the **web server's** root folder by beginning the filepath with "/". Like: ``` /images/some_image.jpg ``` I can put that path in any file in any subdirectory, and it will point to the right image. With PHP, I tried something similar: ``` include("/includes/header.php"); ``` ...
What I do is put a config.php file in my root directory. This file is included by all PHP files in my project. In that config.php file, I then do the following; ``` define( 'ROOT_DIR', dirname(__FILE__) ); ``` Then in all files, I know what the root of my project is and can do stuff like this ``` require_once ROOT_D...
## One strategy I don't know if this is the best way, but it has worked for me. ``` $root = $_SERVER['DOCUMENT_ROOT']; include($root."/path/to/file.php"); ```
How do I set an absolute include path in PHP?
[ "", "php", "" ]
Is it possible somehow to close StreamReader after calling ReadToEnd method in construction like this: ``` string s = new StreamReader("filename", Encoding.UTF8).ReadToEnd(); ``` Any alternative elegant construction with the same semantics will be also accepted.
I think the method you're really after is [File.ReadAllText](http://msdn.microsoft.com/en-us/library/system.io.file.readalltext.aspx), if you're just trying to read all the text from a file in the shortest possible code. If you don't specify the encoding, it will use UTF-8 automatically.
You could use a *[using](http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx)* statement, which *automatically* closes the stream: ``` string s = null; using ( StreamReader reader = new StreamReader( "filename", Encoding.UTF8 ) { s = reader.ReadToEnd(); } ```
Closing StreamReader after ReadToEnd
[ "", "c#", ".net", "file-io", "" ]
We are considering moving the win32 build of our cross-platform C++ application from MS Visual Studio 2003 to MS Visual Studio 2005. (Yes, very forward-looking of us ;) Should we expect to many code changes to get it compiling and working?
I've just migrated a comparatively large codebase from VS2003 to VS2008 via VS2005 and the majority of issues I found were const/non-const issues like assigning the return value of a function that returns a const char \* to char \*. Both VS2005 and VS2008 are a lot more picky when it comes to const correctness and if y...
If your code is already quite clean and compiles without warning, it's not a big step. Check [this article](http://www.devx.com/cplus/10MinuteSolution/28908/1954) and consider how big the impact of those changes would be on your existing code. Cleaning up for-loop conformance can be a bit of work. You can get the fre...
What code changes are required to migrate C++ from VS2003 to VS2005?
[ "", "c++", "visual-studio-2005", "migration", "visual-studio-2003", "" ]
I'm developing a small tray-icon application for Windows and I need to display non-intrusive visual notifications similar to those that appear when you receive a new message in MSN Messenger or any other IM application. I have looked at [Snarl](http://www.fullphat.net/index.php), but it seems to be a separate applicat...
You can do it by depending on a GUI library. For example, with PyQt,it is possible : * [PyQt QSystemTrayIcon Documentation](http://pyqt.sourceforge.net/Docs/PyQt4/qsystemtrayicon.html) * [QSystemTrayIcon Class Reference](http://qt-project.org/doc/qt-4.8/qsystemtrayicon.html) * [Example of QSystemTrayIcon](http://qt-p...
I wrote one for .NET for the Genghis project ([link here](http://www.codeplex.com/genghis)) a while back. Looks like it is over at MS CodePlex now. Look for the "AniForm" class. [Here](http://www.sellsbrothers.com/tools/genghis/screenshots/AniForm.JPG) is a screenshot. It has more of an older MSN Messenger look and fe...
Notification Library for Windows
[ "", "python", "windows", "notifications", "" ]
Can LINQ to SQL query using **NOT IN**? e.g., SELECT au\_lname, state FROM authors WHERE state NOT IN ('CA', 'IN', 'MD')
``` List<string> states = new List<string> { "CA", "IN", "MD" }; var q = from a in authors where !states.Contains(a.state) select new { a.au_lname, a.state }; ``` or ``` var q = authors.Where( a => !states.Contains( a.state ) ) .Select( a => new { a.au_lname, a.sta...
You can do it with Contains: ``` var states = new[] {"CA", "IN", "MD"}; var query = db.Authors.Where(x => !states.Contains(x.state)); ```
LINQ to SQL query using "NOT IN"
[ "", "sql", ".net", "linq", "linq-to-sql", "" ]
Is it possible to get the expiry `DateTime` of an `HttpRuntime.Cache` object? If so, what would be the best approach?
I just went through the System.Web.Caching.Cache in reflector. It seems like everything that involves the expiry date is marked as internal. The only place i found public access to it, was through the Cache.Add and Cache.Insert methods. So it looks like you are out of luck, unless you want to go through reflection, wh...
As suggested by someone in comments that the accepted answer does not work in .NET 4.7 I had a lot of trouble trying to figure out what changes needs to be done to make it work in .NET 4.7 Here's my code for people using .NET 4.7 ``` private DateTime GetCacheUtcExpiryDateTime(string cacheKey) { var aspnetcachest...
How can I get the expiry datetime of an HttpRuntime.Cache object?
[ "", "c#", "asp.net", "caching", "" ]
I have a databases table with ~50K rows in it, each row represents a job that need to be done. I have a program that extracts a job from the DB, does the job and puts the result back in the db. (this system is running right now) Now I want to allow more than one processing task to do jobs but be sure that no task is d...
Here's what I've used successfully in the past: MsgQueue table schema ``` MsgId identity -- NOT NULL MsgTypeCode varchar(20) -- NOT NULL SourceCode varchar(20) -- process inserting the message -- NULLable State char(1) -- 'N'ew if queued, 'A'(ctive) if processing, 'C'ompleted, default 'N' -- NOT NULL CreateTime...
The best way to implement a job queue in a relational database system is to use [`SKIP LOCKED`](https://vladmihalcea.com/database-job-queue-skip-locked/). `SKIP LOCKED` is a lock acquisition option that applies to both read/share (`FOR SHARE`) or write/exclusive (`FOR UPDATE`) locks and is widely supported nowadays: ...
The best way to use a DB table as a job queue (a.k.a batch queue or message queue)
[ "", "sql", "database", "concurrency", "locking", "job-queue", "" ]
I'm using the MessageBox class to show errors to users, and while that might not be the right behavior, it's very convenient. This is a touchscreen application, however, so I need the 'ok' button to be much larger than it is (curse my inordinately large fingers!). I think that if I increase the font size in the dialog...
As far as I'm aware you can't, as the 'normal' dialog boxes are using your default system font settings. Roll your own is probably the best way forward. It's fairly trivial to do, and much fun! And you can build in things that the standard dialog doesn't support (without PInvoke magic) such as centering in the middle ...
please check out my free to use [FlexibleMessageBox](http://www.codeproject.com/Articles/601900/FlexibleMessageBox-A-flexible-replacement-for-the) which can be used instead of MessageBox and has a (static) FONT-Property. Regards, Jörg
MessageBox.Show-- font change?
[ "", "c#", "fonts", "messagebox", "" ]
I have a ListBox control that I want to change into having a toggle selection. i.e. Click once on an item selects it, click again it deselects it. Also, clicking another item in the list should do the default action of deselecting the previous item and selecting the new one. What's the best way of achieving this?
What you want is a RadioButtonList. You can create one by creating an ItemDataTemplate and put a RadioButton inside it. Then you can modify the template of the RadioButton to looks like a button.
I would keep the standard ListBox as that way you will keep the default behaviour you want, then for deselecting an item could you just handle it in the mouse down event? i.e. use something like this: ``` Point newPoint = e.GetPosition(backgroundImage); HitTestResult result = VisualTreeHelper.HitTest(this, newPoint);...
Best way to change ListBox selection to be a toggle selection
[ "", "c#", ".net", "wpf", "silverlight", "listbox", "" ]
I am trying to create a dialog box that will appear only if the browser selected is IE (any version) however I get this error: > Message: HTML Parsing Error: Unable to modify the parent container element before the child element is closed (KB927917) That's all in "Line/Char/Code" 0 so I do not know where is the error...
You're modifying document while it's being loaded (when browser hasn't "seen" closing tag for this element) . This causes very tricky situation in the parser and in IE it's not allowed. [IE blog](http://blogs.msdn.com/ie/archive/2008/04/23/what-happened-to-operation-aborted.aspx) has explanation of this. The solution...
I had this same problem. My issue was that I was calling a Javascript function before the containing `div` was closed. To fix the problem, I call the Javascript function within the jQuery `ready` event handler: ``` $(document).ready(function(){ some_random_javascript_function(); }); ```
Problem with HTML Parser in IE
[ "", "javascript", "html-parsing", "" ]
How to create a windows toolbar-dockable application - like [Winamp Desk Band](http://www.winamp.com/plugins/details/82271) - in .NET?
# C# does Shell, Part 3 <http://www.codeproject.com/KB/shell/csdoesshell3.aspx> # AppBar using C# <http://www.codeproject.com/KB/dotnet/AppBar.aspx>
It sounds like you want to create an **AppBar**. I suggest you first check out the AppBar implementation included with [the Genghis package](http://www.sellsbrothers.com/tools/genghis/). I couldn't say if it's any good since I never used it, but it looks promising. Manually, you would have to use a few Win32 API call...
Windows ToolBar-dockable application
[ "", "c#", ".net", "dockable", "" ]
can anyone show me how to get the users within a certain group using sharepoint? so i have a list that contains users and or groups. i want to retrieve all users in that list. is there a way to differentiate between whether the list item is a group or user. if its a group, i need to get all the users within that group...
The first thing you need to know is that when you have a list with a User / Group field you must be aware of its type. When you have one user or group within the item value, the field type is SPFieldUserValue. However, if the field has multiple user / group selection the field type is SPFieldUserValueCollection. I'll...
note: an SPUser object can also be an AD Group (that is to say, an SPUser object might exist for "DOMAIN\Domain Users"... which is why the SPUser object also contains the property IsDomainGroup. From this information you can start to traverse through AD groups using the SPPrincipalInfo objects... however it's not alwa...
get users by group in sharepoint
[ "", "c#", "sharepoint", "moss", "console", "wss", "" ]
What is the preferred/easiest way to manipulate TDesC strings, for example to obtain a substring. I will give you an example of my scenario. ``` RBuf16 buf; ... CEikLabel label; ... label->SetTextL(buf); // (SetTextL takes a const TDesC&) ``` I want to get a substring from buf. So do I want to manipulate the RBuf16 ...
Read descriptors.blogspot.com (scroll down once loaded). You can use TDes::LeftTPtr, TDes::RightTPtr or TDes::MidTPtr which will give you a substring as a TPtr (i.e. a descriptor which manipulates the original data). You can use the TDes::Copy function if you want to create a copy of your substring.
Best or not, I cannot comment, but I use the following methods to extract sub-strings from descriptors: ``` TDes::LeftTPtr() TDes::MidTPtr() TDes::RightTPtr() ``` or ``` TDesC::Left() TDesC::Mid() TDesC::Right() ``` with the difference between the two sets being that the former returns a new modifiable descriptor, ...
Symbian C++ - Substring operations on descriptors
[ "", "c++", "symbian", "substring", "s60", "" ]
Plone is very complex. [Zope](http://en.wikipedia.org/wiki/Zope)2, [Zope3](http://en.wikipedia.org/wiki/Zope_3), [Five](http://codespeak.net/z3/five/), [ZCML](http://wiki.zope.org/zope3/ZCML), [ZODB](http://en.wikipedia.org/wiki/Zope_Object_Database), [ZEO](http://en.wikipedia.org/wiki/Zope_Object_Database#ZEO), a whol...
If you want to see the complexity of Plone, you have to ask for it. For most people, it's just not there. It installs in a couple of minutes through a one-click installer. Then it's one click to log in, one click to create a page, use a WYSYWIG editor, and one click to save. Everything is through an intuitive web GUI. ...
It's hard to answer your question without any background information. Is the complexity justified if you just want a blog? No. Is the complexity justified if you're building a company intranet for 400+ people? Yes. Is it a good investment if you're looking to be a consultant? Absolutely! There's a lot of Plone work out...
What could justify the complexity of Plone?
[ "", "python", "content-management-system", "plone", "zope", "" ]
My simplified and contrived example is the following:- Lets say that I want to measure and store the temperature (and other values) of all the worlds' towns on a daily basis. I am looking for an optimal way of storing the data so that it is just as easy to get the current temperature in all the towns, as it is to get ...
it DEPENDS on the applications usage patterns... If usage patterns indicate that the historical data will be queried more often than the current values, then put them all in one table... But if Historical queries are the exception, (or less than 10% of the queries), and the performance of the more common current value ...
I would keep the data in one table *unless* you have a very serious bias for current data (in usage) or history data (in volume). A compound index with DATE + TOWNID (in that order) would remove the performance concern in most cases (although clearly we don't have the data to be sure of this at this time). The one thi...
What is the best way to store historical data in SQL Server 2005/2008?
[ "", "sql", "sql-server", "performance", "t-sql", "sql-server-2008", "" ]
``` class MyBase { protected object PropertyOfBase { get; set; } } class MyType : MyBase { void MyMethod(MyBase parameter) { // I am looking for: object p = parameter.PropertyOfBase; // error CS1540: Cannot access protected member 'MyBase.PropertyOfBase' via a qualifier of type 'MyBase'; t...
No, you can't do this. You're only allowed to access protected members of objects of the accessing type (or derived from it). Here, we don't know whether the parameter is of type MyType or SomeOtherCompletelyDifferentType. EDIT: The relevant bit of the C# 3.0 spec is section 3.5.3: > When a protected instance member...
Last time I faced a similar problem, I used the solution of adding a protected static method to the base: ``` class MyBase { protected object PropertyOfBase { get; set; } protected static object GetPropertyOfBaseOf(MyBase obj) { return obj.PropertyOfBase; } } class MyType : MyBase { void...
Is there a way to reach a `protected` member of another object from a derived type?
[ "", "c#", "oop", "" ]
I have div containing a list of flash objects. The list is long so I've set the div height to 400 and overflow to auto. This works fine on FF but on IE6 only the first 5 flash objects that are visible work. The rest of the flash objects that are initially outside the viewable area are empty when I scroll down. The swf...
I think I have a solution for this. I can't be absolutely sure as the page in question was restructured (because of this bug). Later on I stumbled on a similar issue with the same flash component on a different page. The issue there was that sometimes flash gives a Stage.height=0 and Stage.width=0. This is most likely...
A few things that I'd try: * remove all CSS temporarily to determine whether the issue is CSS-specific * add pixel widths to the floated elements as well as their parent element * add the wmode transparent param to swfobject * add position:relative I've heard of a bug in Flash that apparently only occurs if the flash...
Flash inside a scrolling div - IE6 bug
[ "", "javascript", "html", "flash", "internet-explorer-6", "swfobject", "" ]
Is it possible to write a template that changes behavior depending on if a certain member function is defined on a class? Here's a simple example of what I would want to write: ``` template<class T> std::string optionalToString(T* obj) { if (FUNCTION_EXISTS(T->toString)) return obj->toString(); else ...
Yes, with SFINAE you can check if a given class does provide a certain method. Here's the working code: ``` #include <iostream> struct Hello { int helloworld() { return 0; } }; struct Generic {}; // SFINAE test template <typename T> class has_helloworld { typedef char one; struct two { char x[2]; };...
This question is old, but with C++11 we got a new way to check for a functions existence (or existence of any non-type member, really), relying on SFINAE again: ``` template<class T> auto serialize_imp(std::ostream& os, T const& obj, int) -> decltype(os << obj, void()) { os << obj; } template<class T> auto seri...
How can you check whether a templated class has a member function?
[ "", "c++", "templates", "template-meta-programming", "sfinae", "" ]
I'm launching a Weblogic application inside Eclipse via the BEA Weblogic Server v9.2 runtime environment. If this were running straight from the command-line, I'd do a ctrl-BREAK to force a thread dump. Is there a way to do it in Eclipse?
Indeed (thanks VonC to point to the SO thread), Dustin, in a comment to his message, points to [jstack](http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jstack.html "jstack - Stack Trace"). I have run a little Java application (with GUI) in Eclipse, I can see the related javaw.exe in Windows' process manager and its...
You can do it when you are in debug mode: go to the debug view in the debug perspective, click on the process you have launched and click on pause, you will get a graphical stack of all your processes. Note : this also works when using remote debugging, you do not need to launch weblogic from eclipse, you can launch i...
How to Force Thread Dump in Eclipse?
[ "", "java", "eclipse", "memory-leaks", "weblogic", "" ]
I have researched and haven't found a way to run INTERSECT and MINUS operations in MS Access. Does any way exist
INTERSECT is an inner join. MINUS is an outer join, where you choose only the records that don't exist in the other table. --- **INTERSECT** ``` select distinct a.* from a inner join b on a.id = b.id ``` --- **MINUS** ``` select distinct a.* from a left outer join b on a.id = b.id where b.id is null...
INTERSECT is NOT an INNER JOIN. They're different. An INNER JOIN will give you duplicate rows in cases where INTERSECT WILL not. You can get equivalent results by: ``` SELECT DISTINCT a.* FROM a INNER JOIN b on a.PK = b.PK ``` Note that PK must be the primary key column or columns. If there is no PK on the table (...
How can I implement SQL INTERSECT and MINUS operations in MS Access
[ "", "sql", "database", "ms-access", "" ]
This code is executed by many way. When it's executed by the form button it works (the button start a thread and in the loop it call this method = it works). BUT it doesn't work when I have a call to that method from my BackgroundWorker in the form. With the following code: ``` private void resizeThreadSafe(int width...
You need to return at the end of the if block - otherwise you'll resize it in the right thread, and then do it in the wrong thread as well. In other words (if you'd cut and paste the code instead of a picture, this would have been easier...) ``` private void resizeThreadSafe(int width, int height) { if (this.form...
You need write this: ``` if ( this.form.InvokeRequired ) { this.form.Invoke( ...... ); return; } this.form.Size = new Sizte( ... ); ``` OR ``` if ( this.form.InvokeRequired ) { this.form.Invoke( ...... ); } else { this.form.Size = new Sizte( ... ); } ```
Help me with that CrossThread?
[ "", "c#", ".net", "winforms", "multithreading", "" ]
I need to upload images using FileUpload without postback(using Ajax).I tried many examples.But in all postback is coming or they are using PHP.Can anyone help me to do single file upload or multi file upload using ajax in ASP.Net with C#.
SWFUpload <http://demo.swfupload.org/v220beta3/simpledemo/index.php> <http://swfupload.org/> Javascript and Flash, there's no post-back :) and there's .NET implementations available on the site.
Hope you find this useful. <http://aspalliance.com/1442_Building_AJAX_Enabled_File_Uploading_System_with_Progress_Bar_Using_ASPNET_20.all> It's using asp.net and ajax.
FileUpload Using Ajax In ASP.NET With C#
[ "", "javascript", "jquery", "ajax", "" ]
I've written a Custom User Control which returns some user specific data. To load the Custom User Control I use the following line of code: ``` UserControl myUC = (UserControl).Load("~/customUserControl.ascx"); ``` But how can I access `string user` inside the User Control `myUC`?
Let's call your usercontrol "Bob" If you Inherit from UserControl in Bob, then I guess it's safe to do this: ``` Bob b = (Bob).Load("~/customUserControl.ascx"); ``` For the user part, I can't really follow what you want to do, is the "user" in the class were you create the "Bob" usercontrol and you want to set a pro...
Suppose your custom user control's name is "MyUserControl" Try this code: ``` MyUserControl myUC = (UserControl).Load("~/customUserControl.ascx") as MyUserControl; string result = myUC.user; ```
How can I pass a data string to a programmatically loaded custom user control in C#
[ "", "c#", "controls", "pass-data", "" ]
**Is there a YAML driver for the Java [XStream](http://x-stream.github.io/) package?** I'm already using XStream to serialise/deserialise both XML and JSON. I'd like to be able to do the same with YAML.
To parse a YAML document you can use this chain: YAML -> SnakeYAML -> Java -> Your Application (-> XStream -> XML) Emitting YAML is simpler and there are a couple of options: 1) Your Application -> XStream with Custom Writer -> YAML 2) Your Application -> SnakeYAML -> YAML The second option does not require any addit...
You might find that helpful to get a direction: [XStream - how to serialize objects to non XML formats](http://joe.truemesh.com/blog//000479.html)
Serialise to YAML using XStream in Java
[ "", "java", "yaml", "xstream", "" ]
I have a directory full (~103, 104) of XML files from which I need to extract the contents of several fields. I've tested different xml parsers, and since I don't need to validate the contents (expensive) I was thinking of simply using xml.parsers.expat (the fastest one) to go through the files, one by one to extract t...
The quickest way would be to match strings (with, e.g., regular expressions) instead of parsing XML - depending on your XMLs this could actually work. But the most important thing is this: instead of thinking through several options, just implement them and time them on a small set. This will take roughly the same amo...
Usually, I would suggest using ElementTree's [`iterparse`](http://effbot.org/zone/element-iterparse.htm), or for extra-speed, its counterpart from [lxml](http://codespeak.net/lxml/). Also try to use [Processing](http://pypi.python.org/pypi/processing) (comes built-in with 2.6) to parallelize. The important thing about...
What is the most efficient way of extracting information from a large number of xml files in python?
[ "", "python", "xml", "performance", "large-files", "expat-parser", "" ]
I have a few text boxes and buttons on my form. Lets say txtBox1 is next to btnSubmit1, txtBox2 is next to btnSubmit2, txtBox3 is next to btnSubmit3. How can I set the focus on btnSubmit3 when the user starts to type something in txtBox3. Meaning..... if a user type in a text box the program will know what button to ...
If you use a panel, you should be able to set a defaultbutton. I´m not sure if it´s an win forms application or a web forms application, but this is how you should do it with web forms: ``` <asp:Panel id="panel1" runat="server" DefaultButton="Button1"> <asp:TextBox id="textbox1" runat="server" /> <asp:Button id=...
This is an easy solution if you know that the only browser being used is IE. You just have to add to the Page load ``` txtBox1.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + btnSubmit1.UniqueID + "','')"); txtBox2.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) ...
Setting focus to a button from text box?
[ "", "c#", "asp.net", "vb.net", "" ]
I was once given this task to do in an RDBMS: Given tables customer, order, orderlines and product. Everything done with the usual fields and relationships, with a comment memo field on the orderline table. For one customer retrieve a list of all products that customer has ever ordered with product name, year of firs...
You definitely should be able to do this exercise without doing the work equivalent to a `JOIN` in application code, i.e. by fetching all rows from both orderlines and products and iterating through them. You don't have to be an SQL wizard to do that one. **`JOIN` is to SQL what a loop is to a procedural language** -- ...
> Set operations are not as expressive as procedural operations Perhaps more like: "Set operations are not as familiar as procedural operations to a developer used to procedural languages" ;-) Doing it iteratively as you have done now is fine for small sets of data, but simply doesn't scale the same way. The answer t...
When do you give up set operations in SQL and go procedural?
[ "", "sql", "language-agnostic", "procedural", "" ]
I'm bored with surrounding code with try catch like this.. ``` try { //some boring stuff } catch(Exception ex) { //something even more boring stuff } ``` I would like something like ``` SurroundWithTryCatch(MyMethod) ``` I know I can accomplish this behaviour by creating a delegate with the exact signature ...
Firstly, it sounds like you may be using try/catch too often - particularly if you're catching `Exception`. try/catch blocks should be relatively rare; unless you can really "handle" the exception, you should just let it bubble up to the next layer of the stack. Now, assuming you really *do* want all of these try/catc...
Aspect Oriented Programming could also help you, but this may require that you add libraries to your project, [postsharp](http://www.postsharp.org) would help you in this case. See this link <http://doc.postsharp.org/1.0/index.html#http://doc.postsharp.org/1.0/UserGuide/Laos/AspectKinds/OnExceptionAspect.html#idHelpTOC...
How to get rid of try catch?
[ "", "c#", "error-handling", "" ]
I have a right outer join, that almost does what I want... ``` SELECT users_usr.firstname_usr, users_usr.lastname_usr, credit_acc.given_credit_acc, users_usr.created_usr, users_usr.sitenum_usr, users_usr.original_aff_usr, users_usr.id_usr FROM credit_acc right Outer Join users_usr ON credit_acc.uid_usr = users_usr.id_...
``` SELECT users_usr.firstname_usr, users_usr.lastname_usr, credit_acc.given_credit_acc, users_usr.created_usr, users_usr.sitenum_usr, users_usr.original_aff_usr, users_usr.id_usr FROM credit_acc right Outer Join users_usr ON credit_acc.uid_usr = users_usr.id_usr WHERE credit_acc.type_acc = 'init' OR credit_acc.type_ac...
If the row doesn't exist, *credit\_acc.type\_acc* should be null. You could try something like this: ``` WHERE credit_acc.type_acc = 'init' OR credit_acc.type_acc IS NULL; ``` That will only work if there are no null fields in *credit\_acc.type\_acc*.
query join question
[ "", "sql", "mysql", "join", "" ]
Does everyone just use XML in the message? Are there any good alternatives to XML? If you do use XML, do you define an XML Schema so clients know how to send messages to your service?
We use XML, but I think the important thing is to tailor the solution to the problem. The reason we use XML is that we are basically sending an object across in the message. There's no reason it can't be plain text, if applicable for the message you are sending, using headers to send along properties if appropriate. -...
XML is probably the most popular along with JSON a close second - but as others have said in this thread - XML, CSV, JSON or even HTML are fine. XSDs are overrated really - their only real value is if you want your clients/customers to code generate marshalling code (e.g. using JAXB) or if you want to let folks use XS...
How do you format the body of a JMS text message?
[ "", "java", "jms", "" ]
I'm running tomcat and have some jsp pages that display a subset of a table. I show 20 rows at a time on a single page. When the table has large amounts of data, the jsp page doesn't render. I'm guessing that the ResultSet is using a client side cursor. I've worked with ASP in the past, and we always used server side f...
The oracle driver implements server-side cursors via the FetchSize property. Unfortunately, JDBC doesn't explicitly allow for setting client vs server-side cursors, so different drivers implement it in different ways. Here are the other links that helped: [Fetch Size](http://blog.lishman.com/2008/03/jdbc-fetch-size.h...
``` Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY); ResultSet rs = stmt.executeQuery(sql); ``` This should set it but apparently *some* drivers ignore it. You could always try and set it again at ResultSet level. ``` rs.setFetchDirection(ResultSet.TYPE_FORWARD_ONLY); ``` Hope that helps.
How to set Cursor type in JDBC?
[ "", "java", "oracle", "jdbc", "cursors", "" ]
Is it possible to do a "C like" fork in java, using an new independent jvm process ? How?
Funnily, I am just working on this: a Java process running other Java processes. I used the article [From Runtime.exec() to ProcessBuilder](https://www.java-tips.org/java-se-tips-100019/88888889-java-util/426-from-runtimeexec-to-processbuilder.html) as a solid base, and [When Runtime.exec() won't](https://www.infoworld...
This answer is probably a little late but: <http://akuma.kohsuke.org/> seems to be exactly what your looking for
Java - C-Like Fork?
[ "", "java", "c", "fork", "" ]
Almost every new Java-web-project is using a modern MVC-framework such as Struts or Spring MVC for the web tier, Spring for the "Service"/business-logic-layer and an ORM mapper such as Hibernate for persistence. What is the equivalent in .NET? I guess ASP.NET is used for the web tier and ADO.NET for persistence but wh...
The default approach is ADO.NET/Linq-to-Sql, ASP.NET and custom service layer that reinvents the wheel. Microsoft has Unity for autowiring, but I do not feel dependency injection is mainstream in .NET world yet. But if you go for the best practices, it is ASP.NET MVC for UI, any DI framework (Castle,Unity,Autofac,...)...
Something like this? <http://www.asp.net/mvc/>
.NET equivalent of modern Java web architecture
[ "", "java", ".net", "spring", "ado.net", "transactions", "" ]
Is there a native c++ variable type that's "bigger" than a double? float is 7 double is 15 (of course depending on the compiler) Is there anything bigger that's native, or even non-native?
C++ has `long double`, but there is no guarantee that it's any more precise than a plain `double`. On an x86 platform, usually `double` is 64 bits, and `long double` is either 64 or 80 bits (which gives you 19 significant figures, if I remember right). Your mileage may vary, especially if you're not on x86.
A long double typically only uses 10 bytes, but due to alignment may actually take up 12 or 16 (depending on the compiler and options) bytes in a structure. The 10 byte long double provides a 64-bit mantissa; this is very convenient for when you want to store 64 bit integers in floating point without loss of precision...
What's bigger than a double?
[ "", "c++", "types", "variables", "" ]
I'm building an ORM library with reuse and simplicity in mind; everything goes fine except that I got stuck by a stupid inheritance limitation. Please consider the code below: ``` class BaseModel { /* * Return an instance of a Model from the database. */ static public function get (/* varargs */) { ...
in short. this is not possible. in php4 you could implement a terrible hack (examine the `debug_backtrace()`) but that method does not work in PHP5. references: * # [30423](http://bugs.php.net/bug.php?id=30423) * # [37684](http://bugs.php.net/bug.php?id=37684) * # [34421](http://bugs.php.net/bug.php?id=34421) **edit*...
You don't need to wait for PHP 5.3 if you're able to conceive of a way to do this outside of a static context. In php 5.2.9, in a non-static method of the parent class, you can do: ``` get_class($this); ``` and it will return the name of the child class as a string. i.e. ``` class Parent() { function __construc...
Getting the name of a child class in the parent class (static context)
[ "", "php", "inheritance", "static-methods", "" ]
I want to discover at run-time ONLY the static Methods of a class, how can I do this? Or, how to differentiate between static and non-static methods.
Use `Modifier.isStatic(method.getModifiers())`. ``` /** * Returns the public static methods of a class or interface, * including those declared in super classes and interfaces. */ public static List<Method> getStaticMethods(Class<?> clazz) { List<Method> methods = new ArrayList<Method>(); for (Method meth...
You can get the static methods like this: ``` for (Method m : MyClass.class.getMethods()) { if (Modifier.isStatic(m.getModifiers())) System.out.println("Static Method: " + m.getName()); } ```
How can I check if a method is static using reflection?
[ "", "java", "reflection", "" ]
I am writing some new code that will throw a custom exception - I want to include an error string and a status code. Which class should be exception derive from? `std::exception`? `std::runtime_error`? Any other 'gotchas' to worry about? I'm thinking of something like the following: ``` class MyException : public std:...
Boost has a great document on [error and exception](http://www.boost.org/community/error_handling.html) handling which talks about common gotchas and how to properly inherit from std::exception(s).
Consider whether the status code is really appropriate. It's usually superior to create a hierarchy of exception classes. This way, the caller can better control which exceptions to treat and how and it makes the interface simpler. Of course, sometimes status codes are still appropriate (compilers use them all the tim...
Rolling my own exceptions
[ "", "c++", "exception", "" ]
I have 2 handlers using the same form. How do I remove the handlers before adding the new one (C#)?
If you are working in the form itself, you should be able to do something like: PseudoCode: ``` Delegate[] events = Form1.SomeEvent.GetInvokationList(); foreach (Delegate d in events) { Form1.SomeEvent -= d; } ``` From outside of the form, your SOL.
If you know what those handlers are, just remove them in the same way that you subscribed to them, except with -= instead of +=. If you don't know what the handlers are, you can't remove them - the idea being that the event encapsulation prevents one interested party from clobbering the interests of another class in o...
How do I unregister all handlers for a form event?
[ "", "c#", "handler", "" ]
I have an enumeration value marked with the following attribute. The second parameter instructs the compiler to error whenever the value is used. I want this behavior for anyone that implements my library, but I need to use this enumeration value within my library. How do I tell the compiler to ignore the Obsolete erro...
Private a separate constant somewhere like this: ``` private const Choices BackwardsCompatibleThree = (Choices) 3; ``` Note that anyone else will be able to do the same thing.
What about using #pragma to disable the warning around the specfic code? ``` #pragma warning disable 0612 // Call obsolete type/enum member here #pragma warning restore 0612 ``` A note to visitors, this only works with types and enum members. As far as I am aware, this will not work with other type members (e.g. ...
Ignore ObsoleteAttribute Compiler Error
[ "", "c#", "" ]
I'm playing around at the start of a personal project in C# and MySQL. I am familiar with the use of the Gentle Framework (using MyGeneration to generate the classes, based on the data model). Here's what I like about Gentle; * Simple-to-use [class].Retrieve(id) / [object].Persist() semantics with strong-typing of fi...
[link text](http://weblogs.asp.net/zowens/archive/2007/09/18/subsonic-of-the-day-collections.aspx)I would go for Subsonic, mature DAL generator and improves productivity by great margin. We have used it with both MySQL and SQL Server - no headaches. Generates classes for Tables, Stored procedures, column names. So eve...
I had some experience with Gentle and I do have to admit that it was pretty inefficient with queries. I would suggest looking into NHibernate, since it has a rich community. It is true that XML definitions are preferred, but there are ways of doing the mappings using class-level attributes. SubSonic (especially the [3...
C# and MySQL - Gentle Framework alternatives
[ "", "c#", "orm", "" ]
can you set SO\_RCVTIMEO and SO\_SNDTIMEO socket options in boost asio? If so how? Note I know you can use timers instead, but I'd like to know about these socket options in particular.
Absolutely! Boost ASIO allows you to access the native/underlying data, which in this case is the SOCKET itself. So, let's say you have: ``` boost::asio::ip::tcp::socket my_socket; ``` And let's say you've already called `open` or `bind` or some member function that actually makes `my_socket` usable. Then, to get the...
It doesn't appear to be built into Boost.Asio (as of current Boost SVN), but, if you're willing to write your own classes to simulate the `boost::asio::detail::socket_option` ones, you can always follow the examples in `boost/asio/socket_base.hpp` and do the following: ``` typedef boost::asio::detail::socket_option::t...
can you set SO_RCVTIMEO and SO_SNDTIMEO socket options in boost asio?
[ "", "c++", "boost", "boost-asio", "" ]
I'm trying to add a pojo to a collection in another pojo. I'm sure I'm making a really stupid mistake somewhere along the lines but I can't figure out how to solve it. I have a pojo LookupTable which contains a list of Columns: ``` public class LookupTable { private long id; // More properties go here... privat...
Turns out I didn't have a transaction at all. I used almost the same transaction configuration in one of my other config files. The pointcut over there was also called "managers", so my advisor here was referencing the pointcut in the other file. *Renaming the pointcut solved my problem.*
My guess is that the `lookupTableDao.findById` call is getting your object in one session, but the `lookupTableDao.saveOrUpdate` is a different one - how do you get the `Session` object, via Spring? Where is the `Column` object coming from - is that already on the DB or new?
Illegal attempt to associate a collection with two open sessions
[ "", "java", "hibernate", "spring", "transactions", "" ]
If a large module is loaded by some submodule of your code, is there any benefit to referencing the module from that namespace instead of importing it again? For example: I have a module MyLib, which makes extensive use of ReallyBigLib. If I have code that imports MyLib, should I dig the module out like so ``` import...
Python modules could be considered as singletons... no matter how many times you import them they get initialized only once, so it's better to do: ``` import MyLib import ReallyBigLib ``` Relevant documentation on the import statement: <https://docs.python.org/2/reference/simple_stmts.html#the-import-statement> > O...
As others have pointed out, Python maintains an internal list of all modules that have been imported. When you import a module for the first time, the module (a script) is executed in its own namespace until the end, the internal list is updated, and execution of continues after the import statement. Try this code: `...
Does python optimize modules when they are imported multiple times?
[ "", "python", "python-import", "" ]
I know that most people recommend using HttpRuntime.Cache because it has more flexibility... etc. But what if you want the object to persist in the cache for the life of the application? Is there any big downside to using the Application[] object to cache things?
As long as you don't abuse the application state, then I don't see a problem in using it for items that you don't want to expire. Alternatively I would probably use a static variable near the code that uses it. That way you avoid to go through `HttpApplicationState` and then be forced to have a reference to System.Web ...
Application is deprecated by Cache. If you need something with application scope, then you should either create it as a static member of a class or use the Cache. If you want to go the Cache route but don't ever want it to expire, you should use the CacheItemPriority.NotRemovable option when you Insert the value into t...
HttpRuntime.Cache[] vs Application[]
[ "", "c#", "asp.net", "caching", "httpruntime.cache", "" ]
Many of us need to deal with user input, search queries, and situations where the input text can potentially contain profanity or undesirable language. Oftentimes this needs to be filtered out. Where can one find a good list of swear words in various languages and dialects? Are there APIs available to sources that co...
[Obscenity Filters: Bad Idea, or Incredibly Intercoursing Bad Idea?](http://blog.codinghorror.com/obscenity-filters-bad-idea-or-incredibly-intercoursing-bad-idea/) Also, one can't forget [The Untold History of Toontown's SpeedChat](http://habitatchronicles.com/2007/03/the-untold-history-of-toontowns-speedchat-or-block...
Whilst I know that this question is fairly old, but it's a commonly occurring question... There is both a reason and a distinct need for profanity filters (see [Wikipedia entry here](http://en.wikipedia.org/wiki/Profanity_filter)), but they often fall short of being 100% accurate for very distinct reasons; **Context**...
How do you implement a good profanity filter?
[ "", "php", "regex", "user-input", "" ]
I want do something like this: ``` Button btn1 = new Button(); btn1.Click += new EventHandler(btn1_Click); Button btn2 = new Button(); // Take whatever event got assigned to btn1 and assign it to btn2. btn2.Click += btn1.Click; // The compiler says no... ``` Where btn1\_Click is already defined in the class: ``` voi...
Yeah, it's technically possible. Reflection is required because many of the members are private and internal. Start a new [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) project and add two buttons. Then: ``` using System; using System.ComponentModel; using System.Windows.Forms; using System.Reflection; n...
No, you can't do this. The reason is encapsulation - events are *just* subscribe/unsubscribe, i.e. they don't let you "peek inside" to see what handlers are already subscribed. What you *could* do is derive from Button, and create a public method which calls `OnClick`. Then you just need to make `btn1` an instance of ...
Is it possible to "steal" an event handler from one control and give it to another?
[ "", "c#", ".net", "" ]
I have a XML Structure that looks like this. ``` <sales> <item name="Games" sku="MIC28306200" iCat="28" sTime="11/26/2008 8:41:12 AM" price="1.00" desc="Item Name" /> <item name="Games" sku="MIC28307100" iCat="28" sTime="11/26/2008 8:42:12 AM" price="1.00" desc="Item Name" /> ... </sales> `...
There's an overload of XPathExpression.Addsort which takes an IComparer interface. If you implement the comparison yourself as IComparer, you could use this mechanism. ``` class Program { static void Main(string[] args) { XPathDocument saleResults = new XPathDocument( @...
Here you go: ``` XmlDocument myDoc = new XmlDocument(); myDoc.LoadXml(@" <sales> <item name=""Games"" sku=""MIC28306200"" iCat=""28"" sTime=""11/26/2008 8:41:12 AM"" price=""1.00"" desc=""Item Name"" /> <item name=""Games"" sku=""MIC28307100"" iCat=""28"" sTime=""11/26/2008 8:42:12 AM"...
Sorting XML nodes based on DateTime attribute C#, XPath
[ "", "c#", "xml", "sorting", "xpath", "" ]
First off, I apologize if this doesn't make sense. I'm new to XHTML, CSS and JavaScript. I gather that in XHTML, the correct way to have a nested page is as follows (instead of an iframe): ``` <object name="nestedPage" data="http://abc.com/page.html" type="text/html" width="500" height="400" /> ``` If I have a nest...
``` d = document.getElementsByTagName('object').namedItem('nestedPage').getContentDocument(); d.styleSheets[d.styleSheets.length].href = 'whereever'; ``` WARNING: hasn't been tested in all browsers.
I'd suggest using an iframe for this, I don't know if the object-way of doing this is supported as well. Anyway, after the page from the same domain has loaded, you can access all its properties via javascript. For example, in jQuery, you'd use to change the css-file. ``` $("link [rel=stylesheet]", myFrame).attr('hre...
Changing the stylesheet of a nested page at runtime
[ "", "javascript", "css", "xhtml", "" ]
I have several aspx pages that can be opened either normally (full screen in browser), or called from another page as a popup (I am using Greybox, fwiw) If the page is opened as a popup in Greybox, I would like to NOT display the master page content (which displays common top and left menus, etc). As far as I know, t...
Create a simplified master page for the popup. Override the OnPreInit method (of the actual page) and switch out the masterpage based on a querystring argument: ``` protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); if(Request["PopUp"] == "Y") { MasterPageFile = "~...
Well you could conditionally render the navigation controls etc. based on a querystring, pass the string in when it's a popup and if it exists don't render the controls. There are a few different ways to do it, but I think you should have the server not render the controls rather than client side hiding them. P.S. Hav...
Is it possible to hide the content of an asp.net master page, if page is opened as a popup?
[ "", "asp.net", "javascript", "" ]
I'm trying to do something like ``` URL clientks = com.messaging.SubscriptionManager.class.getResource( "client.ks" ); String path = clientks.toURI().getPath(); System.setProperty( "javax.net.ssl.keyStore", path); ``` Where client.ks is a file stored in com/messaging in the jar file that I'm running. The thing that ...
Still working on implementation, but I believe it is possible to load the keystore from the jar via InputStream and explicitly set the TrustStore programatically (vs setting the System properties). See the article: [Setting multiple truststore on the same JVM](https://stackoverflow.com/questions/7591281/setting-multipl...
Here's a cleaned-up version of [user2529737's answer](https://stackoverflow.com/a/17352927/365237), in case it helps. It has removed unneeded trust store setup and added required imports, parameters for keystore type and key password. ``` import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManager; import...
How to use a file in a jar as javax.net.ssl.keystore?
[ "", "java", "jar", "executable-jar", "" ]
Some days ago I realized that [PrintWriter](http://java.sun.com/javase/6/docs/api/java/io/PrintWriter.html) (as well as [PrintStream](http://java.sun.com/javase/6/docs/api/java/io/PrintStream.html)) **never throw an IOException** when writing, flushing or closing. Instead it sets an internal flag (`trouble=true`) when...
I think that since `System.out` and `System.err` are instances of `PrintStream`, some more relaxed error handling was provided. This was probably, as other posters have mentioned, to smooth the way for those transitioning from C/C++ circa 1995. When the Reader/Writer API was added, `PrintWriter` was created to parallel...
I wonder if its because IOExceptions are checked, this would require you placing a try catch block around every System.out. call. update: Or a throws in your method signature. That would get annoying very quickly.
PrintWriter and PrintStream never throw IOExceptions
[ "", "java", "api", "exception", "" ]
[This](https://stackoverflow.com/questions/116090/how-do-i-kill-a-process-using-vbnet-or-c) only helps kills processes on the local machine. How do I kill processes on remote machines?
You can use [wmi](http://www.microsoft.com/technet/scriptcenter/resources/qanda/sept04/hey0927.mspx). Or, if you don't mind using external executable, use [pskill](http://technet.microsoft.com/en-us/sysinternals/bb896683.aspx)
I like this (similar to answer from Mubashar): ``` ManagementScope managementScope = new ManagementScope("\\\\servername\\root\\cimv2"); managementScope.Connect(); ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_Process Where Name = 'processname'"); ManagementObjectSearcher managementObjectSearcher = ne...
Kill a process on a remote machine in C#
[ "", "c#", ".net", "process", "kill", "" ]
My crappy web host did some upgrades the other day and some settings have gone awry, because looking at our company's wiki (MediaWiki), every quote is being escaped with a backslashes. It's not even just data which is being posted (i.e.: the articles) which are affected, but also the standard MediaWiki text. For exampl...
If PHP flags are set with `php_admin_flag`/`php_admin_value`, you can't change it from a `.htaccess` file. This has caused me some headache before. Either disable it in `php.ini` or undo magic quotes in runtime: <http://talks.php.net/show/php-best-practices/26>
You may want to confirm that the data in your DB hasn't been corrupted. If you were addslash()ing your data when, unbeknownst to you, magic\_quotes had been turned on, then you'd be double-slashifying data going into your DB.
Extra backslashes being added in PHP
[ "", "php", "apache", "escaping", "mediawiki", "" ]
I've created a .Net library at work that is used by all of our developers. The security part of it uses Microsoft AzMan for the security backend. In order to create a security (AzMan) ClientContext I have to pass it a token value (as a uint). This is all fine an dandy until I needed to make a COM wrapper for our common...
If your not able to get to token, you could always use the **IAzApplication.InitializeClientContextFromName** while retrieving the user name from the request in your asp page and passing it to your com+ component. <http://msdn.microsoft.com/en-us/library/aa377363(VS.85).aspx>
Are you using anonymous logons in the IIS configuration? If you use Windows Authentication and do the following in classic ASP you should get the logged on user: ``` Request.ServerVariables("LOGON_USER") ```
WindowsIdentity Token in Legacy ASP
[ "", "c#", ".net", "security", "com", "interop", "" ]
Is there a UI library to create a message box or input box in python?
Your best bet is the tkMessageBox module, which should work on all systems (as Python will typically come with Tkinter). If you can restrict yourself to a specific operating system, better choices might be available.
Simple message boxes and input boxes can be created using EasyGui, a small library using Tkinter, which Python comes with. You can get EasyGui here: <http://easygui.sourceforge.net/>
Message Box in Python
[ "", "python", "user-controls", "user-interface", "" ]
I'm using a `java.util.concurrent.ExecutorService` that I obtained by calling `Executors.newSingleThreadExecutor()`. This `ExecutorService` can sometimes stop processing tasks, even though it has not been shutdown and continues to accept new tasks without throwing exceptions. Eventually, it builds up enough of a queue ...
It sounds like you have two different issues: 1) You're over-feeding the work queue. You can't just keep stuffing new tasks into the queue, with no regard for the consumption rate of the task executors. You need to figure out some logic for knowing when you to block new additions to the work queue. 2) Any uncaught ex...
My guess would be that your tasks are blocking indefinitely, rather than dying. Do you have evidence, such as a log statement at the end of your task, suggest that your tasks are successfully completing? This could be a deadlock, or an interaction with some external process that is blocking.
what would make a single task executor stop processing tasks?
[ "", "java", "multithreading", "concurrency", "executorservice", "" ]
I am writing a scraper that downloads all the image files from a HTML page and saves them to a specific folder. All the images are part of the HTML page.
Here is some code to download all the images from the supplied URL, and save them in the specified output folder. You can modify it to your own needs. ``` """ dumpimages.py Downloads all the images on the supplied URL, and saves them to the specified output file ("/test/" by default) Usage: python dumpima...
Ryan's solution is good, but fails if the image source URLs are absolute URLs or anything that doesn't give a good result when simply concatenated to the main page URL. urljoin recognizes absolute vs. relative URLs, so replace the loop in the middle with: ``` for image in soup.findAll("img"): print "Image: %(src)s...
Download image file from the HTML page source
[ "", "python", "screen-scraping", "" ]
My requirement is just to display a set of values retrieved from database on a spread. I am using jquery.
Favor XML over JSON when any of these is true: * You need message validation * You're using XSLT * Your messages include a lot of marked-up text * You need to interoperate with environments that don't support JSON Favor JSON over XML when all of these are true: * Messages don't need to be validated, or validating th...
I use JSON unless I'm required to use XML. It's simpler to understand, and (because it requires less configuration overhead) it's easier to program for reading and writing if the libraries are available in your context, and they're pretty ubiquitous now. When Amazon first exposed their catalogs as a web service, they ...
When to prefer JSON over XML?
[ "", "javascript", "jquery", "xml", "json", "" ]
I'm developing a C++ command-line application in Visual Studio and need to debug it with command-line arguments. At the moment I just run the generated EXE file with the arguments I need (like this `program.exe -file.txt`) , but this way I can't debug. Is there somewhere I can specify the arguments for debugging?
Yes, it's in the *Debug* section of the properties page of the project. In Visual Studio since 2008: right-click on the project node, choose *Properties*, go to the *Debugging* section -- there is a box for "Command Arguments".
The [Mozilla.org FAQ on debugging Mozilla on Windows](https://developer.mozilla.org/en/Debugging_Mozilla_on_Windows_FAQ) is of interest here. In short, the Visual Studio debugger can be invoked on a program from the command line, allowing one to specify the command line arguments when invoking a command line program, ...
Debugging with command-line parameters in Visual Studio
[ "", "c++", "visual-studio", "debugging", "command-line", "" ]
OK so that title sucks a little but I could not think of anything better (maybe someone else can?). So I have a few questions around a subject here. What I want to do is create a program that can take an object and use reflection to list all its properties, methods, constructors etc. I can then manipulate these object...
Try looking at [Crack.NET](http://www.codeplex.com/cracknetproject/Release/ProjectReleases.aspx?ReleaseId=19002). It is used to do runtime manipulation and interrogation on WPF/WinForms but the source is available and might be a good start if it already doesn't meet your needs.
It sound as if Corneliu Tusnea's [Hawkeye](http://www.acorns.com.au/Projects/Hawkeye/) might be close to what you're looking for runtime interrogation of objects/properties/etc. He calls it the .NET Runtime Object Editor. I'm not sure if the homepage I linked to above or the [CodePlex project](http://www.codeplex.com/h...
How to use reflection to create a "reflection machine"
[ "", "c#", "reflection", "" ]
I've got some code that will generically get all Controls in a form and put them in a list. Here's some of the code: ``` private List<Control> GetControlList(Form parentForm) { List<Control> controlList = new List<Control>(); AddControlsToList(parentForm.Controls, controlList); ...
I believe the VS designer does it by getting an instance of the control's designer (see the [`Designer` attribute](http://msdn.microsoft.com/en-us/library/system.componentmodel.designerattribute.aspx)), and, if the designer is a [`ComponentDesigner`](http://msdn.microsoft.com/en-us/library/system.componentmodel.design....
The items such as ToolStripItem etc aren't actually controls, they are simply components that make up a ToolStrip or MenuStrip. Which means, that if you want to include those components in your flattened list of controls then you will need to do the specific checks.
Enumerate .Net control's items generically (MenuStrip, ToolStrip, StatusStrip)
[ "", "c#", ".net-2.0", "" ]
I'm trying to update a hashtable in a loop but getting an error: System.InvalidOperationException: Collection was modified; enumeration operation may not execute. ``` private Hashtable htSettings_m = new Hashtable(); htSettings_m.Add("SizeWidth", "728"); htSettings_m.Add("SizeHeight", "450"); string sKey = ""; string ...
you could read the collection of keys into another IEnumerable instance first, then foreach over that list ``` System.Collections.Hashtable ht = new System.Collections.Hashtable(); ht.Add("test1", "test2"); ht.Add("test3", "test4"); List<string> keys = new List<string>(); fore...
In concept I would do: ``` Hashtable table = new Hashtable(); // ps, I would prefer the generic dictionary.. Hashtable updates = new Hashtable(); foreach (DictionaryEntry entry in table) { // logic if something needs to change or nog if (needsUpdate) { updates.Add(key, newValue); } } // now do the ...
How to update C# hashtable in a loop?
[ "", "c#", "data-structures", "loops", "hashtable", "" ]
We have a Hibernate/Spring application that have the following Spring beans: ``` <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" /> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" /> ``` When wiring the a...
While I haven't used Spring, I have used Hibernate in a project which has classes which must either be instantiated by factory methods or through multiple argument constructors. You can do this through an Interceptor, which is a class which listens in to several key hibernate events, such as when an object needs to be...
Do you know about the property "factory-method" ? You can make spring call that method instead of the constructor to instantiate a bean.
Hibernate and Spring transactions - using private constructors/static factory methods
[ "", "java", "hibernate", "spring", "transactions", "" ]
I have a python module that defines a number of classes: ``` class A(object): def __call__(self): print "ran a" class B(object): def __call__(self): print "ran b" class C(object): def __call__(self): print "ran c" ``` From within the module, how might I add an attribute that give...
``` import sys getattr(sys.modules[__name__], 'A') ```
You can smash this into one for statement, but that'd have messy code duplication. ``` import sys import types this_module = sys.modules[__name__] [x for x in [getattr(this_module, x) for x in dir(this_module)] if type(x) == types.ClassType] ```
How can I dynamically get the set of classes from the current python module?
[ "", "python", "reflection", "metaprogramming", "" ]
I know the rule-of-thumb to read declarations right-to-left and I was fairly sure I knew what was going on until a colleague told me that: ``` const MyStructure** ppMyStruct; ``` means "ppMyStruct is **a pointer to a const pointer to a (mutable) MyStructure**" (in C++). I would have thought it meant "ppMyStruct is *...
Your colleague is wrong. That is a (non-const) pointer to a (non-const) pointer to a const MyStructure. In both C and C++.
In such cases the tool cdecl (or c++decl) can be helpfull: ``` [flolo@titan ~]$ cdecl explain "const struct s** ppMyStruct" declare ppMyStruct as pointer to pointer to const struct s ```
What does a const pointer-to-pointer mean in C and in C++?
[ "", "c++", "c", "pointers", "constants", "" ]
I've got a large amount of data (a couple gigs) I need to write to a zip file in Python. I can't load it all into memory at once to pass to the .writestr method of ZipFile, and I really don't want to feed it all out to disk using temporary files and then read it back. Is there a way to feed a generator or a file-like ...
The only solution is to rewrite the method it uses for zipping files to read from a buffer. It would be trivial to add this to the standard libraries; I'm kind of amazed it hasn't been done yet. I gather there's a lot of agreement the entire interface needs to be overhauled, and that seems to be blocking any incrementa...
Changed in **Python 3.5** (from official docs): Added [support](https://docs.python.org/3/library/zipfile.html#zipfile-objects) for writing to **unseekable** streams. This means that now for `zipfile.ZipFile` we can use streams which do not store the entire file in memory. Such streams [do not support](https://docs.py...
Create a zip file from a generator in Python?
[ "", "python", "zip", "" ]
OK, Here is my problem, I have a master page with a HEAD section that contains my JS includes. I have one JS include ``` <script src="Includes/js/browser.js" language="javascript" type="text/javascript"></script> ``` In my page i consume it like this: ``` <body> <form id="form1" runat="server"> <div> .... <script t...
If you can use Firefox, I would highly recommend installing and enabling the Firebug addon. Otherwise, see some of the following for tools that might help: * [Javascript troubleshooting tools in IE](https://stackoverflow.com/questions/3404/javascript-troubleshooting-tools-in-ie) * [Is there any good or reliable way t...
As you wish. > You just missed something and it's a stupid mistake. :) That being said, I'd try to find out which file it is that has the faulty line 216. Perhaps it's the browser.js file? Other possibilities include: * You messed up the URL and the file isn't loaded; * The function depends on the DOM to be complet...
How do I debug this weird IE JavaScript Problem
[ "", "javascript", "internet-explorer", "" ]
Is there a fast algorithm for finding the Largest Common Substring in two `strings` or is it an NPComplete problem? In PHP I can find a needle in a haystack: ``` <?php if (strstr("there is a needle in a haystack", "needle")) { echo "found<br>\n"; } ?> ``` I guess I could do this in a loop over one of the `strin...
I have since found [a relevant wikipedia article](http://en.wikipedia.org/wiki/Longest_common_substring_problem). It is not a NP complete problem, it can be done in O(mn) time using a dynamic programming algorithm. In PHP I found the [similar\_text](https://www.php.net/manual/en/function.similar-text.php) function ver...
The [similar\_text](https://www.php.net/manual/en/function.similar-text.php) function may be what you want. This calculates the similarity between two strings. Returns the number of matching chars in both strings You may also want to look at [levenshtein](https://www.php.net/manual/en/function.levenshtein.php)
How can I find the Largest Common Substring between two strings in PHP?
[ "", "php", "algorithm", "string", "performance", "spam-prevention", "" ]
One thing that annoys me when debugging programs in Visual Studio (2005 in my case) is that when I use "step over" (by pressing `F10`) to execute to the next line of code, I often end up reaching that particular line of code in a totally different thread than the one I was looking at. This means that all the context of...
I think there is only one answer to your question, which you have discounted as being 'way too much work.' However, I believe that is because you are going about it the wrong way. Let me present steps for adding a conditional breakpoint on Thread ID, which are extremely easy, but not obvious until you know them. 1. St...
You can freeze a different thread or switch to another thread using the Threads debug window (`Ctrl` + `Alt` + `H`).
"Step over" when debugging multithreaded programs in Visual Studio
[ "", "c++", "visual-studio", "multithreading", "debugging", "visual-studio-2005", "" ]
In a [.NET](http://en.wikipedia.org/wiki/.NET_Framework) 2.0 C# application I use the following code to detect the operating system platform: ``` string os_platform = System.Environment.OSVersion.Platform.ToString(); ``` This returns "Win32NT". The problem is that it returns "Win32NT" even when running on Windows Vis...
**UPDATE:** As Joel Coehoorn and others suggest, starting at .NET Framework 4.0, you can just check `Environment.Is64BitOperatingSystem`. --- IntPtr.Size won't return the correct value if running in 32-bit .NET Framework 2.0 on 64-bit Windows (it would return 32-bit). As Microsoft's Raymond Chen describes, you have ...
.NET 4 has two new properties in the Environment class, [Is64BitProcess](http://msdn.microsoft.com/en-us/library/system.environment.is64bitprocess(VS.100).aspx) and [Is64BitOperatingSystem](http://msdn.microsoft.com/en-us/library/system.environment.is64bitoperatingsystem%28VS.100%29.aspx). Interestingly, if you use Ref...
How to detect Windows 64-bit platform with .NET?
[ "", "c#", "windows", "64-bit", ".net-2.0", "platform-detection", "" ]
I'm looking for a way to display multiple colors in a single C#/.NET label. E.g the label is displaying a series of csv separated values that each take on a color depending on a bucket they fall into. I would prefer not to use multiple labels, as the values are variable length and I don't want to play with dynamic layo...
There is no native control in .NET that does this. Your best bet is to write your own UserControl (call it RainbowLabel or something). Normally you would have a custom label control inherit directly from Label, but since you can't get multi-colored text in one label, you would just inherit from UserControl. For render...
You could try using a RichTextBox so that you can get multiple colors for the string and then make it read only and remove the border. Change the background color to the same as the Form it is on and you might get away with it.
Multiple colors in a C# .NET label
[ "", "c#", ".net", "user-interface", "colors", "label", "" ]
I have a bunch of controls (textbox and combobox) on a form with toolstripcontainer and toolstripbuttons for save, cancel etc for edits. We are using .Net 3.5 SP1 There is bunch of logic written in control.lostfocus and control.leave events. These events are not being called when clicked on the toolstrip buttons. Is ...
You could listen to the click events on the buttons, and in the handler call their focus method. That would (hopefully) cause the previously focused control to respond correctly. Add the following handler to each button's click event: ``` private void ButtonClick(object sender, EventArgs e) { if(sender != null) { ...
You can extend those controls and then call the OnLostFocus and OnLeave protected methods of the base class...
Raise LostFocus event on a control manually
[ "", "c#", ".net", "" ]
Have a use case wherein need to maintain a connection open to a database open to execute queries periodically. Is it advisable to close connection after executing the query and then reopen it after the period interval (10 minutes). I would guess no since opening a connection to database is expensive. Is connection po...
You should use connection pooling. Write your application code to request a connection from the pool, use the connection, then return the connection back to the pool. This keeps your code clean. Then you rely on the pool implementation to determine the most efficient way to manage the connections (for example, keeping ...
Yes, connection pooling is the alternative. Open the connection each time (as far as your code is concerned) and close it as quickly as you can. The connection pool will handle the physical connection in an appropriately efficient manner (including any keepalives required, occasional "liveness" tests etc). I don't kno...
Reusing a connection while polling a database in JDBC?
[ "", "java", "" ]
I have the following situation: I have a certain function that runs a loop and does stuff, and error conditions may make it exit that loop. I want to be able to check whether the loop is still running or not. For this, i'm doing, for each loop run: ``` LastTimeIDidTheLoop = new Date(); ``` And in another function, ...
what about: ``` newDate = new Date() newDate.setSeconds(newDate.getSeconds()-30); if (newDate > LastTimeIDidTheLoop) { alert("oops"); } ```
JS date objects store milliseconds internally, subtracting them from each other works as expected: ``` var diffSeconds = (new Date() - LastTimeIDidTheLoop) / 1000; if (diffSeconds > 30) { // ... } ```
How do I compare dates in Javascript?
[ "", "javascript", "date", "" ]
I can't seem to retrieve the AlternateView from System.Net.Mail.AlternateView. I have an application that is pulling email via POP3. I understand how to create an alternate view for sending, but how does one select the alternate view when looking at the email. I've have the received email as a System.Net.MailMessage o...
Its not immediately possible to parse an email with the classes available in the System.Net.Mail namespace; you either need to create your own MIME parser, or use a third party library instead. This great Codeproject article by Peter Huber SG, entitled ['POP3 Email Client with full MIME Support (.NET 2.0)'](http://www...
Mightytighty is leading you down the right path, but you shouldn't presume the type of encoding. This should do the trick: ``` var dataStream = view.ContentStream; dataStream.Position = 0; byte[] byteBuffer = new byte[dataStream.Length]; var encoding = Encoding.GetEncoding(view.ContentType.CharSet); string body = enco...
Retrieving AlternateView's of email
[ "", "c#", "html", "email", "pop3", "plaintext", "" ]
On various pages throughout my PHP web site and in various nested directories I want to include a specific file at a path relative to the root. What single command can I put on both of these pages... ``` http://www.example.com/pageone.php ``` ``` http://www.example.com/somedirectory/pagetwo.php ``` ...to include th...
If you give include() or require() (or the \*\_once versions) an absolute pathname, that file will be included. An absolute pathname starts with a "/" on unix, and with a drive letter and colon on Windows. If you give a relative path (any other path), PHP will search the directories in the configuration value "include...
You can just use `include $_SERVER['DOCUMENT_ROOT'] . "/includes/analytics.php";`
How do I format a PHP include() absolute (rather than relative) path?
[ "", "php", "path", "include", "" ]
I seemed to get the following exception when trying to deploy my application: ``` Caused by: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions java.util.List is an interface, and JAXB can't handle interfaces. this problem is related to the following location: at j...
In my understanding, you will not be able to process a plain `List` via JAXB, as JAXB has no idea how to transform that into XML. Instead, you will need to define a JAXB type which holds a `List<RelationCanonical>` (I'll call it `Type1`), and another one to hold a list of those types, in turn (as you're dealing with a...
If that suits your purpose you can always define an array like this: ``` YourType[] ``` JAXB can certainly figure out what that is and you should be able to immediatly use it client side. I would also recommend you to do it that way, since you should not be able to modify the array retrieved from a server via a List ...
java.util.List is an interface, and JAXB can't handle interfaces
[ "", "java", "web-services", "jakarta-ee", "jaxb", "jbossws", "" ]
I have a table User which has an identity column `UserID`, now what is the correct Linq to Entity line of code that would return me the max `UserID`? I've tried: ``` using (MyDBEntities db = new MyDBEntities()) { var User = db.Users.Last(); // or var User = db.Users.Max(); return user.UserID; } ``` ...
Do that like this ``` db.Users.OrderByDescending(u => u.UserId).FirstOrDefault(); ```
try this ``` int intIdt = db.Users.Max(u => u.UserId); ``` **Update:** If no record then generate exception using above code try this ``` int? intIdt = db.Users.Max(u => (int?)u.UserId); ```
How do I get the max ID with Linq to Entity?
[ "", "c#", "linq", "entity-framework", "linq-to-entities", "" ]
I've found the following code from here "[<http://www.boyet.com/Articles/CodeFromInternet.html>](http://www.boyet.com/Articles/CodeFromInternet.html)". It returns the speed of the CPU in GHz but works only on 32bit Windows. ``` using System; using System.Management; namespace CpuSpeed { class Program { ...
I've used the following code based on the answer by Binoj Antony which returns the speed for each CPU/core, not only the first one: ``` Microsoft.Win32.RegistryKey registrykeyHKLM = Microsoft.Win32.Registry.LocalMachine; string cpuPath = @"HARDWARE\DESCRIPTION\System\CentralProcessor"; Microsoft.Win32.RegistryKey regi...
Code below should do the trick ``` RegistryKey registrykeyHKLM = Registry.LocalMachine; string keyPath = @"HARDWARE\DESCRIPTION\System\CentralProcessor\0"; RegistryKey registrykeyCPU = registrykeyHKLM.OpenSubKey(keyPath, false); string MHz = registrykeyCPU.GetValue("~MHz").ToString(); string ProcessorNameStr...
How to detect CPU speed on Windows 64bit?
[ "", "c#", ".net", "windows", "64-bit", "cpu-speed", "" ]
Having recently gotten into test driven development I am using the Nunit test runner shipped as part of resharper. It has some downsides in terms of there is no shortcut to run tests and I have to go looking for the Nunit test runner to invoke it using the mouse. It has a nice GUI and shows the results as part of the I...
Resharper does have some shortcomings...but it is possible to configure it to do what you want... You can configure keyboard options in Visual Studio. Also, you can use the Unit Test Explorer in Resharper to find the tests you want and add them to the current session. I usually configure a shortcut (Alt+U) that runs a...
I've always been a fan of TestDriven.NET, I much prefer it over using ReSharper.
What is the best Nunit test runner out there?
[ "", "c#", "unit-testing", "nunit", "test-runner", "" ]
I got a core that looks very different from the ones I usually get - most of the threads are in \_\_kernel\_vsyscall() : ``` 9 process 11334 0xffffe410 in __kernel_vsyscall () 8 process 11453 0xffffe410 in __kernel_vsyscall () 7 process 11454 0xffffe410 in __kernel_vsyscall () 6 process 11455 0xffffe410 in...
`__kernel_vsyscal` is the method used by linux-gate.so (a part of the Linux kernel) to make a system call using the fastest available method, preferably the `sysenter` instruction. The thing is properly explained by [Johan Petersson](http://www.trilithium.com/johan/2005/08/linux-gate).
When you make a system call (like reading from a file, talking to hardware, writing to sockets) you're actually creating an interrupt. The system then handles the interrupt in kernel mode and your call returns with the result. Most of the time it's unusual for you to have a lot of threads in syscall unless you're makin...
What is __kernel_vsyscall?
[ "", "c++", "gdb", "" ]
I'm currently developing an application that is comprised of five separate executables that communicate via ActiveMQ. I have a Visual Studio Solution that contains the five executable projects. One of the projects (the launcher.exe) launches the other four projects from their local folders as separate processes. As suc...
What you need is in the Tools menu: Attach to Process. This gives you a list of running processes and allows you to attach your debugger to those processes. For local debugging, Transport and Qualifier should keep their default values. The Attach To value just above the list determines which type of debugging you'll b...
You can pick one at a time by running launcher manually (outside of visual studio, or with <ctrl-f5>) and then attaching to the process you want to debug once it's started. If it's one of the projects in your solution, you can set breakpoints and they'll get picked up when you attach the debugger.
Debugging Multi-Project (C++) Solutions in Visual Studio 2005
[ "", "c++", "visual-studio-2005", "visual-c++-2005", "" ]
I have a Windows application (VS2005/C#) which comes in two versions, Enterprise and Pro. In the Pro version, some of the features and menus are disabled. Currently, I'm doing this by commenting out the disabling code to create the Enterprise version, then I copy each executable file to another location. Obviously this...
from the BUILD menu, select configuration manager option on the active solution configuration dropdown select "new" create two new 'configurations' one for PRO and one for ENTERPRISE close the configuration manager. open the project properties (from the project context menu) select the build tab select the PRO con...
Yes, thats certainly possible. A visual studio solution comes with two configuration by default. (Release and Debug). You can create additional ones like "EnterpriseDebug" and "EnterpriseRelease" Just go to the Configuration Manager under (Build | Configuration Manager ) and then select <New...> The configuration mana...
Configurations and Program features in Visual Studio/C# Windows App
[ "", "c#", "configuration", "visual-studio-2005", "versioning", "" ]
I have a PHP application and a need to generate a PDF with the result of query. The easiest way a found to do this was to use the DOMPDF to generate the PDF for me. So a made a function that generates the HTML for me then a pass this to DOMPDF. In the development and testing enviroment everything was fine but on produc...
I once did a PHP project generating PDF. I used [FPdf](http://www.fpdf.org/). I never had any memory problems. It's free, it's pure PHP code. You don't have to load any extensions. I don't know if there's some helpers to auto-generate document from a query, but in the website, you have some scripts that shows how to ...
I'm amazed nobody uses FOP:) <http://xmlgraphics.apache.org/fop/> ... you basically feed it an XML flie and it generates a PDF file... very quick, and dosent kill your server.
Generating PDFs with PHP
[ "", "php", "pdf", "dompdf", "" ]
Always when I run java application it will display in Windows Task Manager is java.exe or javaw.exe. How to rename java.exe or javaw.exe process without wrapper by other programming languages.
If you are confused by looking at process names that are all the same (*java.exe*), try to use [*Process Explorer*](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) instead of *Task Manager*, and display the *command line* field. This way, you can see the *class* or *jar* arguments that differentiate one ...
You could use [jSmooth](http://jsmooth.sourceforge.net/): > JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications.
How to rename java.exe/javaw.exe process?
[ "", "java", "" ]
Is there a way to cast a user control as a specific user control so I have access to it's public properties? Basicly I'm foreaching through a placeholder's controls collection and I'm trying to access the user control's public properties. ``` foreach(UserControl uc in plhMediaBuys.Controls) { uc.PulblicPropertyIWa...
``` foreach(UserControl uc in plhMediaBuys.Controls) { MyControl c = uc as MyControl; if (c != null) { c.PublicPropertyIWantAccessTo; } } ```
``` foreach(UserControl uc in plhMediaBuys.Controls) { if (uc is MySpecificType) { return (uc as MySpecificType).PulblicPropertyIWantAccessTo; } } ```
Casting a UserControl as a specific type of user control
[ "", "c#", "asp.net", "user-controls", "" ]
Is it ever OK to use [Environment.TickCount](https://learn.microsoft.com/en-us/dotnet/api/system.environment.tickcount) to calculate time spans? ``` int start = Environment.TickCount; // Do stuff int duration = Environment.TickCount - start; Console.WriteLine("That took " + duration " ms"); ``` Because `TickCount` is...
Use the Stopwatch class. There is a decent example on [MSDN](https://en.wikipedia.org/wiki/Microsoft_Developer_Network): *[Stopwatch Class](http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx)* ``` Stopwatch stopWatch = Stopwatch.StartNew(); Thread.Sleep(10000); stopWatch.Stop(); ...
**Environment.TickCount** is based on [GetTickCount()](http://msdn.microsoft.com/en-us/library/ms724408.aspx) WinAPI function. It's in milliseconds. But the actual precision of it is about 15.6 ms. So you can't measure shorter time intervals (or you'll get 0). *Note:* The returned value is Int32, so this counter rolls...
Environment.TickCount vs DateTime.Now
[ "", "c#", ".net", "datetime", "timespan", "" ]
Here I am faced with an issue that I believe(or at least hope) was solved 1 million times already. What I got as the input is a string that represents a length of an object in imperial units. It can go like this: ``` $length = "3' 2 1/2\""; ``` or like this: ``` $length = "1/2\""; ``` or in fact in any other way we...
Here is my solution. It uses [eval()](http://php.net/eval) to evaluate the expression, but don't worry, the regex check at the end makes it completely safe. ``` function imperial2metric($number) { // Get rid of whitespace on both ends of the string. $number = trim($number); // This results in the number o...
The Zend Framework has a measurement component for just that purpose. I suggest you check it out - [here](http://framework.zend.com/manual/en/zend.measure.html). ``` $unit = new Zend_Measure_Length($length,Zend_Measure_Length::YARD); $unit -> convertTo(Zend_Measure_Length::METER); ```
How to convert imperial units of length into metric?
[ "", "php", "regex", "code-snippets", "" ]
For those who like a good WPF binding challenge: I have a nearly functional example of two-way binding a `CheckBox` to an individual bit of a flags enumeration (thanks Ian Oakes, [original MSDN post](http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/c05b7e7e-25cd-4a41-8bf5-e35d2caff797/)). The problem though is...
You could use a value converter. Here's a very specific implementation for the target `Enum`, but would not be hard to see how to make the converter more generic: ``` [Flags] public enum Department { None = 0, A = 1, B = 2, C = 4, D = 8 } public partial class Window1 : Window { public Window1(...
Here's something I came up with that leaves the View nice and clean (no static resources necessary, no new attached properties to fill out, no converters or converter parameters required in the binding), and leaves the ViewModel clean (no extra properties to bind to) The View looks like this: ``` <CheckBox Content="A...
How can you two-way bind a checkbox to an individual bit of a flags enumeration?
[ "", "c#", "wpf", "data-binding", "enums", "bit-manipulation", "" ]
I have an IQueryable and an object of type T. I want to do IQueryable().Where(o => o.GetProperty(fieldName) == objectOfTypeT.GetProperty(fieldName)) so ... ``` public IQueryable<T> DoWork<T>(string fieldName) where T : EntityObject { ... T objectOfTypeT = ...; .... return SomeIQueryable<T>().Wher...
Like so: ``` var param = Expression.Parameter(typeof(T), "o"); var fixedItem = Expression.Constant(objectOfTypeT, typeof(T)); var body = Expression.Equal( Expression.PropertyOrField(param, fieldName), Expression.PropertyOrField(fixedItem, fieldName)); var lambda = Expression.Lambda<Func...
From what I can see so far it's going to have to be something like ... ``` IQueryable<T>().Where(t => MemberExpression.Property(MemberExpression.Constant(t), fieldName) == ParameterExpression.Property(ParameterExpression.Constant(item), fieldName)); ``` While I can get this to compile it's not quite executing the w...
How do I build a Linq Expression Tree that compares against a generic object?
[ "", "c#", "linq", "entity-framework", "generics", "expression-trees", "" ]
I have a function that resembles the one below. I'm not sure how to use the os module to get back to my original working directory at the conclusion of the jar's execution. ``` def run(): owd = os.getcwd() #first change dir to build_dir path os.chdir(testDir) #run jar from test directory os.system...
You simply need to add the line: ``` os.chdir(owd) ``` Just a note this was also answered in your other [question](http://stackoverflow.com/questions/299249/how-can-i-get-my-python-version-25-script-to-run-a-jar-file-inside-a-folder-ins).
A context manager is a very appropriate tool for this job: ``` from contextlib import contextmanager import os @contextmanager def cwd(path): oldpwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(oldpwd) ``` ...used as: ``` os.chdir('/tmp') # for testing purposes, be in a ...
How do I change directory back to my original working directory with Python?
[ "", "python", "" ]
I am working on a big C++ project. It is building using single Ant script which makes possible to compile the same source targeting more than one platform and compiler. But, I have to work only for Windows platform and Visual Studio 2005 C++ compiler. It would be really nice if I could write code and compile in Visual...
To my knowledge, there is no *automatic* way of converting Ant script to NAnt. However, since NAnt is based off of the Ant the conversion process would not be too far from the original, as long as the tasks are the "core" ones. Possibly an XSLT translation could be made on the Ant scripts to convert to NAnt as both are...
In my experience, the best way to integrate VS with ant is on the IDE side to call ant as a custom build step (as Scott Saad suggests), and from ant, to call msbuild.exe as the executable to build the project from the command line. I know that this question is already answered -- I just wanted to suggest the possibili...
Ant -> Nant -> Visual Studio 2005 Build
[ "", "c++", "visual-studio-2005", "ant", "nant", "visual-c++-2005", "" ]
I've got this date time string: ``` post["date"] = "2007-07-18 10:03:19" ``` I'd like to extract just "2007-07-18" as a date. I've seen some reference to `strptime` but I'm not sure how to use it. How can I extract the date from this string?
The other two answers are fine, but if you actually want the date for something else, you can use the `datetime` module: ``` from datetime import datetime d = datetime.strptime('2007-07-18 10:03:19', '%Y-%m-%d %H:%M:%S') day_string = d.strftime('%Y-%m-%d') ``` It might be overkill for now, but it'll come in useful. Y...
In your case, just use split: ``` >>> d1="2007-07-18 10:03:19" >>> d1.split()[0] '2007-07-18' >>> ``` (The 1st part after splitting with whitespace) If you insist on using `strptime`, the format is `"%Y-%m-%d %H:%M:%S"` : ``` >>> import time >>> time.strptime(d1,"%Y-%m-%d %H:%M:%S") time.struct_time(tm_year=2007, t...
Convert a string with date and time to a date
[ "", "python", "datetime", "" ]