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 `char* p`, which points to a `\0`-terminated string. How do I create a C++ `string` from it in an exception-safe way?
Here is an unsafe version:
```
string foo()
{
char *p = get_string();
string str( p );
free( p );
return str;
}
```
An obvious solution would be to try-catch - any easier ways? | You can use `shared_ptr` from [C++11](http://en.cppreference.com/w/cpp/memory/shared_ptr) or [Boost](http://www.boost.org/libs/smart_ptr/):
```
string
foo()
{
shared_ptr<char> p(get_string(), &free);
string str(p.get());
return str;
}
```
This uses a very specific feature of `shared_ptr` not available in ... | Can I ask you what exception you are expecting in your example?
On many platforms (Linux, AIX) new or malloc will never fail and your app will get killed by the os if you run out of memory.
See this link: [What happens when Linux runs out of memory.](http://www.linuxdevcenter.com/pub/a/linux/2006/11/30/linux-out-of-m... | create std::string from char* in a safe way | [
"",
"c++",
"exception",
""
] |
I want to search a table to find all rows where one particular field is one of two values. I know exactly what the values would be, but I'm wondering which is the most efficient way to search for them:
for the sake of example, the two values are "xpoints" and "ypoints". I know for certain that there will be no other v... | As always with SQL queries, run it through the profiler to find out. However, my gut instinct would have to say that the IN search would be quicker. Espcially in the example you gave, if the field was indexed, it would only have to do 2 lookups. If you did a like search, it may have to do a scan, because you are lookin... | Unless all of the data items in the column in question start with 'x' or 'y', I believe IN will always give you a better query. If it is indexed, as @Kibbee points out, you will only have to perform 2 lookups to get both. Alternatively, if it is not indexed, a table scan using IN will only have to check the first lette... | Using IN or a text search | [
"",
"sql",
"mysql",
"optimization",
""
] |
I am attempting to rewrite my [ForestPad](http://ForestPad.com) application utilizing WPF for the presentation layer. In WinForms, I am populating each node programmatically but I would like to take advantage of the databinding capabilities of WPF, if possible.
In general, what is the best way to two-way databind the ... | Well, it would be easier if your element hierarchy was more like...
```
<node type="forest">
<node type="tree">
...
```
...rather than your current schema.
As-is, you'll need 4 `HierarchicalDataTemplate`s, one for each hierarchical element including the root, and one `DataTemplate` for `leaf` elements:
... | We had a similar issue. You may find reading [this article](http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx) helpful. We used the ViewModel pattern described and it simplified everything. | Two-way binding of Xml data to the WPF TreeView | [
"",
"c#",
"wpf",
"xml",
"data-binding",
"treeview",
""
] |
In a [coding style question about infinite loops](https://stackoverflow.com/questions/224138/infinite-loops-top-or-bottom), some people mentioned they prefer the for(;;) style because the while(true) style gives warning messages on MSVC about a conditional expression being constant.
This surprised me greatly, since th... | A warning doesn't automatically mean that code is *bad*, just suspicious-looking.
Personally I start from a position of enabling all the warnings I can, then turn off any that prove more annoying than useful. That one that fires anytime you cast anything to a bool is usually the first to go. | I think the reason for the warning is that you might inadvertently have a more complex expression that evaluates to a constant without realizing it. Suppose you have a declaration like this in a header:
```
const int x = 0;
```
then later on, far from the declaration of x, you have a condition like:
```
if (x != 0) ... | Constant value in conditional expression | [
"",
"c++",
"c",
"warnings",
"visual-c++",
""
] |
I'm using my code-behind page to create a save button programmatically:
```
Button btnSave = new Button();
btnSave.ID = "btnSave";
btnSave.Text = "Save";
```
However I think this must create an html button or perhaps needs something else as I cannot seem to set the OnClick attribute in the following line,... | ```
Button btnSave = new Button();
btnSave.ID = "btnSave";
btnSave.Text = "Save";
btnSave.Click += new System.EventHandler(btnSave_Click);
protected void btnSave_Click(object sender, EventArgs e)
{
//do something when button clicked.
}
``` | Also remember that when the user clicks the button it will force a postback, which creates a *new instance* of your page class. The old instance where you created the button is already gone. You need to make sure that this new instance of the class also adds your button -- and it's event handler -- *prior to the load p... | Creating an asp:Button programmatically? | [
"",
"c#",
"asp.net",
".net",
"servercontrols",
""
] |
In C#, I want to initialize a string value with an empty string.
How should I do this?
What is the right way, and why?
```
string willi = string.Empty;
```
or
```
string willi = String.Empty;
```
or
```
string willi = "";
```
or what? | **Use whatever you and your team find the most readable.**
Other answers have suggested that a new string is created every time you use `""`. This is not true - due to string interning, it will be created either once per assembly or once per AppDomain (or possibly once for the whole process - not sure on that front). ... | There really is no difference from a performance and code generated standpoint. In performance testing, they went back and forth between which one was faster vs the other, and only by milliseconds.
In looking at the behind the scenes code, you really don't see any difference either. The only difference is in the IL, w... | In C#, should I use string.Empty or String.Empty or "" to intitialize a string? | [
"",
"c#",
".net",
"string",
"initialization",
""
] |
I have two C++ processes (A and B), executing under Windows, where one launches the other. I would like to effectively single-thread their execution. For example:
1. Start process A
2. A creates B
3. A suspends
4. B executes some fixed set of operations
5. B suspends and A is resumed
6. A executes some fixed set of op... | Events would work in this case:
* A creates an event an starts Process B
* A waits for the event to be signaled
* B also creates an event, does it's first item, then signals A's event (which either has a well-known name or the handle can be passed to B when it starts or using some other mechanism
* B waits on its even... | Pass two event handles (CreateEvent) to process B. signal one handle when process a is done working, signal the other when process b is done working. Each process calls WaitForSingleObject() to wait for the other process to finish a set of work. | Single-threading two processes | [
"",
"c++",
"multithreading",
"synchronization",
"process",
""
] |
In the Render method of an ASP.NET web-control, I need to alter the output of the Html based on whether JavaScript is enabled or disabled on the clients browser,
Does anyone know the right incantation to figure that out? | The problem with using script to check whether javascript is enabled is that you only find that out after the script hasn't run.
Some solutions try the opposite - they use javascript to set a value and then supply Javascript enabled controls if that value is later detected. However, this fails with javascript-sometime... | The [noscript](http://www.w3schools.com/TAGS/tag_noscript.asp) tag is used to define an alternate content (text) if a script is NOT executed.
EDIT: Hi Kieron, take a look at this link: [Creating a Server Control for JavaScript Testing](http://www.15seconds.com/issue/030303.htm), and [Detect if JavaScript is enabled in... | Detect when JavaScript is disabled in ASP.NET | [
"",
"asp.net",
"javascript",
"controls",
"progressive-enhancement",
""
] |
I am currently investigating how to make a connection to a SQL Server database from my Java EE web application using Windows Authentication instead of SQL Server authentication. I am running this app off of Tomcat 6.0, and am utilizing the Microsoft JDBC driver. My connection properties file looks as follows:
```
dbDr... | I do not think one can push the user credentials from the browser to the database (and does it makes sense ? I think not)
But if you want to use the credentials of the user running Tomcat to connect to SQL Server then you can use Microsoft's JDBC Driver.
Just build your JDBC URL like this:
```
jdbc:sqlserver://localh... | look at
<http://jtds.sourceforge.net/faq.html#driverImplementation>
What is the URL format used by jTDS?
The URL format for jTDS is:
```
jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
```
...
domain
Specifies the Windows domain to authenticate in. If present and the user name a... | Can I connect to SQL Server using Windows Authentication from Java EE webapp? | [
"",
"java",
"sql-server",
"tomcat",
"jdbc",
"jakarta-ee",
""
] |
I would like to implement a producer/consumer scenario that obeys interfaces that are roughly:
```
class Consumer {
private:
vector<char> read(size_t n) {
// If the internal buffer has `n` elements, then dequeue them
// Otherwise wait for more data and try again
}
public:
void run() {
... | This code is not production ready.
No error checking is done on the results of any library calls.
I have wrapped the lock/unlock of the mutex in LockThread so it is exception safe. But that's about it.
In addition if I was doing this seriously I would wrap the mutex and condition variables inside objects so they can ... | I tend to use what I call a "Syncronized Queue". I wrap the normal queue and use a Semaphore class for both locking and making read block just as you desire:
```
#ifndef SYNCQUEUE_20061005_H_
#define SYNCQUEUE_20061005_H_
#include <queue>
#include "Semaphore.h"
// similar, but slightly simpler interface to std::queu... | How to implement blocking read using POSIX threads | [
"",
"c++",
"multithreading",
"pthreads",
"producer-consumer",
""
] |
I have a web page that uses a scrolling div to display table information. When the window is resized (and also on page load), the display is centered and the div's scrollbar positioned to the right of the page by setting its width. For some reason, the behaviour is different under firefox than IE. IE positions/sizes th... | You are dealing with "[one of the best-known software bugs in a popular implementation of Cascading Style Sheets (CSS)](http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug)" according to Wikipedia. I recommend the [Element dimensions](http://www.quirksmode.org/viewport/elementdimensions.html) and [CSS Object M... | Ok, I found the problem. Seems to be that firefox does not include the style.paddingLeft value in its style.width setting, whereas IE does, thus the div was ending up exactly style.paddingLeft too wide. That is, if for example style.paddingLeft is 8, IE's style.width value would be 8 more than FireFox's - and thus the ... | What is different with window and div widths between firefox and IE | [
"",
"javascript",
"html",
"internet-explorer",
"firefox",
""
] |
I'm wanting to add a class to the body tag without waiting for the DOM to load, but I'm wanting to know if the following approach would be valid. I'm more concerned with validity than whether the browsers support it for now.
```
<body>
$("body").addClass("active");
...
</body>
```
Thanks,
Steve | The [.elementReady() plugin](http://plugins.jquery.com/project/elementReady) seems to be pretty close to what you're looking for.
It operates by using a `setInterval` loop, that exits as soon as `document.getElementById()` returns an element for a given `id`.
You could probably do a slight modification of that plugin... | If the element doesn't exist in the DOM, the search will fail to find it and the action won't be applied. If you can't do it in the $(document).ready() function, you might want to try putting the code after the element being referenced. I believe this will work.
```
<body>
<div id='topStories'></div>
<script typ... | Can I target an element before it's closed? | [
"",
"javascript",
"jquery",
"html",
"css",
"dom",
""
] |
I'm trying to create a unit test to test the case for when the timezone changes on a machine because it has been incorrectly set and then corrected.
In the test I need to be able to create DateTime objects in a none local time zone to ensure that people running the test can do so successfully irrespective of where the... | [Jon's answer](https://stackoverflow.com/questions/246498/creating-a-datetime-in-a-specific-time-zone-in-c-fx-35#246512) talks about [TimeZone](http://msdn.microsoft.com/en-us/library/system.timezone.aspx), but I'd suggest using [TimeZoneInfo](http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx) instead.
... | The DateTimeOffset structure was created for exactly this type of use.
See:
<http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx>
Here's an example of creating a DateTimeOffset object with a specific time zone:
`DateTimeOffset do1 = new DateTimeOffset(2008, 8, 22, 1, 0, 0, new TimeSpan(-5, 0, 0));` | Creating a DateTime in a specific Time Zone in c# | [
"",
"c#",
".net",
"datetime",
"timezone",
".net-3.5",
""
] |
Should I always wrap external resource calls in a try-catch? (ie. calls to a database or file system) Is there a best practice for error handling when calling external resources? | Catch **only exceptions** that you **can handle**. So for example when using external resources, the best practice is to catch **specific** exceptions that you know you can handle. In case of files this can be (IOException, SecurityException, etc), in case of Database the exception can be SqlException or others.
In an... | I think there are three reasons to have a catch block:
* You can handle the exception and recover (from "low level" code)
* You want to rewrap the exception (again, from "low level" code)
* You're at the top of the stack, and while you can't recover the operation itself, you don't want the whole app to go down
If you... | always try-catch external resource calls? | [
"",
"c#",
"exception",
"external",
""
] |
I'm creating a custom Java Struts tag that is for building and formatting an html select box in a standardised way (part of our usability guidelines).
Each select box has an additional/initial value which describes the requirement of the value returned by the select element, i.e.:
* *Mandatory* - with the label "Plea... | **NOTE: See EDIT below for a different approach than the one given here**
How about `requirementConstraint`?
```
<my:customSelect requirementConstraint="Mandatory">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</my:customSelect>
```
Another possiblity is not to tri-... | 'multiplicity' would seem the right name.
Looks like you're describing the following values:
Mandatory: 1
Optional: 0+
Select All: n | What descriptive variable name can I use here? | [
"",
"java",
"variables",
"struts",
"html-select",
""
] |
I was wondering if there is some way to name or rename a property on an Anonymous type to include a space in the property name. For example:
```
var resultSet = from customer in customerList
select new
{
FirstName = customer.firstName;
};
```
In this example I would like FirstName to be "First Nam... | What about doing something like this:
```
var resultSet = from customer in customerList
select new
{
Value = customer.firstName,
Title = "First Name"
};
```
Then in your user control use Value as the contents and Title as the col... | No, its not possible, spaces are not allowed in the names of members, you can use perhaps underscore or programmatically change the captions of your columns after the data is bound... | C# 3.0 Anonymous Types: Naming | [
"",
"c#",
"naming",
"anonymous-types",
".net-3.0",
""
] |
I've done some research and I can't really find a preferred way to do updating of form controls from a worker thread in C#. I know about the BackgroundWorker component, but what is the best way to do it without using the BackgroundWorker component? | There's a general rule of thumb that says don't update the UI from any thread other than the UI thread itself. Using the features of the BackgroundWorker is a good idea, but you don't want to and something is happening on a different thread, you should do an "Invoke" or BeginInvoke to force the delegate to execute the ... | Why dont you want to do it using the BackgroundWorker? It has a fantastic callback event called ProgressChanged which lets the UI thread know about updates, perfect for progess bar-type updates and the like.
[link to details](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.progresschange... | What is the best way to update form controls from a worker thread? | [
"",
"c#",
"multithreading",
"forms",
""
] |
What happen when SQL Server 2005 happen to reach the maximum for an IDENTITY column? Does it start from the beginning and start refilling the gap?
What is the behavior of SQL Server 2005 when it happen? | **You will get an overflow error when the maximum value is reached**. If you use the bigint datatype with a maximum value of `9,223,372,036,854,775,807` this will most likely never be the case.
The error message you will get, will look like this:
```
Msg 220, Level 16, State 2, Line 10
Arithmetic overflow error for d... | It will not fill in the gaps. Instead inserts will fail until you change the definition of the column to either drop the identity and find some other way of filling in the gaps or increase the size (go from int to bigint) or change the type of the data (from int to decimal) so that more identity values are available. | What happen in SQL 2005 when it run out of number for an autonumber column? | [
"",
"sql",
"sql-server-2005",
"identity",
"limits",
""
] |
I'd like to implement a big int class in C++ as a programming exercise—a class that can handle numbers bigger than a long int. I know that there are several open source implementations out there already, but I'd like to write my own. I'm trying to get a feel for what the right approach is.
I understand that the genera... | Things to consider for a big int class:
1. Mathematical operators: +, -, /,
\*, % Don't forget that your class may be on either side of the
operator, that the operators can be
chained, that one of the operands
could be an int, float, double, etc.
2. I/O operators: >>, << This is
where you figure out how... | A fun challenge. :)
I assume that you want integers of arbitrary length. I suggest the following approach:
Consider the binary nature of the datatype "int". Think about using simple binary operations to emulate what the circuits in your CPU do when they add things. In case you are interested more in-depth, consider r... | How to implement big int in C++ | [
"",
"c++",
"biginteger",
"bignum",
"largenumber",
""
] |
I am using partial classes to split some functionality between 2 files, but I am getting an error. What am I doing wrong?
A1.cs:
```
private partial class A
{
private string SomeProperty { get { return "SomeGeneratedString"; } }
}
```
A2.cs:
```
private partial class A
{
void SomeFunction()
{
... | Are the two partial classes in the same namespace? That could be an explanation. | Same answer as @Andrey K but in simple terms
**Set the build action of all your partial classes to 'Compile' using the 'Properties' windows of each of those files**
[](https://i.stack.imgur.com/eLv99.png) | Error with C# Partial classes | [
"",
"c#",
"partial-classes",
""
] |
I'm stuck in .NET 2.0 Windows Forms.
It doesn't look like the ability to select multiple nodes exists in the standard `TreeView` control.
I'm trying to do this for a context menu selection. So check boxes aren't an acceptable UI paradigm here.
What's the best way to provide that very necessary functionality? | We did this in a WTL project once, but the basic work needed is the same for .NET. To achieve a multiple selection tree control, you will need to draw the tree items yourself and override the keyboard and mouse handling. You will also need to maintain your own list of items that are selected.
Don't forget to consider ... | [TreeView.CheckBoxes](http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.checkboxes.aspx) | Allow multi-select in a .NET TreeView | [
"",
"c#",
".net",
"winforms",
".net-2.0",
"treeview",
""
] |
*[This question is related to but not the same as [this one](https://stackoverflow.com/questions/206564/what-is-the-performance-implication-of-converting-to-bool-in-c).]*
If I try to use values of certain types as boolean expressions, I get a warning. Rather than suppress the warning, I sometimes use the ternary opera... | The argument of the ! operator and the first argument of the ternary operator are both implicitly converted to bool, so !! and ?: are IMO silly redundant decorations of the cast. I vote for
```
b = (t != 0);
```
No implicit conversions. | Alternatively, you can do this: `bool b = (t != 0)` | Is !! a safe way to convert to bool in C++? | [
"",
"c++",
"visual-c++",
"boolean",
""
] |
In general, is it a best practice to have simple POJO Java classes implement java.io.Serializable? | Generally not. Joshua Bloch says to [implement Serializable judiciously](http://my.safaribooksonline.com/0201310058/ch10lev1sec1 "Implement Serializable judiciously"). A summary of drawbacks that he describes:
* decreases flexibility of changing class implementation later - the serialized form is part of the class's A... | Only if you need to be able to serialise them. It's [not worth the effort](http://en.wikipedia.org/wiki/YAGNI) otherwise. | Is implementing java.io.Serializable even in simple POJO Java classes a best practice? | [
"",
"java",
"serialization",
""
] |
Does anyone know how to stop jQuery fromparsing html you insert through before() and after()? Say I have an element:
```
<div id='contentdiv'>bla content bla</div>
```
and I want to wrap it in the following way:
```
<div id='wrapperDiv'>
<div id='beforeDiv'></div>
<div id='contentDiv'>bla content bla</div>
... | ```
$('#contentDiv').each(function() {
$(this).wrap('<div id="wrapperDiv">');
$(this).before('<div id="beforeDiv">');
$(this).after('<div id="afterDiv">');
});
```
produces:
```
<div id='wrapperDiv'>
<div id='beforeDiv'></div>
<div id='contentDiv'>bla content bla</div>
<div id='afterDiv'></div... | your markup isn't complete...before and after are to take complete nodes only...
what you are trying to do is **wrap** your content, which is different.
you want this:
.wrap(html);
<http://docs.jquery.com/Manipulation/wrap#html> | How to keep jQuery from parsing inserted HTML? | [
"",
"javascript",
"jquery",
"html",
"dom",
""
] |
After using them a while I can't help but feel that the hoops you're forced to jump through when using anonymous classes are not worth it.
You end up with `final` all over the place and no matter what the code is more difficult to read than if you'd used a well named inner class.
So what are the advantages of using t... | The advantage is that it's an implementation of closures. It's clunky, but it's the best we've got in Java at the moment. In other words, you don't have to create a new class just for the sake of preserving some state which you've already got as a local variable somewhere.
I have [an article comparing C# and Java clos... | Well I usually only use it when needing an implementation of an interface for a single purpose (and an interface with few functions or the code because really fast ugly)...
like in the following example :
```
this.addListener(new IListener(){
public void listen() {...}
});
``` | Are Anonymous Classes a bad idea? | [
"",
"java",
""
] |
I'm reading through the [Zend Framework coding standards](http://framework.zend.com/manual/en/coding-standard.coding-style.html), where they state that curly brace after a Class definitions should be on the next line, the "one true brace form".
```
class MyClass
{
function....
}
```
I usually have the braces on t... | Personal preference is really the only real "reason". | Having the braces on lines by themselves helps to visually separate the inner part from the outer part. That makes it easier to quickly scan through source code and distinguish blocks from their surroundings.
Plus, having the braces at the same indentation level makes it easier for the eye to find a match. | Whats the reasoning behind the different brace forms? | [
"",
"php",
"coding-style",
""
] |
I am just beginning to write an application. Part of what it needs to do is to run queries on a database of nutritional information. What I have is the USDA's [SR21 Datasets](http://www.ars.usda.gov/Services/docs.htm?docid=17478) in the form of flat delimited ASCII files.
What I need is advice. I am looking for the be... | It looks pretty small, so I'd work out an appropriate object model, load the whole lot into memory, and then use LINQ to Objects.
I'm not quite sure what you're asking about in terms of "persistent storage" - aren't you just reading the data? Don't you already have that in the text files? I'm not sure why you'd want t... | I would import the flat files into SQL Server and access via standard ADO.NET functionality. Not only is DB access always better (more robust and powerful) than file I/O as far as data querying and manipulation goes, but you can also take advantage of SQL Server's caching capabilities, especially since this nutritional... | .Net Data Handling Suggestions | [
"",
"c#",
".net",
"database",
"persistence",
"text-files",
""
] |
I have an application in which most requests are submitted via AJAX, though some are submitted via "regular" HTTP requests. If a request is submitted and the user's session has timed out, the following JSON is returned:
```
{"authentication":"required"}
```
The JavaScript function which submits all AJAX requests hand... | You cannot add a handler to the JSP that way. Anything you add to it will make it a non-JSON producing page.
There are two options that I can see:
Add a parameter to the page by appending a URL parameter to the screen that modifies the output.
URL: <http://domain/page.jsp?ajaxRequest=true>
would output json only
URL... | 3) Change your AJAX code to add a variable to the GET or POST: `outputJson=1` | detecting JSON loaded by browser | [
"",
"javascript",
"json",
"jsp",
""
] |
I am creating an application which displays some messages and its directions in the DataGridView. I would like to replace some columns content with pictures. For example I would like to replace number 0 which represents the incoming call with a green arrow (some .jpg image).
Does anyone know how this could be achieved... | We stored the images in the resource file as BMP files. Then, we handle the CellFormatting event in the DataGridView like this:
```
private void messageInfoDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// Is this the correct column? (It's actually a DataGridViewIma... | GridViews have the ability to use an image field as opposed to a data bound field. This sounds like it would do the trick. | Replacing DataGridView words and numbers with images | [
"",
"c#",
"datagridview",
""
] |
How can I display a sort arrow in the header of the sorted column in a list view which follows the native look of the operating system? | You can use the following extension method to set the sort arrow to a particular column:
```
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ListViewExtensions
{
[StructLayout(LayoutKind.Sequential)]
public struct HDITEM
{
public Mask mask;
public int cxy;
[Marshal... | Great answer by Andrew. If Anyone is looking for the VB.net equivalent here it is:
```
Public Module ListViewExtensions
Public Enum SortOrder
None
Ascending
Descending
End Enum
<StructLayout(LayoutKind.Sequential)>
Public Structure HDITEM
Public theMask As Mask
... | How to I display a sort arrow in the header of a list view column using C#? | [
"",
"c#",
"listview",
""
] |
I'm still getting used to the sizers in wxWidgets, and as such can't seem to make them do what I want.
I want a large panel that will contain a list of other panels/boxes, which each then contain a set of text fields
```
----------------------
| label text box |
| label2 text box2 |
----------------------
-----... | "If theres too many to fit in the containing panel a vertical scroll bar is also required."
You could have a look at wxScrolledWindow.
"additional added items are just a small box in the top left of the main panel"
I am not sure, but, maybe a call to wxSizer::Layout() will help.
"Also whats the best way to lay out ... | May I suggest to you to post this question to one of the [wxWidgets mailing list](http://www.wxwidgets.org/support/maillst2.htm)? They will be able to help you very quickly. | Understanding wxWidgets sizers | [
"",
"c++",
"wxwidgets",
""
] |
I'm writing a web application which uses windows authentication and I can happily get the user's login name using something like:
```
string login = User.Identity.Name.ToString();
```
But I don't need their login name I want their DisplayName. I've been banging my head for a couple hours now...
Can I access my orga... | How about this:
```
private static string GetFullName()
{
try
{
DirectoryEntry de = new DirectoryEntry("WinNT://" + Environment.UserDomainName + "/" + Environment.UserName);
return de.Properties["displayName"].Value.ToString();
}
catch { return null; }
}
... | See related question: [Active Directory: Retrieve User information](https://stackoverflow.com/questions/132277/active-directory-retrieve-user-information)
See also: [Howto: (Almost) Everything In Active Directory via C#](http://www.codeproject.com/KB/system/everythingInAD.aspx) and more specifically section "[Enumerat... | How do I find a user's Active Directory display name in a C# web application? | [
"",
"c#",
"active-directory",
""
] |
I've been asked to add Google e-commerce tracking into my site. This tracking involves inserting some javascript on your receipt page and then calling it's functions. From my asp.net receipt page, I need to call one function (\_addTrans) for the transaction info and then another (\_addItem) for each item on the order. ... | Probably the easiest way is to build up the required Javascript as a string with something like
```
StringBuilder sb = new StringBuilder()
sb.AppendLine( "<script>" );
sb.AppendLine( "var pageTracker = _gat._getTracker('UA-XXXXX-1');" );
sb.AppendLine( "pageTracker._trackPageview();" );
sb.AppendFormat( "pageTracker._... | Here i just wrote an Google Analytics E-Commerce class to dynamically add analytics transactions.
<http://www.sarin.mobi/2008/11/generate-google-analytics-e-commerce-code-from-c/>
Hope this hope. | Tracking e-commerce with Google | [
"",
"c#",
"asp.net",
"e-commerce",
""
] |
We are rolling out a site for a client using IIS tomorrow.
I am to take the site down to the general public (Sorry, we are updating message) and allow the client to test over the weekend after we perform the upgrade.
If it is successful, I open it to everbody - if not, I rollback.
What is the easiest way to put a "W... | Redirect via IIS. Create a new website in IIS and put your "Sorry updating" message in the Default.aspx. Then switch ports between the real site (will go from 80, to something else (6666)) and the 'maintenance' site (set on 80).
Then tell your testers to go to yoursite.com:6666.
Then switch the real site back to 80 a... | I thought it would be worthwhile to mention ASP.NET 2.0+'s "app offline" feature. (Yes, I realize the questioner wants to leave the app up for testing, but I'm writing this for later readers who might come here with different needs).
If you really want to take the application offline for *everyone* (for instance to do... | Take down website to public, but leave for testing... "We're Not Open" | [
"",
"c#",
"asp.net",
"iis",
"web",
"rollout",
""
] |
I receive this message (see image below) when I try to edit in debugging. This occur only in my Vista64bits OS, not in my XP computer. Why and what should I do?
**Update**
I found that I need to compile in x86 to be able to change value when debugging. So my question is WHY that I can't do it in x64?
[alt text http:/... | There is no technical reason, it is just simply not implemented. According to some sources, Microsoft wants to implement it by the next release of the CLR.
See:
<http://blogs.msdn.com/stevejs/archive/2005/11/15/493018.aspx#499593> | Mike Stall [says](http://blogs.msdn.com/jmstall/archive/2006/02/13/cant-do-enc.aspx):
> EnC does some very low-level things
> that are pretty OS-specific and so
> limiting to a single platform was
> primarily a resource-constraint.
> Future CLRs will no doubt expand this.
> Our porting effort also started from
> scrat... | Change to 64 bits not allowed when trying to edit in debug, why? | [
"",
"c#",
".net",
".net-2.0",
"editing",
"compilation",
""
] |
I'm using Python's Imaging Library and I would like to draw some bezier curves.
I guess I could calculate pixel by pixel but I'm hoping there is something simpler. | A bezier curve isn't that hard to draw yourself. Given three points `A`, `B`, `C` you require three linear interpolations in order to draw the curve. We use the scalar `t` as the parameter for the linear interpolation:
```
P0 = A * t + (1 - t) * B
P1 = B * t + (1 - t) * C
```
This interpolates between two edges we've... | ```
def make_bezier(xys):
# xys should be a sequence of 2-tuples (Bezier control points)
n = len(xys)
combinations = pascal_row(n-1)
def bezier(ts):
# This uses the generalized formula for bezier curves
# http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Generalization
result = []
... | How can I draw a bezier curve using Python's PIL? | [
"",
"python",
"python-imaging-library",
"bezier",
"imaging",
""
] |
Several times, while perusing the Boost library's documentation, I've run across return values that are marked "[convertible to `bool`](http://www.boost.org/doc/libs/1_36_0/libs/utility/Collection.html)" (search that page for the phrase "convertible to bool", it's about a third of the way down). I once stumbled across ... | “convertible to bool” simply means anything which can meaningfully be used in a boolean context (e.g. in an `if` condition). This makes sense in implicit conversions. Imagine an object which you want to use in a boolean context, e.g. `std::fstream`:
```
ifstream ifs("filename");
while (ifs >> token)
cout "token " ... | `bool`s are promotable to `int`s and can participate in arithmetic operations. This is often not the desired outcome, when a value should just be used for truth testing.
A convertible-to-`bool` is usually something like a `void*`, where the null pointer is false, and anything else is true, and yet can't be used for ar... | Why do Boost libraries return things "convertible to `bool`" rather than just returning `bool`s? | [
"",
"c++",
"boost",
""
] |
Is there a cross database platform way to get the primary key of the record you have just inserted?
I noted that [this answer](https://stackoverflow.com/questions/165156/easy-mysql-question-regarding-primary-keys-and-an-insert) says that you can get it by Calling `SELECT LAST_INSERT_ID()` and I think that you can call... | Copied from my code:
```
pInsertOid = connection.prepareStatement(INSERT_OID_SQL, Statement.RETURN_GENERATED_KEYS);
```
where pInsertOid is a prepared statement.
you can then obtain the key:
```
// fill in the prepared statement and
pInsertOid.executeUpdate();
ResultSet rs = pInsertOid.getGeneratedKeys();
if (rs.ne... | extraneon's answer, although correct, **doesn't work for Oracle**.
The way you do this for Oracle is:
```
String key[] = {"ID"}; //put the name of the primary key column
ps = con.prepareStatement(insertQuery, key);
ps.executeUpdate();
rs = ps.getGeneratedKeys();
if (rs.next()) {
generatedKey = rs.getLong(1);
}
... | Primary key from inserted row jdbc? | [
"",
"java",
"jdbc",
"identity",
""
] |
I'm working with jQuery and looking to see if there is an easy way to determine if the element has a specific CSS class associated with it.
I have the id of the element, and the CSS class that I'm looking for. I just need to be able to, in an if statement, do a comparison based on the existence of that class on the el... | Use the `hasClass` method:
```
jQueryCollection.hasClass(className);
```
or
```
$(selector).hasClass(className);
```
The argument is (obviously) a string representing the class you are checking, and it returns a boolean (so it doesn't support chaining like most jQuery methods).
**Note:** If you pass a `className` ... | from the [FAQ](http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_test_whether_an_element_has_a_particular_class.3F)
```
elem = $("#elemid");
if (elem.is (".class")) {
// whatever
}
```
or:
```
elem = $("#elemid");
if (elem.hasClass ("class")) {
// whatever
}
``` | Determine if an element has a CSS class with jQuery | [
"",
"javascript",
"jquery",
"css",
""
] |
I have a WinForms application (I'm using VB) that can be minimized to the system tray. I used the "hackish" methods described in multiple posts utilizing a NotifyIcon and playing with the Form\_Resize event.
This all works fine aesthetically, but the resources and memory used are unaffected. I want to be able to minim... | Calling MiniMizeMemory() will do a garbage collection, trim the process working size, then compact the process' heap.
```
public static void MinimizeMemory()
{
GC.Collect(GC.MaxGeneration);
GC.WaitForPendingFinalizers();
SetProcessWorkingSetSize(
Process.GetCurrentProcess().Handle,
(UIntPtr... | You're probably looking for this function call: [SetProcessWorkingSetSize](http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx)
If you execute the API call SetProcessWorkingSetSize with -1 as an argument, then Windows will trim the working set immediately.
However, if most of the memory is still being held b... | .NET Minimize to Tray AND Minimize required resources | [
"",
"c#",
".net",
"vb.net",
"visual-studio",
"winforms",
""
] |
I'm trying to change default firstDayOfWeek for java.util.Calendar from SUNDAY to MONDAY. Is it possible to achieve this through JVM configuration instead of adding this piece of code?
```
cal.setFirstDayOfWeek(Calendar.MONDAY);
``` | The first day of the week is derived from the current locale. If you don't set the locale of the calendar ([Calendar.getInstance(Locale)](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html#getInstance(java.util.Locale)), or [new GregorianCalendar(Locale)](http://java.sun.com/j2se/1.5.0/docs/api/java/util/G... | According to the API:
> Calendar defines a locale-specific seven day week using two parameters: the first day of the week and the minimal days in first week (from 1 to 7). These numbers are taken from the locale resource data when a Calendar is constructed. They may also be specified explicitly through the methods for... | How to specify firstDayOfWeek for java.util.Calendar using a JVM argument | [
"",
"java",
"calendar",
"jvm-arguments",
""
] |
If I have a method such as:
```
public void MyMethod(int arg1, string arg2)
```
How would I go about getting the actual names of the arguments?
I can't seem to find anything in the MethodInfo which will actually give me the name of the parameter.
I would like to write a method which looks like this:
```
public stat... | ```
public static string GetParamName(System.Reflection.MethodInfo method, int index)
{
string retVal = string.Empty;
if (method != null && method.GetParameters().Length > index)
retVal = method.GetParameters()[index].Name;
return retVal;
}
```
The above sample should do what you need. | Try something like this:
```
foreach(ParameterInfo pParameter in pMethod.GetParameters())
{
//Position of parameter in method
pParameter.Position;
//Name of parameter type
pParameter.ParameterType.Name;
//Name of parameter
pParameter.Name;
}
``` | How can you get the names of method parameters? | [
"",
"c#",
".net",
"reflection",
""
] |
The following two queries each give the same result:
```
SELECT column FROM table GROUP BY column
SELECT DISTINCT column FROM table
```
Is there anything different in the way these commands are processed, or are they the same thing?
(This is not a question about aggregates. The use of `GROUP BY` with aggregate funct... | [MusiGenesis](https://stackoverflow.com/questions/164319/is-there-any-difference-between-group-by-and-distinct#164485)' response is functionally the correct one with regard to your question as stated; the SQL Server is smart enough to realize that if you are using "Group By" and not using any aggregate functions, then ... | `GROUP BY` lets you use aggregate functions, like `AVG`, `MAX`, `MIN`, `SUM`, and `COUNT`.
On the other hand `DISTINCT` just removes duplicates.
For example, if you have a bunch of purchase records, and you want to know how much was spent by each department, you might do something like:
```
SELECT department, SUM(amo... | Is there any difference between GROUP BY and DISTINCT? | [
"",
"sql",
"group-by",
"distinct",
""
] |
If a variable is declared as `static` in a function's scope it is only initialized once and retains its value between function calls. What exactly is its lifetime? When do its constructor and destructor get called?
```
void foo()
{
static string plonk = "When will I die?";
}
``` | The lifetime of function `static` variables begins the first time[0] the program flow encounters the declaration and it ends at program termination. This means that the run-time must perform some book keeping in order to destruct it only if it was actually constructed.
Additionally, since the standard says that the de... | Motti is right about the order, but there are some other things to consider:
Compilers typically use a hidden flag variable to indicate if the local statics have already been initialized, and this flag is checked on every entry to the function. Obviously this is a small performance hit, but what's more of a concern is... | What is the lifetime of a static variable in a C++ function? | [
"",
"c++",
"static",
"lifetime",
""
] |
I am launching a child process with ProcessBuilder, and need the child process to exit if the parent process does. Under normal circumstances, my code is stopping the child properly. However, if I cause the OS to kill the parent, the child will continue running.
Is there any way to "tie" the child process to the paren... | There is no tie between a child process and its parent. They may know each others process ID, but there's no hard connection between them. What you're talking about a [orphan process](http://en.wikipedia.org/wiki/Orphan_process). And it's an OS level concern. Meaning any solution is probably platform dependent.
About ... | While you cannot protect against a hard abort (e.g. SIGKILL on Unix), you can protect against other signals that cause your parent process to shut down (e.g. SIGINT) and clean up your child process. You can accomplish this through use of shutdown hooks: see [Runtime#addShutdownHook](http://java.sun.com/javase/6/docs/ap... | How can I cause a child process to exit when the parent does? | [
"",
"java",
"process",
""
] |
I know how to program Console application with parameters, example : myProgram.exe param1 param2.
My question is, how can I make my program works with |, example : echo "word" | myProgram.exe? | You need to use `Console.Read()` and `Console.ReadLine()` as if you were reading user input. Pipes replace user input transparently. You can't use both easily (although I'm sure it's quite possible...).
**Edit:**
A simple `cat` style program:
```
class Program
{
static void Main(string[] args)
{
stri... | The following will not suspend the application for input and works when data is *or* is not piped. A bit of a hack; and due to the error catching, performance could lack when numerous piped calls are made but... easy.
```
public static void Main(String[] args)
{
String pipedText = "";
bool isKeyAvailable;
... | C# Console receive input with pipe | [
"",
"c#",
"pipe",
""
] |
I have two tables:
Table 1:
ID, PersonCode, Name,
Table 2:
ID, Table1ID, Location, ServiceDate
I've got a query joining table 1 to table 2 on table1.ID = table2.Table1ID where PersonCode = 'XYZ'
What I want to do is return Table1.PersonCode,Table1.Name, Table2.Location, Table2.ServiceDate, I don't want all rows, In... | Something like this:
```
SELECT
Table1.PersonCode, Table1.Name, Table2.Location, MAX(Table2.ServiceDate)
FROM
Table1
INNER JOIN Table2 on Table1.ID = Table2.Table1ID
WHERE
TABLE1.PersonCode = 'XYZ'
GROUP BY
Table1.PersonCode,Table1.Name, Table2.Location
``` | Use MAX(ServiceDate) | Help with sql join | [
"",
"sql",
"sql-server",
""
] |
My group has a source analysis tool that enforces certain styles that we have to comply with. I can't change it, and some of the rules are just a pain. One example is that all properties have to come before methods, and all constructors must come before properties. It seems silly to me that I have to take time to do so... | You have different possibilities, depending on what exactly you want to do:
Resharper: There is a auto-format function which formats the source code of a single file or all files in the project / solution depending on your selected rules. So you set the settings for braces, naming, whitespaces, operators, lamdas, ... ... | Unless they bake it into VS2010, Resharper has the auto formatting capabilities you're probably looking for. CodeSmith probably has it too, I just haven't used it... | Is there a C# auto formatter that I can use to define custom rules for formatting? | [
"",
"c#",
"formatting",
"text-formatting",
""
] |
I have a .NET class library containing a class with a method that performs some lengthy operation. When a client calls this method it should perform the lengthy operation on a new thread in order to avoid blocking the caller. But once the method finishes it should execute some code on the main thread. In a WinForms app... | I found a simple solution to the problem :
My COM object is declared like this:
```
public class Runner
{
public void Run(string executable, object processExitHandler)
{
ThreadPool.QueueUserWorkItem(state =>
{
var p = new Process()
{
StartInfo = new Proc... | You can invoke a function on a specific thread by using a `System.Windows.Threading.Dispatcher` object (from the WindowsBase assembly).
For example:
```
public class ClassCreatedBySomeThread
{
Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
public void SafelyCallMeFromAnyThread(Action a)
{
... | How to invoke a function on parent thread in .NET? | [
"",
"c#",
"multithreading",
""
] |
In spring you can initialize a bean by having the applicationContext.xml invoke a constructor, or you can set properties on the bean. What are the trade offs between the two approaches? Is it better to have a constructor (which enforces the contract of having everything it needs in one method) or is it better to have a... | I'm not sure there is a "best" way to initialize a bean. I think there are pros and cons to each, and depending on the situation, one or the other might be appropriate. This certainly isn't an exhaustive list, but here are some things to consider.
Using a constructor allows you to have an immutable bean. Immutable obj... | IMO the major advantage of constructor injection is that it is compatible with immutability. However, if a class has more than about 3 dependencies, this requires providing a constructor which takes a large number of parameters, which is unwieldy.
When using setter-injection, I prefer to use the `@PostConstruct` annot... | What is the best way to initialize a bean? | [
"",
"java",
"spring",
""
] |
Newish to Oracle programming (from Sybase and MS SQL Server). What is the "Oracle way" to avoid filling the trans log with large updates?
In my specific case, I'm doing an update of potentially a very large number of rows. Here's my approach:
```
UPDATE my_table
SET a_col = null
WHERE my_table_id IN
(SELECT my_table... | The amount of updates to the redo and undo logs will not at all be reduced if you break up the UPDATE in multiple runs of, say 1000 records. On top of it, the total query time will be most likely be higher compared to running a single large SQL.
There's no real way to address the UNDO/REDO log issue in UPDATEs. With I... | Depends on the percent of rows almost as much as the number. And it also depends on if the update makes the row longer than before. i.e. going from null to 200bytes in every row. This could have an effect on your performance - chained rows.
Either way, you might want to try this.
Build a new table with the column cor... | Oracle SQL technique to avoid filling trans log | [
"",
"sql",
"oracle",
"optimization",
""
] |
I want something that can check if a string is `"SELECT"`, `"INSERT"`, etc. I'm just curious if this exists. | Easy enough to add :
```
HashSet<String> sqlKeywords =
new HashSet<String>(Arrays.asList(
new String[] { ... cut and paste a list of sql keywords here .. }));
``` | If you're trying to prevent SQL injection, it would be better to leverage the built in features of JDBC, such as prepared statements. In general, using string concatenation to form the SQL statement is dangerous. From [Preventing SQL Injection in Java](http://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java):
... | Is there a class or method in Java that will check if a string is a SQL Server keyword? | [
"",
"java",
"sql-server",
""
] |
A friend of mine asked me to implement a blue and a red pointer to represent the inputs of two separate mice to expedite a mixing desk scenario for real time audio mixing. I'd love to, but as much as I think it is a great idea, I don't have a clue as to where to start looking for a possible solution.
Where should I st... | Look at [jinput](http://java.net/projects/jinput).
I have had multiple keyboards working with it, I am nearly certain it supports multiple mice too. | dont know about java.. but for C#/c++ you can try the
[Microsoft Windows MultiPoint Software Development Kit](http://www.microsoft.com/downloads/details.aspx?FamilyID=A137998B-E8D6-4FFF-B805-2798D2C6E41D&displaylang=en)
i've tried it on windows.. it works with 2 USB mice. | How can I handle multiple mouse inputs in Java? | [
"",
"java",
"mouse",
"human-computer-interface",
""
] |
Currently I'm using
```
var x = dict.ContainsKey(key) ? dict[key] : defaultValue
```
I'd like some way to have dictionary[key] return null for nonexistant keys, so I could write something like
```
var x = dict[key] ?? defaultValue;
```
this also winds up being part of linq queries etc. so I'd prefer one-line solut... | With an extension method:
```
public static class MyHelper
{
public static V GetValueOrDefault<K, V>(this IDictionary<K, V> dic,
K key,
V defaultVal = default(V))
{
V ret;
bool found = dic.TryGetValue(key,... | You can use a helper method:
```
public abstract class MyHelper {
public static V GetValueOrDefault<K,V>( Dictionary<K,V> dic, K key ) {
V ret;
bool found = dic.TryGetValue( key, out ret );
if ( found ) { return ret; }
return default(V);
}
}
var x = MyHelper.GetValueOrDefault( ... | C# dictionaries ValueOrNull / ValueorDefault | [
"",
"c#",
".net",
"dictionary",
""
] |
I have two html pages, when you click on something on the first html, it will go to the second one. What I want to do is to show text according to what you clicked on the first html. different texts are wrapped with different ids. Here's how I wrote:
```
<a href="secondpage.html#one"></a>
<a href="secondpage.html#two"... | What you want to do is simulate a click on your anchor when the page loads. Since you're using jQuery, the simplest approach (but far form best) would be the following:
```
$(window).observe('domready', function () {
$(location.hash).click();
});
```
attach ondomready-event to window. Fetch element with id=one (w... | tags do not have id's but names to handle the anchors in Urls, you will still need the ID to manage them in JS though.
So your list should be:
```
<ul id="menu" class="aaa">
<li><a id="one" name="one" href="#">one</a></li>
<li><a id="two" name="two" href="#">two</a></li>
<li><a id="three" name="three" href="#">three</... | JavaScript anchor- access to id on another HTML page | [
"",
"javascript",
"html",
"anchor",
""
] |
I want to get the method `System.Linq.Queryable.OrderyBy<T, TKey>(the IQueryable<T> source, Expression<Func<T,TKey>> keySelector)` method, but I keep coming up with nulls.
```
var type = typeof(T);
var propertyInfo = type.GetProperty(group.PropertyName);
var propertyType = propertyInfo.PropertyType;
var sorterType = ... | Solved (by hacking LINQ)!
I saw your question while researching the same problem. After finding no good solution, I had the idea to look at the LINQ expression tree. Here's what I came up with:
```
public static MethodInfo GetOrderByMethod<TElement, TSortKey>()
{
Func<TElement, TSortKey> fakeKeySelector = element... | A variant of your solution, as an extension method:
```
public static class TypeExtensions
{
private static readonly Func<MethodInfo, IEnumerable<Type>> ParameterTypeProjection =
method => method.GetParameters()
.Select(p => p.ParameterType.GetGenericTypeDefinition());
public ... | Get a generic method without using GetMethods | [
"",
"c#",
".net",
"generics",
"reflection",
""
] |
I am talking about Google Text Translation User Interface, in [Google Language Tools](http://www.google.com/language_tools).
I like the fact that you can get translations of text for a lot of languages. However, I think is not so good always to show all options of translation. I believe is preferably to show, in first... | I've been frustrated with this interface as well. I think it would be a good idea to (a) use cookies to give preference to the languages this user has selected in the past; and (b) to display a limited list (4-8 languages) of the most common languages, with a "more..." option that expands the list.
I really appreciate... | I think it's probably fine. There are only a little over 30 languages in the list, and close to half of them are pretty common languages, so I don't think it really makes sense to put the common ones first. It's not like a country list where you have to search through 180+ countries to find yours.
The only thing I wou... | What ideas do you think can it be applied to this GUI to make it more effective for real people usage? | [
"",
"javascript",
"user-interface",
""
] |
I just spent half an one our to find out what caused the Error-Message "Ci is not defined" in my JavaScript code. I finally found the reason:
It should be (jQuery):
```
$("asd").bla();
```
It was:
```
("asd").bla();
```
(Dollar sign gone missing)
Now after having fixed the problem I'd like to understand the messa... | I don't know which version of FF you are using, but regardless, the message is probably referring to the fact that `bla()` is not a function available on the String object. Since you were missing the `$`, which means you were missing a function, `("asd")` would evaluate to a string, and then the JavaScript interpreter ... | Jason seems to be right. Many plugins (e.g. Firebug, Geode) use Ci as a shortcut:
```
const Ci = Components.interfaces;
```
So the plugins seem to cause that strange error message. | JavaScript: Ci is not defined | [
"",
"javascript",
"firefox",
"continuous-integration",
""
] |
I have a website built using Asp.net and LinqToSql for Data Access. In a certain section of the site, LinqToSql produces a query that looks like this (from my dev machine):
```
select ...
from table1
left outer join table2 on table1 where ...
left outer join table3 on table2 where ...
```
Since the connection between... | I have checked the following:
1. Both use the same database
2. Both have the identical code
3. Both have the identical dbml file
I know that something has to be out of synch somewhere, but I can't find it.
So I have implemented the following workaround: I added a view to my database that includes both left outer joi... | Is your production database different to your development one, e.g. SQL Server 2008 instead of 2005? I believe LINQ to SQL will vary the SQL it generates based on the actual execution-time database it's talking to.
Also, are the schemas exactly the same on both databases? | LinqToSql Producing Different Sql Queries on Different Machines for Identical Code | [
"",
".net",
"asp.net",
"sql",
"linq-to-sql",
""
] |
I'm not sure if the title is very clear, but basically what I have to do is read a line of text from a file and split it up into 8 different string variables. Each line will have the same 8 chunks in the same order (title, author, price, etc). So for each line of text, I want to end up with 8 strings.
The first proble... | The best way is to not use a StringTokenizer at all, but use String's [split](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#split(java.lang.String)) method. It returns an array of Strings, and you can get the length from that.
For each line in your file you can do the following:
```
String[] tokens = ... | Regular expression is the way. You can convert your incoming String into an array of String using the split method
<http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)> | What's the best way to have stringTokenizer split up a line of text into predefined variables | [
"",
"java",
"string",
"tokenize",
""
] |
I have a file I need to rename to that of an existing file. This is a copy, modify, replace original operation on an existing JAR file. I've got the first two steps done, I just need help with the replace original bit. What's the best way to rename the new version of the JAR to that of the old. The old JAR doesn't need... | You're going to need to create two `java.io.File` objects: one for the new file, one for the old file.
Lets call these `oldFile` and `newFile`.
```
oldFile.delete()
newFile.renameTo(oldFile);
```
Edit: mmyers beat me to it. | `Java.io.File.renameTo(java.io.File)`
You might need to call `File.delete()` first on the original file first - some systems won't rename a file onto an existing file. | Rename file onto another in java | [
"",
"java",
"file",
""
] |
I've got an MS access database and I would need to create an SQL query that allows me to select all the not distinct entries in one column while still keeping all the values.
In this case more than ever an example is worth thousands of words:
Table:
```
A B C
1 x q
2 y w
3 y e
4 z r
5 z t
6 z y
```
*SQL magic*
Res... | ```
Select B, C
From Table
Where B In
(Select B From Table
Group By B
Having Count(*) > 1)
``` | Another way of returning the results you want would be this:
```
select *
from
my_table
where
B in
(select B from my_table group by B having count(*) > 1)
``` | Multiple NOT distinct | [
"",
"sql",
"ms-access",
"distinct",
""
] |
I have a image button. I wanted to add a text "Search" on it. I am not able to add it because the "imagebutton" property in VS 2008 does not have text control in it. Can anyone tell me how to add text to a image button??
```
<asp:ImageButton ID="Searchbutton" runat="server" AlternateText="Search"
CssClass="... | ```
<button runat="server"
style="background-image:url('/Content/Img/stackoverflow-logo-250.png')" >
your text here<br/>and some more<br/><br/> and some more ....
</button>
``` | This tip from [dotnetslave.com](http://forums.asp.net/t/1024015.aspx) worked for me:
```
<asp:LinkButton
CssClass="lnkSubmit"
ID="lnkButton"
runat="server">SUBMIT</asp:LinkButton>
a.lnkSubmit:active
{
margin:0px 0px 0px 0px;
background:url(../../images/li_bg1.jpg) left center no-repeat;
... | Text on an Image button in c# asp.net 3.5 | [
"",
"c#",
"asp.net",
""
] |
I have a page where my combo box has hundreds of elements which makes it very hard to pick the one item I want. Is there a good Javascript replacement that would do better than
```
<select id="field-component" name="field_component">
<option selected="selected">1</option><option>2</option>...
</sele... | 
You have [dhtmlCombo](http://www.dhtmlx.com/docs/products/dhtmlxCombo/index.shtml), using ajax to retrieve data when you are filling the input field.
dhtmlxCombo is a cross-browser JavaScript combobox with autocomplete feature.
It e... | In HTML 5 there's standard combo box.
Currently only Opera supports it, but if you happen to be time traveller or writing Opera-only application, it's a nice solution :)
```
<input type=text list=listid>
<datalist id=listid>
<select><option>1<option>2</select>
</datalist>
``` | Good Javascript Combo Box replacement for combo boxes with tons of elements? | [
"",
"javascript",
"html",
"combobox",
"dhtml",
""
] |
What is the best way to manage a database connection in a Java servlet?
Currently, I simply open a connection in the `init()` function, and then close it in `destroy()`.
However, I am concerned that "permanently" holding onto a database connection could be a bad thing.
Is this the correct way to handle this? If not,... | I actually disagree with using Commons DBCP. You should really defer to the container to manage connection pooling for you.
Since you're using Java Servlets, that implies running in a Servlet container, and all major Servlet containers that I'm familiar with provide connection pool management (the Java EE spec may eve... | As everybody says, you need to use a connection pool. Why? What up? Etc.
**What's Wrong With Your Solution**
I know this since I also thought it was a good idea once upon a time. The problem is two-fold:
1. All threads (servlet requests get served with one thread per each) will be sharing the same connection. The re... | Best way to manage database connection for a Java servlet | [
"",
"java",
"database",
"servlets",
"connection",
""
] |
Either for comparisons or initialization of a new variable, does it make a difference which one of these you use?
I know that BigDecimal.ZERO is a 1.5 feature, so that's a concern, but assuming I'm using 1.5 does it matter?
Thanks. | `BigDecimal.ZERO` is a predefined constant and therefore doesn't have to be evaluated from a string at runtime as `BigDecimal("0")` would be. It will be faster and won't require creation of a new object.
If your code needs to run on pre-1.5, then you can use the (much maligned) Singleton pattern to create an object eq... | Using ZERO doesn't create a new object or require any parsing. Definitely the way to go. | Is there a difference between BigDecimal("0") and BigDecimal.ZERO? | [
"",
"java",
"bigdecimal",
"zero",
""
] |
An application that has been working well for months has stopped picking up the JPA `@Entity` annotations that have been a part of it for months. As my integration tests run I see dozens of "`org.hibernate.MappingException: Unknown entity: com.whatever.OrderSystem`" type errors.
It isn't clear to me what's gone wrong ... | I seem to recall I had a similar issue at one time.
Its a long shot, but if you're not already doing this, have you explicitly specified the provider you are using?
```
<persistence ...>
<persistence-unit ...>
<provider>org.hibernate.ejb.HibernatePersistence</provider> <---- explicit setting
....
</... | verify in your entity classe that you import javax.persistent.Entity and not org.hibernate.annotations.Entity | Hibernate/JPA Annotations -- Unknown Entity | [
"",
"java",
"hibernate",
"jpa",
"annotations",
""
] |
Is keeping JMS connections / sessions / consumer always open a bad practice?
Code draft example:
```
// app startup code
ConnectionFactory cf = (ConnectionFactory)jndiContext.lookup(CF_JNDI_NAME);
Connection connection = cf.createConnection(user,pass);
Session session = connection.createSession(true,Session.TRANSACT... | That is a very common and acceptable practice when dealing with long lived connections. For many JMS servers it is in fact preferable to creating a new connection each time it is needed. | Agreed. Here are some [good tips on how to use JMS efficiently](http://activemq.apache.org/how-do-i-use-jms-efficiently.html) which includes keeping around connections/sessions/producers/consumers.
You might also want to check the [recommendation on using transactions](http://activemq.apache.org/should-i-use-transacti... | Long lived JMS sessions. Is Keeping JMS connections / JMS sessions always opened a bad practice? | [
"",
"java",
"jms",
""
] |
I cannot understand how this is possible. Please help!!
I have an app with a trayicon. I want a form to be show when the user double clicks the trayicon. I have a problem where it is possible to get 2 or more forms showing by quickly triple or quadruple clicking the trayicon. The reason I don't want a singleton is tha... | Have an additional boolean variable, "m\_formUnderConstruction" which you test for before constructing the form, and which you set as soon as you've decided to construct it.
The re-entrancy makes all of this a little icky, unfortunately. I've removed the lock, as if this ever gets called from a different thread then y... | Use Interlocked.Increment to change the nr of the tries. If it is 1, open the form, otherwise, don't. And use Interlocked.Decrement after the test or on form's close.
```
private int openedForms = 0;
private Form1 m_form1;
private void ShowForm1()
{
if (Interlocked.Increment(ref openedForms) = 1)
{
m_f... | Single instance form but not singleton | [
"",
"c#",
"winforms",
"multithreading",
""
] |
I am working on a project to enhance our production debugging capabilities. Our goal is to reliably produce a minidump on any unhandled exception, whether the exception is managed or unmanaged, and whether it occurs on a managed or unmanaged thread.
We use the excellent [ClrDump](http://www.debuginfo.com/tools/clrdump... | Windows Forms has a built-in exception handler that does the following by default:
* Catches an unhandled managed exception when:
+ no debugger attached, and
+ exception occurs during window message processing, and
+ jitDebugging = false in App.Config.
* Shows dialog to user and prevents app termination.
You ca... | If you want your GUI thread exceptions to work just like your-non GUI ones, so that they get handled the same way, you can do this:
```
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
```
Here's the background:
In a manged GUI app, by default, exceptions that originate in the GUI thread... | How does SetUnhandledExceptionFilter work in .NET WinForms applications? | [
"",
"c#",
".net",
"debugging",
"clrdump",
""
] |
I've just started experimenting with SDL in C++, and I thought checking for memory leaks regularly may be a good habit to form early on.
With this in mind, I've been running my 'Hello world' programs through Valgrind to catch any leaks, and although I've removed everything except the most basic `SDL_Init()` and `SDL_Q... | Be careful that Valgrind isn't picking up false positives in its measurements.
Many naive implementations of memory analyzers flag lost memory as a leak when it isn't really.
Maybe have a read of some of the papers in the external links section of the [Wikipedia article on Purify](http://en.wikipedia.org/wiki/IBM_Rat... | You have to be careful with the definition of "memory leak". Something which is allocated once on first use, and freed on program exit, will sometimes be shown up by a leak-detector, because it started counting before that first use. But it's not a leak (although it may be bad design, since it may be some kind of globa... | Is there an acceptable limit for memory leaks? | [
"",
"c++",
"memory-leaks",
"sdl",
""
] |
I'm looking for a good way to run a Apache Derby server in network mode. I'm using the NetworkServerControl to start the server and it's working great.
I start the server like this:
```
/**
* starts the network server
* @return true if sucessfull
*/
public boolean start()
{
try
{
// just to be sure... | We ended up with using a file that is created when the server is to be killed, then on the server process we periodically check if the file exists, if it's there we kill the server. | I did a project awhile ago with derby (including running in network mode), and I seem to remember that there is some SQL you can execute on the server which shuts derby down.
So, assuming that's the case (no time to google for it atm sorry) you could, on start up, look for your network instance. If it exists, run this... | Kill Derby DB Network Server on background | [
"",
"java",
"derby",
"javadb",
""
] |
According to [Wikipedia](http://en.wikipedia.org/wiki/Rounding) when rounding a negative number, you round the absolute number. So by that reasoning, -3.5 would be rounded to -4. But when I use java.lang.Math.round(-3.5) returns -3. Can someone please explain this? | According to the [javadoc](http://java.sun.com/javase/6/docs/api/java/lang/Math.html#round(double))
> Returns the closest long to the
> argument. The result is rounded to an
> integer by adding 1/2, taking the
> floor of the result, and casting the
> result to type long. In other words,
> the result is equal to the va... | There are a variety of methods of rounding; the one you are looking at is called Symmetrical Arithmetic Rounding (as it states). The section you are referring to states: "This method occurs commonly used in mathematical applications, for example in accounting. It is the one generally taught in elementary mathematics cl... | Rounding negative numbers in Java | [
"",
"java",
"rounding",
""
] |
As well-known, C++ has steeper learning curve than most of the mainstream languages, which results in better performance . But, does using C++ over other languages[like Java,Ruby,Python] for Qt development have still (major) advantages,let's say about Qtopia? If any, what are they? | Qt is natively a C++ API, so any other languages have to have wrapper code around it which needs to be maintained, etc. The primary documentation will also be for the C++ API.
I'm not sure if there are any "official" bindings to other languages which are maintained and released together with Qt. | If you are looking at Qtopia, you are probably looking into embedded systems. In that case, C++ will likely be the one you want to choose, specifically for those performance reasons.
Otherwise, Trolltech maintains a Java binding, and I imagine that some of the other language bindings aren't too bad either, since those... | What advantages does C++ have over other languages for Qt development? | [
"",
"c++",
"qt",
""
] |
I have recently been exposed to naked objects. It looks like a pretty decent framework. However I do not see it in widespread use like say, Spring. So why is this framework not getting any mainstream application credit. What are its shortcomings as you see? | From my experience using NOF 3.0.3...
The good:
* Automagically generates an DnD UI for your domain objects, like what db4o does for persistence.
* This is what MVC was always meant to be, according to the MVC pattern creator.
* The framework only asks your domain objects (POJOs) to be subclassed from AbstractDomainO... | I've been working on the naked objects approach for over a year now and I haven't even begun to scratch the surface of the possibilities it provides for your system's architecture. To properly utilize it though, it requires that you create a paradigm shift and seek out full OO solutions and revert from resorting to fun... | Naked Objects. Good or Bad | [
"",
"java",
"frameworks",
"naked-objects",
""
] |
Could someone please tell me which objects types can be tested using Regular Expressions in C#? | If I understand you correctly and you are asking which object types can be tested against regular expressions then the answer is: strings and only strings.
Thus your test would be:
```
if(obj is string){...}
``` | Regular expressions only apply to strings. What does it even mean to apply a regular expression to (say) a SqlConnection?
If you need some other sort of pattern matching (e.g. being able to match the values of particular properties) you should think about and then explain those requirements in detail. | What objects can be tested with Regular Expressions in C# | [
"",
"c#",
"regex",
""
] |
Is one more preferred, or performs better over the other? | [`is_int()`](http://php.net/is_int) returns true if the argument is an integer type, [`ctype_digit()`](http://www.php.net/ctype_digit) takes a string argument and returns true if all the characters in the string are digits.
**Example:**
```
┌──────────┬───────────┬────────────────┐
│ │ is_int: │ ctype_dig... | There is also [`is_numeric`](http://php.net/manual/en/function.is-numeric.php) which returns true if passed in value can be parsed as number.
[](https://i.stack.imgur.com/iwREU.png)
If I try to compare performance of functions on **PHP 5.5.30** here ... | Is there a difference between is_int() and ctype_digit()? | [
"",
"php",
"function",
"numbers",
""
] |
I would be interested to learn about large scale development in Python and especially in how do you maintain a large code base?
* When you make incompatibility changes to the signature of a method, how do you find all the places where that method is being called. In C++/Java the compiler will find it for you, how do y... | Since nobody pointed out pychecker, pylint and similar tools, I will: pychecker and pylint are tools that can help you find incorrect assumptions (about function signatures, object attributes, etc.) They won't find everything that a compiler might find in a statically typed language -- but they can find problems that s... | ## Don't use a screw driver as a hammer
Python is not a statically typed language, so don't try to use it that way.
When you use a specific tool, you use it for what it has been built. For Python, it means:
* **Duck typing** : no type checking. Only behavior matters. Therefore your code must be designed to use this ... | How can I use Python for large scale development? | [
"",
"python",
"development-environment",
""
] |
I'm familiar with the issue behind ORA-01775: looping chain of synonyms, but is there any trick to debugging it, or do I just have to "create or replace" my way out of it?
Is there a way to query the schema or whatever to find out what the current definition of a public synonym is?
Even more awesome would be a graphi... | As it turns out, the problem wasn't actually a looping chain of synonyms, but the fact that the synonym was pointing to a view that did not exist.
Oracle apparently errors out as a looping chain in this condition. | If you are using TOAD, go to View>Toad Options>Oracle>General and remove TOAD\_PLAN\_TABLE from EXPLAIN PLAN section and put PLAN\_TABLE | How to debug ORA-01775: looping chain of synonyms? | [
"",
"sql",
"oracle",
"synonym",
""
] |
I want to change the registry values on the pocketPC. I ran the following code:
```
if(enabled)
{
dwData = 120;
}
if(RegSetValueEx(HKEY_LOCAL_MACHINE, _T("System\\CurrentControlSet\\Control\\Power\\Timeouts\\BattSuspendTimeout"), 0, REG_DWORD, (LPBYTE)&dwData, sizeof(DWORD)))
{
return FALSE;
}
```
but it does... | There are a two problems with what you are doing:
1: RegSetValueEx does not take a path, only a valuename. So you need to open the key path first.
e.g.
```
HKEY key;
if(ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Control\\Power\\Timeouts", 0, 0, &key))
{
if(RegSetValueEx(key, _T... | RegSetValueEx returns a descriptive error code. You can get a human-readable message out of this error code using FormatMessage and possibly via the Error Lookup tool, or the @ERR facility in VS. The code you have looks correct so see what the error message tells you. | Edit Registry Values | [
"",
"c++",
"windows-mobile",
"registry",
"pocketpc",
""
] |
I'm using a decimal column to store money values on a database, and today I was wondering what precision and scale to use.
Since supposedly char columns of a fixed width are more efficient, I was thinking the same could be true for decimal columns. Is it?
And what precision and scale should I use? I was thinking prec... | If you are looking for a one-size-fits-all, I'd suggest `DECIMAL(19, 4)` is a popular choice (a quick Google bears this out). I think this originates from the old VBA/Access/Jet Currency data type, being the first fixed point decimal type in the language; `Decimal` only came in 'version 1.0' style (i.e. not fully imple... | We recently implemented a system that needs to handle values in multiple currencies and convert between them, and figured out a few things the hard way.
**NEVER USE FLOATING POINT NUMBERS FOR MONEY**
Floating point arithmetic introduces inaccuracies that may not be noticed until they've screwed something up. All valu... | Storing money in a decimal column - what precision and scale? | [
"",
"sql",
"database",
"database-design",
"currency",
""
] |
I have a large existing c++ codebase. Typically the users of the codebase edit the source with gvim, but we'd like to start using the nifty IDE features in Eclipse. The codebase has an extensive directory hierarchy, but the source files use include directives without paths due to some voodoo we use in our build process... | This feature has already been implemented in the current CDT development stream and will be available in CDT 6.0, which will be released along with Eclipse 3.5 in June 2009.
Basically if you have an #include and the header file exists somewhere in your project then CDT will be able to find it without the need to manua... | The way that CDT manages build paths is by looking at the .cdtbuild xml file in the base of your projects directory (it might be a different name on windows... not sure)
In this you should see something like
```
<option id="gnu.c.compiler.option.include.paths....>
<listoptionValue builtIn="false" value=""${works... | Search entire project for includes in Eclipse CDT | [
"",
"c++",
"eclipse",
"eclipse-cdt",
""
] |
I've always wondered why the C++ Standard library has instantiated basic\_[io]stream and all its variants using the `char` type instead of the `unsigned char` type. `char` means (depending on whether it is signed or not) you can have overflow and underflow for operations like get(), which will lead to implementation-de... | Possibly I've misunderstood the question, but conversion from unsigned char to char isn't unspecified, it's implementation-dependent (4.7-3 in the C++ standard).
The type of a 1-byte character in C++ is "char", not "unsigned char". This gives implementations a bit more freedom to do the best thing on the platform (for... | I have always understood it this way: the purpose of the `iostream` class is to read and/or write a stream of characters, which, if you think about it, are abstract entities that are only represented by the computer using a character encoding. The C++ standard makes great pains to avoid pinning down the character encod... | Why do C++ streams use char instead of unsigned char? | [
"",
"c++",
"types",
"stream",
"overflow",
"iostream",
""
] |
I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the `HttpRequest` object?
My `HttpRequest.GET` currently returns an empty `QueryDict` object.
I'd like to learn how to do this without a library, so I can ... | When a URL is like `domain/search/?q=haha`, you would use `request.GET.get('q', '')`.
`q` is the parameter you want, and `''` is the default value if `q` isn't found.
However, if you are instead just configuring your `URLconf`\*\*, then your captures from the `regex` are passed to the function as arguments (or named ... | To clarify [camflan](https://stackoverflow.com/users/22445/camflan)'s [explanation](https://stackoverflow.com/a/150518/11573842), let's suppose you have
* the rule `url(regex=r'^user/(?P<username>\w{1,50})/$', view='views.profile_page')`
* an incoming request for `http://domain/user/thaiyoshi/?message=Hi`
The URL dis... | How to get GET request values in Django? | [
"",
"python",
"django",
"url",
"get",
"url-parameters",
""
] |
At the risk of being downmodded, I want to ask what the best mechanism (best is obviously subjective for the practice violation inherent here) for viewing data from a table, using C#, with a *lot* of columns. By a lot, I mean something like 1000.
Now before you get all click happy, or throw out responses like "why the... | Ok, what turned out to be the right answer for me was to use the [ReportViewer control](http://msdn.microsoft.com/en-us/library/ms251671(VS.80).aspx), but not in any manner documented in MSDN. The problem is that I have dynamic data, so I need a dynamic report, and all of the tutorials, etc. seem to assume you have the... | If you're going to implement your own custom user control, you could do a Fisheye Grid like this:
> [Dead image link](http://img145.imageshack.us/img145/6793/nothingbettertodocd5.jpg)
This example shows a full-size 3x4 panel moving around within a 9x10 table. Since (I assume) you don't need to edit this data, the UI ... | Best way to view a table with *lots* of columns? | [
"",
"c#",
"database",
"reporting",
""
] |
What I am looking for is the equivalent of `System.Windows.SystemParameters.WorkArea` for the monitor that the window is currently on.
**Clarification:** The window in question is `WPF`, not `WinForm`. | `Screen.FromControl`, `Screen.FromPoint` and `Screen.FromRectangle` should help you with this. For example in WinForms it would be:
```
class MyForm : Form
{
public Rectangle GetScreen()
{
return Screen.FromControl(this).Bounds;
}
}
```
I don't know of an equivalent call for WPF. Therefore, you need to do s... | You can use this to get desktop workspace bounds of the primary screen:
[`System.Windows.SystemParameters.WorkArea`](http://msdn.microsoft.com/en-us/library/system.windows.systemparameters.workarea.aspx)
This is also useful for getting just the size of the primary screen:
[`System.Windows.SystemParameters.PrimaryScr... | How can I get the active screen dimensions? | [
"",
"c#",
"wpf",
""
] |
Unsure if I've phrased this correctly, but in the callback how do I reference the controls property of the base class?
This has been bugging me for some time and I usually work around it, but I'd be grateful if anybody can enlighten me on how I should do this properly.
```
var base = function() {
var controls = {... | Use the power of closures:
```
var base = function() {
var controls = {};
return {
init: function(c) {
this.controls = c
},
foo: function(args) {
var self = this;
this.init(args.controls);
$(this.controls.DropDown).change... | Although [closures](https://stackoverflow.com/questions/254200/access-parent-property-in-jquery-callback#254233) are [preferred](https://stackoverflow.com/questions/254200/access-parent-property-in-jquery-callback#254237), you could also use jquery `bind` to pass an object along:
```
var base = function() {
var co... | Access parent property in jQuery callback | [
"",
"javascript",
"jquery",
""
] |
Uhm I'm not sure if anyone has encountered this problem
a brief description is on IE6 any `<select>` objects get displayed over any other item, even div's... meaning if you have a fancy javascript effect that displays a div that's supposed to be on top of everything (e.g: lightbox, multibox etc..) onclick of a certa... | You don't have to hide every `select` using a loop. All you need is a CSS rule like:
```
* html .hideSelects select { visibility: hidden; }
```
And the following JavaScript:
```
//hide:
document.body.className +=' hideSelects'
//show:
document.body.className = document.body.className.replace(' hideSelects', '');
``... | There is a plugin for jquery called [bgiframe](http://plugins.jquery.com/project/bgiframe) that makes the iframe method quite easy to implement.
Personally, as a web developer, I'm to the point where I no longer care about the user experience in IE6. I'll make it render as close to "correct" as possible, and make sure... | iframe shimming or ie6 (and below) select z-index bug | [
"",
"javascript",
"internet-explorer-6",
"shim",
""
] |
FORTRAN provides several functions to convert a double precision number to an integral value. The method used for truncation/rounding differs. I am converting complex scientific algorithms which use these.
According to FORTRAN documentation:
**aint(x)** returns the integral value between x and 0, nearest x.
**anin... | From your definitions of the calls, **`nint`** and **`anint`** are provided by `Math.Round` using `MidpointRounding.AwayFromZero`.
For **`aint`**, an explicit cast from `double` to `int` will achieve that result. | From what I can see, `aint()` is just `Math.Floor()`.
For the other two, I think you are right that the only difference is the return type: `nint()` returns an actual integer, while `anint()` returns a double (fortran: real) that happens to have an integral value. | Matching FORTRAN rounding in C# | [
"",
"c#",
"fortran",
"rounding",
"truncation",
""
] |
I'm passing small (2-10 KB)XML documents as input to a WCF service. now I've two option to read data values from incoming XML
1. Deserialize to a strongly typed object and use object properties to access values
2. use XPath to access values
which approach is faster? some statistics to support your answer would be gre... | I would deserialize it.
If you use xpath, you will deserialize (or "load") it to XmlDocument or something anyway. So both solutions use time deserializing. After this is done, xpath will be slower because of the time spent parsing that string, resolving names, executing functions and so on. Also, if you go with xpath,... | There's a third option of sticking with XML, but query with whatever XML API you're using - e.g. LINQ to XML makes queries relatively straightforward in code.
Have you already parsed the text into an XML document?
Are you convinced that this is actually a significant performance bottleneck in your code? (e.g. if you'... | XPath vs DeSerialization: which one is better in performance for read operations | [
"",
"c#",
"wcf",
"performance",
"serialization",
"xpath",
""
] |
I have an app that is failing on the install. The vendor says I probably have ini\_set() disabled. How can I check this? | I did some research on this, and it turns out that sometimes ini\_set will not return FALSE, but an empty string. This is mentioned in the URL pointed out by gabriel1836. The best way to check if it works is to first check the disable\_functions flag in php.ini to see if it is disabled, and then (if it is not disabled)... | You might want to take a look at the CHANGEABLE directives in php.ini:
<https://www.php.net/manual/en/ini.php#ini.list>
In regard to verify whether an ini\_set function worked, you can check the return value to make certain that it worked:
<https://www.php.net/manual/en/function.ini-set.php>
The code would look somet... | How do I check if ini_set() is enabled either in the global PHP.INI or in my PHP script? | [
"",
"php",
"ini-set",
""
] |
How can I transform a `String` value into an `InputStreamReader`? | [ByteArrayInputStream](http://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html) also does the trick:
```
InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) );
```
Then convert to reader:
```
InputStreamReader reader = new InputStreamReader(is);
``` | I also found the apache commons `IOUtils` class , so :
```
InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));
``` | How do I turn a String into a InputStreamReader in java? | [
"",
"java",
"string",
"stream",
""
] |
This was an job placement interview I faced. They asked whether we can realloc Array, I told yes. Then They asked - then why we need pointers as most of the people give reason that it wastes memory space. I could not able to give satisfactory answer. If any body can give any satisfactory answer, I'll be obliged. Please... | You can only reallocate an array that was allocated dynamically. If it was allocated statically, it cannot be reallocated [safely].\*
Pointers hold addresses of data in memory. They can be allocated, deallocated, and reallocated dynamically using the new/delete operators in C++ and malloc/free in C.
I would strongly ... | The phrasing is a bit strange, but to me it seems like the interview question was an open ended question designed to get you to explain what you know about arrays, pointers, dynamic memory allocation, etc. If I was the interviewer I'd want the candidate to articulate the differences between `int *a = malloc(10 * sizeof... | can realloc Array, then Why use pointers? | [
"",
"c++",
"c",
"pointers",
"data-structures",
""
] |
I have a query that is currently using a correlated subquery to return the results, but I am thinking the problem could be solved more eloquently perhaps using ROW\_NUMBER().
The problem is around the profile of a value v, through a number of years for an Item. Each item has a number of versions, each with its own pro... | I would do it with a CTE:
```
WITH Result AS
(
SELECT Row_Number() OVER (PARTITION BY ItemId, Year
ORDER BY ItemversionId DESC) AS RowNumber
,ItemId
,ItemversionId
,Year
,Value
FROM table
)
SELECT ItemId
,ItemversionId
,Year
,Value
FROM Result
WHERE RowNumber = 1
ORDER BY ItemId, Year... | I think it's okay how you do it. You could check if there is a **composite index on ItemId and Year**.
You could inspect the query plan to see the impact of that query.
If there is an "Item" table in your database you could try another approach. **Insert a column ItemVersionId** in that table and make sure you update... | T SQL - Eloquent replacement of Correlated Subquery | [
"",
"sql",
"sql-server-2005",
""
] |
I am pretty new to php, but I am learning! I have a simple form on a client website. I am testing the form and when I click submit, I get the following error:
Form Mail Script
```
Wrong referrer (referring site). For security reasons the form can only be used, if the referring page is part of this website.
Note for ... | The referrer is a value that's usually sent to a server by a client (your browser) along with a request. It indicates the URL from which the requested resource was linked or submitted. This error is part of a security mechanism in FormMail that is intended to prevent the script from handling input that doesn't originat... | You are obviously using the Form Mail script on your page. It has a security feature that prevents other domains from submitting to the form. This is done to prevent bots from using the script to send out spam.
In the configuration for the form mail script or in the script itself, you will find an array or variable wi... | PHP "Wrong referrer" error when submitting a mail form | [
"",
"php",
"formmail",
""
] |
I'm writing a program in C# that runs in the background and allows users to use a hotkey to switch keyboard layouts in the active window. (Windows only supports `CTRL`+`SHIFT` and `ALT`+`SHIFT`)
I'm using RegisterHotKey to catch the hotkey, and it's working fine.
The problem is that I can't find any API to change the... | Another way that may be acceptable if you are writing something just for yourself: define a separate key combination for every layout (such as Alt+Shift+1, etc), and use [SendInput](http://msdn.microsoft.com/en-us/library/ms646310.aspx "SendInput") to switch between them.
The circumstances in which this is usable are ... | ```
PostMessage(handle,
WM_INPUTLANGCHANGEREQUEST,
0,
LoadKeyboardLayout( StrCopy(Layout,'00000419'), KLF_ACTIVATE)
);
``` | Change Keyboard Layout for Other Process | [
"",
"c#",
".net",
"winapi",
"keyboard-layout",
"registerhotkey",
""
] |
I'm playing around with BCEL. I'm not using it to generate bytecode, but instead I'm trying to inspect the structure of existing compiled classes.
I need to be able to point to an arbitrary .class file anywhere on my hard drive and load a [JavaClass](http://jakarta.apache.org/bcel/apidocs/org/apache/bcel/classfile/Jav... | The straightforward way is to create a ClassParser with the file name and call parse(). Alternatively you can use SyntheticRepository and supply a classpath (that is not your classpath, IYSWIM). | The existing .class can be class loaded to java lang class object. Then it can be converted into BCEL intermediate javaclass structure. The following code may help:-
```
Class<?> javaClass1 = null;
javaClass1 = ucl.loadClass("com.sample.Customer");
org.apache.bcel.classfile.JavaClass javaClazz1=org.apache.bcel.Reposit... | Create a BCEL JavaClass object from arbitrary .class file | [
"",
"java",
"bytecode",
"bcel",
""
] |
OK, I have a somewhat complicated system in C++. In a nutshell, I need to add a method to a third party abstract base class. The third party also provides a ton of derived classes that also need the new functionality.
I'm using a library that provides a standard Shape interface, as well as some common shapes.
```
cla... | We had a very similar problem in a project and we solved it by just NOT deriving ImprovedShape from Shape. If you need Shape functionality in ImprovedShape you can dynamic\_cast, knowing that your cast will always work. And the rest is just like in your example. | Why does this class need to derive from shape?
```
class ImprovedShape : public virtual Shape
{
virtual double GetArea() const = 0;
};
```
Why not just have
```
class ThingWithArea
{
virtual double GetArea() const = 0;
};
```
ImprovedSquare is a Shape and is a ThingWithArea | Looking for a better way than virtual inheritance in C++ | [
"",
"c++",
"inheritance",
"multiple-inheritance",
""
] |
I have been thinking about starting a side project at home to exercise my brain a bit. [Reversi](http://en.wikipedia.org/wiki/Reversi) looks like a simply game, where mobility has a profound effect on game play.
It is at least a step up from tic tac toe. This would be a single player against an AI of some sort.
I am t... | In overall, issues you will end up running onto will depend on you and your approaches. Friend tends to say that complex is simple from different perspective.
Choice of graphics library depends about what kind of game you are going to write? OpenGL is common choice in this kind of projects, but you could also use some... | Issues...
Well, just be sure when writing the strategy part of the game, not to simply do the move that gives you the most pieces. You must also give weight to board position. For example, given the opportunity to place a piece in a board corner should take priority over any other move (besides winning the game) as th... | How would you go about implementing the game reversi? (othello) | [
"",
"c++",
"graphics",
""
] |
I’m trying to implement a dictionary for use with WCF. My requirements are:
* actual (private variable or base
class) type equivalent to
Dictionary
* Comparer
= `System.StringComparer.InvariantCultureIgnoreCase`
* Custom (override/new) Add(key,
value) method (to include
validations).
* Override ToString()
* ... | * Use the `CollectionDataContract` attribute as jezell suggested
* Manually generate the reference (proxy) code with SvcUtil, using the /collectionType parameter. This parameter is not supported by the vs2008 service reference GUI.
Source: [WCF Collection Type Sharing](http://www.codeproject.com/KB/WCF/WCFCollectionTy... | Add CollectionDataContract to the Dictionary class:
For more information on using collection data contracts to implement dictionaries, check this link:
<http://msdn.microsoft.com/en-us/library/aa347850.aspx> | How to implement an inherited Dictionary over WCF | [
"",
"c#",
"wcf",
"c#-3.0",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.