Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part.
I'd like to do the equivalent of:
```
iconv -t utf-8 $file > converted/$file # this is shell code
```
Thanks! | You can use the [codecs module](https://docs.python.org/2/library/codecs.html), like this:
```
import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
with codecs.open(targetFileName, "w", "utf-8") as targetFile:
... | This worked for me in a small test:
```
sourceEncoding = "iso-8859-1"
targetEncoding = "utf-8"
source = open("source")
target = open("target", "w")
target.write(unicode(source.read(), sourceEncoding).encode(targetEncoding))
``` | How to convert a file to utf-8 in Python? | [
"",
"python",
"encoding",
"file",
"utf-8",
""
] |
I'm messing around with 2D game development using C++ and DirectX in my spare time. I'm finding that the enterprisey problem domain modeling approach doesn't help as much as I'd like ;)
I'm more or less looking for a "best practices" equivalent to basic game engine design. How entities should interact with each other,... | [Gamedev.net](http://www.gamedev.net) is usually where I turn to get an idea of what other people in the game development community are doing.
That said, I'm afraid that you'll find that the idea of "best practices" in game development is more volatile than most. Games tend to be such specialized applications that it'... | Make a game. After you're done, make another. Look at what you liked and what you didn't like and then make another.
Seriously though, you can read all of the "best practices" guides to game design you'd like, but ultimately it comes down to experience. The only way to get experience is to sit down and write a game. A... | What are some good resources on 2D game engine design? | [
"",
"c++",
"directx",
""
] |
I am analyzing a .dmp file that was created and I have a call stack which gives me a lot of info. But I'd like to double click on the call stack and have it bring me to the source code.
I can right click on the call stack and select symbol settings.. where I can put the location to the PDB. But there is no option for ... | The source code directory is unfortunately hard coded into the pdb's however if you know the folders required you can use windows concept of symbolic links, junctions.
I use the tool [Junction Link Magic](http://www.rekenwonder.com/linkmagic.htm) | Read [this article](http://msdn.microsoft.com/en-us/magazine/cc163563.aspx) about how to set up a Source Server (aka SrcSrv) integration at your site.
I took the time to follow these steps for our codebase, and now we are able to take a .dmp file from any build of our software in the past 6 months... get a stack trace... | how do I specify the source code directory in VS when looking at the call stack of a memory dump? | [
"",
"c++",
"visual-studio",
"crash-reports",
"memory-dump",
""
] |
What is SafeHandle? how does it differ from IntPtr? When should I use one? What are its advantages? | I think [MSDN](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.aspx) is pretty clear in definition:
> The SafeHandle class provides critical
> finalization of handle resources,
> preventing handles from being
> reclaimed prematurely by garbage
> collection and from being recycled by
>... | You should use a derivative of SafeHandle whenever possible where managed code is receiving an IntPtr from unmanaged code. While the name, general use, and even documentation of the SafeHandle class implies that it is only supposed to be used to contain Windows operating system handles, a few internal .NET framework cl... | Safehandle in C# | [
"",
"c#",
".net",
""
] |
I'm working on a method that accepts an expression tree as a parameter, along with a type (or instance) of a class.
The basic idea is that this method will add certain things to a collection that will be used for validation.
```
public interface ITestInterface
{
//Specify stuff here.
}
private static void DoSome... | Collecting PropertyInfo objects from Expression.Body seems similar to [my solution](https://stackoverflow.com/questions/123088/possible-pitfalls-of-using-this-extension-method-based-shorthand#144982) to another question. | I rely heavily on expression trees to push a lot of what I want to do with my current application to compile-time, i.e. static type checking.
I traverse expression trees to translate them into something else which "makes sense".
One thing I've ended up doing a lot is that instead of URLs I rely on a MVC like approach... | Advice on C# Expression Trees | [
"",
"c#",
"reflection",
"expression-trees",
""
] |
I am asking this out of a curiosity. Basically my question is when you have a database which needs a row entry to have things which act like flags, what is the best practice? A good example of this would be the badges on stack overflow, or the operating system field in bugzilla. Any subset of the flags may be set for a... | If you really need an unbounded selection from a closed set of flags (e.g. stackoverflow badges), then the "relational way" would be to create a table of flags and a separate table which relates those flags to your target entities. Thus, users, flags and usersToFlags.
However, if space efficiency is a serious concern ... | Generally speaking, I avoid bitmask fields. They're difficult to read in the future and they require a much more in-depth knowledge of the data to understanding.
The relational solution has been proposed previously. Given the example you outlined, I would create something like this (in SQL Server):
```
CREATE TABLE U... | Flags in a database rows, best practices | [
"",
"sql",
"database",
"flags",
""
] |
I'm relatively new to web application programming so I hope this question isn't too basic for everyone.
I created a HTML page with a FORM containing a dojox datagrid (v1.2) filled with rows of descriptions for different grocery items. After the user selects the item he's interested in, he will click on the "Submit" bu... | You could just use a hidden input field; that gets transmitted as part of the form.
```
<html>
<head>
</head>
<body>
<script type="text/javascript">
function updateSelectedItemId() {
document.myForm.selectedItemId.value = 2;
alert(document.myForm.selectedItemId.value);
// For yo... | It's good one, but better is to use some script language such as JSP,PHP, ASP....and you can use simple POST and GET methods. | What is the best practice for passing variables from one HTML page to another? | [
"",
"javascript",
"html",
"grails",
"dojo",
""
] |
I wrote a C# application for a client a couple of years ago, but I no longer have the source code. All I have is the EXE that I deployed on the client's PC. Is there a way I can generate C# source code from the EXE? | [Reflector](http://www.red-gate.com/products/reflector/index.htm) and its add-in [FileDisassembler](http://www.denisbauer.com/Home/ReflectorFileDisassembler).
Reflector will allow to see the source code. FileDisassembler will allow you to convert it into a VS solution. | When Red Gate said there would no longer be a free version of .Net Reflector, I started using [ILSpy](https://github.com/icsharpcode/ILSpy/) and Telerik's [JustDecompile](http://www.telerik.com/products/decompiler.aspx). I have found ILSpy to decompile more accurately than JustDecompile (which is still in Beta). Red Ga... | How do I decompile a .NET EXE into readable C# source code? | [
"",
"c#",
".net",
"reverse-engineering",
"decompiling",
""
] |
In my understanding of Servlet, the Servlet will be instantiated by the Container, its `init()` method will be called once, and the servlet will live like a singleton until the JVM shuts down.
I do not expect my servlet to be serialized, since it will be constructed new when the app server recovers or is starts up nor... | Technically, I believe the servlet container is allowed to "passivate" the servlet object to disk, in a similar way that EJB session beans can be. So you're correct to ask the question if your app will fail due to non-serializable fields.
In practise, I've never heard of a container doing this, so it's really just leg... | HttpServlet should by serialized to disk and survive restart of servlet container. For example tomcat allows you to set up flag which enable this kind of survive. The next option is transfer using JNDI. This is not garbage, it is used only in extreme use cases. | Why does HttpServlet implement Serializable? | [
"",
"java",
"session",
"servlets",
"serializable",
""
] |
We'd like to override DataGridView's default behavior when using a mouse wheel with this control. By default, the DataGridView scrolls a number of rows equal the SystemInformation.MouseWheelScrollLines setting. What we'd like to do is scroll just one item at a time.
(We display images in the DataGridView, which are so... | I just did a little scrounging and testing of my own. I used [Reflector](http://www.red-gate.com/products/reflector/) to investigate and discovered a couple things. The `MouseWheel` event provides a `MouseEventArgs` parameter, but the `OnMouseWheel()` override in `DataGridView` casts it to **`Handled`**`MouseEventArgs`... | **UPDATE:** Since I've now learned that the `DataGridView` has a `MouseWheel` event, I've added a second, simpler override.
One way to accomplish this is to subclass the `DataGridView` and override the `WndProc` to add special handling of the `WM_MOUSEWHEEL` message.
This example catches the mouse wheel movement and ... | How can you make a DataGridView scroll one item at a time using the mouse wheel? | [
"",
"c#",
".net",
"datagridview",
""
] |
I need to create an access (mdb) database without using the ADOX interop assembly.
How can this be done? | Before I throw away this code, it might as well live on stackoverflow
Something along these lines seems to do the trick:
```
if (!File.Exists(DB_FILENAME))
{
var cnnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DB_FILENAME;
// Use a late bound COM object to create a new catalog. This is so we avoid... | I've done the same as Autsin, create an Access db then included it into my project as a managed resource. Once there, it is included in the compiled code and you can copy it to hard disk as many times as you want. Empty databases are relatively small too, so there isn't much overhead.
The added bonus is the ability to... | How do I create a Microsoft Jet (Access) database without an interop assembly? | [
"",
"c#",
"interop",
"jet",
""
] |
I have created a non-visual component in C# which is designed as a placeholder for meta-data on a form.
The component has a property which is a collection of custom objects, this object is marked as Serializable and implements the GetObjectData for serilizing and public constuctor for deserilizing.
In the resx file ... | I have since discovered where I was going wrong.
The component I was implementing a custom collection (inherited from CollectionBase), I changed this to a List and added the DesignerSerializationVisibility(DesignerSerializationVisibility.Content) attribute to the List property, this list is also read-only. This would ... | You might want to try the alternate approach of getting everything to serialize as generated code. To do that is very easy. Just implement your non-visual class from **Component**. Then expose your collection as you already are but ensure each object placed into the collection is itself derived from **Component**. By d... | Design time serialization in C# | [
"",
"c#",
".net",
"serialization",
""
] |
What is the easiest way to check if events have been logged in the eventlog during a period of time?
I want to perform a series of automated test steps and then check if any errors were logged to the Application Event Log, ignoring a few sources that I'm not interested in. I can use System.Diagnostics.EventLog and the... | Just to be a good Wiki citizen and strive for completion, there are other ways. I didn't suggest it earlier because it is complete overkill for something that is only going to be run in-house as part of a test suite, and you said right in the title you wanted something easy.
But if you need to see events as they occur... | That having been said, here's an answer that actually should be pretty straightforward even for your test application and is .NET Framework specific.
You need to open the EventLog before you start your test, and subscribe an event handler to the [EventLog.EntryWritten](http://msdn.microsoft.com/en-us/library/system.di... | What is the easiest way using .net to check if events have been logged in the eventlog? | [
"",
"c#",
".net",
"testing",
"event-log",
""
] |
I am currently creating a custom control that needs to handle animation in a C# project. It is basically a listbox that contains a fixed number of elements that are subject to move. An element (another user control with a background image and a couple of generated labels) can move upwards, downwards or be taken out of ... | your best bet for flicker-free animation is to do the painting yourself (use the Graphics object in the Paint event handler) and use double-buffering. In your custom control you will need code like this in the constructor:
```
this.SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer |
ControlSt... | A similar discussion took place this morning on this question. [visual c# form update results in flickering.](https://stackoverflow.com/questions/181374/visual-c-form-update-results-in-flickering) so I will be lazy and give the same answer I gave there:
You could try to call **this.SuspendLayout();** before you start ... | What is the best way to do a flicker-free animated C# custom control? | [
"",
"c#",
"animation",
"controls",
"doublebuffered",
""
] |
I've got a column in a database table (SQL Server 2005) that contains data like this:
```
TQ7394
SZ910284
T r1534
su8472
```
I would like to update this column so that the first two characters are uppercase. I would also like to remove any spaces between the first two characters. So `T q1234` would become `TQ1234`.
... | Here is a solution:
**EDIT:** **Updated to support replacement of multiple spaces between the first and the second non-space characters**
```
/* TEST TABLE */
DECLARE @T AS TABLE(code Varchar(20))
INSERT INTO @T SELECT 'ab1234x1' UNION SELECT ' ab1234x2'
UNION SELECT ' ab1234x3' UNION SELECT 'a b1234x4' ... | ```
UPDATE YourTable
SET YourColumn = UPPER(
SUBSTRING(
REPLACE(YourColumn, ' ', ''), 1, 2
)
)
+
SUBSTRING(YourColumn, 3, LEN(YourColumn))
``` | Uppercase first two characters in a column in a db table | [
"",
"sql",
"sql-server",
"t-sql",
"language-agnostic",
""
] |
Often I want to add a value to a table or update the value if its key already exists. This can be accomplished in several ways, assuming a primary or unique key is set on the 'user\_id' and 'pref\_key' columns in the example:
**1. Blind insert, update if receiving a duplicate key error:**
```
// Try to insert as a ne... | Will there be concurrent INSERTs to these rows? DELETEs?
"ON DUPLICATE" sounds great (the behavior is just what you want) provided that you're not concerned about portability to non-MySQL databases.
The "blind insert" seems reasonable and robust provided that rows are never deleted. (If the INSERT case fails because ... | have a look at the ON DUPLICATE KEY syntax in <http://dev.mysql.com/doc/refman/5.0/en/insert-select.html>
```
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
SELECT ...
[ ON DUPLICATE KEY UPDATE col_name=expr, ... ]
``` | Is there a disadvantage to blindly using INSERT in MySQL? | [
"",
"sql",
"mysql",
""
] |
For PHP
I have a date I want line wrapped.
I have $date = '2008-09-28 9:19 pm';
I need the first space replaced with a br
to become
```
2008-09-28<br>9:19 pm
```
If it wasn't for that second space before PM, I would just str\_replace() it. | ```
$date = preg_replace('/ /', '<br>', $date, 1);
``` | `s/ /<br\/>/` should do it. Though PHP regex might be greedy and replace all spaces.
## edit
I support Ben Hoffstein's PHP solution. Where possible, avoid regex as it nearly *always* has unintended side effects. | How to do a regex replacement, adding characters in a date string? | [
"",
"php",
"regex",
""
] |
In a few large projects i have been working on lately it seems to become increasingly important to choose one or the other (XML or Annotation). As projects grow, consistency is very important for maintainability.
My questions are: what are the advantages of XML-based configuration over Annotation-based configuration a... | Annotations have their use, but they are not the one silver bullet to kill XML configuration. I recommend mixing the two!
For instance, if using Spring, it is entirely intuitive to use XML for the dependency injection portion of your application. This gets the code's dependencies away from the code which will be using... | There is a wider issue here, that of externalised vs inlined meta-data. If your object model is only ever going to persisted in one way, then inlined meta-data (i.e. annotations) are more compact and readable.
If, however, your object model was reused in different applications in such a way that each application wante... | Xml configuration versus Annotation based configuration | [
"",
"java",
"xml",
"spring",
"annotations",
""
] |
Our situation is as follows, but I'm curious about this problem in any situation.
We have a framework consisting of 4 projects:
* beans
* util
* framework
* web
We also have modules that need a version and depend on a version of beans and util.
Finally we have a customer project that consists of a specific version ... | We use major.minor.bugfix. A major release only happens for huge changes. A minor release is called for when there is an API change. All other releases are bugfix releases. There's definitely utility in having a build or revision number there too for troubleshooting, although if you've got really rigorous CM you might ... | I use {major}.{minor}.{buildday}.{sequential}. For Windows, we use the utilities [stampver.exe](http://blog.dixo.net/downloads/stampver-win32-version-resource-stamping/) and [UpdateVersion.exe](http://code.mattgriffith.net/UpdateVersion/) for .NET projects that handle that mostly automatically. | How do you version your projects and manage releases? | [
"",
"java",
"language-agnostic",
"maven-2",
"versioning",
""
] |
I'm about to inherit a rather large Java enterprise project that has a large amount of third party dependencies. There is at least seventy JARs included and some of them would seem to be unused e.g. spring.jar which I know isn't used.
It seems that over the years as various developers have touched upon the code base t... | Personally, I think you have to start by assessing the scale of the problem. It's going to be fairly painful, but I'd make a list of the dependencies and work out exactly which parts of the project use which ones.
Then I'd work out exactly what features of each you're actually making use of (in many cases, you'll end ... | structure101 <http://www.headwaysoftware.com/products/structure101/index.php>
It's a great tool for showing dependencies. I've been using it for a couple of years. | How does one weed out dependencies in a large project? | [
"",
"java",
"dependencies",
"project",
""
] |
I have an `<img>` in an HTML document that I would like to highlight as though the user had highlighted it using the mouse. Is there a way to do that using JavaScript?
I only need it to work in Mozilla, but any and all information is welcome.
*EDIT: The reason I want to select the image is actually not so that it app... | Here's an example which selects the first image on the page (which will be the Stack Overflow logo if you test it out on this page in Firebug):
```
var s = window.getSelection()
var r = document.createRange();
r.selectNode(document.images[0]);
s.addRange(r)
```
Relevant documentation:
* <http://developer.mozilla.org... | You might also want to call s.removeAllRanges() before s.addRange(r). | How can I select an <img> element programmatically using JavaScript? | [
"",
"javascript",
"html",
"firefox",
"dom",
""
] |
Currently we have a table that we use to track inivitations. We have an email field that is indexed but we also have three optional keys that the user can specify when adding new record emails. We don't allow duplicates so we have to query if the email plus the optional keys already exists. Currently the keys are only ... | Personally I would recommend this approach.
Try the method with the single index that covers everything, if I recall correctly it will still perform well if you only query on the first of the included columns. Once you have the index in place, run the Index Advisor.
Then try the other route and repeat.
It really dep... | It depends on how often the table is updated, and how complex the indexes are. If you go nuts creating indexes, then every time a record is inserted/updated/deleted, every index will have to be modified to reflect that information.
If you only put three indexes on, and they are relatively simple, then you shouldn't ha... | Individual indexes vs multiple field indexes | [
"",
"sql",
"indexing",
""
] |
Is there a more efficient way to convert an HTMLCollection to an Array, other than iterating through the contents of said collection and manually pushing each item into an array? | ```
var arr = Array.prototype.slice.call( htmlCollection )
```
will have the same effect using "native" code.
**Edit**
Since this gets a lot of views, note (per @oriol's comment) that the following more concise expression is *effectively* equivalent:
```
var arr = [].slice.call(htmlCollection);
```
But note per @J... | not sure if this is the most efficient, but a concise ES6 syntax might be:
```
let arry = [...htmlCollection]
```
---
Edit: Another one, from Chris\_F comment:
```
let arry = Array.from(htmlCollection)
``` | Most efficient way to convert an HTMLCollection to an Array | [
"",
"javascript",
"arrays",
"object",
""
] |
I am displaying a scrolled data table in a web page. This table has several thousands of dynamic rows, so it is loaded from the server (via AJAX).
The user can scroll up and down, so what I need is to **detect when the user reaches the end of the scrollbar** (that is, the last row at the bottom of the table) in order ... | Thank you for your answers. That's my final working code (inspired by Greg and [ajaxian.com](http://ajaxian.com/archives/implementing-infinite-scrolling-with-jquery)), that uses some jQuery functions and works with the [YUI DataTable](http://developer.yahoo.com/yui/datatable/).
```
$(".yui-dt-bd").scroll(load_more);
... | I'm not familiar with the specific element you are using, but in order
to implement this on a full size window, you can do the following:
```
$wnd.onscroll = function() {
if (($wnd.height - $wnd.scrollTop) < SOME_MARGIN) then doSomething();
};
```
Where scrollTop is essentially "how many pixels have been scrolled... | "Endless scrolling" effect in a HTML table | [
"",
"javascript",
"datatable",
"yui",
"scroll",
"dhtml",
""
] |
Could you please explain what the practical usage is for the `internal` keyword in C#?
I know that the `internal` modifier limits access to the current assembly, but when and in which circumstance should I use it? | Utility or helper classes/methods that you would like to access from many other classes within the same assembly, but that you want to ensure code in other assemblies can't access.
From [MSDN](https://web.archive.org/web/20130305112130/http://msdn.microsoft.com/en-us/library/7c5ka91b(v=vs.80).aspx) (via archive.org):
... | If Bob needs BigImportantClass then Bob needs to get the people who own project A to sign up to guarantee that BigImportantClass will be written to meet his needs, tested to ensure that it meets his needs, is documented as meeting his needs, and that a process will be put in place to ensure that it will never be change... | Practical uses for the "internal" keyword in C# | [
"",
"c#",
".net-assembly",
"access-modifiers",
"internals",
""
] |
I've noticed RAII has been getting lots of attention on Stackoverflow, but in my circles (mostly C++) RAII is so obvious its like asking what's a class or a destructor.
So I'm really curious if that's because I'm surrounded daily, by hard-core C++ programmers, and RAII just isn't that well known in general (including ... | For people who are commenting in this thread about RAII (resource acquisition is initialisation), here's a motivational example.
```
class StdioFile {
FILE* file_;
std::string mode_;
static FILE* fcheck(FILE* stream) {
if (!stream)
throw std::runtime_error("Cannot open file");
... | There are plenty of reasons why RAII isn't better known. First, the name isn't particularly obvious. If I didn't already know what RAII was, I'd certainly never guess it from the name. (Resource acquisition is initialization? What does that have to do with the destructor or cleanup, which is what *really* characterizes... | Do programmers of other languages, besides C++, use, know or understand RAII? | [
"",
"c++",
"language-agnostic",
"raii",
""
] |
What's the most efficient way to read a stream into another stream? In this case, I'm trying to read data in a Filestream into a generic stream. I know I could do the following:
1. read line by line and write the data to the stream
2. read chunks of bytes and write to the stream
3. etc
I'm just trying to find th... | Stephen Toub discusses a stream pipeline in his MSDN .NET matters column [here](http://msdn.microsoft.com/en-us/magazine/cc163290.aspx). In the article he describes a CopyStream() method that copies from one input stream to another stream. This sounds quite similar to what you're trying to do. | I rolled together a quick extension method (so VS 2008 w/ 3.5 only):
```
public static class StreamCopier
{
private const long DefaultStreamChunkSize = 0x1000;
public static void CopyTo(this Stream from, Stream to)
{
if (!from.CanRead || !to.CanWrite)
{
return;
}
var buffer ... | Read data in FileStream into a generic Stream | [
"",
"c#",
"stream",
""
] |
I need help understanding some C++ operator overload statements. The class is declared like this:
```
template <class key_t, class ipdc_t>
class ipdc_map_template_t : public ipdc_lockable_t
{
...
typedef map<key_t,
ipdc_t*,
less<key_t>> map_t;
...
```
The creator of the class has c... | These are typecast operators, so you can do this:
```
{
key_t key = iter;
ipdc_t *val = iter;
}
```
Or, since `ipdc_map_template::iterator` is a subclass of `std::map::iterator`, you can still use the original accessors (which I find more readable):
```
{
key_t key = (*iter).first;
ipdc_t *val = ... | The creator of the class has overridden the cast operators.
So by just assigning the iter to an object of the correct type it should auto cast itself via the methods into the correct values.
**N.B.**: The value type is being stored as a pointer. So when you extract the value you need to specify the pointer to the valu... | Operator overloading for C++ maps | [
"",
"c++",
"templates",
""
] |
What is the best way to manage the JavaScript files and the functions/objects context in an ASP.NET MVC app? | Google says <http://javascriptmvc.com/> | If you're looking for something like that, you should definitely check out [MooTools](http://mootools.net/) as they implement classes almost exactly the way you describe. Overall, I've found their approach to be very clean, extensible, and maintainable. For example, here is a class template I use to write all of my cla... | What is a good and known JavaScript MVC pattern? | [
"",
"javascript",
"asp.net-mvc",
"design-patterns",
""
] |
So i am reorganizing a winforms C# solution to help decouple and make it cleaner and more organized. The solution tracks a small business orders,etc . .
I have broken out the projects so far into
**App.View** - all GUI Related Code
**App.Data** - just data structures and interfaces. No other implementation code
*... | Actually, I think you have things a little off from a traditional layered architecture. Normally, the models of your data that your application works on would be kept in a business layer, along with the code to operate on them. Your data layer would have both the data models of your persistence framework and the code t... | You have specified that App.Data should contain only data structures and interfaces, no implementation code, which is fine if you want to do that, but that leaves you with nowhere to put your database access code except in your App.BusinessLogic assembly.
Perhaps you really need to rename App.Data to App.Model (or som... | Structuring a winforms C# solution | [
"",
"c#",
"winforms",
"model-view-controller",
"mvp",
"projects",
""
] |
A feature of C++ is the ability to create unnamed (anonymous) namespaces, like so:
```
namespace {
int cannotAccessOutsideThisFile() { ... }
} // namespace
```
You would think that such a feature would be useless -- since you can't specify the name of the namespace, it's impossible to access anything within it fr... | ~~The C++ Standard reads in section 7.3.1.1 Unnamed namespaces, paragraph 2:~~
> The use of the static keyword is
> deprecated when declaring objects in a
> namespace scope, the unnamed-namespace
> provides a superior alternative.
Static only applies to names of objects, functions, and anonymous unions, not to type d... | Putting methods in an anonymous namespace prevents you from accidentally violating the [One Definition Rule](http://en.wikipedia.org/wiki/One_Definition_Rule), allowing you to never worry about naming your helper methods the same as some other method you may link in.
And, as pointed out by [luke](https://stackoverflow... | Why should you prefer unnamed namespaces over static functions? | [
"",
"c++",
"static",
"namespaces",
"unnamed-namespace",
""
] |
I have a controller with an action method as follows:
```
public class InventoryController : Controller
{
public ActionResult ViewStockNext(int firstItem)
{
// Do some stuff
}
}
```
And when I run it I get an error stating:
> The parameters dictionary does not contain a valid value of type 'Syste... | Your routing needs to be set up along the lines of `{controller}/{action}/{firstItem}`. If you left the routing as the default `{controller}/{action}/{id}` in your `global.asax.cs` file, then you will need to pass in `id`.
```
routes.MapRoute(
"Inventory",
"Inventory/{action}/{firstItem}",
new { controller... | you can change firstItem to id and it will work
you can change the routing on global.asax (i do not recommed that)
and, can't believe no one mentioned this, you can call :
```
http://localhost:2316/Inventory/ViewStockNext?firstItem=11
```
In a @Url.Action would be :
```
@Url.Action("ViewStockNext", "Inventory", ne... | ASP.NET MVC - passing parameters to the controller | [
"",
"c#",
"asp.net-mvc",
""
] |
I haven't been around Java development for 8 years, but am starting to build a NetBeans Web Application. When I walk through the Web Application wizard, it asks for the server I'm going to be using.
What would be the best and simplest server for me to start using with NetBeans? | Since the NetBeans IDE is a Sun product, I would assume that the Glassfish application server would be a natural fit.
That said, one of the pluses of developing a web application in Java is that the interface for working with the http is standardized (i.e. the Servlet specification), so that you can pick any servlet c... | Unless you are deploying to a full J2EE application server, I would recommend using Tomcat. Tomcat can run as a standalone web/servlet/jsp server and avoids some of the complexities of a full J2EE app server.
The web development bundle for Netbeans will include installers for and automated integration with Glassfish a... | What web server should I use with NetBeans? | [
"",
"java",
"netbeans",
"webserver",
""
] |
I have been asking myself this question for a long time now. Thought of posting it. C# doesn't support Multiple Inheritance(this is the fact). All classes created in C# derive out of 'Object' class(again a fact).
So if C# does not support Multiple inheritance, then how are we able to extend a class even though it alre... | Joel's answer is correct. There is a difference between multiple inheritance and an inhertance tree (or derivation chain). In your example, you actually show an inhertance tree: One object inherits (derives) from another object higher in the tree. Multiple inheritance allows one object to inherit from multiple base cla... | You're confusing mutliple inheritance with an inheritance tree. You can inherit from something other than Object. It's just that Object is sitting way up there at the top of your tree. And someone can inherit your class, but because Object is still up there at the top that class will also inherit from object. Your "Mul... | Single Inheritance in C# - object class? | [
"",
"c#",
""
] |
So in my documentation it says:
> public event TreeViewPlusNodeCheckedEventHandler NodeChecked()
>
> You can use this event to run cause a method to run whenever the
> check-box for a node is checked on the tree.
So how do I add a method to my code behind file that will run when a node is checked? The method I want t... | You need to assign a delegate to the event and have it run the method you want. Something like :
TreeViewControl.NodeChecked += new TreeViewPlusNodeCheckedEventHandler(TOCNodeCheckedServer) | Just add a handler to the event.
```
myTreeView.NodeChecked += new TreeViewPlusNodeCheckedEventHandler(TOCNodeCheckedServer);
```
or (because instantiating the TreeViewPlusNodeCheckedEventHandler isn't actually necessary)
```
myTreeView.NodeChecked += TOCNodeCheckedServer;
``` | How can I use an event to cause a method to run? | [
"",
"c#",
".net",
"events",
"methods",
""
] |
What's the difference between:
```
class Child(SomeBaseClass):
def __init__(self):
super(Child, self).__init__()
```
and:
```
class Child(SomeBaseClass):
def __init__(self):
SomeBaseClass.__init__(self)
```
I've seen `super` being used quite a lot in classes with only single inheritance. I c... | The benefits of `super()` in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods.
However, it's almost impossible to use multiple-inheritance without `super()`. This includes common idioms like mixins, interfaces, abstract clas... | ## What's the difference?
```
SomeBaseClass.__init__(self)
```
means to call `SomeBaseClass`'s `__init__`. while
```
super().__init__()
```
means to call a bound `__init__` from the parent class that follows `SomeBaseClass`'s child class (the one that defines this method) in the instance's Method Resolution Order (... | What does 'super' do in Python? - difference between super().__init__() and explicit superclass __init__() | [
"",
"python",
"oop",
"inheritance",
"multiple-inheritance",
"super",
""
] |
I'm a long-time Windows developer, having cut my teeth on win32 and early COM. I've been working with .NET since 2001, so I'm pretty fluent in C# and the CLR. I'd never heard of Castle Windsor until I started participating in Stack Overflow. I've read the Castle Windsor "Getting Started" guide, but it's not clicking.
... | Castle Windsor is an inversion of control tool. There are others like it.
It can give you objects with pre-built and pre-wired dependencies right in there. **An entire object graph created via reflection and configuration rather than the "new" operator.**
Start here: <http://tech.groups.yahoo.com/group/altdotnet/mess... | Mark Seemann wrote and excellent book on DI (Dependency Injection) which is a subset of IOC. He also compares a number of containers. I cannot recommend this book enough. The book's name is: "Dependency Injection in .Net" <https://www.manning.com/books/dependency-injection-in-dot-net> | What is Castle Windsor, and why should I care? | [
"",
"c#",
"dependency-injection",
"inversion-of-control",
"castle-windsor",
""
] |
Is it possible to prevent stack allocation of an object and only allow it to be instiated with 'new' on the heap? | One way you could do this would be to make the constructors private and only allow construction through a static method that returns a pointer. For example:
```
class Foo
{
public:
~Foo();
static Foo* createFoo()
{
return new Foo();
}
private:
Foo();
Foo(const Foo&);
Foo& operator=(... | In the case of C++11
```
class Foo
{
public:
~Foo();
static Foo* createFoo()
{
return new Foo();
}
Foo(const Foo &) = delete; // if needed, put as private
Foo & operator=(const Foo &) = delete; // if needed, put as private
Foo(Foo &&) = delete; // if needed, put as private
Fo... | Is it possible to prevent stack allocation of an object and only allow it to be instantiated with 'new'? | [
"",
"c++",
"c++-faq",
""
] |
I'm just starting to wean myself from ASP.NET UpdatePanels. I'm using jQuery and jTemplates to bind the results of a web service to a grid, and everything works fine.
Here's the thing: I'm trying to show a spinner GIF while the table is being refreshed (à la UpdateProgress in ASP.NET) I've got it all working, except t... | It's not the Ajax call that's freezing the browser. It's the success handler (applyTemplate). Inserting HTML into a document like that can freeze IE, depending on how much HTML there is. It's because the IE UI is single threaded; if you notice, the actual IE menus are frozen too while this is happening.
As a test, try... | I don't remember precisely what caused it, but we had a similar issue with IE6 in a busy box and we fixed it with this incredible hack in the Javascript:
```
setTimeout("document.images['BusyImage'].src=document.images['BusyImage'].src",10);
```
That just sets the image source to what it was before, but it is apparen... | Why does my spinner GIF stop while jQuery ajax call is running? | [
"",
"javascript",
"jquery",
""
] |
I'm using a column of checkboxes in a YUI DataTable, I works fine. But I haven't found a way to put a name and value attribute so I can use when the form is submitted.
Thanks in advance. | Does the API reference at <http://developer.yahoo.com/yui/docs/YAHOO.widget.CheckboxCellEditor.html> help? | In order to get a name and value attribute, you use a checkbox like this:
```
<input type="checkbox" name="the_name" value="the_value" />
```
In your server-side code, you would look into the POST or GET data for the name of the checkbox. If it is there, the checkbox was checked. If it isn't there, the checkbox was n... | checkbox in YUI DataTable | [
"",
"javascript",
"yui",
""
] |
I have recently been thinking about the difference between the two ways of defining an array:
1. `int[] array`
2. `int array[]`
Is there a difference? | They are semantically identical. The `int array[]` syntax was only added to help C programmers get used to java.
`int[] array` is much preferable, and less confusing. | There is one slight difference, if you happen to declare more than one variable in the same declaration:
```
int[] a, b; // Both a and b are arrays of type int
int c[], d; // WARNING: c is an array, but d is just a regular int
```
Note that this is bad coding style, although the compiler will almost certainly catch... | Difference between int[] array and int array[] | [
"",
"java",
"arrays",
""
] |
Is there a way to format a UTC time into any arbitrary string format I want in java? Basically I was thinking of having some class take the timestamp and I pass it is string telling it how I want it formated, and it returns the formatted string for me. Is there a way to do this? | The java.text.SimpleDateFormat class provides formatting and parsing for dates in a locale-sensitive manner.
The javadoc header for [SimpleDateFormat](http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html) is a good source of detailed information. There is also a [Java Tutorial](https://docs.oracle.... | The [DateFormat](http://java.sun.com/j2se/1.4.2/docs/api/java/text/DateFormat.html) class or [SimpleDateFormat](http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html) should get you there. For example, <http://www.epochconverter.com/> lists the following example to convert a epoch time to human readab... | Formatting Timestamps in Java | [
"",
"java",
"date",
""
] |
What’s the difference between the `System.Array.CopyTo()` and `System.Array.Clone()`? | The **[Clone()](http://msdn.microsoft.com/en-us/library/system.array.clone.aspx)** method returns a new array (a shallow copy) object containing all the elements in the original array. The **[CopyTo()](http://msdn.microsoft.com/en-us/library/system.array.copyto.aspx)** method copies the elements into another existing a... | One other difference not mentioned so far is that
* with `Clone()` the destination array need not exist yet since a new one is created from scratch.
* with `CopyTo()` not only does the destination array need to already exist, it needs to be large enough to hold all the elements in the source array from the index you s... | Difference between the System.Array.CopyTo() and System.Array.Clone() | [
"",
"c#",
".net",
"arrays",
".net-2.0",
""
] |
I am using SQL Server 2005. I want to constrain the values in a column to be unique, while allowing NULLS.
My current solution involves a unique index on a view like so:
```
CREATE VIEW vw_unq WITH SCHEMABINDING AS
SELECT Column1
FROM MyTable
WHERE Column1 IS NOT NULL
CREATE UNIQUE CLUSTERED INDEX unq... | Pretty sure you can't do that, as it violates the purpose of uniques.
However, this person seems to have a decent work around:
<http://sqlservercodebook.blogspot.com/2008/04/multiple-null-values-in-unique-index-in.html> | Using SQL Server 2008, you can [create a filtered index](https://learn.microsoft.com/en-us/sql/relational-databases/indexes/create-filtered-indexes).
```
CREATE UNIQUE INDEX AK_MyTable_Column1 ON MyTable (Column1) WHERE Column1 IS NOT NULL
```
Another option is a trigger to check uniqueness, but this could affect per... | How to create a unique index on a NULL column? | [
"",
"sql",
"sql-server",
"indexing",
"constraints",
"unique",
""
] |
I have code similar to this filtering entries in an Array of Objects:
```
var filterRegex = new RegExp(".*blah.*","ig");
if (filterRegex.test(events[i].thing) && events[i].show) {
console.log("SUCCESS: filtering thing " + i + " " + events[i].thing);
events[i].show = false;
numevents--;
}
```
I get inconsi... | Ok, i see it now. The key to your problem is the use of the `g` (global match) flag: when this is specified for a regex, it will be set up such that it can be executed multiple times, beginning each time at the place where it left off last time. It keeps a "bookmark" of sorts in its `lastIndex` property:
```
var testR... | I just can't imagine there is any situation where two JavaScript expressions evaluate to true individually, but not when combined.
Are you sure both expressions actually produce a boolean value every time? (Okay, to make `regex.test()` not produce a boolean value is difficult, but how about `event.show`. Might that be... | Why am I seeing inconsistent JavaScript logic behavior looping with an alert() vs. without it? | [
"",
"javascript",
"regex",
""
] |
What are the pros and cons of using nested public C++ classes and enumerations? For example, suppose you have a class called `printer`, and this class also stores information on output trays, you could have:
```
class printer
{
public:
std::string name_;
enum TYPE
{
TYPE_LOCAL,
TYPE_NETWOR... | ## Nested classes
There are several side effects to classes nested inside classes that I usually consider flaws (if not pure antipatterns).
Let's imagine the following code :
```
class A
{
public :
class B { /* etc. */ } ;
// etc.
} ;
```
Or even:
```
class A
{
public :
class B ;
// etc.
... | One con that can become a big deal for large projects is that it is impossible to make a forward declaration for nested classes or enums. | Pros and cons of using nested C++ classes and enumerations? | [
"",
"c++",
"class",
"enums",
"nested",
""
] |
I know that this is a simple question for PHP guys but I don't know the language and just need to do a simple "get" from another web page when my page is hit. i.e. signal the other page that this page has been hit.
EDIT: curl is not available to me. | If curl wrappers are on (they are per default), you can use:
```
file_get_contents('http://www.example.org');
```
Note that this happens synchronous, so before the request has completed, your page won't either. It would be better to log access to a logfile (or database) and export the data occasionally. Alternatively... | Beware `file_get_contents()` and `fopen()`:
> If PHP has decided that filename specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that allow\_url\_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen call will fail. | How do I get using php? | [
"",
"php",
""
] |
I have a form showing progress messages as a fairly long process runs. It's a call to a web service so I can't really show a percentage complete figure on a progress bar meaningfully. (I don't particularly like the Marquee property of the progress bar)
I would like to show an animated GIF to give the process the feel ... | It's not too hard.
1. Drop a picturebox onto your form.
2. Add the .gif file as the image in the picturebox
3. Show the picturebox when you are loading.
**Things to take into consideration:**
* Disabling the picturebox will prevent the gif from being animated.
**Another way of doing it:**
Another way that I have f... | I had the same problem. Whole form (including gif) stopping to redraw itself because of long operation working in the background. Here is how i solved this.
```
private void MyThreadRoutine()
{
this.Invoke(this.ShowProgressGifDelegate);
//your long running process
System.Threading.Thread.Sleep(5000);
t... | How do you show animated GIFs on a Windows Form (c#) | [
"",
"c#",
"winforms",
"animated-gif",
""
] |
How can I change the class of an HTML element in response to an `onclick` or any other events using JavaScript? | ## Modern HTML5 Techniques for changing classes
Modern browsers have added [**classList**](https://developer.mozilla.org/en-US/docs/DOM/element.classList) which provides methods to make it easier to manipulate classes without needing a library:
```
document.getElementById("MyElement").classList.add('MyClass');
docum... | You could also just do:
```
document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');
```
And to toggle a class (remove if exists else add it):
```
document.getElementById('id').classList.toggle('class');
``` | How can I change an element's class with JavaScript? | [
"",
"javascript",
"html",
"dom",
""
] |
I have a java webapp that has to be deployed on either Win or Linux machines. I now want to add log4j for logging and I'd like to use a relative path for the log file as I don't want to change the file path on every deployment. The container will most likely be Tomcat but not necessarily.
What's the best way of doing ... | I've finally done it in this way.
Added a ServletContextListener that does the following:
```
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
System.setProperty("rootPath", context.getRealPath("/"));
}
```
Then in the log4j.properties file:
```... | Tomcat sets a catalina.home system property. You can use this in your log4j properties file. Something like this:
```
log4j.rootCategory=DEBUG,errorfile
log4j.appender.errorfile.File=${catalina.home}/logs/LogFilename.log
```
On Debian (including Ubuntu), `${catalina.home}` will not work because that points at /usr/s... | Log4j, configuring a Web App to use a relative path | [
"",
"java",
"web-applications",
"log4j",
""
] |
The title pretty much says it all. I want to create a SqlConnection and then check that connection without opening a database, cause at that point I don't know yet where will I connect to. Is it possible to do that?
The SqlConnection class has a 'Open' member which tries to open the database you'd set in the Database p... | Connect to temp db. Everybody has accecss to tempdb so you will be able to authenticate yourself for access. Later when you know the actual database , you can change this property to connect to the db you want. | I am not sure if this is what you need.
[Check if a user has access to a database in Sql Server 2005](http://www.sqlservercurry.com/2008/03/check-if-user-has-access-to-database.html?showComment=1221349680000)
```
SELECT HAS_DBACCESS('Northwind');
```
HAS\_DBACCESS returns information about whether the user has acces... | How to test SqlServer connection without opening a database | [
"",
".net",
"sql",
"sql-server",
"sqlconnection",
""
] |
I've been trying this a few different ways, but I'm reaching the conclusion that it can't be done. It's a language feature I've enjoyed from other languages in the past. Is it just something I should just write off? | No, static indexers aren't supported in C#. Unlike other answers, however, I see how there could easily be point in having them. Consider:
```
Encoding x = Encoding[28591]; // Equivalent to Encoding.GetEncoding(28591)
Encoding y = Encoding["Foo"]; // Equivalent to Encoding.GetEncoding("Foo")
```
It would be relativel... | You can simulate static indexers using static indexed properties:
```
public class MyEncoding
{
public sealed class EncodingIndexer
{
public Encoding this[string name]
{
get { return Encoding.GetEncoding(name); }
}
public Encoding this[int codepage]
{
... | Are static indexers not supported in C#? | [
"",
"c#",
".net",
"clr",
""
] |
When iterating over elements of a vector it is preferred to use iterators instead of an index (see [Why use iterators instead of array indices?](https://stackoverflow.com/questions/131241/why-use-iterators-instead-of-array-indices)).
```
std::vector<T> vec;
std::vector<T>::iterator it;
for ( it = vec.begin(); it != ve... | If you're planning on using exclusively a vector, you may want to switch back to the indexed loop, since it conveys your intent more clearly than iterator-loop. However, if evolution of your program in the future may lead to a change of container, you should stick to the iterators and use std::distance, which is guaran... | Using std::distance is a bit more generic since it works for all iterators, not just random access iterators. And it should be just as fast as It - vec.begin() in case of random access iterators.
It - vec.begin() is basically pointer arithmetic. | Obtain an index into a vector using Iterators | [
"",
"c++",
"indexing",
"vector",
"iterator",
""
] |
The issue is there is a database with around 20k customer records and I want to make a best effort to avoid duplicate entries. The database is Microsoft SQL Server 2005, the application that maintains that database is Microsoft Dynamics/SL. I am creating an ASP.NET webservice that interacts with that database. My servi... | The specifics of which [algorithm](http://www.cs.sunysb.edu/~algorith/files/approximate-pattern-matching.shtml) will work best for you depends greatly on your domain, so I'd suggest experimenting with a few different ones - you may even need to combine a few to get optimal results. Abbreviations, especially domain spec... | Look into [SOUNDEXing](http://msdn.microsoft.com/en-us/magazine/cc163731.aspx) within SQL Server. I believe it will give you the fuzziness of probable matches that you're looking for.
[SOUNDEX @ MSDN](http://msdn.microsoft.com/en-us/library/aa259235(SQL.80).aspx)
[SOUNDEX @ Wikipedia](http://en.wikipedia.org/wiki/Sou... | intelligent database search | [
"",
"c#",
"asp.net",
"sql-server",
"web-services",
"dynamics-sl",
""
] |
I have a multi-threaded C++ app which does 3D rendering with the OpenSceneGraph library. I'm planning to kick off OSG's render loop as a separate thread using boost::threads, passing a data structure containing shared state in to the thread. I'm trying to avoid anything too heavyweight (like mutexes) for synchronizatio... | In C++11 and later, which has standards-defined concurrency, use `std::atomic<bool>` for this purpose. From <http://en.cppreference.com/w/cpp/atomic/atomic>:
> If one thread writes to an atomic object while another thread reads from it, the behavior is well-defined (see memory model for details on data races).
---
T... | Why not simply use an [interlocked variable](http://msdn.microsoft.com/en-us/library/ms684122(VS.85).aspx)? | In a multi-threaded C++ app, do I need a mutex to protect a simple boolean? | [
"",
"c++",
"multithreading",
"boolean",
"mutex",
"openscenegraph",
""
] |
For homework, I was given the following 8 code fragments to analyze and give a Big-Oh notation for the running time. Can anybody please tell me if I'm on the right track?
```
//Fragment 1
for(int i = 0; i < n; i++)
sum++;
```
I'm thinking O(N) for fragment 1
```
//Fragment 2
for(int i = 0; i < n; i+=2)
sum++... | I think fragment 5 is O(n^3), and similarly fragment 7 is O(n^5)\*. It also looks like O(log(n)) for fragment 8.
For the n \* n problems, you have to execute the body of the loop n \* n times, so it would be O(n^2), then you compound that with the order of the other code. Fragment 8 actually doubles the counter instea... | Fragment 7 is O(n^5), not O(n^4) as the currently accepted comment claims. Otherwise, it's correct. | Big O Notation Homework--Code Fragment Algorithm Analysis? | [
"",
"java",
"big-o",
""
] |
From C#, is it possible to detect the number of context switches that occurred while executing a block of code on a particular thread? Ideally, I'd like to know how many times and what CPU my thread code was scheduled on.
I know I can use tools like [Event Tracing for Windows](http://msdn.microsoft.com/en-us/magazine/... | It looks like procexp might be using the kernel thread (KTHREAD) or executive thread (ETHREAD) data structures that have a ContextSwitches field on them. It might be possible to get this from managed code. | It sounds like you may be looking for a programmatic solution, but if not, Microsoft's [Process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) tool will tell you very easily the number of context switches for a particular thread.
Once in the tool, double-click your process, select the Threads... | How to detect the number of context switches that occurred while running C# code? | [
"",
"c#",
"multithreading",
""
] |
In PHP, I want to read a file into a variable and process the PHP in the file at the same time without using output buffering. Is this possible?
Essentially I want to be able to accomplish this without using `ob_start()`:
```
<?php
ob_start();
include 'myfile.php';
$xhtml = ob_get_clean();
?>
```
Is this possible in... | A little known feature of PHP is being able to treat an included/required file like a function call, with a return value.
For example:
```
// myinclude.php
$value = 'foo';
$otherValue = 'bar';
return $value . $otherValue;
// index.php
$output = include './myinclude.php';
echo $output;
// Will echo foobar
``` | From what I can tell in the PHP documentation, no. Why do you want to avoid output buffering?
The only way to get around this would be hacky methods involving either invoking the command line php client or doing a curl request based on what's available and what the particular requirements are. | In PHP, is there a way to capture the output of a PHP file into a variable without using output buffering? | [
"",
"php",
"eval",
"output-buffering",
""
] |
Is there a way to statically/globally request a copy of the ApplicationContext in a Spring application?
Assuming the main class starts up and initializes the application context, does it need to pass that down through the call stack to any classes that need it, or is there a way for a class to ask for the previously c... | If the object that needs access to the container is a bean in the container, just implement the [BeanFactoryAware](http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-aware-beanfactoryaware) or [ApplicationContextAware](http://static.springframework.org/spring/docs/2.5.x/api/org/sprin... | You can implement `ApplicationContextAware` or just use `@Autowired`:
```
public class SpringBean {
@Autowired
private ApplicationContext appContext;
}
```
`SpringBean` will have `ApplicationContext` injected, within which this bean is instantiated. For example if you have web application with a pretty standard c... | Getting Spring Application Context | [
"",
"java",
"spring",
"configuration",
"applicationcontext",
""
] |
I have used C# in Visual Studio with .NET, and I have played around a little with Mono on openSUSE Linux, but I don't really understand how it works.
If I write an app in Windows on .NET, how does this relate to Mono? I can't just execute an a Windows .exe file on Linux without Wine, so it doesn't help me execute apps... | This is an old question (with an already selected answer) but I do not believe the question has really been answered well.
First, a little background...
**How does .NET work?**
A traditional Windows .EXE file is a binary file that represents a series of machine language instructions that your computer understands an... | A Windows EXE contains multiple "parts". *Simplified*, the .net Code (=MSIL) is only a Part of the EXE, and there is also a "real" native Windows Part inside the EXE that serves as some sort of launcher for the .net Framework which then executes the MSIL.
Mono will just take the MSIL and execute it, ignoring the nativ... | How does Mono work | [
"",
"c#",
"mono",
""
] |
I've run into this issue quite a few times and never liked the solution chosen. Let's say you have a list of States (just as a simple example) in the database. In your code-behind, you want to be able to reference a State by ID and have the list of them available via Intellisense.
For example:
```
States.Arizona.Id ... | I believe that if it shows up in Intellisense, then, by definition, it is hard-coded into your program.
That said, if your goal is make the hard-coding as painless as possible, on thing you might try is auto-generating your enumeration based on what's in the database. That is, you can write a program that reads the da... | Personally, I would store lookup data in a database, and simply try to avoid the type of hard coding that binds rules to things like individual states. Perhaps some key property *of* those states (like .ApplyDoubleTax or something). And non-logic code doesn't need to use intellisense - it typically just needs to list t... | How would you reference lookup/meta data? | [
"",
"c#",
".net",
"asp.net",
""
] |
We are designing a Payroll Generation System for a client.
The organization we are targeting has a hierarchy as follows:
Company -> Cluster -> Business Unit (BU) -> Department -> Employee
The salary for an employee is made up of various salary components.
Each salary component has 3 rules associated with it, a Calcul... | I always try to shy away from putting business logic in the DB layer. It is more difficult to write, debug and maintain. In addition, the DB is generally the most expensive layer to scale. If you end up needing to beef up your system to support more users it is relatively cheap and easy to add new webservers to a syste... | If you store the formulas as in for example JEP (for java) it's not much of a problem. Just keep the full formula as a string: i.e: "pay=((0.3 \* Basic) + 800) and then parse it into a tree.
You can see some of jep documentation for info, and take the ideas from there. Shouldn't be 2 problematic to implement simple so... | Payroll System Design, Business Logic in SPs or Application Layer (C#.Net), Maintainability - Repost | [
"",
"c#",
"database",
"oop",
"web-applications",
"n-tier-architecture",
""
] |
I have a many to many index table, and I want to do an include/exclude type query on it.
fid is really a integer index, but here as letters for easier understanding. Here's a sample table :
table t
```
eid | fid
----+----
1 | A
1 | B
1 | C
2 | B
2 | C
3 | A
3 | C
4 | A
4 | B
5 | B
```
Here are s... | Here's an example of a query for 1 (2 works much the same)
```
select t1.eid
from t t1
where t1.fid = 'B'
and not exists
(select 1
from t t2
where t2.eid = t1.eid
and t2.fid = 'A')
``` | Use [set subtraction](http://msdn.microsoft.com/en-us/library/ms188055.aspx)
> ```
> Select eid from t where fid = 'B'
> EXCEPT
> select eid from t where fid = 'A'
> ``` | Many to many table queries | [
"",
"sql",
"join",
""
] |
I found this [PECL package called threads](http://pecl.php.net/package/threads), but there is not a release yet. And nothing is coming up on the PHP website. | There is nothing available that I'm aware of. The next best thing would be to simply have one script execute another via CLI, but that's a bit rudimentary. Depending on what you are trying to do and how complex it is, this may or may not be an option. | From the PHP manual for the [**pthreads**](http://php.net/pthreads) extension:
> pthreads is an Object Orientated API that allows user-land multi-threading in PHP. It includes all the tools you need to create multi-threaded applications targeted at the Web or the Console. PHP applications can create, read, write, exec... | Does PHP have threading? | [
"",
"php",
"multithreading",
"apache",
"command-line-interface",
""
] |
I am writing code for a search results page that needs to highlight search terms. The terms happen to occur within table cells (the app is iterating through GridView Row Cells), and these table cells may have HTML.
Currently, my code looks like this (relevant hunks shown below):
```
const string highlightPattern = @"... | This regex should do the job : `(?<!<[^>]*)(regex you want to check: Fred|span)` It checks that it is impossible to match the regex `<[^>]*` going backward starting from a matching string.
Modified code below:
```
const string notInsideBracketsRegex = @"(?<!<[^>]*)";
const string highlightPattern = @"<span class=""Hi... | You can use a regex with balancing groups and backreferences, but I strongly recommend that you use a [parser](http://www.antlr.org/) here. | What regex will match text excluding what lies within HTML tags? | [
"",
"c#",
"regex",
""
] |
Say if I had a table of books in a MySQL database and I wanted to search the 'title' field for keywords (input by the user in a search field); what's the best way of doing this in PHP? Is the MySQL `LIKE` command the most efficient way to search? | Yes, the most efficient way usually is searching in the database. To do that you have three alternatives:
* [LIKE, ILIKE](http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html) to match exact substrings
* [RLIKE](http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html) to match POSIX regexes
* [... | Here's a simple way you can break apart some keywords to build some clauses for filtering a column on those keywords, either ANDed or ORed together.
```
$terms=explode(',', $_GET['keywords']);
$clauses=array();
foreach($terms as $term)
{
//remove any chars you don't want to be searching - adjust to suit
//your... | What's the best way to search a MySQL database with PHP? | [
"",
"php",
"mysql",
"search",
""
] |
I have a Delphi DLL with a function defined as:
function SubmitJobStringList(joblist: tStringList; var jobno: Integer): Integer;
I am calling this from C#. How do I declare the first parameter as a tStringList does not exist in C#. I currently have the declaration as:
```
[DllImport("opt7bja.dll", CharSet = CharSet.... | You'll most likely not have any luck with this. The TStringList is more than just an array, it's a full-blown class, and the exact implementation details may differ from what is possible with .NET. Take a look at the Delphi VCL source code (that is, if you have it) and try to find out if you can rebuild the class in C#... | If this is your DLL, I'd rewrite the function to accept an array of strings instead. Avoid passing classes as DLL parameters.
Or, if you *really* want to use a TStringList for some reason, Delphi's VCL.Net can be used from any .Net language.
An old example using TIniFile: <http://cc.codegear.com/Item/22691>
The exam... | tStringList passing in C# to Delphi DLL | [
"",
"c#",
"delphi",
"dll",
"tstringlist",
""
] |
I am developing a wizard for a machine that is to be used as a backup of other machines. When it replaces an existing machine, it needs to set its IP address, DNS, WINS, and host name to match the machine being replaced.
Is there a library in .net (C#) which allows me to do this programatically?
There are multiple NI... | Just made this in a few minutes:
```
using System;
using System.Management;
namespace WindowsFormsApplication_CS
{
class NetworkManagement
{
public void setIP(string ip_address, string subnet_mask)
{
ManagementClass objMC =
new ManagementClass("Win32_NetworkAdapterConfiguration");
Mana... | Refactored the code from balexandre a little so objects gets disposed and the new language features of C# 3.5+ are used (Linq, var, etc). Also renamed the variables to more meaningful names. I also merged some of the functions to be able to do more configuration with less WMI interaction. I removed the WINS code as I d... | How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C# | [
"",
"c#",
".net",
"configuration",
"networking",
""
] |
> Timsort is an adaptive, stable,
> natural mergesort. It has supernatural
> performance on many kinds of partially
> ordered arrays (less than lg(N!)
> comparisons needed, and as few as
> N-1), yet as fast as Python's previous
> highly tuned samplesort hybrid on
> random arrays.
Have you seen [timsort](http://svn.pyt... | Yes, it makes quite a bit of sense to use timsort outside of CPython, in specific, or Python, in general.
There is currently an [effort underway](https://bugs.java.com/bugdatabase/view_bug?bug_id=6804124) to replace Java's "modified merge sort" with timsort, and the initial results are quite positive. | The algorithm is pretty generic, but the benefits are rather Python-specific. Unlike most sorting routines, what Python's list.sort (which is what uses timsort) cares about is avoiding unnecessary comparisons, because generally comparisons are a *lot* more expensive than swapping items (which is always just a set of po... | Is timsort general-purpose or Python-specific? | [
"",
"python",
"algorithm",
"sorting",
""
] |
When I dynamically create a Datagrid and add in a new buttoncolumn how do I access the buttoncolumn\_click event?
Thanks. | ```
protected void Page_Load(object sender, EventArgs e)
{
DataGrid dg = new DataGrid();
dg.GridLines = GridLines.Both;
dg.Columns.Add(new ButtonColumn {
CommandName = "add",
HeaderText = "Event Details",
Text = "Details",
ButtonType = ButtonColumnType.PushButton
});
dg.DataSource = getData... | This article on the MSDN site clearly explains how to go about [adding a button into a datagrid](http://msdn.microsoft.com/en-us/library/aa984252(VS.71).aspx). Instead of using the click event of the button you'll use the command event of the DataGrid. Each button will be passing specific commandarguments that you will... | Accessing a dynamitcally added buttoncolumn's (in a Datagrid) click event. C#/ASP.NET | [
"",
"c#",
"asp.net",
""
] |
One of our providers are sometimes sending XML feeds that are tagged as UTF-8 encoded documents but includes characters that are not included in the UTF-8 charset. This causes the parser to throw an exception and stop building the DOM object when these characters are encountered:
```
DocumentBuilder.parse(ByteArrayInp... | if the problem truly is the wrong encoding (as opposed to a mixed encoding), you don't need to re-encode the document to parse it. just parse it as a Reader instead of an InputStream and the dom parser will ignore the header:
```
DocumentBuilder.parse(new InpputSource(new InputStreamReader(inputStream, "<real encoding... | You should manually take a look at the invalid documents and see what is the common problem to them. It's quite probable they are in fact in another encoding (most probably windows-1252), and the best solution then would be to take every document from the broken system and recode it to UTF-8 before parsing.
Another po... | Repairing wrong encoding in XML files | [
"",
"java",
"xml",
"parsing",
"encoding",
"xerces",
""
] |
There have been a few questions asked here about why you can't define static methods within interfaces, but none of them address a basic inconsistency: why can you define static fields and static inner types within an interface, but not static methods?
Static inner types perhaps aren't a fair comparison, since that's ... | An [official proposal](http://docs.google.com/Doc?docid=dfkwr6vq%5F30dtg2z9d8&hl=en) has been made to allow static methods in interfaces in Java 7. This proposal is being made under [Project Coin](http://blogs.oracle.com/darcy/entry/project_coin).
My personal opinion is that it's a great idea. There is no technical di... | I'm going to go with my pet theory with this one, which is that the lack of consistency in this case is a matter of convenience rather than design or necessity, since I've heard no convincing argument that it was either of those two.
Static fields are there (a) because they were there in JDK 1.0, and many dodgy decisi... | Why no static methods in Interfaces, but static fields and inner classes OK? [pre-Java8] | [
"",
"java",
"interface",
"jls",
""
] |
What's the best way to pipe the output from an java.io.OutputStream to a String in Java?
Say I have the method:
```
writeToStream(Object o, OutputStream out)
```
Which writes certain data from the object to the given stream. However, I want to get this output into a String as easily as possible.
I'm considering w... | I would use a `ByteArrayOutputStream`. And on finish you can call:
```
new String( baos.toByteArray(), codepage );
```
or better:
```
baos.toString( codepage );
```
For the `String` constructor, the `codepage` can be a `String` or an instance of [java.nio.charset.Charset](http://docs.oracle.com/javase/7/docs/api/ja... | I like the Apache Commons IO library. Take a look at its version of [ByteArrayOutputStream](https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/output/ByteArrayOutputStream.html), which has a `toString(String enc)` method as well as `toByteArray()`. Using existing and trusted components ... | Get an OutputStream into a String | [
"",
"java",
"string",
"io",
"stream",
""
] |
I have one of those "I swear I didn't touch the server" situations. I honestly didn't touch any of the php scripts. The problem I am having is that php data is not being saved across different pages or page refreshes. I know a new session is being created correctly because I can set a session variable (e.g. $\_SESSION[... | Thanks for all the helpful info. It turns out that my host changed servers and started using a different session save path other than /var/php\_sessions which didn't exist anymore. A solution would have been to declare `ini_set(' session.save_path','SOME WRITABLE PATH');` in all my script files but that would have been... | Check to make sure you are not mixing https:// with http://. Session variables do not flow between secure and insecure sessions. | PHP Session data not being saved | [
"",
"php",
"session",
""
] |
Kind of a random question...
What I'm looking for is a way to express a cast operation which uses a defined operator of the class instance I'm casting from, and generates a compile-time error if there is not a defined cast operator for the type. So, for example, what I'm looking for is something like:
```
template< t... | The code you posted works with the [Cameau compiler](http://www.comeaucomputing.com/tryitout/) (which is usually a good indication that it's valid C++).
As you know a valid cast consists of no more than one user defined cast, so a possible solution I was thinking of was adding another user defined cast by defining a n... | Using a converting constructor marked [explicit](https://stackoverflow.com/questions/121162/what-does-the-explicit-keyword-in-c-mean) is how you would prevent the compiler from allowing implicitly converted types from initializing your wrapper class. | Any way to cast with class operator only? | [
"",
"c++",
"compiler-construction",
"casting",
""
] |
I'm running my site through the W3C's validator trying to get it to validate as XHTML 1.0 Strict and I've gotten down to a particularly sticky (at least in my experience) validation error. I'm including certain badges from various services in the site that provide their own API and code for inclusion on an external sit... | The following fragment is valid XHTML and does the job:
```
<div id="twitter_div">
<h2 class="twitter-title"><a href="http://twitter.com/stopsineman" title="Tim's Twitter Page.">Twitter Updates</a></h2>
<div id="myDiv" />
</div>
<script type="text/javascript">
var placeHolderNode = document.getElementByI... | Perhaps you could use javascript to write the initial badge HTML? You'd probably only want the badge code to be inserted in your document if javascript were available to populate it, right?
You'd just need to make sure your document writing happens before the javascript for your various badges.
Could you give a speci... | How do you write Valid XHTML 1.0 Strict code when you are using javascript to fill an element that requires a child? | [
"",
"javascript",
"validation",
"twitter",
"w3c-validation",
"xhtml-1.0-strict",
""
] |
We are hosting a site for a client and they want us to include the header they have on their server into the pages we are hosting. So whenever they change it, it will automatically change on our site.
We are attempting to use the "include" tag in our JSP code. The code we are using is as follows:
`<%@ include file="w... | If you choose to do this in Java, it's nice and easy using the HttpClient from Apache Commons.
```
public static String fetchSourceHtml( String urlString ) {
try {
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod( urlString );
getMethod.setFollowRedirects( true );
int h... | JSP includes don't support including remote files, which is why a relative URL is required: <http://java.sun.com/products/jsp/syntax/1.2/syntaxref1214.html>
I suggest writing a function which opens a connection to that page and downloads the contents and then prints them to your own `out` stream. Then you can put that... | How do I include a header into my site that is hosted externally? | [
"",
"java",
"jsp",
"include",
"jspinclude",
""
] |
This is likely going to be an easy answer and I'm just missing something, but here goes...If I have a Type, (that is, an actual System.Type...not an instance) how do I tell if it inherits from another specific base type? | Use the [IsSubclassOf](http://msdn.microsoft.com/en-us/library/system.type.issubclassof.aspx) method of the [System.Type](http://msdn.microsoft.com/en-us/library/system.type_members.aspx) class. | One thing to clarify between `Type.IsSubTypeOf()` and `Type.IsAssignableFrom()`:
* `IsSubType()` will return `true` only if the given type is derived from
the specified type. It will return `false` if the given type **IS**
the specified type.
* `IsAssignableFrom()` will return `true` if the given type is either th... | How do you determine whether or not a given Type (System.Type) inherits from a specific base class (in .Net)? | [
"",
"c#",
".net",
"reflection",
"inheritance",
""
] |
Is it possible to add attributes at runtime or to change the value of an attribute at runtime? | Attributes are static metadata. Assemblies, modules, types, members, parameters, and return values aren't first-class objects in C# (e.g., the `System.Type` class is merely a reflected representation of a type). You can get an instance of an attribute for a type and change the properties if they're writable but that wo... | This really depends on what exactly you're trying to accomplish.
The [System.ComponentModel.TypeDescriptor](http://msdn.microsoft.com/en-us/library/system.componentmodel.typedescriptor.aspx) stuff can be used to add attributes to types, properties and object instances, and it has the limitation that you have to use it... | Can attributes be added dynamically in C#? | [
"",
"c#",
".net",
"attributes",
""
] |
I'm trying to call the OpenThemeData (see msdn [OpenThemeData](http://msdn.microsoft.com/en-us/library/bb759821%28v=VS.85%29.aspx)) function but I couldn't determine what are the acceptable Class names to be passed in by the `pszClassList` parameter.
```
HTHEME OpenThemeData(
HWND hwnd,
LPCWSTR pszClassL... | You can look in "AeroStyle.xml" as a previous poster noted, which gives an exact list for Vista/Aero. However, if you want to play safe (and you probably do) the class names should, in general, be Windows class names of Windows common controls. For example, push buttons and check boxes use the class name "Button", the ... | The article [**Parts and States**](http://msdn.microsoft.com/en-us/library/bb773210%28v=VS.85%29.aspx) on MSDN contains a table which shows the *control classes*, *parts*, and *states*. The values in the table are defined in `Vsstyle.h` and `Vssym32.h`.
Here is a quick reference:
```
BUTTON, CLOCK, COMBOBOX, COMMUNIC... | What are the possible classes for the OpenThemeData function? | [
"",
"c++",
"winapi",
"mfc",
"themes",
"msdn",
""
] |
Say for example you just queried a database and you recieved this 2D array.
```
$results = array(
array('id' => 1, 'name' => 'red' , 'spin' => 1),
array('id' => 2, 'name' => 'green', 'spin' => -1),
array('id' => 3, 'name' => 'blue' , 'spin' => .5)
);
```
I often find myself writing loops like this.
```... | As of June 20th in PHP-5.5 there is a new function [array\_column](https://www.php.net/array_column)
For example:
```
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe'
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_n... | I voted @Devon's response up because there really isn't a way to do what you're asking with a built-in function. The best you can do is write your own:
```
function array_column($array, $column)
{
$ret = array();
foreach ($array as $row) $ret[] = $row[$column];
return $ret;
}
``` | Isolate a single column in a multi-dimensional array | [
"",
"php",
"arrays",
"associative-array",
""
] |
I seem to be seeing more 'for' loops over iterators in questions & answers here than I do for\_each(), transform(), and the like. Scott Meyers suggests that [stl algorithms are preferred](http://www.ddj.com/cpp/184401446), or at least he did in 2001. Of course, using them often means moving the loop body into a functio... | It depends on:
* Whether high-performance is required
* The readability of the loop
* Whether the algorithm is complex
If the loop isn't the bottleneck, and the algorithm is simple (like for\_each), then for the current C++ standard, I'd prefer a hand-rolled loop for readability. (Locality of logic is key.)
However,... | I’m going to go against the grain here and advocate that using STL algorithms with functors makes code much easier to understand and maintain, but you have to do it right. You have to pay more attention to readability and clearity. Particularly, you have to get the naming right. But when you do, you can end up with cle... | Should one prefer STL algorithms over hand-rolled loops? | [
"",
"c++",
"algorithm",
"stl",
""
] |
Say you have a large PHP project and suddenly, when attempting to run it, you just end up with a blank page. The script terminates and you want to find exactly where that is with as little effort as possible.
Is there a tool/program/command/IDE that can, on PHP script termination, tell you the location of a script exi... | With some inspiration from the nonworking but still right-direction answer from RoBorg, I used the following code in the beginning:
```
function shutdown() {
global $dbg_stack_a;
print_r($dbg_stack_a);
}
register_shutdown_function('shutdown');
```
And then I made a global conditional breakpoint (global = brea... | I use the following code and need no special debugging environment. Note that this might take really long; you can set the ticks count higher - that makes it faster, but blurry.
```
function shutdown_find_exit()
{
var_dump($GLOBALS['dbg_stack']);
}
register_shutdown_function('shutdown_find_exit');
function write_d... | Fastest way to determine where PHP script exits | [
"",
"php",
""
] |
Which types of objects fall into the domain of "subscriptable"? | It basically means that the object implements the `__getitem__()` method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries. | Off the top of my head, the following are the only built-ins that are subscriptable:
```
string: "foobar"[3] == "b"
tuple: (1,2,3,4)[3] == 4
list: [1,2,3,4][3] == 4
dict: {"a":1, "b":2, "c":3}["c"] == 3
```
But [mipadi's answer](https://stackoverflow.com/a/216980/8554766) is correct - any class that implemen... | What does it mean if a Python object is "subscriptable" or not? | [
"",
"python",
"terminology",
""
] |
I'm implementing a secure WCF service. Authentication is done using username / password or Windows credentials. The service is hosted in a Windows Service process. Now, I'm trying to find out the best way to implement *authorization* for each service operation.
For example, consider the following method:
```
public E... | For question 1, absolutely do authorization first. No code (within your control) should execute before authorization to maintain the tightest security. Paul's example above is excellent.
For question 2, you could handle this by subclassing your concrete service implementation. Make the true business logic implementati... | For question 1, it's best to perform authorization first. That way, you don't leak validation error messages back to unauthorized users.
BTW, instead of using a home-grown authentication method (which I assume is what your CheckAccessPermission is), you might be able to hook up to WCF's out-of-the-box support for ASP.... | WCF Service authorization patterns | [
"",
"c#",
".net",
"wcf",
"authorization",
""
] |
I'm using NetBeans, trying to change the familiar Java coffee cup icon to a png file that I have saved in a resources directory in the jar file. I've found many different web pages that claim they have a solution, but so far none of them work.
Here's what I have at the moment (leaving out the try-catch block):
```
UR... | ```
java.net.URL url = ClassLoader.getSystemResource("com/xyz/resources/camera.png");
```
May or may not require a '/' at the front of the path. | You can simply go Netbeans, in the design view, go to `JFrame` property, choose icon image property, Choose Set Form's `iconImage` property using: "Custom code" and then in the `Form.SetIconImage()` function put the following code:
```
Toolkit.getDefaultToolkit().getImage(name_of_your_JFrame.class.getResource("image.p... | How do I change the default application icon in Java? | [
"",
"java",
"icons",
""
] |
I'm trying to implement an IErrorHandler in my WCF service in order to log every exception that hits the service boundary before it's passed to the client. I already use IErrorHandlers for translating Exceptions to typed FaultExceptions, which has been very useful. According to the MSDN for IErrorHandler.HandleError(),... | I ended up putting the logging in IErrorHandler.ProvideFault() instead of IErrorHandler.HandlerError(). The ProvideFault call is made in the operation thread, so I can use OperationContext.Current to get some information to log. | I use the IErrorHanlder in the same way that you describe, but not for logging. Instead on service classes (WCF or not) I use an interceptor as described [here](http://ayende.com/Blog/archive/2008/07/31/Logging--the-AOP-way.aspx). I believe that this technique will capture the information you are interested in. | WCF Error Logging at Service Boundary | [
"",
"c#",
"wcf",
"exception",
"error-handling",
""
] |
My code is in c# asp.net 3.5
In the following code the "Msg" has many words with spaces and characters (eg:Failed to prepare Sync Favorites : Directory does not exist: \STL-FNP-02\ryounes$\Sync\Favorites). This "Msg" is pulled from database to a gridview. I am not able to create hyperlink for this "Msg" in gridview. S... | The easiest way to get around it is to use something like
```
<asp:TemplateField HeaderText="Msg">
<asp:HyperLink runat="server" Text='<%# HttpUtility.UrlEncode(Eval("Msg")) %>' NavigateUrl='<%#Eval("Msg")%>' />
</asp:TemplateField>
```
Not 100% certain that the syntax is correct but you get the general idea | It doesn't create the link as it is not a valid URL, rather than using a hyperlink column most likely you are going to need to migrate to a template and manage it yourself, or at minimum do some formatting on it.
I would be cautious regardless of making that a hyperlink, where is it going to go anway?
If there is a s... | create hyperlink in gridview asp.net c# | [
"",
"c#",
"asp.net",
"linq",
""
] |
I have the following class which uses BinaryReader internally and implements IDisposable.
```
class DisposableClass : IDisposable
{
private BinaryReader reader;
public DisposableClass(Stream stream)
{
reader = new BinaryReader(stream);
}
protected virtual void D... | It won't work because the `Dispose` method on `BinaryReader` has been explicitly implemented.
Instead of being implicitly implemented, as in:
```
public void Dispose()
{
}
```
...it has been explicitly implemented, as in:
```
void IDisposable.Dispose()
{
}
```
...which means it can only be accessed via the `IDispo... | Expanding on my comments [here](https://stackoverflow.com/questions/222996/why-calling-dispose-on-binaryreader-results-in-compile-error#223020), the `BinaryReader` class does not properly implement the Dispose pattern.
Looking at this class in Reflector, it looks like this (for .NET 3.5):
```
public class BinaryReade... | Why calling Dispose() on BinaryReader results in compile error? | [
"",
"c#",
".net",
""
] |
If I have an assembly (A) which references another assembly (B).
I want to reference A in a project, I add the reference and it copies A into my BIN directory. It does not copy B as well, even though A depends on it, so the code doesn't compile.
How can I set things up so that whenever I reference A, both A and B get c... | I dont think there is any way around what you ask other than to explicitly add both. I dont think however adding projects for the sake of getting references copied is a viable solution to the issue. Not all projects that a solution depends on should necassarily be added to the solution. This would completely depdend on... | In Visual Studio, add each project to the same solution. Ensure you use Project References instead of direct file references (ie browsing for the assembly). | Assembly dependencies with .Net projects | [
"",
"c#",
".net",
"vb.net",
""
] |
It seems pretty common to want to let your javascript know a particular dom node corresponds to a record in the database. So, how do you do it?
One way I've seen that's pretty common is to use a class for the type and an id for the id:
```
<div class="thing" id="5">
<script> myThing = select(".thing#5") </script>
```... | Note that an ID cannot start with a digit, so:
```
<div class="thing" id="5">
```
is invalid HTML. See [What are valid values for the id attribute in HTML?](https://stackoverflow.com/questions/70579/what-is-a-valid-value-for-id-attributes-in-html#70586)
In your case, I would use ID's like `thing5` or `thing.5`. | ```
<div class="thing" id="myapp-thing-5"/>
// Get thing on the page for a particular ID
var myThing = select("#myapp-thing-5");
// Get ID for the first thing on the page
var thing_id = /myapp-thing-(\d+)/.exec ($('.thing')[0].id)[1];
``` | Opinion: in HTML, Possible Duplicate IDs or Non-Standard Attributes? | [
"",
"javascript",
"html",
"database",
""
] |
What is the best way to bind WPF properties to ApplicationSettings in C#? Is there an automatic way like in a Windows Forms Application? Similar to [this question](https://stackoverflow.com/questions/18421/best-way-to-bind-windows-forms-properties-to-applicationsettings-in-c), how (and is it possible to) do you do the ... | You can directly bind to the static object created by Visual Studio.
In your windows declaration add:
```
xmlns:p="clr-namespace:UserSettings.Properties"
```
where `UserSettings` is the application namespace.
Then you can add a binding to the correct setting:
```
<TextBlock Height="{Binding Source={x:Static p:Sett... | In case you are a **VB.Net** developer attempting this, the answer is a smidge different.
```
xmlns:p="clr-namespace:ThisApplication"
```
Notice the .Properties isn't there.
---
In your binding it's MySettings.Default, instead of Settings.Default - since the app.config stores it differently.
```
<TextBlock Height=... | Best way to bind WPF properties to ApplicationSettings in C#? | [
"",
"c#",
".net",
"wpf",
"visual-studio",
""
] |
If you create a panel on a form and set it to Dock=Top and drop another panel and set its Dock=Fill, it may fill the entire form, ignoring the first panel. Changing the tab order does nothing. | Docking layout depends on the **order** of sibling controls. Controls are docked "bottom up", so **the last control in the collection is docked first**. A docked control only take the layout of *previously* docked siblings into account. Hence the control with Dock=Fill should be first (top) in the sibling order, if you... | Right click on the panel with Dock=Fill and click 'Bring to Front'.
This makes this control be created last, which takes into account the Dock settings on other controls in the same container. | Panel.Dock Fill ignoring other Panel.Dock setting | [
"",
"c#",
".net",
"winforms",
"visual-studio-2005",
""
] |
Let's say that a class has a `public int counter` field that is accessed by multiple threads. This `int` is only incremented or decremented.
To increment this field, which approach should be used, and why?
* `lock(this.locker) this.counter++;`,
* `Interlocked.Increment(ref this.counter);`,
* Change the access modifie... | ### Worst (won't actually work)
> Change the access modifier of `counter` to `public volatile`
As other people have mentioned, this on its own isn't actually safe at all. The point of `volatile` is that multiple threads running on multiple CPUs can and will cache data and re-order instructions.
If it is **not** `vol... | **EDIT:** As noted in comments, these days I'm happy to use `Interlocked` for the cases of a *single variable* where it's *obviously* okay. When it gets more complicated, I'll still revert to locking...
Using `volatile` won't help when you need to increment - because the read and the write are separate instructions. A... | Volatile vs. Interlocked vs. lock | [
"",
"c#",
"multithreading",
"locking",
"volatile",
"interlocked",
""
] |
I want to check the login status of a user through an ajax request. Depending wether the user is logged in I want to display either the username/password input or the username. Currently the request is sent on body.onload and a prgoress indicator is shown until the response arrives. Is there a better way?
---
Let's a... | If you don't want to depend on a toolkit, you can create your own DOMReady function that looks kinda like this:
```
/* Usage: DOMReady(ajaxFunc); */
function DOMReady(f) {
if (!document.all) {
document.addEventListener("DOMContentLoaded", f, false);
} else {
if (document.readystate == 'complete... | This sounds like an operation that should be done on the server first, before the page is rendered. If someone has javascript disabled, what would happen? | How do i submit an ajax request before the page is loaded | [
"",
"javascript",
"ajax",
""
] |
In terms of Java, when someone asks:
> what is polymorphism?
Would **overloading** or **overriding** be an acceptable answer?
I think there is a bit more to it than that.
*IF you had a abstract base class that defined a method with no implementation, and you defined that method in the sub class, is that still overr... | The clearest way to express polymorphism is via an abstract base class (or interface)
```
public abstract class Human{
...
public abstract void goPee();
}
```
This class is abstract because the `goPee()` method is not definable for Humans. It is only definable for the subclasses Male and Female. Also, Human is ... | **Polymorphism** is the ability of a class instance to behave as if it were an instance of another class in its inheritance tree, most often one of its ancestor classes. For example, in Java all classes inherit from Object. Therefore, you can create a variable of type Object and assign to it an instance of any class.
... | Polymorphism vs Overriding vs Overloading | [
"",
"java",
"oop",
"polymorphism",
"overloading",
"overriding",
""
] |
I want to combine these:
```
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
```
into a single dictionary:
```
{'name': 'Monty', 'age': 42, 'food': 'spam'}
```
How can I do this? | Like this:
```
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print(dictionary) # {'a': 1, 'b': 2, 'c': 3}
```
Voila :-) The pairwise [`dict`](https://docs.python.org/3/library/functions.html#func-dict) constructor and [`zip`](https://docs.python.org/3/library/functions.html#zip) funct... | > Imagine that you have:
>
> ```
> keys = ('name', 'age', 'food')
> values = ('Monty', 42, 'spam')
> ```
>
> **What is the simplest way to produce the following dictionary ?**
>
> ```
> dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
> ```
## Most performant, `dict` constructor with `zip`
```
new_dict = dict(z... | Make a dictionary (dict) from separate lists of keys and values | [
"",
"python",
"list",
"dictionary",
""
] |
Can anyone give me a complete list of string manipulation function in Microsoft SQL Server (2000 or 2005)?
(I don't need a lecture about doing all my string processing in the presentation layer. And, I don't need a list of MySQL string functions.)
Thanks! | [String Functions (Transact-SQL)](http://msdn.microsoft.com/en-us/library/ms181984.aspx) | MSDN and Google are your friends
[here is the 2008 version](http://msdn.microsoft.com/en-us/library/ms181984.aspx), drill down to your specific flavor. | String Manipulation in MS SQL Server | [
"",
"sql",
"sql-server",
"string",
""
] |
I often need to run reduce (also called foldl / foldr, depending on your contexts) in java to aggregate elements of an Itterable.
Reduce takes a collection/iterable/etc, a function of two parameters, and an optional start value (depending on the implementation details). The function is successively applied to an eleme... | you could probably roll your own generic pretty easily, based on your description:
```
public interface Reducer<A, T>
{
public A foldIn(A accum, T next);
}
```
Then using the strategy pattern:
```
public class Reductor<A, T>
{
private Reducer<A, T> worker;
public Reductor<A, T>(Reducer<A, T> worker)
... | Based on Luke's suggestion, here is a legit Java implementation:
```
public interface Reducer<A,T>
{
A foldIn(A accum, T next);
}
public static <T> T reduce(final Reducer<T,T> reducer,
final Iterable<? extends T> i)
{
T result = null;
final Iterator<? extends T> iter = i.iterator();
if (iter.... | Is there a type-safe Java implementation of 'reduce'? | [
"",
"java",
"collections",
"reduce",
""
] |
I am looking out for some good practices on naming assemblies and versioning them. How often do you increment the major or minor versions?
In some cases, I have seen releases going straight from version 1.0 to 3.0. In other cases, it seems to be stuck at version 1.0.2.xxxx.
This will be for a shared assembly used in ... | Some good information from [this article](http://blogs.msdn.com/suzcook/archive/2003/05/29/57148.aspx) on Suzanne Cook's blog on MSDN (posted 2003-05-30):
> # When to Change File/Assembly Versions
>
> First of all, file versions and assembly versions need not coincide
> with each other. I recommend that file versions ... | One way to define your versioning is to give semantic meaning to each portion:
* Go from N.x to N+1.0 when compatibility breaks with the new relase* Go from N.M to N.M+1 when new features are added which do not break compatibility* Go from N.M.X to N.M.X+1 when bug fixes are added
The above is just an example -- you'... | Best practices for assembly naming and versioning? | [
"",
"c#",
".net",
"assemblies",
"versioning",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.