Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a UserControl with some predefined controls (groupbox,button,datagridview) on it, these controls are marked as protected and the components variable is also marked as protected.
I then want to inherit from this base UserControl to another UserControl, however the DataGridView is always locked in the designer.
... | By the looks of it, DataListView (and some other controls) do not support visual inheritance. There's a connect issue [logged here](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=116457) which doesn't look hopeful.
There have been similar issues logged with other form controls, e.g. [f... | [1] create Your Custom UserControl
[2] make your custom userControl use the below Inherited DataGridView:
```
[Designer(typeof System.Windows.Forms.Design.ControlDesigner))]
public class InheritedDataGridView : DataGridView { }
```
[3] Inherit from your Custom UserControl , And viola !!
[4] Ohh dont forget to add "... | DataGridView locked on a inherited UserControl | [
"",
"c#",
".net",
"winforms",
"inheritance",
""
] |
I want a method of the class: "`One`" ("`AccessibleWithinSameNamespace`") to be accessible by the class: "`Two`", without having "`Two`" extending "`One`".
Both classes are in the same namespace, so I'm thinking that maybe there's an access-modifier that emulates the "*protected*" modifyer, but for namespaces.
Some c... | You can use the [internal](http://msdn.microsoft.com/en-us/library/7c5ka91b.aspx) modifier if both classes are in the same assembly.
With your example:
```
namespace Test
{
class One
{
public void AccessibleToAll()
{
}
internal void AccessibleWithinSameNamespace()
{
... | C# and .NET have no concept of "within the same namespace". Internal is the closest equivalent. | Class-member access-modifiers | [
"",
"c#",
".net-3.5",
""
] |
I have an ASP.net website ( <http://www.erate.co.za> ) version 2.0.
When someone opens my website in Firefox everything looks different.
Why is that and how can I make it compatible?
Please help!
Etienne | The problems don't have anything to do with ASP.NET / C# Specifically.
They have to do with your understanding of web design / HTML / CSS and how you can make a cross-browser compatible UI.
I'd suggest you look at <http://www.w3schools.com/> for some information on good web design practices.
Some obvious problems wi... | The underlying server technology should not have any impact on your websites appearence as long as you are just producing HTML.
What you need to do is make sure that your HTML and CSS works as intended in all browsers. A good way to start is to make sure that you only output standards compliant code. | Making my ASP.NET website compatible with Firefox? | [
"",
"c#",
"asp.net",
"vb.net",
"firefox",
""
] |
I have an object that starts a thread, opens a file, and waits for input from other classes. As it receives input, it writes it to disk. Basically, it's a thread safe data logging class...
Here's the weird part. When I open a form in the designer (Visual Studio 2008) that uses the object the file gets created. It's ob... | You can check the UsageMode of the LicenseManager, to check if the code is in design time or not.
System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime
Here is a quick example:
```
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace Test
{
... | The constructor of a control or form does not get executed when editing that class in the designer (nor does OnLoad get called). I've occasionally used this to set one value in the designer (eg. making its child controls all Visible in the designer) but override some of them to a different default value in the construc... | .NET Windows Forms design time rules | [
"",
"c#",
".net",
"winforms",
"design-time",
""
] |
Imagine the following
A type T has a field Company.
When executing the following method it works perfectly:
```
Type t = typeof(T);
t.GetProperty("Company")
```
Whith the following call I get null though
```
Type t = typeof(T);
t.GetProperty("company", BindingFlags.IgnoreCase)
```
Anybody got an idea? | You've overwritten the default look-up flags, if you specify new flags you need to provide all the info so that the property can be found. For example: `BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance` | You need to add `BindingFlags.Public | BindingFlags.Instance` | BindingFlags.IgnoreCase not working for Type.GetProperty()? | [
"",
"c#",
"reflection",
"getproperty",
"bindingflags",
""
] |
Is there any way to find out what exceptions might be thrown by any method in .NET code? Ideally I want to see what might be thrown and choose which ones I want to handle. I guess I want the information you'd get from the throws clause in java.
The situation is I'm doing a linq query on an xml document from the networ... | .NET does not have enforced ("checked") exceptions like java. The intellisense *might* show this information, if the developer has added a `/// <exception.../>` block - but ultimately more exceptions can happen than you expect (`OutOfMemoryException`, `ThreadAbortException`, `TypeLoadException`, etc can all happen fair... | I think that [Exception hunter](http://www.red-gate.com/products/Exception_Hunter/index.htm) can provide this information however it costs money... | Finding out what exceptions a method might throw in C# | [
"",
"c#",
".net",
"exception",
""
] |
how do i check if an item is selected or not in my listbox?
so i have a button remove, but i only want that button to execute if an item is selected in the list box. im using asp.net code behind C#. I'd prefer if this validation occurred on the server side.
cheers.. | ```
for (int i = 0; i < lbSrc.Items.Count; i++)
{
if (lbSrc.Items[i].Selected == true)
{
lbSrc.Items.RemoveAt(lbSrc.SelectedIndex);
}
}
```
this is what i came up with. | On the callback for the button click, just check if the selected index of the list box is greater than or equal to zero.
```
protected void removeButton_Click( object sender, EventArgs e )
{
if (listBox.SelectedIndex >= 0)
{
listBox.Items.RemoveAt( listBox.SelectedIndex );
}
}
``` | listbox validation | [
"",
"c#",
"asp.net",
"listbox",
"validation",
""
] |
I have a page with a "Print" link that takes the user to a printer-friendly page. The client wants a print dialog box to appear automatically when the user arrives at the print-friendly page. How can I do this with javascript? | ```
window.print();
```
unless you mean a custom looking popup. | You could do
```
<body onload="window.print()">
...
</body>
``` | How can I pop-up a print dialog box using Javascript? | [
"",
"javascript",
""
] |
I have multiple RequireFieldValidators on my aspx page.
On the backend (C#) I want to be able to tell which control specifically wasn't valid so I can apply a style to that control.
I use the Page.IsValid method to see if the overall page passed validation but I need to know specifically which one control failed. | As others have mentioned, you need to loop the validator collection of the page and check their states. [MSDN has examples here.](http://msdn.microsoft.com/en-us/library/dh9ad08f.aspx)
```
If (Me.IsPostBack) Then
Me.Validate()
If (Not Me.IsValid) Then
Dim msg As String
' Loop through all validation controls to... | All Validators are added to the ValidatorCollection of the Page (property Page.Validators).
You can loop through this collection to validate each control manually.
Call method IValidator.Validate(); | How to tell which RequiredFieldValidator failed | [
"",
"c#",
".net",
"validation",
""
] |
I am working on a simple notification service that will be used to deliver messages to the users surfing a website. The notifications do not have to be sent in real time but it might be a better user experience if they happened more frequently than say every 5 minutes. The data being sent to and from the client is not ... | Because using a push requires an open HTTP connection to be maintained between your server and each client, I'd go for poll as well - not only is that going to consume a lot of server resources but it's also going to be significantly more tricky to implement as matt b mentioned.
My experience with polling is that if y... | I'm surprised noone here has mentioned long-polling. Long polling means keeping an open connection for a longer period (say 30-60 seconds), and once it's closed, re-opening it again, and simply having the socket/connection listen for responses. This results in less connections (but longer ones), and means that response... | Client notification, should I use an AJAX Push or Poll? | [
"",
"javascript",
"ajax",
"web-services",
"server-push",
""
] |
Basically, I have an `iframe` embedded in a page and the `iframe` has some [JavaScript](http://en.wikipedia.org/wiki/JavaScript) routines I need to invoke from the parent page.
Now the opposite is quite simple as you only need to call `parent.functionName()`, but unfortunately, I need exactly the opposite of that.
Pl... | Assume your iFrame's id is "targetFrame" and the function you want to call is `targetFunction()`:
```
document.getElementById('targetFrame').contentWindow.targetFunction();
```
You can also access the frame using `window.frames` instead of `document.getElementById`.
```
// this option does not work in most of latest... | There are some quirks to be aware of here.
1. `HTMLIFrameElement.contentWindow` is probably the easier way, but it's not quite a standard property and some browsers don't support it, mostly older ones. This is because the DOM Level 1 HTML standard has nothing to say about the `window` object.
2. You can also try `HTML... | Invoking JavaScript code in an iframe from the parent page | [
"",
"javascript",
"html",
"iframe",
""
] |
Is there any tool that enables you to "hot swap" JavaScript contents while executing a webpage?
I am looking for something similar to what HotSpot does for Java, a way to "hot deploy" new JS code without having to reload the whole page.
Is there anything like that out there?
**Clarifying in case people don't underst... | Interesting idea :)
I wrote the following bookmarklet:
```
function reload(){var scripts=document.getElementsByTagName("script");var head=document.getElementsByTagName("head")[0];var newScripts=[];var removeScripts=[];for(var i=0;i<scripts.length;i++){var parent=scripts[i].parentNode;if(parent==head&&scripts[i].src){... | Since I had a similar problem to solve I wrote a small js lib to hotswap javascript, css and image files. It´s of course open source on github: [hotswap.js](https://github.com/geo-at-github/hotswap.js)
Hope it helps.
**Update**: I have attached the full lib source here. To use it simply copy the content into a file (... | Is there a way to "hot swap" JavaScript code within the browser? | [
"",
"javascript",
"debugging",
"frameworks",
""
] |
I remember from C days that we were encouraged to use
```
i > -1
```
instead of
```
i >= 0
```
because of performance.
Does this still apply in the C# .NET world? What are the performance implications of using one over the other with today's compilers? i.e. Is the compiler clever enough to optimize these for you?
... | No, there are no performance issues associated with comparison operators. And any good compiler would optimize something this trivial anyway.
I'm not sure where you got the suggestion to use "i > -1" rather than "i >= 0". On the x86 architecture, it makes no difference which you use: either case takes exactly two inst... | Quite apart from the fact that any decent compiler does the right thing, and apart from that fact that in modern architectures there's no speed difference between `>` and `>=` comparisons, the bigger picture says that this is a "micro-optimisation" that doesn't affect runtime performance in the vast majority of cases.
... | Use "greater than or equals" or just "greater than" | [
"",
"c#",
".net",
"c",
""
] |
I am using msbuild to build a C++ project and I want to suppress the 'Post-Build Event'. I have tried the following properties with no success:
```
/property:PostBuildEvent=
/property:VCPostBuildEventTool=
```
Neither will make any difference and the post build events are still executed.
Does anyone know how to supp... | I just figured out how to do this. There's 2 steps involved:
First, if you're not starting the msbuild process using a batch file already, create a batch file that calls the msbuild process. Then add a variable in the batch file before you call the msbuild process. Something like this:
```
set ISFULLBUILD=True
msbuil... | If you are able to modify the post-build events, you could do this with an environment variable, say `SKIP_POST_BUILD_EVENTS`. You can then set that environment variable before calling `msbuild`, and check whether the variable exists in the post-build event before executing whatever code is there. | Suppressing C++ 'Post-Build Event' when using msbuild | [
"",
"c++",
"msbuild",
""
] |
I received a WSDL file for a web service interface that our system should call somewhere in the future.
Until then, I'd like to setup a dummy/mockup web service that does nothing else than to log the web service invocations and return dummy data.
What I've done so far is to generate Java objects from the WSDL file.
... | We just faced this same problem, and found [SoapUI](http://www.soapui.org/) to be the perfect tool. Given a WSDL it'll create a service on your machine you can call, and it allows you to edit the response as you need. | You can also use [Fiddler](http://www.fiddlertool.com/fiddler/), a HTTP Debugging Proxy. You can easily configure Fiddler to return a pre-defined HTTP response with its AutoResponder feature when a request is sent to a particular URL. | Dummy web service | [
"",
"java",
"web-services",
"mockups",
""
] |
I've tried Red Gate's SQL Prompt and like it, but cannot afford it at the moment. I miss the good code completion that this tool provides. Are there any good free tools out there that have SQL code completion (table and column names, etc)?
I've tried TOAD, but it was quite buggy. It would crash, and would also leave c... | Red Gate's [SQL Prompt](http://www.red-gate.com/products/SQL_Prompt/index.htm) is what you want. It's not free, but it **is** worth it. | I have tried a few different tools myself, and nothing really compared to SQL Prompt.
I personally recommend contacting Red Gate if you like the tool, they are known to have "specials" at given times where you might be able to get a discount, especially this time of the month.
Otherwise, contact me and I get get you ... | What is a good tool to get SQL code completion with SQL Server 2005? | [
"",
"sql",
"sql-server",
""
] |
I develop and maintain small intranet web apps written in JSP and Java.
They run on a Resin web server, without dedicated httpd like Apache.
Before performing maintenance, I activate a very simple Ajax message to urge users to logout.
What I want is, while I do maintenance, a user trying to log in to that particular ... | Setup an alternate site on your webserver with the outage message. Then when doing maintenance, redirect your website to the maintenance site while up update it. That way if users have pages other than the default page bookmarked, they will still get the outage message. Otherwise, a simple approach is to just swap out ... | I just swap out the first page of the web app with a linkless page containing the message you mentioned. | How can I show a "temporarily out of service" page to web-app users during maintenance? | [
"",
"java",
"jsp",
""
] |
Let's say we have a method signature like
```
public static function explodeDn($dn, array &$keys = null, array &$vals = null,
$caseFold = self::ATTR_CASEFOLD_NONE)
```
we can easily call the method by omitting all parameters after `$dn`:
```
$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com'... | It's because you can't have a reference to null.
You can have a reference to a variable that contains null - that is exactly what the default value does. Or you can pass in null as a literal value - but since you want an out parameter this is not possible here. | While you must create a dummy variable for by-ref arguments if you want to pass NULL explicitly, you don't have to create that variable on a separate line. You can use an assignment expression like $dummy=NULL directly as a function argument:
```
function foo (&$ref = NULL) {
if (is_null($ref)) $ref="bar";
ec... | PHP by-reference parameters and default null | [
"",
"php",
"null",
"pass-by-reference",
""
] |
Is there a preference or behavior difference between using:
```
if(obj.getClass().isArray()) {}
```
and
```
if(obj instanceof Object[]) {}
```
? | In most cases, you should use the `instanceof` operator to test whether an object is an array.
Generally, you test an object's type before downcasting to a particular type which is known at compile time. For example, perhaps you wrote some code that can work with a `Integer[]` or an `int[]`. You'd want to guard your c... | In the latter case, if obj is null you won't get a NullPointerException but a false. | Java array reflection: isArray vs. instanceof | [
"",
"java",
"arrays",
"reflection",
""
] |
Is it possible to `typedef` long types that use templates? For example:
```
template <typename myfloat_t>
class LongClassName
{
// ...
};
template <typename myfloat_t>
typedef std::vector< boost::shared_ptr< LongClassName<myfloat_t> > > LongCollection;
LongCollection<float> m_foo;
```
This doesn't work, but is ... | No, that isn't possible currently. It will be made possible in C++0X AFAIK.
The best I can think of is
```
template<typename T> struct LongCollection {
typedef std::vector< boost::shared_ptr< LongClassName<T> > > type;
};
LongCollection<float>::type m_foo;
``` | If you don't want to go the macro way you have to make individual typedefs for each type:
```
typedef std::vector< boost::shared_ptr< LongClassName<float> > > FloatCollection;
typedef std::vector< boost::shared_ptr< LongClassName<double> > > DoubleCollection;
``` | typedefs for templated classes? | [
"",
"c++",
"templates",
"typedef",
""
] |
Looking up LINQ and Or in google is proving somewhat difficult so here I am.
I want to so the following:
```
(from creditCard in AvailableCreditCards
where creditCard.BillToName.ToLowerInvariant().Contains(txtFilter.Text.ToLowerInvariant())
**or creditCard.CardNumber.().Contains(txtFilter.Text)**
orderby creditCard.... | C# keywords supporting LINQ are still C#. Consider `where` as a conditional like `if`; you perform logical operations in the same way. In this case, a logical-OR, you use `||`
```
(from creditCard in AvailableCreditCards
where creditCard.BillToName.ToLowerInvariant().Contains(
txtFilter.Text.ToLowerInva... | You can use the .Where() function to accomplish this.
```
var cards = AvailableCreditCards.Where(card=> card.CardNumber.Contains(txtFilter.Text) || card.BillToName.ToLowerInvariant().Contains(txtFilter.Text.ToLowerInvariant());
``` | Can I perform an "or" operation in LINQ to objects? | [
"",
"c#",
"linq",
""
] |
I want to pass an int list (List) as a declarative property to a web user control like this:
```
<UC:MyControl runat="server" ModuleIds="1,2,3" />
```
I created a TypeConverter to do this:
```
public class IntListConverter : System.ComponentModel.TypeConverter
{
public override bool CanConvertFrom(
Sy... | After hooking a debugger into Cassini, I see that the null ref is actually coming from System.Web.Compilation.CodeDomUtility.GenerateExpressionForValue, which is basically trying to get an expression for the int[] array you pass into the List constructor. Since there's no type descriptor for the int[] array, it fails (... | I solved something simular by creating 2 properties:
```
public List<int> ModuleIDs { get .... set ... }
public string ModuleIDstring { get ... set ... }
```
The ModuleIDstring converts its value set to a list and sets the ModuleIDs property.
This will also make the ModuleIDs usable from a PropertyGrid etc.
Ok, not... | Passing int list as a parameter to a web user control | [
"",
"c#",
"asp.net",
"typeconverter",
""
] |
I am trying to use `ResourceBundle#getStringArray` to retrieve a `String[]` from a properties file. The description of this method in the documentation reads:
> Gets a string array for the given key from this resource bundle or one of its parents.
However, I have attempted to store the values in the properties file a... | A `Properties` object can hold **`Object`s**, not just `String`s. That tends to be forgotten because they're overwhelmingly used to load .properties files, and so often will only contain `String`s. [The documentation](https://web.archive.org/web/20081217073139/http://java.sun.com/j2se/1.4.2/docs/api/java/util/ResourceB... | You can use [Commons Configuration](http://commons.apache.org/proper/commons-configuration/userguide/howto_properties.html), which has methods `getList` and `getStringArray` that allow you to retrieve a list of comma separated strings. | How do I specify values in a properties file so they can be retrieved using ResourceBundle#getStringArray? | [
"",
"java",
"resourcebundle",
""
] |
What is the state generating Excel documents from a PHP application on a Linux server?
I am interesting in creating Office 97 (xls) Excel files. My limited research on the subject has turned up this [Pear package](http://pear.php.net/package/Spreadsheet_Excel_Writer). It appears to be in beta status since 2006.
Can y... | There is something much better than the PEAR package out there!
[PHPExcel](http://phpexcel.codeplex.com/) | I've used the PEAR package with lots of success, but there are some limitations when implementing complex formulas. It has something to do with the way excel stores the formula, along with the last calculated result. Sometimes even though the formula is correct, when first opening the sheet the cells show as empty. Onc... | Can I reliably create Excel documents from a PHP application on a Linux server? | [
"",
"php",
"linux",
"export-to-excel",
""
] |
> **Possible Duplicate:**
> [When will C++0x be finished?](https://stackoverflow.com/questions/5436139/when-will-c0x-be-finished)
What are the latest news about C++0X? (or should I say C++1X) Any release date decided yet? | ## UPDATE : years later...
The last Draft have been officially finalized few weeks ago, in Mars 2011 and will be officially out around July 2011. The name of the new standard would be C++2011 : <http://herbsutter.com/2011/03/25/we-have-fdis-trip-report-march-2011-c-standards-meeting/>
Microsoft C++ compiler (VC10) pr... | It's unlikely that this committee draft will become the FCD. I would say there will be at least 2 more meetings of the standard committee before it goes to FCD.
I think there is something like a 1 year lag between the FCD and the actual standard, so it could be 2011 (or even later!!!) | C++0X when? | [
"",
"c++",
"c++11",
""
] |
I have code similar to the following in many places:
```
var dbParams = db.ReadParams(memberID, product, GetSubscriptionFields());
Debug.Assert(dbParams.Count == 4);
_memberCode = dbParams[0];
_password = dbParams[1];
_userName = dbParams[2];
_reasonCode = dbParams[3];
```
ReadParams() returns an array of strings, t... | Why not use constants instead?
Then in your code you could have
```
dbParams[MEMBER_CODE]
dbParams[PASSWORD]
dbParams[USERNAME]
dbParams[REASON_CODE]
```
which meets your goal of meaningful names without changing the way the method works. | You are writing code in a highly object oriented language, so why don't you use objects?
```
Member m = db.ReadParams(memberID, product, GetSubscriptionFields());
```
and in your code you use
```
m.memberCode
m.password
m.username
m.reasonCode
```
Of course you don't have to make the values publicly accessible, you... | Variable number of results from a function | [
"",
"c#",
""
] |
I'm trying to figure out a way to add a self-update feature to a Java/Swing application I'm working on.
Basically I've got a bunch of jar files with extra functionality to be re-deployed to the installed users when they change. Nothing complicated, just check if a new version has been released, download them over HTTP... | I did the exact same thing. But that was long back so there are probably better tools today.
What I found out I needed was a loader. The loader main program did not have the app jars in classpath. It first downloaded an update if required and then created a custom classloader with the app jars in class path and invoke... | Updates, plugins, separation of concern etc. are exactly what [OSGi](http://www.osgi.org) is about - you might want to take a look at this. It won't come free (read: with a steep initial learning curve, especially when you are currently using classloading tricks) at least there are good open source implementations (fel... | What's the best way to add a self-update feature to a Java Swing application? | [
"",
"java",
"swing",
""
] |
In AJAX applications that need to poll the server in regular intervals (like a chat applications), what is the recommended minimum time between two calls, so that the update is done as quickly as possible? What times are considered as hogs for the server and the client? | It depends on the application, but for chat you probably want to poll pretty often - 1 to 4 seconds I'd say. What you can do is dynamically change the polling interval to decrease your server load - if nobody has said anything for a minute, increase to 10 seconds... after 5 minutes increase to 30 seconds - that kind of... | We have a different solution for AJAX polling in our chat:
The request is sent to the server and polls for the data on the *server side* in cycle with very short delay intervals (like 0.5 sec). Ones data is get, the request returns. Then next request is sent immediately to the server. All requests' timeout is set to s... | Minimum time between subsequent AJAX calls | [
"",
"javascript",
"html",
"ajax",
""
] |
How do I get a function's name as a string?
```
def foo():
pass
>>> name_of(foo)
"foo"
``` | ```
my_function.__name__
```
Using `__name__` is the preferred method as it applies uniformly. Unlike `func_name`, it works on built-in functions as well:
```
>>> import time
>>> time.time.func_name
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'builtin_function_or_method' object h... | To get the current function's or method's name from inside it, consider:
```
import inspect
this_function_name = inspect.currentframe().f_code.co_name
```
`sys._getframe` also works instead of `inspect.currentframe` although the latter avoids accessing a private function.
To get the calling function's name instead,... | How to get a function name as a string? | [
"",
"python",
"string",
"function",
""
] |
An easy jQuery question.
I have several identical forms ( except their name ) on one page with a few hidden inputs in each. I want to refer to them by using the form name and then the input name. ( the input names are not unique in my page )
So for instance:
```
var xAmt = $('#xForm'+num).('#xAmt');
```
I really wa... | ```
function queryX( args ) {
var queryString = [ "XID=", args.XID, "&xNumber=", args.xNumber, "&xAmt=", args.xAmt ].join("");
$.ajax({
url: "X.asp",
cache: false,
type: "POST",
data: queryString,
success : function( data ) {
return data;
}
});
}... | The flexible way to do it has already been answered here, but you can also just make it work with your current code. (Forgive me if this was too basic for what you're looking for.)
Drill down from the unique form name by using the CSS descendant selector (a space):
```
var xAmt = $('#xForm'+num+ ' #xAmt').val();
```
... | How to reference an input within a form in jQuery | [
"",
"javascript",
"jquery",
"ajax",
""
] |
There is a console Java application which is supposed to run until it is stopped by `Ctrl`+`C` or closing the console window. How that application can be programmed to execute a clean up code before exit? | You could use a [Shutdown Hook](http://www.onjava.com/pub/a/onjava/2003/03/26/shutdownhook.html).
Basically you need to create a Thread which will perform your shutdown actions, and then [add it as a shutdown hook](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)). For exa... | A Shutdown hook is the way to go, but be aware that there is no guarantee that the code is actually executed. JVM crashes, power failures, or a simple "kill -9" on your JVM can prevent the code from cleaning up. Therefore you must ensure that your program stays in a consistent state even if it has been aborted abruptly... | Get notification on a Java process termination | [
"",
"java",
""
] |
My servlet application includes a number of library .jars, some of which contain embedded log4j.xml or log4j.properties files. I'd like to ensure that log4j finds my log4j.xml first! I've tried searching for some specification of the priorities of the various classpath elements in a servlet (e.g. does WEB-INF/classes a... | As far as I understand the resource selection from the classpath is non-deterministic (from the point of view of the app developer). Even if the same file is loaded consistently the behaviour could change:
1. When you upgrade the version of your current container.
2. If you switch containers.
The simplest solution wil... | # Tomcat 8.5
Ditto Tomcat 8.0.
See documentation: [Class Loader HOW-TO](https://tomcat.apache.org/tomcat-8.5-doc/class-loader-howto.html).
# Tomcat 8.0
The answer is simple, taken from the Tomcat documentation page, [Class Loader HOW-TO](https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html). In particul... | Controlling the classpath in a servlet | [
"",
"java",
"tomcat",
"servlets",
"classpath",
""
] |
What is the best way to use ListView and a set of GroupBoxes as an Options window?
For example, Listview will have items such as General, Sounds, Shortcuts and there will be three groupboxes defining those same things.
What would be the best programmatical way to navigate through them everytime an item in the listvie... | I don't know if there's a better way, but in the past that what you described is the general approach I have taken. | I may have misunderestimated your question, but perhaps a TreeView would be more appropriate for your problem? This would allow you to have top-level category nodes (like General, Sounds etc.) and then lists of items under each node. | What is the best way to use ListView and GroupBoxes as an "options" window? | [
"",
"c#",
"user-interface",
""
] |
I've seen (and used) on various projects this layout, with a group of fields followed by a group of properties:
```
private int MyIntField;
private string MyStringField;
public int MyInt {
get { return MyIntField; }
set { MyIntField = value; }
}
public string MyString {
get { return MyStringField; }... | I think it is whatever the team feels comfortable with. Settle on a standard for the project/company/language and stick to it. I prefer the private variables all together, the methods/interfaces together, the private members....I think you get the point. | I group them at the top of the class.
In fact the only thing that is over my private attribute is all constant of the class. | Do you group private fields or put them with their property? | [
"",
"c#",
"layout",
"coding-style",
""
] |
Is it possible to search every field of every table for a particular value in Oracle?
There are hundreds of tables with thousands of rows in some tables so I know this could take a very long time to query. But the only thing I know is that a value for the field I would like to query against is `1/22/2008P09RR8`.
<
I'... | Quote:
> I've tried using this statement below
> to find an appropriate column based on
> what I think it should be named but it
> returned no results.\*
>
> ```
> SELECT * from dba_objects WHERE
> object_name like '%DTN%'
> ```
A column isn't an object. If you mean that you expect the column name to be like '%DTN%',... | I did some modification to the above code to make it work faster if you are searching in only one owner.
You just have to change the 3 variables v\_owner, v\_data\_type and v\_search\_string to fit what you are searching for.
```
SET SERVEROUTPUT ON SIZE 100000
DECLARE
match_count INTEGER;
-- Type the owner of the ... | Search All Fields In All Tables For A Specific Value (Oracle) | [
"",
"sql",
"oracle",
"search",
"plsql",
"database-table",
""
] |
I have a directory of bitmaps that are all of the same dimension. I would like to convert these bitmaps into a video file. I don't care if the video file (codec) is wmv or avi. My only requirement is that I specify the frame rate. This does not need to be cross platform, Windows (Vista and XP) only. I have read a few t... | At the risk of being voted down, I'll offer a possible alternative option-- a buffered Bitmap animation.
```
double framesPerSecond;
Bitmap[] imagesToDisplay; // add the desired bitmaps to this array
Timer playbackTimer;
int currentImageIndex;
PictureBox displayArea;
(...)
currentImageIndex = 0;
playbackTimer.I... | You can use [Splicer](http://www.codeplex.com/splicer) to do this.
Please see example 3 at <http://www.codeplex.com/splicer/Wiki/View.aspx?title=News%20Feeds&referringTitle=Home>
Edit:
```
using (ITimeline timeline = new DefaultTimeline(25))
{
IGroup group = timeline.AddVideoGroup(32, 160, 100);
ITrack vide... | How can I create a video from a directory of images in C#? | [
"",
"c#",
"directshow",
"media",
"multimedia",
"wmv",
""
] |
I realise this is not the ideal place to ask about this in terms of searchability, but I've got a page whose JavaScript code throws "Stack overflow in line 0" errors when I look at it in Internet Explorer.
The problem is quite clearly not in line 0, but somewhere in the list of stuff that I'm writing to the document. ... | You can turn *off* the `"Disable Script Debugging"` option inside of Internet Explorer and start debugging with `Visual Studio` if you happen to have that around.
I've found that it is one of few ways to diagnose some of those `IE` specific issues. | I ran into this problem recently and wrote up a post about the particular case in our code that was causing this problem.
<http://cappuccino.org/discuss/2010/03/01/internet-explorer-global-variables-and-stack-overflows/>
The quick summary is: recursion that passes through the host global object is limited to a stack ... | "Stack overflow in line 0" on Internet Explorer | [
"",
"javascript",
"internet-explorer",
"error-handling",
""
] |
Can every possible value of a `float` variable can be represented exactly in a `double` variable?
In other words, for all possible values `X` will the following be successful:
```
float f1 = X;
double d = f1;
float f2 = (float)d;
if(f1 == f2)
System.out.println("Success!");
else
System.out.println("Failure!");
`... | Yes.
Proof by enumeration of all possible cases:
```
public class TestDoubleFloat {
public static void main(String[] args) {
for (long i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i++) {
float f1 = Float.intBitsToFloat((int) i);
double d = (double) f1;
float f2 = (fl... | In theory, there is not such a value, so "yes", every float should be representable as a double.. Converting from a float to a double should involve just tacking four bytes of 00 on the end -- they are stored using the same format, just with different sized fields. | Can every float be expressed exactly as a double? | [
"",
"java",
"floating-point",
""
] |
Is there a way to dynamically invoke a method in the same class for PHP? I don't have the syntax right, but I'm looking to do something similar to this:
```
$this->{$methodName}($arg1, $arg2, $arg3);
``` | There is more than one way to do that:
```
$this->{$methodName}($arg1, $arg2, $arg3);
$this->$methodName($arg1, $arg2, $arg3);
call_user_func_array(array($this, $methodName), array($arg1, $arg2, $arg3));
```
You may even use the reflection api <http://php.net/manual/en/class.reflection.php> | You can use the Overloading in PHP:
[Overloading](http://php.net/manual/en/language.oop5.overloading.php)
```
class Test {
private $name;
public function __call($name, $arguments) {
echo 'Method Name:' . $name . ' Arguments:' . implode(',', $arguments);
//do a get
if (preg_match('/^ge... | Dynamic class method invocation in PHP | [
"",
"php",
""
] |
One of our customers wants to be able to enter a date with only 2 digits for the year component. The date will be in the past, so we want it to work for the previous century if the 2 digit year is after the current year, but work for the current century if the 2 digit year is equal to or less than the current year.
as... | Groovy script (easy enough to throw into java) demonstrating the point @bobince made about SimpleDateFormat.
```
import java.text.SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat('MM/dd/yy')
SimpleDateFormat fmt = new SimpleDateFormat('yyyy-MM-dd')
Calendar cal = Calendar.getInstance()
cal.add(Calendar.Y... | SimpleDateFormat already does two-digit year parsing for you, using the two-letter ‘yy’ format. (It'll still allow four digits, obviously.)
By default it uses now-80→now+20, so it's not exactly the same rule you propose, but it's reasonable and standardised (in the Java world at least), and can be overridden using set... | What is the best way to parse a date in MM/DD/YY format and adjust it to the current / previous century? | [
"",
"java",
"date",
"date-format",
""
] |
I'm trying to read a single XML document from stream at a time using dom4j, process it, then proceed to the next document on the stream. Unfortunately, dom4j's SAXReader (using JAXP under the covers) keeps reading and chokes on the following document element.
Is there a way to get the SAXReader to stop reading the str... | I was able to get this to work with some gymnastics using some internal JAXP classes:
* Create a custom scanner, a subclass of XMLNSDocumentScannerImpl
+ Create a custom driver, an implementation of XMLNSDocumentScannerImpl.Driver, inside the custom scanner that returns END\_DOCUMENT when it sees an declaration or a... | Most likely, you don't want to have more than one document in the same stream at the same time. I don't think that the SAXReader is smart enough to stop when it gets to the end of the first document. Why is it necessary to have multiple documents in the same stream like this? | Reading a single XML document from a stream using dom4j | [
"",
"java",
"xml",
"stream",
"sax",
"dom4j",
""
] |
I have a project with a number of different classes querying and modifying data in a common set of tables. I've set up a .dbml file which provides us with a DataContext class. My question is whether a single instance of the DataContext should be used by all objects, or whether multiple instances are safe to use. I'm al... | Rick Strahl has a nice article about your options: <http://www.west-wind.com/weblog/posts/246222.aspx>.
See also: [LINQ to SQL - where does your DataContext live?](https://stackoverflow.com/questions/196253/linq-to-sql-where-does-your-datacontext-live).
You may want a slightly different strategy for each type of depl... | I use an new instance of DataContext for every transaction.
Reusing old instances can be troublesome, and will bloat the content of the DataContext, since any item that has been loaded at some time, will have to be tracked - your app will get slower and slower, bloating up memory.
If you need an item longer than for ... | Multiple/single instance of Linq to SQL DataContext | [
"",
"c#",
"linq-to-sql",
""
] |
Is there anyway to decompile java webstart application? | Start the application, then fetch the JAR(s) from the webstart cache. Proceed to decompile like with any other Java application. | Yes, there is. A Java Webstart application is just one form of deployment. The result is a bunch of jars copied to the users home directory. And these can of course be decompiled for example with [jad](http://www.kpdus.com/jad.html). | java webstart decompiler | [
"",
"java",
"decompiling",
""
] |
```
function main()
{
Hello();
}
function Hello()
{
// How do you find out the caller function is 'main'?
}
```
Is there a way to find out the call stack? | **Note that this solution is deprecated and should no longer be used according to MDN documentation**
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller>
---
```
function Hello()
{
alert("caller is " + Hello.caller);
}
```
Note that this feature is **non-standard**... | ## StackTrace
You can find the entire stack trace using browser specific code. The good thing is [someone already made it](http://eriwen.com/javascript/stacktrace-update/); here is the [project code on GitHub](http://github.com/eriwen/javascript-stacktrace).
But not all the news is good:
1. It is really slow to get ... | How do you find out the caller function in JavaScript? | [
"",
"javascript",
"callstack",
""
] |
If I have a property that I want to let inheritors write to, but keep readonly externally, what is the preferred way to implement this? I usually go with something like this:
```
private object m_myProp;
public object MyProp
{
get { return m_myProp; }
}
protected void SetMyProp(object value)
{
m_myProp = value... | ```
private object m_myProp;
public object MyProp
{
get { return m_myProp; }
protected set { m_myProp = value; }
}
```
Or in C# 3.0
```
public object MyProp {get; protected set;}
``` | This is definitely the way to go.
```
public object MyProp {get; protected set;}
```
If you're on an older version of C# then this is the way to go.
```
private object _myProp;
public object MyProp
{
get { return _myProp; }
protected set { _myProp = value; }
}
``` | What is the best way to implement a property that is readonly to the public, but writable to inheritors? | [
"",
"c#",
".net",
"properties",
"readonly",
""
] |
I always hear that programmers try to pick the right tool for the job. I've never programmed in Java, so I was wondering What are its benefits? Why is it so popular? What should I use it for?
I just program recreationally. Is there anything about it that makes it particularly fun?? | I think after 12 years or so, the "write once, run anywhere" mantra is *almost* true. Writing Java code pretty much isolates you from the platform dependent aspects of the systems on which you deploy it. | * Portability
* Incredible breadth of libraries
* Bottom-up security
* Performance
* Robustness | What are the benefits of Java? | [
"",
"java",
""
] |
I've often used pointers to const objects, like so...
```
const int *p;
```
That simply means that you can't change the integer that `p` is pointing at through `p`. But I've also seen reference to const pointers, declared like this...
```
int* const p;
```
As I understand it, that means that the pointer variable *i... | When you're designing C programs for embedded systems, or special purpose programs that need to refer to the same memory (multi-processor applications sharing memory) then you need constant pointers.
For instance, I have a [32 bit MIPs processor](http://flickr.com/photos/adavis/2945502665/) that has a [little LCD](htt... | It allows you to protect the pointer from being changed. This means you can protect assumptions you make based on the pointer never changing or from unintentional modification, for example:
```
int* const p = &i;
...
p++; /* Compiler error, oops you meant */
(*p)++; /* Increment the number */
``` | What use are const pointers (as opposed to pointers to const objects)? | [
"",
"c++",
"c",
"constants",
""
] |
Basically I am inserting an image using the listviews inserting event, trying to resize an image from the fileupload control, and then save it in a SQL database using LINQ.
I found some code to create a new bitmap of the content in the fileupload control, but this was to store it in a file on the server, from [this so... | You should be able to change this block to
```
System.IO.MemoryStream stream = new System.IO.MemoryStream();
newBMP.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
PHJProjectPhoto myPhoto =
new PHJProjectPhoto
{
ProjectPhoto = stream.ToArray(), // ... | If you've got a `MemoryStream` already, just call [`MemoryStream.ToArray`](http://msdn.microsoft.com/en-us/library/system.io.memorystream.toarray.aspx) to get the data out. | How do I convert a Bitmap to byte[]? | [
"",
"c#",
"linq",
"asp.net-3.5",
"byte",
"image-uploading",
""
] |
We all know that you can overload a function according to the parameters:
```
int mul(int i, int j) { return i*j; }
std::string mul(char c, int n) { return std::string(n, c); }
```
Can you overload a function according to the return value? Define a function that returns different things according to how the return va... | ```
class mul
{
public:
mul(int p1, int p2)
{
param1 = p1;
param2 = p2;
}
operator int ()
{
return param1 * param2;
}
operator std::string ()
{
return std::string(param2, param1 + '0');
}
private:
int param1;
int param2;
};
```
Not that I wo... | You have to tell the compiler which version to use. In C++, you can do it three ways.
## Explicitly differentiate the calls by typing
You somewhat cheated because you sent an integer to a function waiting for a char, and wrongly sent the number six when the char value of '6' is not 6 but 54 (in ASCII):
```
std::stri... | Overload a C++ function according to the return value | [
"",
"c++",
"function",
"puzzle",
"overloading",
""
] |
whats the best way to export a Datagrid to excel? I have no experience whatsoever in exporting datagrid to excel, so i want to know how you guys export datagrid to excel.
i read that there are a lot of ways, but i am thinking to just make a simple export excel to datagrid function.i am using asp.net C#
cheers.. | The simplest way is to simply write either csv, or html (in particular, a `<table><tr><td>...</td></tr>...</table>`) to the output, and simply pretend that it is in excel format via the content-type header. Excel will happily load either; csv is simpler...
Here's a similar example (it actually takes an IEnumerable, bu... | You can do it in this way:
```
private void ExportButton_Click(object sender, System.EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWr... | export Datagrid to excel asp | [
"",
"c#",
"asp.net",
"datagrid",
"export-to-excel",
""
] |
Currently, I'm using:
```
DataTable dt = CreateDataTableInSomeWay();
List<DataRow> list = new List<DataRow>();
foreach (DataRow dr in dt.Rows)
{
list.Add(dr);
}
```
Is there a better/magic way? | If you're using .NET 3.5, you can use [`DataTableExtensions.AsEnumerable`](http://msdn.microsoft.com/en-us/library/system.data.datatableextensions.asenumerable.aspx) (an extension method) and then if you really need a `List<DataRow>` instead of just `IEnumerable<DataRow>` you can call [`Enumerable.ToList`](http://msdn.... | ```
List<Employee> emp = new List<Employee>();
//Maintaining DataTable on ViewState
//For Demo only
DataTable dt = ViewState["CurrentEmp"] as DataTable;
//read data from DataTable
//using lamdaexpression
emp = (from DataRow row in dt.Rows
select new Employee
{
_FirstName = row["FirstName"].ToString(... | How do you convert a DataTable into a generic list? | [
"",
"c#",
"generics",
"datatable",
""
] |
How can I restart(recycle) IIS Application Pool from C# (.net 2)?
Appreciate if you post sample code? | If you're on **IIS7** then this will do it if it is stopped. I assume you can adjust for restarting without having to be shown.
```
// Gets the application pool collection from the server.
[ModuleServiceMethod(PassThrough = true)]
public ArrayList GetApplicationPoolCollection()
{
// Use an ArrayList to transfer ob... | Here we go:
```
HttpRuntime.UnloadAppDomain();
``` | Restarting (Recycling) an Application Pool | [
"",
"c#",
".net",
"asp.net-mvc",
"iis",
"application-pool",
""
] |
Why was C# designed this way?
As I understand it, an interface only describes behaviour, and serves the purpose of describing a contractual obligation for classes implementing the interface that certain behaviour is implemented.
If classes wish to implement that behavour in a shared method, why shouldn't they?
Here ... | Assuming you are asking why you can't do this:
```
public interface IFoo {
void Bar();
}
public class Foo: IFoo {
public static void Bar() {}
}
```
This doesn't make sense to me, semantically. Methods specified on an interface should be there to specify the contract for interacting with an object. Static met... | My (simplified) technical reason is that static methods are not in the [vtable](http://en.wikipedia.org/wiki/Virtual_table), and the call site is chosen at compile time. It's the same reason you can't have override or virtual static members. For more details, you'd need a CS grad or compiler wonk - of which I'm neither... | Why Doesn't C# Allow Static Methods to Implement an Interface? | [
"",
"c#",
"oop",
"language-features",
""
] |
Consider that I have a transaction:
```
BEGIN TRANSACTION
DECLARE MONEY @amount
SELECT Amount AS @amount
FROM Deposits
WHERE UserId = 123
UPDATE Deposits
SET Amount = @amount + 100.0
WHERE UserId = 123
COMMIT
```
And it gets executed on 2 threads, in the order:
1. thread 1 - select
2. thread 2 - select
3. th... | Nice well stated scenario. I decided to test it.
Here's my setup script:
```
CREATE TABLE Deposits(Amount Money, UserID int)
INSERT INTO Deposits (Amount, UserID)
SELECT 0.0, 123
--Reset
UPDATE Deposits
SET Amount = 0.00
WHERE UserID = 123
```
Here's my test script.
```
SET TRANSACTION ISOLATION LEVEL Serializable
... | Others already addressed the issue of using REPEATABLE READ.
So I'll chime in with a different piece of advice...
Why use two statements and not just one statement like the following?
```
UPDATE Deposits
SET Amount = Amount + 100.0
WHERE UserId = 123
```
Also, your real transactions are going off of something more ... | How does SQL Server locking work in this scenario? | [
"",
"sql",
"sql-server",
"locking",
""
] |
I have read the answers for [What's the best way to check if a file exists in C? (cross platform)](https://stackoverflow.com/questions/230062/whats-the-best-way-to-check-if-a-file-exists-in-c-cross-platform), but I'm wondering if there is a better way to do this using standard c++ libs? Preferably without trying to ope... | Use [boost::filesystem](http://www.boost.org/doc/libs/1_37_0/libs/filesystem/doc/index.htm):
```
#include <boost/filesystem.hpp>
if ( !boost::filesystem::exists( "myfile.txt" ) )
{
std::cout << "Can't find my file!" << std::endl;
}
``` | Be careful of race conditions: if the file disappears between the "exists" check and the time you open it, your program will fail unexpectedly.
It's better to go and open the file, check for failure and if all is good then do something with the file. It's even more important with security-critical code.
Details about... | What’s the best way to check if a file exists in C++? (cross platform) | [
"",
"c++",
"file",
"file-io",
""
] |
The install instructions are:
```
$ python setup.py build
$ sudo python setup.py install # or su first
```
This gives me an .egg file. How do I tell the install to dump the files as a normal, uncompressed library?
Thanks! | OK, I hate to answer my own question, but:
find your python site-packages (mine is /usr/local/lib/python2.5/site-packages )
then:
```
$ unzip MySQL_python-1.2.2-py2.5-linux-i686.egg
```
This worked fine for me | I'm a little late to this party, but here's a way to do it that seems to work great:
```
sudo python setup.py install --single-version-externally-managed --root=/
```
And then you don't use a .python-egg, any \*.pth files etc. | Install MySQLdb (for python) as non-compressed egg | [
"",
"python",
"installation",
"mysql",
"egg",
""
] |
I am implementing a BFS, and what it is going to do is go through an ordered tree to find the shortest solution to a puzzle.
What i will be doing is creating a Snapshot object that holds the current position of each piece in a puzzle. I will add this Snapshot object into the queue and check if it is the solution. Howe... | There is a way - you use the [Preprocessor's Token-Pasting Operator](http://msdn.microsoft.com/en-us/library/09dwwt6y(VS.80).aspx). This allows you to create a name based on a variable, so you'd specify:
```
#define S(variable) snapshot#variable
```
and you'd be able to create variables named snapshot1, snapshot2 etc... | I think you're asking how do you create and keep lots of objects when you don't know how many there will be.
You need to create an array of the objects. Then you can access them as snapshot[1], snapshot[2]... snapshot[i]. | Variable naming schemes for objects in C++? | [
"",
"c++",
"oop",
"search",
"breadth-first-search",
""
] |
I have a NotifyIcon control that appears in the system tray. How can I find the location (x, y) of the icon on the screen?
Thanks | You can't. It isn't hard to get the window handle for the system tray, GetClassName() returns "ToolbarWindow32", the class name of the standard TOOLBAR common control. Beware that a 64-bit OS has two of them. Then you can send messages to it like TB\_GETBUTTONINFO. Chief hang-ups are that you won't know what button ID ... | Actually you can do this, here is code that shows you how and much more.
In any Mouse Event from NotifyIcon, simply look at Control.MousePosition, this contains the (x,y) of the mouse. The same can be done to position a ContextMenu on a form/control exactly where the form/control was clicked using these (x,y) values.
... | How to find the location of the icon in the system tray | [
"",
"c#",
"winforms",
"visual-studio-2008",
"notifyicon",
""
] |
e.g,
```
foo1
foo2
foo10
foo100
```
rather than
```
foo1
foo10
foo100
foo2
```
Update: not interested in coding the sort myself (although that's interesting in its own right), but having the database to do the sort for me. | You can use functions in your order-by clause. In this case,
you can split the non-numeric and numeric portions of the
field and use them as two of the ordering criteria.
```
select * from t
order by to_number(regexp_substr(a,'^[0-9]+')),
to_number(regexp_substr(a,'[0-9]+$')),
a;
```
You can also... | # For short strings, small number of numerics
If number of "numerics" and the maximum length are limited, there is a regexp-based solution.
The idea is:
* Pad all numerics with 20 zeroes
* Remove excessive zeroes using another regexp. This might be slow due to [regexp backtracking](http://www.regular-expressions.inf... | Oracle: How can I implement a "natural" order-by in a SQL query? | [
"",
"sql",
"oracle",
""
] |
Take the following function:
```
DataTable go() {
return someTableAdapter.getSomeData();
}
```
When I set a breakpoint in this function, is there a possibility to inspect the returned value? `go()` is directly coupled to a datagrid in an `.aspx` page.
The only way to inspect the returned datatable is to use a te... | Not that I know of. Note that if you *do* add a variable, it will get removed by the compiler in release builds anyway...
**Update:**
[This functionality has been added to VS2013](https://devblogs.microsoft.com/devops/seeing-function-return-values-in-the-visual-studio-2013-debugger/).
You can see the return values in ... | This can be done in Visual Studio 2013 with CLR 4.5.1 [according to the customer feedback site](http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2206747-function-return-value-in-debugger). It was not available in previous versions for C#.
(Visual Studio 2008 and earlier supported it for VB.NET... | Can I find out the return value before returning while debugging in Visual Studio? | [
"",
"c#",
"visual-studio",
"visual-studio-debugging",
""
] |
Looking at `System.Collections.Generic.Dictionary<TKey, TValue>`, it clearly implements `ICollection<KeyValuePair<TKey, TValue>>`, but doesn't have the required "`void Add(KeyValuePair<TKey, TValue> item)`" function.
This can also be seen when trying to initialize a `Dictionary` like this:
```
private const Dictionar... | The expected API is to add via the two argument `Add(key,value)` method (or the `this[key]` indexer); as such, it uses explicit interface implementation to provide the `Add(KeyValuePair<,>)` method.
If you use the `IDictionary<string, int>` interface instead, you will have access to the missing method (since you can't... | Some interface methods are implemented [explicitly](http://msdn.microsoft.com/en-us/library/aa664591(VS.71).aspx). If you use reflector you can see the explicitly implemented methods, which are:
```
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair);
bool ICollection<KeyValuePair... | C#: How can Dictionary<K,V> implement ICollection<KeyValuePair<K,V>> without having Add(KeyValuePair<K,V>)? | [
"",
"c#",
".net",
"dictionary",
"interface",
""
] |
Is there a built-in way to know if a given session variable is a serialized object? Say I retrieve a value like $\_SESSION['foo'], but I don't know if it was originally a string or if it is a serialized object. Is there some way to check, or once serialized does PHP just see a string as a string as a string? | It's a pretty common misconception that you have to manually serialize objects before putting them in session. That is not the case. You can simply assign an object instance to a slot in `$_SESSION`, and PHP will automagically serialize and unserialize it for you, between requests. | A string is a string is a string. I think the best you'll be able to do is just try to unserialize it, and if it works, it works. If it doesn't, it doesn't.
The only other option would be to use a regex to see if it "looks" like a serialized object. Just running `unserialize()` on it might be easier though. | Checking for Serialized Objects | [
"",
"php",
"serialization",
"session-variables",
""
] |
This is a little confusing to explain, so bear with me here...
I want to set up a system where a user can send templated emails via my website, except it's not actually sent using my server - it instead just opens up their own local mail client with an email ready to go. The application would fill out the body of the ... | The way I'm doing it now is basically like this:
The HTML:
```
<textarea id="myText">
Lorem ipsum...
</textarea>
<button onclick="sendMail(); return false">Send</button>
```
The Javascript:
```
function sendMail() {
var link = "mailto:me@example.com"
+ "?cc=myCCaddress@example.com"
... | Here's the way doing it using jQuery and an "element" to click on :
```
$('#element').click(function(){
$(location).attr('href', 'mailto:?subject='
+ encodeURIComponent("This is my subject")
+ "&body="
+ encodeURIComponent("Thi... | Sending emails with Javascript | [
"",
"javascript",
"email",
"client-side",
""
] |
I'm wondering if there are any simple ways to get a list of all fixed-width (monospaced) fonts installed on a user's system in C#?
I'm using .net 3.5 so have access to the WPF System.Windows.Media namespace and LINQ to get font information, but I'm not sure what I'm looking for.
I want to be able to provide a filtere... | Have a look at:
<http://www.pinvoke.net/default.aspx/Structures/LOGFONT.html>
Use one of the structures in there, then loop over families, instantiating a Font, and getting the LogFont value and checking lfPitchAndFamily.
The following code is written on the fly and untested, but something like the following should ... | Unfortunately **ToLogFont** function does not fill **lfPitchAndFamily** field to correct values. In my case it's always 0.
One approximation to detect which fonts might be fixed is the following
```
foreach ( FontFamily ff in FontFamily.Families ) {
if ( ff.IsStyleAvailable( FontStyle.Regular ) ) {
... | How do I get all installed fixed-width fonts? | [
"",
"c#",
"wpf",
"fonts",
"monospace",
""
] |
How do I check for an open connection in jdbc for oracle database?
Note: `conn.isClosed()` cannot be used for this. | Usually a Connection Pool will also use the Connection.isClosed() method to check if the Connection is still valid. The problem is that not all JDBC drivers will handle this call correctly. So I assume that there are some simple check statements just like RealHowTo said. For Oracle he already mentioned the "SELECT 1 FR... | Something like:
```
Statement stmt = null;
ResultSet rs =null;
try {
stmt = conn.createStatement();
// oracle
rs = stmt.executeQuery("SELECT 1 FROM Dual");
// others
// rs = stmt.executeQuery("SELECT 1");
if (rs.next())
return true; // connection is valid
}
catch (SQLException e) {
// TODO :... | programmatically checking for open connection in JDBC | [
"",
"java",
"oracle",
"jdbc",
""
] |
I was looking for something like Server.MapPath in the ASP.NET realm to convert the output of Assembly.GetExecutingAssembly().CodeBase into a file path with drive letter.
The following code works for the test cases I've tried:
```
private static string ConvertUriToPath(string fileName)
{
fileName = fileName.Repla... | Try looking at the [Uri.LocalPath](http://msdn.microsoft.com/en-us/library/system.uri.localpath.aspx) property.
```
private static string ConvertUriToPath(string fileName)
{
Uri uri = new Uri(fileName);
return uri.LocalPath;
// Some people have indicated that uri.LocalPath doesn't
// always return the co... | I looked for an answer a lot, and the most popular answer is using [Uri.LocalPath](http://msdn.microsoft.com/en-us/library/system.uri.localpath.aspx). But System.Uri fails to give correct LocalPath if the Path contains “#”. Details are [here](https://stackoverflow.com/questions/896572/system-uri-fails-to-give-correct-a... | Is there a .NET Framework method for converting file URIs to paths with drive letters? | [
"",
"c#",
".net",
"winforms",
"uri",
""
] |
I have 3 lists, I will make them simple here.
list of letters
A
B
C
list of numbers
1
2
3
Mixed
A,1
A,2
B,2
B,3
C,1
C,3
I need to know what is missing:
A,3
B,1
C,2
The list of letters has about 85 entries
and the list of numbers has about 500 entries.
The mixed list has about 75,00... | There's no need to create extra tables. The following query would work just as well:
```
SELECT c.chr, n.num
FROM chars c, nums n
WHERE NOT EXISTS (SELECT 1
FROM mix m
WHERE m.chr = c.chr AND m.num = n.num)
``` | A cross join would produce every combination there is, given that you have both of your lists in SQL tables:
```
SELECT
Letter + ',' + Number AS Combination
FROM
NumberList,
LetterList
```
Using the combined result (maybe save it into a temporary table), you can use a NOT EXISTS query to find what is missing:
... | Search multiple list for missing entries | [
"",
"sql",
"delphi",
"comparison",
"list",
""
] |
When I use `DateTime.Now` I get the date and time from the server point of view. Is there any way to get the *client* date and time in ASP.NET? | What I'd do is create a hidden input field and then wire a Javascript routine to the onsubmit event for the form. This routine would populate the hidden field with the time on the client machine.
The hidden field can used with ASP.NET by using the HTML control "HtmlInputHidden" class. You just give you input control a... | I like the idea of either using the browser/system time and time zone or letting them select their time zone. In a past project I used something like this:
```
<script language="javascript">
function checkClientTimeZone()
{
// Set the client time zone
var dt = new Date();
SetCookieCrumb("ClientDateTime", d... | How to get client date and time in ASP.NET? | [
"",
"c#",
".net",
"asp.net",
"datetime",
"client-side",
""
] |
In C# some of default name space such as System.Collections are listed without typing in using blah. In visual basic, they are not imports for you. Is there a way to force vb to auto imports some of default name space or VB work differently than C#? | I think the first item posted by John Rudy is what you're looking for- add them in the project properties.
However, VB.Net does also work differently than C#, in that it means a different thing in VB to import a namespace than it does in C#. When you import a namespace in VB, it also brings child namespaces 'in scope'... | I'm not sure what you're asking. I can see potentially two questions there:
1. Can you change the VB auto-imports?
2. Can you get auto-import behavior in C#?
For #1, yes you can. Assuming Visual Studio 2005 or higher, go into your project properties, and select the References tab. The auto-imports are listed under "I... | Visual basic auto imports namespaces | [
"",
"c#",
"vb.net",
"visual-studio",
""
] |
We've got a fairly complex httphandler for handling images. Basically it streams any part of the image at any size that is requested. Some clients use this handler without any problems. But we've got one location that gives us problems, and now it also gives problems on my development environment.
What happens is that... | A client will limit the number of simultaneous requests it will make to any one server. Furthermore when requesting from a resource that requires session state (the default) other requests for resources requiring session state will block.
When using `HttpWebResponse` you must dispose either that object or the stream r... | First off, there are better ways of dealing with streams that using an array for the entire thing (i.e. `MemoryStream` *might* be unnecessary here).
I would envisage a loop:
```
const int BUFFER_SIZE = 4096; // pick your poison
bute[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while((bytesRead = inStream.Read(bu... | HttpHandler response is never returned | [
"",
"c#",
"asp.net",
"httphandler",
""
] |
I want to use input from a user as a regex pattern for a search over some text. It works, but how I can handle cases where user puts characters that have meaning in regex?
For example, the user wants to search for Word `(s)`: regex engine will take the `(s)` as a group. I want it to treat it like a string `"(s)"` . I ... | Use the `re.escape()` function for this:
[4.2.3 `re` Module Contents](http://docs.python.org/library/re.html#re.escape)
> **escape(string)**
>
> Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
... | You can use [`re.escape()`](http://docs.python.org/library/re.html#re.escape):
> re.escape(string)
> Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
```
>>> import re
>>> re.escape('^a.*$')
'\\... | Escaping regex string | [
"",
"python",
"regex",
""
] |
I have a Perl module that I would like to use from Java. Is there a way to call this code using either ActiveState Perl on Windows or the generic Perl that comes with Linux? I have found references to JPL but it doesn’t appear to be maintained anymore. | [Inline-Java](http://search.cpan.org/~patl/Inline-Java-0.52/Java.pod) is the usual library to call java from Perl, and this [post propose a **org.perl.java**](http://www.piersharding.com/blog/archives/2004/04/calling_perl_fr.html) module which should allow calling Perl from Java, as asked.
However, because of the unpr... | Is this not what Runtime.exec() is for?
```
Runtime.getRuntime().exec("/usr/bin/perl myPerl.pl");
```
Or am I misunderstanding the question? | How can I call Perl from Java? | [
"",
"java",
"perl",
""
] |
I am writing multi-thread socket chat in C++Builder 2009.
It is almost complete in accordance with what I need to do but I have a little problem.
I need to pass the TMemo\* pointer into CreateThread WinAPI function which upcasts it to void\*.
I tryed this way:
```
HANDLE xxx = MemoChat->Handle;
hNetThread = CreateT... | Call:
```
TMemo* MemoChat = // You defined that somewhere I assume
HANDLE hNetThread = CreateThread(NULL, 0, NetThread, MemoChat, 0, &dwNetThreadId);
```
What is happening here is that any pointer you pass as the third parameter is being auto converted into a void pointer (or in WinTerms LPVOID). That's fin... | Please understand that a HANDLE is **not** a pointer, but a concept of the Win32 API. So the first line casts the LPVOID to HANDLE - this is correct, as the parameter of the thread routine really is given as a handle (xxx). However, it then goes on converting the HANDLE to a MyMemo object; this treats the bits in the h... | How can I correctly downcast the pointer from void* to TMemo* in C++Builder2009? | [
"",
"c++",
"c++builder",
"downcast",
"tmemo",
""
] |
I have some elements on a page which are draggable. These same elements have a click event which navigates to another page. I'm trying to determine the best way of preventing the click event from firing if the user is dragging but still allow the click event if not dragging. Anyone have any ideas of the best way to acc... | I solved this by using something like the following:
```
new Draggable('id', {
onStart: function() {
dPhoto = $('id');
Event.stopObserving('id', 'click');
},
onEnd : function() {
setTimeout("Event.observe('id', 'click', function() { location.href = 'url'; });", 500);
},
reve... | ```
var click_func;
function onDragStart(drgObj,mouseEvent){
click_func = mouseEvent.target.onclick;
mouseEvent.target.onclick = function(e){
mouseEvent.target.onclick = click_func;
return false;
}
}
``` | Preventing JavaScript click event with Scriptaculous drag and drop | [
"",
"javascript",
"events",
"event-handling",
"drag-and-drop",
"scriptaculous",
""
] |
I've written a paged search stored procedure using SQL Server 2005. It takes a number of parameters and the search criteria is moderately complex.
Due to the front-end architecture I need to be able to return the number of results that would come back **without** actually returning the results. The front end would the... | I personally go with the two query approach, yes, you have to maintain the search logic in two places, but I've found that the performance optimization benefit, and overall cleanness of the code pays off in the end.
Using a flag passed to a single procedure, is a potential solution, but I just find that very hard to m... | This isn't a normal problem and you usually want the total counts at the same time your getting a page.
That said, use two different procedures. The reason is that you have two very different actions which only resemble each other superficially. | Getting counts for a paged SQL search stored procedure | [
"",
"sql",
"t-sql",
"search",
"stored-procedures",
"paging",
""
] |
If I'm reading a text file in shared access mode and another process truncates it, what is the easiest way to detect that? (I'm excluding the obvious choice of refreshing a FileInfo object periodically to check its size) Is there some convenient way to capture an event? (Filewatcher?) | There is, **It's called [FileSystemWatcher](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx)**.
If you are developing a windows forms application, you can drag-and-drop it from the toolbox.
Here's some usage example:
```
private void myForm_Load(object sender, EventArgs e)
{
var fileWatc... | FSW cannot work reliably, it is asynchronous. Assuming you don't get an exception, StreamReader.ReadLine() will return null when the file got truncated. Then check if the size changed. Beware of the unavoidable race condition, you'll need to verify assumptions about timing. | How to detect a truncated file in C# | [
"",
"c#",
".net",
""
] |
I'm attempting to resize pngs with transparent backgrounds in PHP and the code samples I've found online don't work for me. Here's the code I'm using, advice will be much appreciated!
```
$this->image = imagecreatefrompng($filename);
imagesavealpha($this->image, true);
$newImage = imagecreatetruecolor($width, $height... | From what I can tell, you need to set the blending mode to `false`, and the save alpha channel flag to `true` **before** you do the imagecolorallocatealpha()
```
<?php
/**
* https://stackoverflow.com/a/279310/470749
*
* @param resource $image
* @param int $newWidth
* @param int $newHeight
* @return resource
*/... | Here is a final solution that is working fine for me.
```
function resizePng($im, $dst_width, $dst_height) {
$width = imagesx($im);
$height = imagesy($im);
$newImg = imagecreatetruecolor($dst_width, $dst_height);
imagealphablending($newImg, false);
imagesavealpha($newImg, true);
$transparent ... | How do I resize pngs with transparency in PHP? | [
"",
"php",
"png",
"gd",
"resize",
""
] |
How do I import a Python module given its relative path?
For example, if `dirFoo` contains `Foo.py` and `dirBar`, and `dirBar` contains `Bar.py`, how do I import `Bar.py` into `Foo.py`?
Here's a visual representation:
```
dirFoo\
Foo.py
dirBar\
Bar.py
```
`Foo` wishes to include `Bar`, but restructu... | Assuming that both your directories are real Python packages (do have the `__init__.py` file inside them), here is a safe solution for inclusion of modules relatively to the location of the script.
I assume that you want to do this, because you need to include a set of modules with your script. I use this in productio... | Be sure that dirBar has the `__init__.py` file -- this makes a directory into a Python package. | Import a module from a relative path | [
"",
"python",
"relative-path",
"python-import",
""
] |
Is there a way to create register a handler that will be called exactly at the time when the last reference to a certain object is released?
An example would be an object that is backed by a physical data file and once the object become unreferenced, the file should be closed and than renamed. It would be nice if this... | In short, **no.**
The Java specification explicitly denies you the ability to know when the last reference is released. JVM implementations (and optimizations) depend on this. There is no hook. | I think WeakReference does what you want. A WeakReference gets put into the ReferenceQueue as soon as its weakly reachable (i.e. all strong references are gone).
See this article by [Ethan Nicholas](http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html).
If you are worried about some references ... | How to detect when an object is no longer referenced | [
"",
"java",
"reference",
"weak-references",
""
] |
Is there a way to copy an entire directory to the output directory in a console application in C#.NET?
I know for files you can right click them, properties and mark copy to output directory. But I'm not going to do that for 20.000 files...
Thx, Lieven Cardoen aka Johlero | Are you sure you want all 20000 files in the output?
Besides manual copy-paste operation I see two options: one is you can have a post-build task to copy all the files and another is to have 20000 files zipped, zip file added as a content item to your project with "copy always" set and either console application unzip... | 1. While in development, use application configuration to point to where these files CURRENTLY reside, instead of copying them. (copying that many objects on each build is a nightmare. Even if copying only new/updated files)
2. When preparing a release build, you might want to consider using a build script and MSBuild ... | Copy Directory to Output Directory - Console Application .NET | [
"",
"c#",
"include",
"directory",
"copy",
""
] |
If I have a date, how do I calculate the week number for that date within that year?
For example, in 2008, January 1st to January 6th are in week 1 and January 7th to the 13th are in week 2, so if my date was January 10th 2008, my week number would be 2.
An algorithm would be great to get me started and sample code w... | Pseudocode:
```
int julian = getDayOfYear(myDate) // Jan 1 = 1, Jan 2 = 2, etc...
int dow = getDayOfWeek(myDate) // Sun = 0, Mon = 1, etc...
int dowJan1 = getDayOfWeek("1/1/" + thisYear) // find out first of year's day
// int badWeekNum = (julian / 7) + 1 // Get our week# (wrong! Don't use this)
int weekNum =... | Be aware that while your definition of *nth* week of the year is tenable, it is also not 'the' standard one.
ISO 8601 defines a standard for the representation of dates, times and time zones. It defines weeks that start on a Monday. It also says Week 1 of a year is the one which contains at least 4 days from the given... | How do I calculate the week number given a date? | [
"",
"c++",
"windows",
"algorithm",
"time",
""
] |
PHP (among others) will execute the deepest function first, working its way out. For example,
```
$text = strtoupper(str_replace('_', ' ', file_get_contents('file.txt')));
```
I'm doing something very similar to the above example for a template parser. It looks for the tags
```
{@tag_name}
```
and replaces it with ... | I'm not sure I understand the nesting in your example, as the example doesn't demonstrate a purpose behind nesting. Your example input could very easily be
```
'This is my test {@a} {@b} string.'
```
And using arrays in str\_replace would handle this very simply and quickly.
```
$aVars = array('{@a}' => 'hello', '{@... | This is not a trivial task. You need to parse the string manually and do your own logical substitutions. There's no magic function or functionality that will do this for you.
My own template engine does about that (and more) and only the core (no template macros) weighs in at 600+ LOC | How does PHP do recursive function calls? | [
"",
"php",
"string",
"recursion",
""
] |
Currently i have this method:
```
static boolean checkDecimalPlaces(double d, int decimalPlaces){
if (d==0) return true;
double multiplier = Math.pow(10, decimalPlaces);
double check = d * multiplier;
check = Math.round(check);
check = check/multiplier;
return (d==check);
}
```... | The test fails, because you have reached the accuracy of the binary floating point representation, which is approximately 16 digits with [IEEE754 double precision](http://en.wikipedia.org/wiki/Double_precision). Multiplying by 649632196443.4279 by 10000 will truncate the binary representation, leading to errors when ro... | If your goal is to represent a number with exactly *n* significant figures to the right of the decimal, [BigDecimal](http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html) is the class to use.
> Immutable, arbitrary-precision signed
> decimal numbers. A BigDecimal consists
> of an arbitrary precision integ... | How to check if a double has at most n decimal places? | [
"",
"java",
"floating-point",
"decimal",
""
] |
I'm pivoting data in MS SQL stored procedure. Columns which are pivoted are dynamically created using stored procedure parameter (for exampe: "location1,location2,location3,") so number of columns which will be generated is not known. Output should look like (where locations are taken from stored procedure parameter):
... | Assuming truly dire dynamic need, you could use [DataContext.ExecuteQuery](http://msdn.microsoft.com/en-us/library/bb361109.aspx)
Just whip up a type that will cover the result space (the property names must match the column names in the query):
```
public class DynamicResult
{
public DateTime OrderDate {get;set;}
... | You can create your linq object for access after your returned dataset.
But would that really be of any use. Linq are usefull for typesafe calls and not dynamic results. You would not know what to look for compile time. | Accessing dynamically created stored procedure from LINQ | [
"",
"sql",
"linq",
"stored-procedures",
"pivot",
""
] |
Was wondering if it is recomended to pass a database connection object around(to other modules) or let the method (in the other module) take care of setting it up. I am leaning toward letting the method set it up as to not have to check the state of the connection before using it, and just having the caller pass any ne... | Personally I like to use tightly scoped connections; open them late, use them, and close them (in a "using" block, all within the local method). Connection pooling will deal with re-using the connection in most cases, so there is no real overhead in this approach.
The main advantage in passing connections *used* to be... | Personally, I like storing a stack of my current open connection and transactions on top of the [Thread Local Storage](http://msdn.microsoft.com/en-us/library/system.runtime.remoting.messaging.callcontext_methods.aspx) using SetData and GetData. I define a class that manages my connections to the database and allow it ... | passing DB Connection object to methods | [
"",
"c#",
".net",
"ado.net",
"database-connection",
""
] |
What is the most efficient way to create a **constant** (never changes at runtime) mapping of `string`s to `int`s?
I've tried using a [const Dictionary](https://stackoverflow.com/questions/268064/c-how-can-dictionarykv-implement-icollectionkeyvaluepairkv-without-having-addke), but that didn't work out.
I could implem... | Creating a truly compile-time generated constant dictionary in C# is not really a straightforward task. Actually, none of the answers here really achieve that.
There is one solution though which meets your requirements, although not necessarily a nice one; remember that according to the C# specification, switch-case t... | There are precious few immutable collections in the current framework. I can think of one relatively pain-free option in .NET 3.5:
Use `Enumerable.ToLookup()` - the [`Lookup<,>`](http://msdn.microsoft.com/en-us/library/bb460184.aspx) class is immutable (but multi-valued on the rhs); you can do this from a `Dictionary<... | Creating a constant Dictionary in C# | [
"",
"c#",
".net",
"collections",
"dictionary",
"constants",
""
] |
What is the best compiler to experiment with C++0x features? I have been experimenting with GNU g++ 4.4. | Definitely **GCC Trunk**. **ConceptGCC** misses many features GCC trunk has. It is being merged into GCC currently though. It has all these features, including the new `auto`-typed variables (no new function declaration syntax yet though): <http://gcc.gnu.org/projects/cxx0x.html> .
There is a GCC branch containing par... | **[Comeau](http://www.comeaucomputing.com/tryitout/)** - just for trying it online | What is the best compiler to use when you want to experiment with C++0x features? | [
"",
"c++",
"compiler-construction",
""
] |
I have a type ahead text field, and when the user hits "Enter" I want to make an ajax call and not submit the form at the same time. My html looks like this:
```
<input id="drug_name" class="drugs_field" type="text" size="30" onkeypress="handleKeyPress(event,this.form); return false;" name="drug[name]" autocomplete="o... | You should add an event handler to the form itself which calls a function to decide what to do.
```
<form onsubmit="return someFunction();">
```
And then make sure that your someFunction() returns false on success. If it returns true the form will submit normally (which is what you are trying to prevent!). So you can... | Trap the event and cancel it.
It's something like trap onSubmit(event) and event.ignoreDefault(). The event can tell you that it was triggered by a keystroke, and which. | How can I prevent a webform from submiting on 'Enter' | [
"",
"javascript",
"html",
"ruby-on-rails",
"webforms",
""
] |
*Background*: I am currently using custom controls within my C# project (basic controls just drawing a custom look and feel (using gdi+?)). The majoritiy of these controls have transparent segments for irregular shapes etc.
*Problem*: I am looking to overlay a semi-transparent (irregularly shaped) panel over a group o... | AFAIK you can't really mix GDI+ and OpenGL/DX.
If you're getting slow performance and are **absolutely sure** that it's a bottleneck in GDI+ rather than in your code, than it *could* make sense to ditch GDI+ and replace it with DX/OGL. (You would have to write your own controls, though, which would be a major pain in ... | Look at WPF and Silverlight. you would sleep better at night. | C# Combine GDI+ and OpenGL/DirectX | [
"",
"c#",
"winforms",
"opengl",
"directx",
"gdi+",
""
] |
I know it's simple to implement, but I want to reuse something that already exist.
Problem I want to solve is that I load configuration (from XML so I want to cache them) for different pages, roles, ... so the combination of inputs can grow quite much (but in 99% will not). To handle this 1%, I want to have some max n... | You can use a [LinkedHashMap](http://docs.oracle.com/javase/6/docs/api/index.html?java/util/LinkedHashMap.html) (Java 1.4+) :
```
// Create cache
final int MAX_ENTRIES = 100;
Map cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) {
// This method is called just after a new entry has been added
public boolean... | This is an old question, but for posterity I wanted to list [ConcurrentLinkedHashMap](https://github.com/ben-manes/concurrentlinkedhashmap), which is thread safe, unlike [LRUMap](https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/map/LRUMap.html). Usage is quite easy:
```
Con... | Easy, simple to use LRU cache in java | [
"",
"java",
"caching",
"lru",
""
] |
I have a page on which I must load controls dynamically based on the user selection.
Let's say that I have something like this:
```
public static readonly Dictionary<string, string> DynamicControls = new Dictionary<string, string>
{
{ "UserCtrl1", "~/Controls/UserCtrl1.ascx" },
{ "User... | You don't need to cast the result from LoadControl.
This should do:
```
private Control GetControl()
{
string dynamicCtrl = CurrentItem.DynamicControl;
string path = SomeClass.DynamicControls[dynamicCtrl];
Control ctrl = LoadControl(path);
return ctrl;
}
``` | You probably want something like this (pseudo-ish code):
```
foreach key in dictionary
if key = dynamicControl then
ctrl = (Type.GetType(key))LoadControl(dictionary.get(key))
end if
next
``` | Refactoring solution needed | [
"",
"c#",
"asp.net",
"refactoring",
""
] |
I just wrote a new web part and now I am getting this error when I try to deploy them on my non-dev servers:
> the default namespace
> '<http://schemas.microsoft.com/WebPart/v2>'
> is a reserved namespace for base Web
> Part propertiees. Custom Web Part
> properties require a unique namespace
> (specified through an
>... | Well, it looks like your webpart definition file si somehow broken. The wey i do it is to put webpart into page and then export it. You can do this just by opening webpart galery, which can be located in site settings of root site collection and add your webpart there.
After that just place webpart to any page and use... | A bit of a educated guess here but anyway :-
First check that you have XmlRoot attribute like this in your web part
```
[XmlRoot(Namespace = "Your.Namespace")]
public class YourWebPart: WebPart
{
...
```
and XmlElement attribute on your custom properties
```
[DefaultValue(0)]
[WebPartStorage(Storage.Shared)... | Error when trying to deploy web part | [
"",
"c#",
"sharepoint",
"web-parts",
""
] |
I am refering to the [question](https://stackoverflow.com/questions/252893/how-do-you-change-the-classpath-within-java#252905) on changing the classpath programmatically.
I read and found out that there is some function under **System** class as getproperties where we can retrieve the properties and then also can set ... | You can certainly set any system properties you want at any point of time. The question is, will it have any effect? In the case of classpath, the answer is NO. The system class loader is initialized at a very early point in the startup sequence. It copies the classpath into its own data structures, and the classpath p... | ## Modify Classpath
Even though you cannot set the classpath using the system properties (because the JVM reads system properties once: at startup), you can still change the classpath by forcibly invoking the `addURL` method of the classloader. Note that the solution below does not take into consideration the current ... | Why can't System.setProperty() change the classpath at runtime? | [
"",
"java",
"classpath",
""
] |
Of the two methods below, which do you prefer to read?
Is there another (better?) way to check if a flag is set?
```
bool CheckFlag(FooFlag fooFlag)
{
return fooFlag == (this.Foo & fooFlag);
}
```
And
```
bool CheckFlag(FooFlag fooFlag)
{
return (this.Foo & fooFlag) != 0;
}
```
---
Please vote ... | The two expressions do different things (if fooFlag has more than one bit set), so which one is better really depends on the behavior you want:
```
fooFlag == (this.Foo & fooFlag) // result is true iff all bits in fooFlag are set
(this.Foo & fooFlag) != 0 // result is true if any bits in fooFlag are set
``` | ```
bool CheckFlag(FooFlag fooFlag)
{
return fooFlag == (this.Foo & fooFlag);
}
``` | How should I check if a flag is set in a flags enum? | [
"",
"c#",
"coding-style",
""
] |
I have information spread out across a few databases and want to put all the information onto one webpage using PHP. I was wondering how I can connect to multiple databases on a single PHP webpage.
I know how to connect to a single database using:
```
$dbh = mysql_connect($hostname, $username, $password)
or ... | **Warning :** `mysql_xx` functions are deprecated since php 5.5 and removed since php 7.0 (see <http://php.net/manual/intro.mysql.php>), use `mysqli_xx` functions or see the answer below from @Troelskn
---
You can make multiple calls to `mysql_connect()`, but if the parameters are the same you need to pass true for t... | If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use [PDO](http://docs.php.net/manual/en/book.pdo.php), since this is slowly becoming the new standard. One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code.
You would connect th... | How do you connect to multiple MySQL databases on a single webpage? | [
"",
"php",
"mysql",
""
] |
I need to make some changes to a ClickOnce application that I haven't touched for over a year and therefore the certificate has expired.
I've read that publishing with a new certificate will make the application fail, because it will be signed with a different key.
Therefore I think I need to use the same certificate... | If you're after a quick solution, then you can "renew" your existing certificate and just give it a longer expiry date.
Cliff Stanford has cleaned up the Microsoft "workaround" and made it available as a simple command line exe - available here: <http://may.be/renewcert/> - Nice work Cliff ! | Here's the definitive MSDN article on certificate expiration, which also includes a link to an update on RenewCert. <http://msdn.microsoft.com/en-us/library/ff369721.aspx> This covers all cases.
If you are targeting .NET 3.5, using automatic updates, and don't have a VSTO app, OR you are targeting .NET 4, changing the... | How can I renew my expired ClickOnce certificate? | [
"",
"c#",
"visual-studio",
"visual-studio-2008",
"clickonce",
""
] |
As a web developer, a number of the projects I work on fall under government umbrellas and hence are subject to [508 Accessibility](http://www.section508.gov/) laws, and sometimes [W3C accessibility](http://www.w3.org/TR/WCAG/) guidelines. To what extent can JavaScript be used while still meeting these requirements?
A... | If accessibility is your primary concern, always start a website using standards-compliant (pick a Document Type Definition and stick to it) HTML. If it's a web application (form submissions, etc), make sure the forms will work using just HTTP GET and POST. Once you have a complete website/application you can add bits ... | Progressive enhancement is certainly one route but unobtrusiveness is not the be all and end all of JavaScript accessibility as screen readers tend to use browsers as a basis for their work. Since those browsers support JavaScript, scripts on your page will still run. This is a particular problem with AJAX as clicking ... | Javascript and Accessibility | [
"",
"javascript",
"jquery",
"ajax",
"accessibility",
"screen-readers",
""
] |
I want to convert for example a particular date 12-11-2008 11:33:04.510 to UTC datetime. Can anyone help me how to do this. I want to do this in c# coding. | Just use [DateTime.ToUniversalTime](http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx), assuming it's in the local timezone of your computer at the moment. | DateTime is not timezone-aware. It can be treated as local time or UTC time, and as Jon Skeet said, DateTime.ToUniversalTime can convert between them.
In .NET3.5 there is also the TimeZoneInfo class which allows for conversion of DateTime's between arbitrary timezones, but for your needs, the former is probably good e... | Is there any function for UTC to convert to particular datetime to UTC date time | [
"",
"c#",
""
] |
I do TDD on a daily basis for my C++ development on Solaris10. It has greatly reduced the time I have to spend using my debugger but sometime this is the only option.
DBX is pretty powerful but not that user friendly. Note that I'm talking about console DBX not the SunStudio GUI for DBX).
What are the best productivi... | I have bookmarked a few sites related to dbx. Here they are, in no particular order in case they might be useful to you:
* [Why Can't dbx Find My Function?](http://developers.sun.com/solaris/articles/dbxerr.html)
* [Online Help for the Dbx Debugger](http://blogs.oracle.com/quenelle/resource/dbxhelp.html)
* [Sun Studio... | One of the powerful features of dbx is the built in ksh. You can write shell functions that are as complex as you might want to print customized views of data structures, or follow pointers in a specific route. The shell is an old variation of pdksh, so it's not the nicest for programming, but it's much better than not... | how to get as much as possible from dbx | [
"",
"c++",
"debugging",
"solaris",
"dbx",
""
] |
I have a multidimensional array. I need to search it for a specific range of values, edit those values and return the edited data.
Example array:
```
array(3) {
["first"]=>
array(1) {
[0]=>
string(4) "baz1"
}
["second"]=>
array(1) {
[0]=>
string(4) "foo1"
}
["third"]=>
array(1) {
[... | If your array will not be extremely deep, this can work.
($array being what you want to replace later with yours)
```
$array= array('first' => array('bazi1'), 'second' => array('foo1'), 'third' => array('foo2') );
function modify_foo(&$item, $key)
{
$item = str_replace('foo', 'foo-bar', $item);
}
array_walk_recursi... | How about something like this:
```
function addDashBar($arr)
{
foreach ($arr as $key => $value)
{
if (is_array($value))
$arr[$key] = addDashBar($value)
else
{
$arr[$key] = str_replace($value, "foo", "foo-bar");
}
}
return $arr;
}
``` | PHP - Editing multiple array values (if they exist) | [
"",
"php",
"arrays",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.