Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
In my web app I use several asmx (Web Services) from the same provider, they have one for this, other for that, but all require a SOAP Header with Authentication.
It is simple to add the Authentication:
```
public static SoCredentialsHeader AttachCredentialHeader()
{
SoCredentialsHeader ch = new SoCredentialsHead... | Create a file called whatever.tt (the trick is the .tt extension) anywhere in your VS solution and paste the following code:
```
using System;
namespace Whatever
{
public static class Howdy
{
<#
string[] webServices = new string[] {"wsContact", "wsDiary"};
foreach (string wsName in webServices)
{... | I don't know if this is something you wish to consider, as it definitely has it's down sides, but - as ultimately these ( the varoius SoCredentialsHeader classes) are all copies of the same class definition in different namespaces so with a little bit of refactoring you could simply have one class and one method.
Copy... | Create an "all-in-one" function using DS in C# | [
"",
"c#",
"asp.net",
"design-patterns",
""
] |
Say we have:
```
class Base
{
virtual void f() {g();};
virtual void g(){//Do some Base related code;}
};
class Derived : public Base
{
virtual void f(){Base::f();} override;
virtual void g(){/*Do some Derived related code*/} override;
};
int main()
{
Base *pBase = new Derived;
pBase->f(... | The g of the derived class will be called. If you want to call the function in the base, call
```
Base::g();
```
instead. If you want to call the derived, but still want to have the base version be called, arrange that the derived version of g calls the base version in its first statement:
```
virtual void g() {
... | It is the Derived::g, unless you call g in Base's constructor. Because Base constructor is called before Derived object is constructed, Derived::g can not logically be called cause it might manipulate variables that has not been constructed yet, so Base::g will be called. | virtual function call from base class | [
"",
"c++",
"polymorphism",
"virtual",
""
] |
Well, I must be brain-damaged, because I can't find the java source for Sun's persistence.jar or JBoss's ejb3-persistence.jar JPA package. They *are* open-source aren't they?
I looked all over the java.sun.com site as well as the GlassFish wiki, but came up empty.
I'd like a src.zip or folder like Sun delivers with J... | I have found the version 1.0.2 GA it here: <http://grepcode.com/snapshot/repository.jboss.com/maven2/org.hibernate/ejb3-persistence/1.0.2.GA> | I just did a search on <http://www.mvnrepository.com> for persistence api
<http://mirrors.ibiblio.org/pub/mirrors/maven2/javax/persistence/persistence-api/1.0/persistence-api-1.0-sources.jar>
also available in the java.net maven 1 repository
<http://download.java.net/maven/1/javax.persistence/java-sources/>
for the ... | ejb3-persistence.jar source | [
"",
"java",
"jpa",
"open-source",
"persistence",
""
] |
I was wondering why `shared_ptr` doesn't have an implicit constructor. The fact it doesn't is alluded to here: [Getting a boost::shared\_ptr for this](https://stackoverflow.com/questions/142391/getting-a-boostsharedptr-for-this)
(I figured out the reason but thought it would be a fun question to post anyway.)
```
#in... | In this case, the shared\_ptr would attempt to free your stack allocated int. You wouldn't want that, so the explicit constructor is there to make you think about it. | The logical reason is that:
* calling the `delete` operator is not implicit in C++
* **the creation of any owning smart pointer** (`shared_`whatever, `scoped_`whatever, ...) **is really a (delayed) call to the `delete` operator** | Why shared_ptr has an explicit constructor | [
"",
"c++",
"boost",
"refcounting",
""
] |
I have a few things that I cannot find a good way to perform in Visual Studio:
1. Pre-build step invokes a code generator that generates some source files which are later compiled. This can be solved to a limited extent by adding blank files to the project (which are later replaced with real generated files), but it d... | 1. If you need make behavior and are used to it, you can create [visual studio makefile projects](http://msdn.microsoft.com/en-us/library/txcwa2xx(VS.80).aspx) and include them in your project.
2. If you want less clunky, you can write visual studio [macros](http://visualstudiohacks.com/articles/general/customize-your-... | I've gone through this exact problem and I did get it working using Custom Build Rules.
But it was always a pain and worked poorly. I abandoned visual studio and went with a Makefile system using cygwin. Much better now.
cl.exe is the name of the VS compiler.
Update: I recently switched to using cmake, which comes w... | Complex builds in Visual Studio | [
"",
"c++",
"c",
"windows",
"visual-studio",
"build",
""
] |
I have a Windows application written in C++ that occasionally evaporates. I use the word evaporate because there is nothing left behind: no "we're sorry" message from Windows, no crash dump from the Dr. Watson facility...
On the one occasion the crash occurred under the debugger, the debugger did not break---it showed... | You could try using the adplus utility in the [windows debugging tool package](http://www.microsoft.com/whdc/devtools/debugging/default.mspx).
```
adplus -crash -p yourprocessid
```
The auto dump tool provides mini dumps for exceptions and a full dump if the application crashes. | If you are using Visual Studio 2003 or later, you should enable the debuggers "First Chance Exception" handler feature by turning on ALL the Debug Exception Break options found under the Debug Menu | Exceptions Dialog. Turn on EVERY option before starting the debug build of the process within the debugger.
By default ... | How can I debug a win32 process that unexpectedly terminates silently? | [
"",
"c++",
"debugging",
"winapi",
"crash",
""
] |
In java, does `file.delete()` return `true` or `false` where `File file` refers to a non-existent file?
I realize this is kind of a basic question, and easy to very through test, but I'm getting strange results and would appreciate confirmation. | Doesn't that result in a FileNotFoundException?
EDIT:
Indeed it does result in false:
```
import java.io.File;
public class FileDoesNotExistTest {
public static void main( String[] args ) {
final boolean result = new File( "test" ).delete();
System.out.println( "result: |" + result + "|" );
}
}
```
p... | From [<http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#delete()>](http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#delete()):
Returns: true if and only if the file or directory is successfully deleted; false otherwise
Therefore, it should return false for a non-existent file. The following test con... | Does file.delete() return true or false for non-existent file? | [
"",
"java",
"file",
""
] |
I want to cast both MenuItem objects and Button control objects to an object type of whose "Tag" property I can reference.
Is there such an object type?
E.g.
```
void itemClick(object sender, EventArgs e)
{
Control c = (Control)sender;
MethodInvoker method = new MethodInvoker(c.Tag.ToString(), "Execute");
... | Use "as" operator.
```
object tag;
Button button;
MenuItem menuItem = sender as MenuItem;
if (menuItem != null)
{
tag = menuItem.Tag;
}
else if( (button = sender as Button) != null )
{
tag = button.Tag;
}
else
{
//not button nor MenuItem
}
``` | I am writing this without IDE.
```
object myControlOrMenu = sender as MenuItem ?? sender as Button;
if (myControlOrMenu == null)
// neither of button or menuitem
``` | Is there a type of object, to which I can cast both Buttons AND MenuItem objects in order to access their Tag properties? | [
"",
"c#",
".net",
"casting",
""
] |
Is it possible to declare an instance of a generic without knowing the type at design-time?
Example:
```
Int i = 1;
List<typeof(i)> list = new List<typeof(i)>();
```
where the type of i could be anything, instead of having to do:
```
List<int> list = new List<int();
``` | If you don't know the type at compile-time, but you want the actual type (i.e. not `List<object>`) *and* you're not in a generic method/type with the appropriate type parameter, then you have to use reflection.
To make the reflection simpler, I've sometimes introduced a new generic type or method in my own code, so I ... | If you don't know the type at design-time, I'd say you have a list of OBJECTS (the base class for all other types).
```
List<object> list = new List<object>();
``` | Declare a generic type instance dynamically | [
"",
"c#",
".net",
"generics",
""
] |
I have this line of JavaScript and the behavior I am seeing is that the `selectedLi` instantly disappears without "sliding up". This is not the behavior that I expected.
What should I be doing so that the `selectedLi` slides up before it is removed?
```
selectedLi.slideUp("normal").remove();
``` | Might be able to fix it by putting the call to remove in a callback arg to slideUp?
e.g
```
selectedLi.slideUp("normal", function() { $(this).remove(); } );
``` | You need to be more explicit: rather than saying "this" (which I agree should work), you should do this:
```
$("#yourdiv").slideUp(1000, function() {
$(this).remove();
});
``` | jQuery slideUp().remove() doesn't seem to show the slideUp animation before remove occurs | [
"",
"javascript",
"jquery",
"animation",
""
] |
I think my eclipse's ctrl+clicking links might benefit greatly...
**Edit:** I'm using eclipse PDT.
**Edit 2:** I'm very happy with the solution of putting docblocks before functions (and variables) with an @return or @var statement, I've just updated the documentation of my app and now eclipse is showing me what func... | ```
// [...]
/**
* Return the Request object
*
* @return Zend_Controller_Request_Abstract
*/
public function getRequest()
{
return $this->_request;
}
// [...]
```
works perfectly with Eclipse PDT. Which plugin do you use? | Short answer: no.
Long answer: consider adding docblocks with @return declarations. | Can you hint return types in PHP 5.2.5? | [
"",
"php",
"eclipse",
"return-value",
"php-5.2",
"type-hinting",
""
] |
I need to provide email sending and receiving capabilities within my java web-application. Think of it as providing a lightweight IMAP client embedded within the application.
Are there any good java based open-source libraries/projects/webmail solutions that provide similar functionality?
Please note that I don't wan... | The "canonical" Java IMAP solution would, in my experience, be [JavaMail](http://java.sun.com/products/javamail/). And yes, that's open-source now, too: <https://maven-repository.dev.java.net/nonav/repository/javax.mail/java-sources/> | Look here: [Open Source Web Mail Clients in Java](http://java-sources.org/open-source/web-mail) | Java based Webmail solutions | [
"",
"java",
"webmail",
""
] |
Let's say I have a payments table like so:
```
CREATE TABLE Payments (
PaymentID INT,
CustomerID INT,
Value INT,
PaidOn DATE
);
INSERT INTO Payments
VALUES
(1, 1, 5, '2000-01-01'),
(2, 1, 10, '2000-02-01'),
(3, 2, 10, '2000-01-02'),
(4, 2, 10, '2000-01-20'),
(5, 2, 5, '2000-02-02'),
```
And I want to run a... | The following query will accomplish that. It pulls out all the rows for which there is not a greater Value.
```
SELECT *
FROM payments p
WHERE NOT EXISTS (
SELECT *
FROM payments p2
WHERE p2.CustomerID = p.CustomerId
AND p2.Value > p.Value
)
``` | ```
select PaymentID, CustomerID, Value, PaidOn
from payments
where (customerID, value) in
( select customerID, max(value)
from payments
group by customerID
);
```
Note that this can return more than one row per customer if they have more than one payment with the maximum value. | SQL query for finding representative rows in a table | [
"",
"sql",
"groupwise-maximum",
""
] |
I've implemented my own event handler and added it to the selection model of the table:
```
table.getSelectionModel().addListSelectionListener(event);
```
And implemented the method for "event" (mentioned above):
```
public void valueChanged(ListSelectionEvent e) {
log.debug("value changed");
}
```
Unfortunatel... | 1) I think you'll find it fires once for de-selecting the old selection and once for selecting the new selection. If you log the details of the event you should see exactly what's going on. I can't remember the details, so perhaps this is wrong. Either way you should be able to call getValueIsAdjusting() on the event a... | Thanks Draemon..It Works fine....
## Our Code
```
vMachinesTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent lse) {
if (!lse.getValueIsAdjusting()) {
System.out.println("Selection Changed");
}
}
});
```
Th... | JTable selection change event handling: find the source table dynamically | [
"",
"java",
"event-handling",
"jtable",
""
] |
What is the best way to have an associative array with arbitrary value types for each key in C++?
Currently my plan is to create a "value" class with member variables of the types I will be expecting. For example:
```
class Value {
int iValue;
Value(int v) { iValue = v; }
std::string sValue;
Value(s... | [boost::variant](http://www.boost.org/doc/libs/1_37_0/doc/html/variant.html) seems exactly what you are looking for. | Your approach was basically into the right direction. You *will* have to know the type you put into. You can use `boost::any` and you will be able to put just about anything into the map, as long as you know what you put into:
```
std::map<std::string, boost::any> table;
table["hello"] = 10;
std::cout << boost::any_ca... | C++ associative array with arbitrary types for values | [
"",
"c++",
"arrays",
"stl",
"boost",
""
] |
I want to access Microsoft SQL Server Compact Edition databases from Java. How can I do that? I searched for JDBC driver for SQLCE, but I didn't find any. | According to [a newsgroup post sent this Tuesday (2008-12-09) by Jimmy Wu@Mircrosoft](http://groups.google.com/group/microsoft.public.sqlserver.jdbcdriver/browse_thread/thread/2ba56d70e6b35ee7):
> The Microsoft SQL Server JDBC Driver
> does not support connecting to SQL
> Server Compact. At this time there
> isn't a s... | According to [MSDN](http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=770916&SiteID=1), there isn't one and there aren't any plans neither. | How to use SQL Server Compact Edition (CE) from Java? | [
"",
"java",
"sql-server",
"jdbc",
"sql-server-ce",
""
] |
I want to spruce up some areas of my website with a few jQuery animations here and there, and I'm looking to replace my AJAX code entirely since my existing code is having some cross-browser compatibility issues. However, since jQuery is a JavaScript library, I'm worried about my pages not functioning correctly when Ja... | If you consider the "Cascading Order" of css, could you not just add a css style at the very end of all your previous css definition in order to cancel any css effect you currently have for tooltip effect ?
That css rule would only be declared if Javascript is activated and JQuery detected.
That way, you are sure you... | If something can be done completely in CSS I say keep it that way. If lack of javascript in the browser is a concern, then most of the time I show the entire page unaffected.
Say for instance I'm going to use jQuery to toggle an element when a checkbox is clicked. On page load I look at the checkbox and update the ele... | jQuery Graceful Degradation | [
"",
"javascript",
"jquery",
"css",
"backwards-compatibility",
""
] |
Is there something like python's interactive REPL mode, but for Java?
So that I can, for example, type `InetAddress.getAllByName( localHostName )` in a window, and immediately get results, without all this public static void nightmare() thing? | **edit**
Since Java 9 there's [JShell](https://en.wikipedia.org/wiki/JShell)
*Original answer follows*
You can also use [Groovy Console](http://www.groovy-lang.org/groovyconsole.html). It is an interactive console where you can do what you want. Since Groovy also includes classes from the core java platform, you'll b... | Eclipse has a feature to do this, although it's not a loop. It's called a "Scrapbook Page". I assume the analogy is supposed to be that you have a scrapbook where you collect little snippets of code.
Anyway, to make it work, open a project in Eclipse (your Scrapbook Page is going to be associated with a project -- Ecl... | Is there something like python's interactive REPL mode, but for Java? | [
"",
"java",
"read-eval-print-loop",
""
] |
I have a DataGridView that I want to query using Linq (C# WinForm). I want to "count" rows where a certain criteria is met. For example,
```
variable1 = "count rows where ColumnBoxAge > 3 || < 5"
label1.Text = variable1
```
How to do this in C# WinForm using Linq? | I don't know if it could work but you can try this;
```
dataSet.Tables[0].AsEnumerable().Where(c => c.Field<int>("ageColumn") > 3 ||
c.Field<int>("ageColumn") < 5).Count();
```
Edit : Where instead of Select. | So your query is wrong! Try to put '&&' instead of '||';
```
dataSet.Tables[0].AsEnumerable().Where(c => c.Field<int>("ageColumn") > 3 &&
c.Field<int>("ageColumn") < 5).Count();
```
Edit : Where instead of Select. | How to Query A DataGridView Using Linq | [
"",
"sql",
"sql-server",
"linq",
"datagridview",
""
] |
I can't seem to retrieve an ID I'm sending in a html.ActionLink in my controller, here is what I'm trying to do
```
<li>
<%= Html.ActionLink("Modify Villa", "Modify", "Villa", new { @id = "1" })%></li>
public ActionResult Modify(string ID)
{
ViewData["Title"] =ID;
return View();
}
``... | Doesn't look like you are using the correct overload of ActionLink. Try this:-
```
<%=Html.ActionLink("Modify Villa", "Modify", new {id = "1"})%>
```
This assumes your view is under the /Views/Villa folder. If not then I suspect you need:-
```
<%=Html.ActionLink("Modify Villa", "Modify", "Villa", new {id = "1"}, nul... | In MVC 4 you can link from one view to another controller passing the Id or Primary Key via
```
@Html.ActionLink("Select", "Create", "StudentApplication", new { id=item.PersonId }, null)
``` | ASP.NET MVC passing an ID in an ActionLink to the controller | [
"",
"c#",
"asp.net-mvc",
""
] |
I have a YouTube's player in the webpage. I need to change the video played by this player dynamicaly.
This is (relatively) easy using YouTube's chromeless player. It has method [`loadVideoById()`](http://code.google.com/apis/youtube/chromeless_player_reference.html#loadVideoById) which works perfectly. The problem is... | You can not do that, cause the calls in the "regular youtube player" have the VideoID in the URL instead as a parameter:
* Regular Video: <http://www.youtube.com/v/VIDEO_ID&enablejsapi=1&playerapiid=ytplayer>
* Chromeless: <http://www.youtube.com/apiplayer?enablejsapi=1>
Instead of that you can easily create your own... | You can do this...
<http://code.google.com/apis/ajax/playground/#change_the_playing_video> | loadVideoById() in YouTube's regular player (not chromeless) | [
"",
"javascript",
"api",
"youtube",
""
] |
any generic way to trace/log values of all local variables when an exception occurs in a method?
(in C# 3) | Answer: Using PostSharp (Policy Injection), XTraceMethodBoundary attribute, override OnException .
this logs all the method input and return parameters types and values. I modified PostSharp to add a simple method to log parameters. not perfect but good enough
```
private static void TraceMethodArguments(MethodExecuti... | You can't, basically. Reflection lets you get at *instance* (and static) variables but if you want to log local variables, you'll have to do so explicitly. It's possible that you could do a bit better using the profiling API, but that would be a pretty extreme step. | How to Trace all local variables when an exception occurs | [
"",
"c#",
".net",
"exception",
"logging",
""
] |
I want to change the behavior of a JavaScript used to display a banner, coming from a central source.
Today I include a script-tag inline in code, like this:
```
<script type="text/javascript" src="http://banner.com/b?id=1234"></script>
```
But what that returns is code which uses `document.write`, like this:
```
i... | Yes, you can override document.write. Prototyping is not necessary, you can do it directly on the document object itself. I do this commonly for analysing malware, but it could certainly be used to capture ad script output, as long as the ad script doesn't do any particularly convoluted processing that would turn up th... | Have you tried overriding document.write? I don't have time to try it right now but give this a go:
```
var foo = document.write;
var bannerCode = '';
document.write = function(str) { bannerCode += str; };
```
Then include the script file, then do
```
document.write = foo;
alert(bannerCode);
``` | JavaScript Banner changing | [
"",
"javascript",
"html",
""
] |
I'm working on a windows client written in WPF with C# on .Net 3.5 Sp1, where a requirement is that data from emails received by clients can be stored in the database. Right now the easiest way to handle this is to copy and paste the text, subject, contact information and time received manually using an arthritis-induc... | I found a great [article](http://www.codeproject.com/KB/office/outlook_drag_drop_in_cs.aspx) that should do exactly what you need to.
**UPDATE**
I was able to get the code in that article working in WPF with a little tweaking, below are the changes you need to make.
Change all references from System.Windows.Forms.ID... | I found a lot of solutions suggesting you use the “FileGroupDescriptor” for all the file names and the “FileContents” on the DragEventArgs object to retrieve the data of each file. The “FileGroupDescriptor” works fine for the email message names, but “FileContents” returns a null because the implementation of the IData... | Drag'n'drop one or more mails from Outlook to C# WPF application | [
"",
"c#",
"wpf",
"outlook",
"drag-and-drop",
""
] |
How would I go about dynamically allocating a multi-dimensional array? | If you know the size of nested dimensions already, you can also literally allocate a multi dimensional array using new:
```
typedef int dimensions[3][4];
dimensions * dim = new dimensions[10];
dim[/* from 0 to 9 */][/* from 0 to 2 */][/* from 0 to 3 */] = 42;
delete [] dim;
```
instead of `10`, a runtime determined ... | How about using Boost.Multiarray ? I believe it answers your need quite well !
<http://www.boost.org/doc/libs/1_37_0/libs/multi_array/doc/user.html#sec_introduction>
Here is an excerpt from the documentation page :
```
#include < boost/multi_array.hpp >
#include < cassert >
int main ()
{
// Create a 3D array... | C++ Multi-dimensional Arrays on the Heap | [
"",
"c++",
"arrays",
"memory",
"heap-memory",
"allocation",
""
] |
Given the following class
```
public class Foo
{
public int FooId { get; set; }
public string FooName { get; set; }
public override bool Equals(object obj)
{
Foo fooItem = obj as Foo;
if (fooItem == null)
{
return false;
}
return fooItem.FooId == t... | Yes, it is important if your item will be used as a key in a dictionary, or `HashSet<T>`, etc - since this is used (in the absence of a custom `IEqualityComparer<T>`) to group items into buckets. If the hash-code for two items does not match, they may *never* be considered equal ([Equals](https://learn.microsoft.com/en... | It's actually very hard to implement `GetHashCode()` correctly because, in addition to the rules Marc already mentioned, the hash code should not change during the lifetime of an object. Therefore the fields which are used to calculate the hash code must be immutable.
I finally found a solution to this problem when I ... | Why is it important to override GetHashCode when Equals method is overridden? | [
"",
"c#",
"overriding",
"hashcode",
""
] |
I've several textboxes. I would like to make the Enter button act as Tab. So that when I will be in one textbox, pressing Enter will move me to the next one. Could you please tell me how to implement this approach without adding any code inside textbox class (no override and so on if possible)? | Here is the code that I usually use.
It must be on KeyDown event.
```
if (e.KeyData == Keys.Enter)
{
e.SuppressKeyPress = true;
SelectNextControl(ActiveControl, true, true, true, true);
}
```
**UPDATE**
Other way is sending "TAB" key! And overriding the method make it so easier :)
```
protected override boo... | You can write on the **keyDown** of any control:
```
if (e.KeyCode == Keys.Enter)
{
if (this.GetNextControl(ActiveControl, true) != null)
{
e.Handled = true;
this.GetNextControl(ActiveControl, true).Focus();
}
}
```
GetNextC... | How to make Enter on a TextBox act as TAB button | [
"",
"c#",
".net",
"winforms",
""
] |
We're a team of a designer and a programmer. Me, the programmer, is hopeless on design of all sorts, so the user interface of the game must be created by the designer. We were thinking of a main screen, where the character walks around, a small minimap in the top, an inventory section, etc.
All these things would have... | It really depends on a few things..Is it for J2ME or are you considering this for desktop (OpenGL/JOGL)?
For J2ME you have to really know a bit about making games for devices with constrained memory. J2ME comes with its own GameCanvas and Sprite related classes that you can utilise. I Would recommend you read up on J2... | take a look at this:
<http://www.cs.qub.ac.uk/~P.Hanna/CSC207/lectures/lectures.htm> | How to design interface for a game in Java | [
"",
"java",
"swing",
"2d",
""
] |
I want to retrieve a set of records from a database, do a rs.next() and then assign the result of this to a variable to pass to a method that will use this record, in the same way that I would without assigning it to a variable and passing it to a method
is there any way to do this?
I'm using JAVA (1.5)
---
Thank you... | You want to assign the result of *rs.next()* to a variable?
I'm afraid you cannot do that. You can have a reference from that rs and process it in other method ( the same way you would without assign it to a var )
When you pass the rs as an argument to a method that is exactly what you're doing already.
```
while( r... | No, that is not supported out of the box, but maybe the following idea may help you:
```
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
Map<String,Object> row = new HashMap<String,Object>();
for (int i = 1; i <= meta.getColumnCount(); ++i) {
row.put(meta.getColumnName(i), rs.getObject(i));
}
... | assigning a specific record in a ResultSet to a variable | [
"",
"java",
"jdbc",
"resultset",
""
] |
I have an app that display's the current time when a page opens. I would like that time to update every 30 seconds. I've read about prototype's Ajax.PeriodicalUpdater and it seems to be an answer. This is how I achieve the static time display on page load with php:
```
<tr>
<td>
<input class="standar... | Unless you want your time output to always match the timezone of the server, you could do this very quickly with a bit of Javascript on the client side and skip contacting the server entirely.
```
<html>
<body onload="init();">
<div id=time></div>
</body>
</html>
<script type=text/javascript>
function init()
{
... | This can be accomplished without hitting up the server. Prototype's PeriodicalExecuter class encapsulates JavaScript's setInterval function, which allows you to run a JavaScript function every X seconds.
**time.html**
```
<html>
<head>
<title>Time</title>
<script type="text/javascript" src="time.js">
</head>
<body>
... | Display Current Time each minute (with Prototype's Ajax.PeriodicalUpdater ?) | [
"",
"javascript",
"prototypejs",
""
] |
I want to insert multiple invisible watermarks into my JPEG pictures through C# code. That means that I need a .NET library that does this work and not some external batch application.
Any suggestions? | there is a port of image magick library to c# , and it can easily perform that operation for you... | Storing "invisible" data in pictures is known as "steganography". A Google-search for "steganography .net" yields [this article](http://www.devx.com/dotnet/Article/22667/0/page/1) as its top hit - might prove useful. | Adding an invisible image watermark in C#? | [
"",
"c#",
".net",
"image",
"watermark",
"invisible",
""
] |
Something's slowing down my Javascript code in IE6 to where there's a noticeable lag on hover. It's fine in FF, so using firebug isn't that helpful. What tools are out there to help debug this in IE?
**A little more info:** I don't think there's actually any JS running on the objects that I'm mousing over. (At least n... | I think I've found the source of the slowdown for anyone who's curious: I'm using [bgiframe](http://plugins.jquery.com/project/bgiframe) to solve the IE6 select box z-index problem ([discussed elsewhere](https://stackoverflow.com/questions/224471/iframe-shimming-or-ie6-and-below-select-z-index-bug) on SO). | Just a tip of what that "something" could be...
**String concatenation** in IE is (or at least was when I [tested](http://forums.thedailywtf.com/forums/p/8931/169331.aspx)) very slow. Opera finished after 0.2s, Firefox after 4.1s and Internet Explorer 7 still hadn’t finished after 20 **minutes**!!!
Don't do:
```
for... | How to find slow-down in Javascript in IE6 | [
"",
"javascript",
"debugging",
"internet-explorer-6",
""
] |
Ok, I have the following structure. Basically a plugin architecture
```
// assembly 1 - Base Class which contains the contract
public class BaseEntity {
public string MyName() {
// figure out the name of the deriving class
// perhaps via reflection
}
}
// assembly 2 - contains plugins based on the Base Cl... | I think you can do it through GetType:
```
public class BaseEntity {
public string MyName() {
return this.GetType().Name
}
}
``` | ```
public class BaseEntity {
public string MyName() {
return this.GetType().Name;
}
}
```
"this" will point to the derived class, so if you were to do:
```
BaseEntity.MyName
"BaseEntity"
BlueEntitiy.MyName
"BlueEntity"
```
EDIT: Doh, Gorky beat me to it. | How to get the name of the class | [
"",
"c#",
"visual-studio-2008",
""
] |
Apparently I can't move files on different volumes using Directory.Move.
I have read that I have to copy each file individually to the destination, then delete the source directory.
Do I have any other option? | Regardless of whether or not Directory.Move (or any other function) performed the move between volumes, it would essentially be doing a copy and delete anyway underneath. So if you want a speed increase, that's not going to happen. I think the best solution would be to write your own reusable move function, which would... | To my knowledge there is no other way however deleting a directory has a catch: Read Only Files might cause a `UnauthorizedAccessException` when deleting a directory and all of its contents.
This recurses a directory and unsets all the read only flags. Call before `Directory.Delete`:
```
public void removeReadOnlyDee... | Moving files on different volumes in .NET | [
"",
"c#",
".net",
"file-io",
"directory-structure",
""
] |
When I create utility classes I typically create a class that has a private constructor and exposes all of it's methods and properties as static. What's the best approach for this? What's the difference between the way I do or creating a static class? | Static classes are automatically sealed, so people can't inherit and override their behavior.
That is the only real difference (unless there is something special in the IL)
So if you use a static class, you save yourself the trouble of making the constructor private, and declaring the class sealed.
I would add, that... | A static class can never be instantiated. No way, no how.
A non-static class with a private constructor but all static methods can be abused in various ways - inheritance, reflection, call the private constructor in a static factory - to instantiate the class.
If you never want instantiation, I'd go with the static c... | Static Class Vs. Class with private constructor and all static properties and methods? | [
"",
"c#",
".net",
""
] |
Let's assume I'm a complete lazy bum and I don't want to invest the several dozen keystrokes needed for my own exception class (it's not utterly important which gets used, really). However, to pretend I'm following good practices here, I want a pre-existing one that best fits my situation.
**Problem:** I need to throw... | `IllegalArgumentException` | Winner by Accuracy:
[java.lang.IllegalArgumentException](http://java.sun.com/javase/6/docs/api/java/lang/IllegalArgumentException.html) | Which Java exception should I use? | [
"",
"java",
"exception",
""
] |
I have a small lightweight application that is used as part of a larger solution. Currently it is written in C but I am looking to rewrite it using a cross-platform scripting language. The solution needs to run on Windows, Linux, Solaris, AIX and HP-UX.
The existing C application works fine but I want to have a single... | Because of your requirement for fast startup time and a calling frequency greater than 1Hz I'd recommend either staying with C and figuring out how to make it portable (not always as easy as a few ifdefs) or exploring the possibility of turning it into a service daemon that is always running. Of course this depends on ... | Lua is a scripting language that meets your criteria. It's certainly the fastest and lowest memory scripting language available. | Scripting language choice for initial performance | [
"",
"python",
"ruby",
"perl",
"bash",
"scripting-language",
""
] |
I have a database table with a large number of rows and one numeric column, and I want to represent this data in memory. I could just use one big integer array and this would be very fast, but the number of rows could be too large for this.
Most of the rows (more than 99%) have a value of zero. Is there an effective d... | I would expect that the map/dictionary/hashtable of the non-zero values should be a fast and economical solution.
In Java, using the Hashtable class would introduce locking because it is supposed to be thread-safe. Perhaps something similar has slowed down your implementation.
**--- update: using Google-fu suggests t... | This is an example of a *sparse* data structure and there are multiple ways to implement such sparse arrays (or matrices) - it all depends on how you intend to use it. Two possible strategies are:
* Store only non-zero values. For each element different than zero store a pair (index, value), all other values are known... | Data structure question | [
"",
"c#",
".net",
""
] |
Py3k [just came out](http://mail.python.org/pipermail/python-list/2008-December/518408.html) and has gobs of [neat new stuff](http://docs.python.org/3.0/whatsnew/3.0.html)! I'm curious, what are SO pythonistas most excited about? What features are going to affect the way you write code on a daily basis, or have you bee... | There are a few things I'm quite interested in:
* *Text and data* instead of *unicode and 8 bit*
* [Extended Iterable Unpacking](http://www.python.org/dev/peps/pep-3132)
* [Function annotations](http://www.python.org/dev/peps/pep-3107/)
* Binary literals
* [New exception catching syntax](http://www.python.org/dev/peps... | I hope that [exception chaining](http://www.python.org/dev/peps/pep-3134/) catches on. Losing exception stack traces due to the antipattern presented below had been my pet peeve for a long time:
```
try:
doSomething( someObject)
except:
someCleanup()
# Thanks for passing the error-causing object,
# but th... | What features of Python 3.0 will change your everyday coding? | [
"",
"python",
"python-3.x",
""
] |
I'm the developer of twittertrend.net, I was wondering if there was a faster way to get headers of a URL, besides doing curl\_multi? I process over 250 URLs a minute, and I need a really fast way to do this from a PHP standpoint. Either a bash script could be used and then output the headers or C appliation, anything t... | I think you need a multi-process batch URL fetching daemon. PHP does not support multithreading, but there's nothing stopping you from spawning multiple PHP daemon processes.
Having said that, PHP's lack of a proper garbage collector means that long-running processes can leak memory.
Run a daemon which spawns lots of... | I recently wrote a blog post on how to speed up curl\_multi. Basically I process each request as soon as it finishes and use a queue to keep a large number of requests going at once. I've had good success with this technique and am using it to process ~6000 RSS feeds a minute. I hope this helps!
<http://onlineaspect.c... | Better support for CURL with PHP and Linux | [
"",
"php",
"mysql",
"linux",
"curl",
"curl-multi",
""
] |
I hope someone could help me on this.
I want to add a month to a database date, but I want to prevent two jumping over month on those days at the end.
For instance I may have:
Jan 31 2009
And I want to get
Feb 28 2009
and not
March 2 2009
Next date would be
March 28 2009
Jun 28 2009
etc.
Is there a function... | Oracle has a built-in function [ADD\_MONTHS](http://download.oracle.com/docs/cd/B10501_01/server.920/a96540/functions5a.htm) that does exactly that:
```
SQL> select add_months(date '2008-01-31',1) from dual;
ADD_MONTHS(
-----------
29-FEB-2008
SQL> select add_months(date '2008-02-29',1) from dual;
ADD_MONTHS(
-----... | I think you're looking for LAST\_DAY:
<http://download.oracle.com/docs/cd/B28359_01/olap.111/b28126/dml_functions_2006.htm> | Add date without exceeding a month | [
"",
"sql",
"oracle",
"function",
"date",
"math",
""
] |
In my app I have 2 divs, one with a long list of products that can be dragged into another div (shopping cart). The product div has the overflow but it breaks prototype draggable elements. The prototype hacks are very obtrusive and not compatible with all browsers.
So I am taking a different approach, is it possible t... | Theres a css property to control that.
```
<div style="width:100px;height:100px;overflow:scroll">
</div>
```
<http://www.w3schools.com/Css/pr_pos_overflow.asp> | You can use a frame with content larger than its window. Might make it hard to pass JS events though. | Scrollable div without overflow:auto? | [
"",
"javascript",
"prototypejs",
"scriptaculous",
""
] |
I just recently noticed `Dictionary.TryGetValue(TKey key, out TValue value)` and was curious as to which is the better approach to retrieving a value from the Dictionary.
I've traditionally done:
```
if (myDict.Contains(someKey))
someVal = myDict[someKey];
...
```
unless I know it *has* to be in there.
Is... | TryGetValue is slightly faster, because FindEntry will only be called once.
> How much faster? It depends on the
> dataset at hand. When you call the
> Contains method, Dictionary does an
> internal search to find its index. If
> it returns true, you need another
> index search to get the actual value.
> When you use ... | Well in fact TryGetValue is faster. How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if... | Retrieving Dictionary Value Best Practices | [
"",
"c#",
".net",
"dictionary",
""
] |
Am wondering if anyone might provide some conceptual advice on an efficient way to build a data model to accomplish the simple system described below. Am somewhat new to thinking in a non-relational manner and want to try avoiding any obvious pitfalls. It's my understanding that a basic principal is that "storage is ch... | Thanks to both of you for your suggestions. I've implemented (first iteration) as follows. Not sure if it's the best approach, but it's working.
Class A = Articles. Has a StringListProperty which can be queried on it's list elements
Class B = Tags. One entity per tag, also keeps a running count of the total number of... | counts being pre-computed is not only practical, but also necessary because the count() function returns a maximum of 1000. if write-contention might be an issue, make sure to check out the sharded counter example.
<http://code.google.com/appengine/articles/sharding_counters.html> | Data Modelling Advice for Blog Tagging system on Google App Engine | [
"",
"python",
"google-app-engine",
"data-modeling",
""
] |
How can I get a record id after saving it into database. Which I mean is actually something like that.
I have Document class (which is entity tho from DataBase) and I create an instance like
```
Document doc = new Document() {title="Math",name="Important"};
dataContext.Documents.InsertOnSubmit(doc);
dataContext.Submi... | Once you have run .SubmitChanges then doc.docId should be populated with the Id that was created on the database. | Like everyone has said you should be able to do something like this:
```
Document doc = new Document() {title="Math",name="Important"};
dataContext.Documents.InsertOnSubmit(doc);
dataContext.SubmitChanges();
```
then get the Id with:
```
int ID = doc.docId;
``` | Get Id using LINQ to SQL | [
"",
"c#",
"asp.net",
"linq-to-sql",
".net-3.5",
""
] |
I am creating a pdf document using C# code in my process. I need to protect the docuemnt
with some standard password like "123456" or some account number. I need to do this without
any reference dlls like pdf writer.
I am generating the PDF file using SQL Reporting services reports.
Is there are easiest way. | > I am creating a pdf document using C#
> code in my process
Are you using some library to create this document? The [pdf specification](http://www.adobe.com/devnet/acrobat/pdfs/PDF32000_2008.pdf) (8.6MB) is quite big and all tasks involving pdf manipulation could be difficult without using a third party library. Pass... | It would be very difficult to do this without using a PDF library. Basically, you'll need to develop such library yourselves.
With help of a PDF library everything is much simpler. Here is a sample that shows how a document can easily be protected using [Docotic.Pdf library](https://bitmiracle.com/pdf-library/):
```
... | Password protected PDF using C# | [
"",
"c#",
"pdf-generation",
""
] |
One doubt in MSSQL.
There are two tables in a databases.
Table 1 named Property contain
fields PRPT\_Id(int),PRPT\_Name(varchar), PRPT\_Status(bit)
Table 2 named PropertyImages contain fields PIMG\_Id(int),PIMG\_ImageName(varchar),PRPT\_Id(int),PIMG\_Status(bit)
These two tables follow a one-to-many relationship.
Th... | Assuming that FirstImage means the one with the lowest Id, then this should be at least close enough to test to completion:
> SELECT
> PRPT\_Id,
> PRPT\_Name,
> ISNULL(pi1.ImageName, '') AS FirstImageName,
> COUNT(1) AS ImageCount
>
> FROM Property AS p
>
> LEFT JOIN PropertyImages AS pi
> ON p.PRPT\_Id = pi... | It seems that you have to write nested queries to display what you want.
If that's the case (I'm no SQL expert), I'd recommend you to start with the innermost query, then you go out until you reach the outermost (and final) query.
First, you have to retrieve the PIMGs and group them by PRPT.
```
SELECT PRPT_Id, COUN... | Sql Query Linking Two Tables | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
In a bunch o' places in my code, I have something like this:
```
public Class mySpecialMethod() {
return MySpecialClass.class;
}
```
which causes the warning
> Class is a raw type. References to
> generic type Class should be
> parameterized.
But, if I replace
`Class`
with
`Class<? extends Object>`
the warnin... | It's the correct thing to do only if there really is no common base class or interface that the Class object needs to represent.
Also `Class<?>` is effectively the same as `Class<? extends Object>`. | Yes, it's totally right.
It's a requirement that you specify the type. And if you can't, you have to specify the wildcard.
Further reading: [Java Language Specification: Parameterized Types](http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.5.1) | Is it good practice to replace Class with Class<? extends Object> to avoid warnings? | [
"",
"java",
"generics",
"warnings",
"raw-types",
""
] |
I'm learning C# by writing a home library manager.
I have a BookController that will store the books in a data structure and perform operations on them.
Does C# have a way of saving the data in the dictionary to a local file perhaps in an XML fashion to load later, or am I going to have to write it myself?
What is t... | Actually, C# (the language) doesn't know **anything** about serialization, but .NET (the framework) provides lots of ways... `XmlSerializer`, `BinaryFormatter`, `DataContractSerializer` (.NET 3.0) - or there are a few bespoke serialization frameworks too.
Which to use depends on your requirements; `BinaryFormatter` is... | Look at [Serialization](http://www.codeproject.com/KB/cs/objserial.aspx) and the [ISerializable interface](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx)
It allows you to save an object's state in a portable form. | Saving Data Structures in C# | [
"",
"c#",
"serialization",
""
] |
I've done quite a bit of searching on this and haven't had much luck finding something cohesive. I'm a relatively new developer and have just started in my first professional development position. I know that I have a great deal to learn even in the realm of the basics. Based on listening to PodCasts, reading blogs, pa... | I was in the same situation and i bought these two books
(The PDF version to print out)
<http://www.manning.com/osherove/>
and
<http://www.manning.com/prasanna/> | You should definitely check out the IoC screencasts on [dimecasts.net](http://www.dimecasts.net/). They are very straight-forward and will help you to grasp some of the concepts. | IOC Design Resources | [
"",
"c#",
".net",
"dependency-injection",
"inversion-of-control",
"alt.net",
""
] |
Is it possible to just send a JPanel or any other component to the printer? Or do I have to implement all the drawing to the graphics object by hand?
I have tried to use the Print\* functions of the JPanel to print to the graphics object but the page that gets printed is blank. | Check out the Java printing API [and tutorial](http://java.sun.com/docs/books/tutorial/2d/printing/gui.html) along with JComponent.print(Graphics).
Here is a rudimentary class which will print any component which fits on 1 page (I can't take credit for this, I got the code from [Marty Hall's tutorial](http://courseweb... | [This tutorial](http://java.sun.com/docs/books/tutorial/2d/printing/gui.html) mentions translating the `Graphics` object. Have you tried that? | Send a JPanel to the printer | [
"",
"java",
"swing",
"printing",
""
] |
I've had some experience with Pygame, but there seems to be a lot of buzz around Pyglet these days.
How do these two libraries compare? What would be the advantage of using one over the other, both in features and ease of use?
Finally, would you say that one is more Pythonic than the other? | I was considering both Pygame and Pyglet for a small 2D shooter, and after looking at source code and some tutorials went with Pyglet. I was very happy with the results.
Pyglet worked immediately and was enjoyable to work with, and conceptually very clean. It certainly had a Pythonic feel to me: you could get a straig... | ### License:
* Pygame: LGPL license
* Pyglet: BSD license
### Library dependencies:
* Pygame relies on SDL libraries heavily
* Pyglet is a pure python library with fewer dependencies, I think it requires better understanding of OpenGL
### Community:
* Pygame is around here for a long time, a lot of people used it
... | Differences between Python game libraries Pygame and Pyglet? | [
"",
"python",
"pygame",
"pyglet",
""
] |
I have a java class which fires custom java events. The structure of the code is the following:
```
public class AEvent extends EventObject {
...
}
public interface AListener extends EventListener {
public void event1(AEvent event);
}
public class A {
public synchronized void addAListener(AListener l) {
..
... | I don't see a reason why `BListener` should extend `AListener`.
Do you really want to force everyone interested in `B` events to also implement `event1()`?
Also you can't add `addAListener()`, since a derived class can not reduce the visibility of a method that's present in the parent class. Also, you shouldn't need ... | Don't use inheritence, it's not what you want and will lead to a brittle and difficult to change design. Composition is a more flexible and a better approach for the design. Always try to design interfaces as granular as possible because they should not be changed event. They are your contract with the rest of the syst... | Java Listener inheritance | [
"",
"java",
"inheritance",
"events",
"listener",
""
] |
I fail to understand why this code won't compile
```
ExecutorService executor = new ScheduledThreadPoolExecutor(threads);
class DocFeeder implements Callable<Boolean> {....}
...
List<DocFeeder> list = new LinkedList<DocFeeder>();
list.add(new DocFeeder(1));
...
executor.invokeAll(list);
```
The error msg is:
```
... | Just to expand on saua's answer a little...
In Java 5, the method was declared as:
```
invokeAll(Collection<Callable<T>> tasks)
```
In Java 6, the method is declared as:
```
invokeAll(Collection<? extends Callable<T>> tasks)
```
The wildcarding difference is very important - because `List<DocFeeder>` *is* a `Colle... | That code compiles perfectly fine with Java 6, but fails to compile with Java 5 giving
```
Foo.java:9: cannot find symbol
symbol : method invokeAll(java.util.List)
location: interface java.util.concurrent.ExecutorService
executor.invokeAll(list);
^
1 error
```
However changing the `list` like this:
```
Coll... | invokeAll() is not willing to accept a Collection<Callable<T>> | [
"",
"java",
"executorservice",
"callable",
""
] |
if you browse the internet it's relatively easy to find code that modifies existing script maps (to switch between .NET versions, for example). However, the relatively obvious code to actually add or remove a script map doesn't seem to work. Has anyone succeeded in writing something that can add or delete a scriptmap i... | Here you go:
<http://blogs.msdn.com/david.wang/archive/2004/12/02/273681.aspx> | Look here: [how to add new application mapping in iis](https://stackoverflow.com/questions/265613/how-to-add-new-application-mapping-in-iis) | Adding an extension mapping to IIS | [
"",
"c#",
"iis",
"wmi",
""
] |
My company develop web apps using combination of mod\_perl, axkit and apache.
We have tons of Perl modules, javascripts, etc, all in unix operating system.
Whenever I need to write a new function, I try to do some code reuse, but the thing is all the Perl modules and javascripts are scattered across folders.
i hate t... | **Organize** your source directory so that each functionality has only one place where it should be and it's easy to find something.
Make sure to share **naming convention** to prevent duplication.
**Design** your module so that they do one thing only - and do it well.
**Review** the code to make sure names and loca... | I trust you have some form of version control software ([svn](http://subversion.tigris.org/), [Mercurial](http://selenic.com/wiki/Mercurial), git, whatever but not VSS)? If you don't now is time to get one and start using it. That way, you have at least an idea of which modules you are using and where the code is. You ... | How can I efficiently manage Perl modules for code reuse? | [
"",
"javascript",
"perl",
"code-reuse",
"module-management",
""
] |
When reading data from the Input file I noticed that the ¥ symbom was not being read by the StreamReader. Mozilla Firefox showed the input file type as Western (ISO-8859-1).
After playing around with the encoding parameters I found it worked successfully for the following values:
```
System.Text.Encoding.GetEncoding(... | Code page 1252 isn't quite the same as ISO-Latin-1. If you want ISO-Latin-1, use `Encoding.GetEncoding(28591)`. However, I'd expect them to be the same for this code point (U+00A5). UTF-7 is completely different (and almost never what you want to use).
`Encoding.Default` is *not* safe - it's a really bad idea in most ... | > The existing code did not use any encoding
It may not have explicitly specified the encoding, in which case the encoding probably defaulted to Encoding.UTF8.
The name Encoding.Default might give the impression that this is the default encoding used by classes such as StreamReader, but this is not the case: As Jon S... | StreamReader problem - Unknown file encoding (western iso 88591) | [
"",
"c#",
"encoding",
"character-encoding",
"inputstream",
"streamreader",
""
] |
Aloha
I have a method with (pseudo) signature:
```
public static T Parse<T>(string datadictionary) where T : List<U>
```
This doesn't build. How can I restrict the in the method to accept only generic List<> objects (which should of cource not contain T's but something else :)
I need to restrict the type of T becau... | Well, you can have two type parameters:
```
public static T Parse<T, U>(string datadictionary) where T : List<U>
```
That way you'll also actually know what U is (in a compile-time manner)...
EDIT: Alternatively (and better), just specify the element type and change the return type:
```
public static List<T> Parse<... | Assuming I read the question correctly, and you want to return `T` where `T : List<U>` (for some `T` and `U`)...
As an aside - subclassing `List<T>` isn't usually very useful... `List<T>` doesn't provide any useful virtual methods. Subclassing `Collection<T>` provides more flexibility. Of course, you can make your cod... | How can I specifiy a generic collection as restriction in a generic method | [
"",
"c#",
"generics",
""
] |
We have a PageRoles xml file which contains the page path and the user role that can access that page.
We are maintaining a Dictionary in a static class, which gets loaded int static constructor for the class.
The class has a method CheckIfRoleAllowed that takes in a page path and returns a bool.
Each page call the C... | You do use a singleton. Simply, there are 2 usual implementations for singletons, the other being instantiating the class and having a static member referencing this instance.
Your implementation makes calls simpler IMO :
```
PageAccessChecker.CheckIfRoleAllowed(path);
```
instead of:
```
PageAccessChecker._default... | I can see two advantages of using the singleton pattern (if implemented through, say, a static property):
1. you can delay loading the XML file until the first page is accessed.
2. you can check whether the XML file has changed on disk, and automatically reload it on the next access.
A disadvantage might be that you ... | Singleton vs Static Class for exposing data read from xml | [
"",
"c#",
".net",
"static",
"singleton",
""
] |
i want to get an ending html tag like `</EM>` only if somewhere before it i.e. before any previous tags or text there is no starting `<EM>` tag my sample string is
```
ddd d<STRONG>dfdsdsd dsdsddd<EM>ss</EM>r and</EM>and strong</STRONG>
```
in this string the output should be `</EM>` and this also the second `</EM>` ... | I am not sure regex is best suited for this kind of task, since tags can always be nested.
Anyhow, a C# regex like:
```
(?<!<EM>[^<]+)</EM>
```
would only bring the second `</EM>` tag
Note that:
* `?!` is a negative look*ahead* which explains why both `</EM>` are found.
So... `(?!=<EM>.*)`xxx actually means ca... | You need a [pushdown automaton](http://en.wikipedia.org/wiki/Pushdown_automaton) here. Regular expressions aren't powerful enough to capture this concept, since they are equivalent to [finite-state automata](http://en.wikipedia.org/wiki/Finite_state_automaton), so a regex solution is strictly speaking a no-go.
That sa... | Regex - Match an end html tag if start tag is not present | [
"",
"c#",
".net",
"regex",
""
] |
I'm getting a NullPointerException in a Class from a 3rd party library. Now I'd like to debug the whole thing and I would need to know from which object the class is held. But it seems to me that I cannot set a breakpoint in a Class from a 3rd party.
Does anyone know a way out of my trouble? Of course I'm using Eclips... | The most sure-fire way to do this (and end up with something that's actually useful) is to download the source (you say that it is open-source), and set up another "Java Project" pointing at that source.
To do that, get the source downloaded and unzipped somewhere on your system. Click "File"->"New"->"Java Project". I... | You can easily set method breakpoints in 3rd party libraries without having the source. Just open the class (you'll get the "i-have-no-source" view). Open the outline, right-click on the method you want and click on `Toggle Method Breakpoint` to create the method breakpoint. | How to set a breakpoint in Eclipse in a third party library? | [
"",
"java",
"eclipse",
"debugging",
"breakpoints",
""
] |
I have a CheckedListBox, and I want to automatically tick one of the items in it.
The `CheckedItems` collection doesn't allow you to add things to it.
Any suggestions? | You need to call **[`SetItemChecked`](http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.setitemchecked.aspx)** with the relevant item.
The [documentation for `CheckedListBox.ObjectCollection`](http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.objectcollection.aspx) h... | This is how you can select/tick or deselect/untick all of the items at once:
```
private void SelectAllCheckBoxes(bool CheckThem) {
for (int i = 0; i <= (checkedListBox1.Items.Count - 1); i++) {
if (CheckThem)
{
checkedListBox1.SetItemCheckState(i, CheckState.Checked);
}
... | How to programmatically check an item in a CheckedListBox in C#? | [
"",
"c#",
"winforms",
"checkedlistbox",
""
] |
I'm trying to open a file and create a list with each line read from the file.
```
i=0
List=[""]
for Line in inFile:
List[i]=Line.split(",")
i+=1
print List
```
But this sample code gives me an error because of the `i+=1` saying that `index is out of range`.
What's my problem here? How can I w... | It's a lot easier than that:
```
List = open("filename.txt").readlines()
```
This returns a list of each line in the file. | I did it this way
```
lines_list = open('file.txt').read().splitlines()
```
Every line comes with its end of line characters (\n\r); this way the characters are removed. | Create a List that contain each Line of a File | [
"",
"python",
""
] |
Can someone give me some example code that creates a surface with a transparent background in pygame? | This should do it:
```
image = pygame.Surface([640,480], pygame.SRCALPHA, 32)
image = image.convert_alpha()
```
Make sure that the color depth (32) stays explicitly set else this will not work. | You can also give it a colorkey, much like GIF file transparency. This is the most common way to make sprites. The original bitmap has the artwork, and has a certain color as background that will not be drawn, which is the colorkey:
```
surf.set_colorkey((255,0,255)) // Sets the colorkey to that hideous purple
```
Su... | How to make a surface with a transparent background in pygame | [
"",
"python",
"transparency",
"pygame",
""
] |
I have a PHP file, Test.php, and it has two functions:
```
<?php
echo displayInfo();
echo displayDetails();
?>
```
JavaScript:
```
<html>
...
<script type="text/javascript">
$.ajax({
type:'POST',
url: 'display.php',
data:'id='+id ,
success: fu... | If I understand correctly, you'd like for the `a` link to cancel navigation, but fire the AJAX function?
In that case:
```
$("#mylink").click(function() {
$.ajax({ type: "POST", url: "another.php", data: {id: "somedata"}, function(data) {
$("#response").html(data);
});
return false;
});
``` | You could just use [MooTools](http://en.wikipedia.org/wiki/MooTools) and class [Request.HTML](http://mootools.net/docs/Request/Request.HTML). | How load a PHP page in the same window in jQuery | [
"",
"php",
"jquery",
"ajax",
""
] |
The question is in the title, why :
```
return double.IsNaN(0.6d) && double.IsNaN(x);
```
Instead of
```
return (0.6d).IsNaN && x.IsNaN;
```
I ask because when implementing custom structs that have a special value with the same meaning as NaN I tend to prefer the second.
Additionally the performance of the propert... | Interesting question; don't know the answer - but if it really bugs you, you could declare an extension method, but it would still use the stack etc.
```
static bool IsNaN(this double value)
{
return double.IsNaN(value);
}
static void Main()
{
double x = 123.4;
bool isNan = x.IsNaN();
}
```
It would be n... | Static Methods are thread safe, methods on primitives generally need to be thread safe to support threading in the platform (meaning at least safe from internal race conditions), instance methods take a managed pointer to a structure, meaning that the structure/primitive might be modified concurrently while the method ... | Why IsNan is a static method on the Double class instead of an instance property? | [
"",
"c#",
"oop",
""
] |
Does anyone have any suggestions as to how I can clean the body of incoming emails? I want to strip out disclaimers, images and maybe any previous email text that may be also be present so that I am left with just the body text content. My guess is it isn't going to be possible in any reliable way, but has anyone tried... | In email, there is couple of agreed markings that mean something you wish to strip. You can look for these lines using [regular expressions](http://www.regular-expressions.info/). I doubt you can't really well "sanitize" your emails, but some things you can look for:
1. Line starting with "> " (greater than then white... | A few obvious things to look at:
1. if the mail is anything but pure plain text, the message will be multi-part mime. Any part whose type is "image/\*" (image/jpeg, etc), can probably be dropped. In all likelyhood any part whose type is not "text/\*" can go.
2. A HTML message will probably have a part of type "multipa... | Is it possible to programmatically 'clean' emails? | [
"",
"c#",
".net",
"email",
"email-processing",
""
] |
I'm trying to use the library released by Novell (Novell.Directory.Ldap). Version 2.1.10.
What I've done so far:
* I tested the connection with an application ([LdapBrowser](http://www.mcs.anl.gov/~gawor/ldap/index.html)) and it's working, so its not a communication problem.
* It's compiled in Mono, but I'm working w... | I finally found a way to make this work.
First, theses posts helped me get on the right track : <http://directoryprogramming.net/forums/thread/788.aspx>
Second, I got a compiled dll of the Novell LDAP Library and used the Mono.Security.Dll.
The solution:
I added this function to the code
```
// This is the Callbac... | I came looking for a solution to a similar problem. My bind command would fail as well while using the same code from Novell's website. The solution that worked for me was adding a dynamic Certificate Validation Call back. You can read about it [here](http://msdn.microsoft.com/en-us/library/exchange/dd633677%28v=exchg.... | Novell LDAP C# - Novell.Directory.Ldap - Has anybody made it work? | [
"",
"c#",
".net",
"ldap",
"novell",
""
] |
Is it possible to add a jQuery function so that a click in a table cell will invoke
a hidden <a href="javascript: ..." /> element (that is a descendant of the TD) ?
I've tried with
$('#table td').click(function() {
$(this).find('a').click();
});
An other variants, but to no luck.
--larsw | ```
<html>
<head></head>
<body>
<table border=1>
<tr>
<td>a1<a href=# onclick='alert("a1")' /></td>
<td>a2<a href=# onclick='alert("a2")' /></td>
</tr>
<tr>
<td>b1<a href=# onclick='alert("b1")' /></td>
<td>b2<a href=# onclick='alert("b2")' /></td>
</tr>
</table>
<script ... | Why don't you move your JavaScript code out of the `href` attribute and into your click event? jQuery was made to write unobtrusive JavaScript.
Edit:
No, but really, consider removing those hidden links in favor of unobtrusive JavaScript. Here are the relevant parts of Corey's example rewritten:
JS:
```
$(documen... | jQuery: invoke <a /> sub element of table cell | [
"",
"javascript",
"jquery",
"dhtml",
""
] |
Yesterday I thought it would be nice to implement my own Trigger in a WPF app. I created a class MyTrigger which inherited TriggerBase. TriggerBase is a public abstract class. So inheritance isn't a problem. But the constructors inside this class are marked internal. The compiler throws an error because the is no valid... | If you want the class to be visible, but only allow it to be subclassed within your own assembly. The subclasses may have public constuctors themselves - or they may be accessed with a factory.
I can't comment on whether that's a good design decision for TriggerBase in WPF, but it's at least reasonable in some situati... | One reason that I could think of is that the actual creation of new instances would be handled by another public class in the same assembly. This would force that you create the instance through this other class - possibly some sort of a factory pattern implementation. | internal constructor | [
"",
"c#",
".net",
""
] |
How do I return a constant from an sql statement?
For example how would I change the code below so "my message" would return if my (boolean expression) was true
```
if (my boolean expression)
"my message"
else
select top 1 name from people;
```
I am using ms sql 2000 | Did you try:
```
select 'my message';
``` | ```
select "my message" as message
``` | How do you return a constant from an sql statement? | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2000",
""
] |
I have a set of objects which I iterate through, however I may decide during the iteration that one (or more) of those objects now need to be deleted.
My code goes as follows:
```
if( ! m_Container.empty() )
{
for( typedefedcontainer::iterator it = m_Container.begin();
it != m_Container.end... | It depends on the container. The list container supports deletion during enumeration by returning a new iterator from the erase method that represents the next item in the list. map doesn't support this.
A simple method for map is to accumulate the items you want to erase in a separate list, and then iterate over that... | If the container supports it (which I suspect yours doesn't, but the question title is generic so this may be useful to others if not you):
```
struct SomePredicate {
bool operator()(typedefedcontainer::value_type thing) {
return ! SomeFunction(thing, "test", "TEST", false);
}
};
typedefedcontainer::i... | Best way to in situ delete an element | [
"",
"c++",
"stl",
"set",
""
] |
When developing with .NET 3.5 I naturally use LINQ for data access.
But for .NET 2.0 projects, what data access model is the best one to use? I tend to use TableAdapters mainly, but sometimes also write my own SQL depending on the situation. | Have you tried [NHibernate](http://nhibernate.org)? I haven't used it much myself, but my experience with its Java cousin was very positive.
There are other alternatives such as [LLBLGen](http://www.llblgen.com/defaultgeneric.aspx) as well.
It would be very hard to recommend an overall "best" solution without knowing... | [CodeSmith](http://www.codesmithtools.com/) is another good tool from what I've heard.
There's no such thing as the *best* DAL, only the *best* for the current solution.
We used an in-house one for many years which wasn't too bad but ultimately unmaintainable vs commercial products. | Best data access method in .NET 2.0 | [
"",
".net",
"sql",
"dao",
""
] |
Whenever I write a stored procedure for selecting data based on string variable (varchar, nvarchar, char) I would have something like:
```
procedure dbo.p_get_user_by_username(
@username nvarchar(256)
as
begin
select
u.username
,u.email
--,etc
from
sampleUserTable u
... | You are correct. There is no benefit in using LIKE unless you are doing wild card matching. In addition, using it without wildcard could lead to the use of an inefficient queryplan. | Sunny almost got it right :)
Run the following in QA in a default install of SQL2005
```
select * from sysobjects where name = 'sysbinobjs '
-- returns 1 row
select * from sysobjects where name like 'sysbinobjs '
-- returns 0 rows
```
So, LIKE does not match on trailing spaces, on the query plan side both perfor... | Like vs. "=" for matching strings using SQL Server | [
"",
"sql",
"sql-server",
"like-keyword",
""
] |
I have a script that animates a small DIV popping up on the page. It all works fine in IE, and in FF if I remove the DOCTYPE, but when the DOCTYPE is XHTML/Transitional, in Firefox, the width does not change.
```
this.container.style.visibility = "visible";
alert("this.container.style.width before = " + this.container... | Have you tried setting:
```
this.container.style.visibility = "visible";
alert("this.container.style.width before = " + this.container.style.width);
this.container.style.width = this.width + 'px';
alert("this.container.style.width after = " + this.container.style.width);
this.container.style.height = this.height + 'px... | * Using !important in CSS will override the above JavaScript and the width will not change. ie.
width: 16.5% !important;
* Should become:
width: 16.5%; | javascript style.width not working in firefox with transitional doctype | [
"",
"javascript",
"css",
"doctype",
"transitional",
""
] |
The question is in Java why can't I define an abstract static method? for example
```
abstract class foo {
abstract void bar( ); // <-- this is ok
abstract static void bar2(); //<-- this isn't why?
}
``` | The `abstract` annotation to a method indicates that the method MUST be overriden in a subclass.
In Java, a `static` member (method or field) cannot be overridden by subclasses (this is not necessarily true in other object oriented languages, see SmallTalk.) A `static` member may be **hidden**, but that is fundamental... | Because "abstract" means: "Implements no functionality", and "static" means: "There is functionality even if you don't have an object instance". And that's a logical contradiction. | Why can't static methods be abstract in Java? | [
"",
"java",
"abstract-class",
"static-methods",
""
] |
I have an application that uses a cron like job to update a set of data. The update process happens once a minute and doesn't last long. A servlet exposes this data set to the users. My problem is that during the update process, the servlet requests should block and wait for the process to complete.
In bottom line I h... | Take a look at this article: [Read / Write Locks in Java](http://tutorials.jenkov.com/java-concurrency/read-write-locks.html)
The only drawback I can see in this example is the notifyAll() waking all waiting threads.
It does, however, give priority to write lock requests. | You can use a [ReadWriteLock](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/ReadWriteLock.html) instead of synchronize.
> A ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so ... | How to synchronize requests for data with data update process? | [
"",
"java",
"synchronization",
""
] |
What's the shortest way to get an Iterator over a range of Integers in Java? In other words, implement the following:
```
/**
* Returns an Iterator over the integers from first to first+count.
*/
Iterator<Integer> iterator(Integer first, Integer count);
```
Something like
```
(first..first+count).iterator()
``` | Straight-forward implementation of your homework:
```
List<Integer> ints = new ArrayList<Integer>();
for (int i = 0; i < count; i++) {
ints.add(first + i);
}
``` | This implementation does not have a memory footprint.
```
/**
* @param begin inclusive
* @param end exclusive
* @return list of integers from begin to end
*/
public static List<Integer> range(final int begin, final int end) {
return new AbstractList<Integer>() {
@Override
public Integer... | Shortest way to get an Iterator over a range of Integers in Java | [
"",
"java",
"iterator",
""
] |
Last weekend I changed webhosts for my website. The host server I was on was a 32-bit OS and the one I moved to is 64-bit. Unexpectedly, some of my PHP scripts started giving incorrect results.
In my case the << and >> (bit shift) operations were the culprit. I ended up having to mask the result with 0xFFFFFFFF and th... | It's a high level language, so anything non-bit related (bitwise operators, bitshift) will be the same. | An integer may be 64bit instead of 32bit. There are some bizarre [cases](http://www.mysqlperformanceblog.com/2007/01/09/mysql-automatic-data-truncation-can-backfire/) where this may cause problems. | 32 to 64 bit "Gotchas" in PHP | [
"",
"php",
"32bit-64bit",
""
] |
I was working with the Action Delegates in C# in the hope of learning more about them and thinking where they might be useful.
Has anybody used the Action Delegate, and if so why? or could you give some examples where it might be useful? | MSDN says:
> This delegate is used by the
> Array.ForEach method and the
> List.ForEach method to perform an
> action on each element of the array or
> list.
Except that, you can use it as a generic delegate that takes 1-3 parameters without returning any value. | Here is a small example that shows the usefulness of the Action delegate
```
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Action<String> print = new Action<String>(Program.Print);
List<String> names = new List<String> { "andrew", "nicole" };
na... | Uses of Action delegate in C# | [
"",
"c#",
"lambda",
"delegates",
"action",
""
] |
I have a windows service written in c#. It has a timer inside, which fires some functions on a regular basis. So the skeleton of my service:
```
public partial class ArchiveService : ServiceBase
{
Timer tickTack;
int interval = 10;
...
protected override void OnStart(string[] args)
{
tick... | Like many respondents have pointed out exceptions are swallowed by timer. In my windows services I use System.Threading.Timer. It has Change(...) method which allows you to start/stop that timer. Possible place for exception could be reentrancy problem - in case when tickTack\_Elapsed executes longer than timer period.... | unhandled exceptions in timers are swallowed, and they silently kill the timer
wrap the body of your timer code in a try-catch block | .NET Windows Service with timer stops responding | [
"",
"c#",
"windows-services",
"timer",
""
] |
I'm running on win2003 server, PHP 526, via the cmd-line.
I have a cmdline string:
```
$cmd = ' "d:\Prog Files\foo.exe" -p "d:\data path\datadir" ';
```
Trying to do this in php code
```
$out = `$cmd`; # note use of backticks AKA shell_exec
```
results in a failure by foo.exe as it interprets the -p arg as... | Use escapeshellarg() to escape your arguments, it should escape it with an appropriate combination of quotation marks and escaped spaces for your platform (I'm guessing you're on Windows). | Unlike Unix, which requires quotes within quotes to be escaped, Windows doesn't seem to work this way. How it keeps track of the quotes is beyond me, but this actually seems to work, despite all logic to the contrary:
$cmd = '" "C:\Path\To\Command" "Arg1" "Arg2" "';
$fp = popen($cmd, 'r');
$output='';
while ($l ... | How do I to properly handle spaces in PHP Shell_exec? | [
"",
"php",
"shell-exec",
""
] |
I have a function that looks something like this:
```
//iteration over scales
foreach ($surveyScales as $scale)
{
$surveyItems = $scale->findDependentRowset('SurveyItems');
//nested iteration over items in scale
foreach ($surveyItems as $item)
{
//retrieve a single value from a result table an... | One query that returns a dozen pieces of data is almost 12x faster than 12 queries that return 1 piece of data.
Oh, and NEVER EVER NEVER put a SQL inside a loop, it will always lead in a disaster.
Depending on how your app works, a new connection might be opened for each query, this is especially bad as every DB serv... | I agree with the others -- and I'm the one who designed and coded the table-relationships API in Zend Framework that you're using!
The `findDependentRowset()` is useful if you *already* have a reference to the parent row, and you *might* need to fetch related rows. This function is not efficient in the least, compared... | PHP - Query single value per iteration or fetch all at start and retrieve from array? | [
"",
"php",
"database",
"performance",
""
] |
Suppose I have the following class:
```
public class TestBase
{
public bool runMethod1 { get; set; }
public void BaseMethod()
{
if (runMethod1)
ChildMethod1();
else
ChildMethod2();
}
protected abstract void ChildMethod1();
protected abstract void ChildMethod2();
}
```
I also have t... | You can also set the expectation/setup as Verifiable and do without a strict mock:
```
//expect that ChildMethod1() will be called once. (it's protected)
testBaseMock.Protected().Expect("ChildMethod1")
.AtMostOnce()
.Verifiable();
...
//make sure the method was called
testBase.Verify();
```
**Edit... | I figured out how to do this. You can can mock protected methods with Moq, and by making a strict mock, you can verify that they were called. Now I can test the base class without having to make any subclasses.
```
[Test]
public BaseMethod_should_call_correct_child_method()
{
//strict mocks will make sure all expect... | Verifying protected abstract methods are called using Moq | [
"",
"c#",
"unit-testing",
"testing",
"moq",
""
] |
I've a need to add method that will calculate a weighted sum of worker salary and his superior salary. I would like something like this:
```
class CompanyFinanse
{
public decimal WeightedSumOfWorkerSalaryAndSuperior(Worker WorkerA, Worker Superior)
{
return WorkerA.Salary + Superior.Salary * 2;
... | So it may be impossible to give you a complete answer about "best practices" without knowing more about your domain, but I can tell you that you may be setting yourself up for disaster by thinking about the implementation details this early.
If you're like me then you were taught that good OOD/OOP is meticulously deta... | I would either put it in the worker class, or have a static function in a finance library. I don't think a Finance object really makes sense, I think it would be more of a set of business rules than anything, so it would be static.
```
public class Worker {
public Worker Superior {get;set;}
public readonly d... | Where should I put my first method | [
"",
"c#",
"oop",
"methods",
""
] |
Is there a way to record the screen, either desktop or window, using .NET technologies?
My goal is something free. I like the idea of small, low CPU usage, and simple, but I would consider other options if they created a better final product.
In a nutshell, I know how to take a screenshot in C#, but how would I recor... | There isn’t any need for a third-party DLL. This simple method captures the current screen image into a .NET Bitmap object.
```
private Image CaptureScreen()
{
Rectangle screenSize = Screen.PrimaryScreen.Bounds;
Bitmap target = new Bitmap(screenSize.Width, screenSize.Height);
using(Grap... | You can use the Windows media Encoder SDK to build a C# application to record the screen. There are in-built options to record the entire desktop, a particular window or a portion of the screen. | Record a video of the screen using .NET technologies | [
"",
"c#",
".net",
"video",
"capture",
"video-capture",
""
] |
I have two bitmaps, produced by different variations of an algorithm. I'd like to create a third bitmap by subtracting one from the other to show the differences.
How can this be done in .NET? I've looked over the Graphics class and all its options, including the ImageAttributes class, and I have a hunch it involves t... | The real question is, what differences do you want to show? If you just need to operate on RGB color values, the best bet in my opinion is to just scan through both bitmaps and compare the Color values using GetPixel, and use SetPixel to generate your 'difference' bitmap. Perhaps you simply want to subtract the values ... | Check out this project. It is a motion detector made by Andrew Kirillov. He implements a couple of filters to get the differences between two pictures and uses that to calculate movements. It is really nice done and its easy to modify and use in your own application.
<http://www.codeproject.com/KB/audio-video/Motion_D... | How to subtract one bitmap from another in C#/.NET? | [
"",
"c#",
".net",
"image",
"subtraction",
""
] |
What does the `[string]` indexer of `Dictionary` return when the key doesn't exist in the Dictionary? I am new to C# and I can't seem to find a reference as good as the Javadocs.
Do I get `null`, or do I get an exception? | If you mean the indexer of a `Dictionary<string,SomeType>`, then you should see an exception (`KeyNotFoundException`). If you don't want it to error:
```
SomeType value;
if(dict.TryGetValue(key, out value)) {
// key existed; value is set
} else {
// key not found; value is default(SomeType)
}
``` | As ever, the [documentation](http://msdn.microsoft.com/en-us/library/9tee9ht2.aspx) is the way to find out.
Under Exceptions:
```
KeyNotFoundException
The property is retrieved and key does not exist in the collection
```
(I'm assuming you mean `Dictionary<TKey,TValue>`, by the way.)
Note that this is different fro... | C#: What does the [string] indexer of Dictionary return? | [
"",
"c#",
"dictionary",
""
] |
In PHP you can access characters of strings in a few different ways, one of which is substr(). You can also access the Nth character in a string with curly or square braces, like so:
```
$string = 'hello';
echo $string{0}; // h
echo $string[0]; // h
```
My question is, is there a benefit of one over the other? What'... | use `$string[0]`, the other method (braces) has been removed in PHP 8.0.
For [strings](https://www.php.net/manual/en/language.types.string.php):
> Accessing characters within string literals using the {} syntax has been deprecated in PHP 7.4. This has been removed in PHP 8.0.
And for [arrays](https://www.php.net/man... | [**There is no difference.**](https://stackoverflow.com/a/26809707/632951) Owen's answer is outdated, the latest version of PHP Manual no longer states that it is deprecated [§](http://php.net/manual/en/language.types.string.php#language.types.string.substr):
> Characters within strings may be accessed and modified by... | PHP $string{0} vs. $string[0]; | [
"",
"php",
"string",
""
] |
So the chain of events is:
1. The user submits a form.
2. During the processing of the submission, there is a message generated, such as "Your record was saved."
3. The user is redirected to a new page, say the search results.
4. The new page needs to display the message.
So, the question is how to get the message fr... | I would recommend AGAINST storing these messages either in the database or in the session, for one simple reason: tabs. (Well, really, the stateless nature of HTTP.)
Think of a person who's got multiple tabs open of different sections of your website. This person performs some action and while that loads, switches to ... | I would stick with the session approach only perhaps adding support for this messaging system on the master page. You are on the right way as the all other approaches have a greater cost, of simplicity or performance.
I suppose you have a master page which is the template for all other pages. If you don't have it's a ... | How best to pass a message for the user between pages | [
"",
"php",
"session",
"message",
"status-message",
""
] |
I'm looking for an implementation of IDictionary with better performance of the standard BCL one.
I'm looking for something with constant lookup time that performs really well with large number of elements (>10K) and is more GC friendly.
Ps: No, I'm not able to write one by myself :) | I have not been able to benchmark the implementation, but an alternative - and more comprehensive - selection of generic collection classes is available from the University of Copenhagen here:
<http://www.itu.dk/research/c5/>
They offer a number of generic Dictionary implementations with differing backing solutions (... | The BCL dictionary already performs with amortized constant time and can easily handle 10K elements.
You say it should be "more GC friendly" - what's bothering you about the current version?
Are you adding elements to the dictionary frequently? If so, create it with a large initial capacity to avoid churn. | Is there any implementation of IDictionary<K,V> with better performance of the BCL one? | [
"",
"c#",
".net",
"dictionary",
"hashtable",
""
] |
Is there a preferred way to return multiple values from a C++ function? For example, imagine a function that divides two integers and returns both the quotient and the remainder. One way I commonly see is to use reference parameters:
```
void divide(int dividend, int divisor, int& quotient, int& remainder);
```
A var... | For returning two values I use a `std::pair` (usually typedef'd). You should look at `boost::tuple` (in C++11 and newer, there's `std::tuple`) for more than two return results.
With introduction of structured binding in C++ 17, returning `std::tuple` should probably become accepted standard. | In C++11 you can:
```
#include <tuple>
std::tuple<int, int> divide(int dividend, int divisor) {
return std::make_tuple(dividend / divisor, dividend % divisor);
}
#include <iostream>
int main() {
using namespace std;
int quotient, remainder;
tie(quotient, remainder) = divide(14, 3);
cout << q... | Returning multiple values from a C++ function | [
"",
"c++",
""
] |
I'm trying to find URLs in some text, using javascript code. The problem is, the regular expression I'm using uses \w to match letters and digits inside the URL, but it doesn't match non-english characters (in my case - Hebrew letters).
So what can I use instead of \w to match all letters in all languages? | Because `\w` only matches ASCII characters 48-57 ('0'-'9'), 67-90 ('A'-'Z') and 97-122 ('a'-'z'). Hebrew characters and other special foreign language characters (for example, umlaut-o or tilde-n) are outside of that range.
Instead of matching foreign language characters (there are so many of them, in many different A... | The ECMA 262 v3 standard, which defines the programming language commonly known as JavaScript, stipulates that `\w` should be equivalent to [a-zA-Z0-9\_] and that `\d` should be equivalent to [0-9]. `\s` on the other hand matches both ASCII and Unicode whitespace, according to the standard.
JavaScript does not support... | Why does \w match only English words in javascript regex? | [
"",
"javascript",
"regex",
"hebrew",
""
] |
I have an ASP.NET program where i am downloading a file from web using DownloadFile method of webClient Class and the do some modifications on it. then i am Saving it to another folder with a unique name.When I am getting this error
> The process cannot access the file 'D:\RD\dotnet\abc\abcimageupload\images\TempStora... | Generally, I think your code should looking something like this.
```
WebClient wc = new WebClient();
wc.DownloadFile("http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png", "Foo.png");
FileStream fooStream;
using (fooStream = new FileStream("foo.png", FileMode.Open))
{
// do stuff
}
File.Move("foo.png",... | I've had very good success using the tools from SysInternals to track which applications are accessing files and causing this kind of issue.
[Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) is the tool you want - set it up to filter the output to just files in the folder you're interest... | Cant Access File because it is being used by another process | [
"",
"c#",
".net",
"exception",
""
] |
I have an xml file ('videofaq.xml') that defines a DTD using the following DOCTYPE
```
<!DOCTYPE video-faq SYSTEM "videofaq.dtd">
```
I am loading the file from the classpath (from a JAR actually) at Servlet initialization time using:
```
getClass().getResourceAsStream("videofaq.xml")
```
The XML is found correctly... | A custom EntityResolver will work, but you might be able to avoid having to create a custom class by setting a SystemID to allow the processor to "find" relative paths.
<http://www.onjava.com/pub/a/onjava/excerpt/java_xslt_ch5/index.html?page=5>
> By providing a system identifier as a
> parameter to the StreamSource,... | When you do
```
getClass().getResourceAsStream("videofaq.xml")
```
It's not xerces you are calling and as such, when you give the stream to xerces, it can't know where the file is loaded from. It loads it from the application root path (which you have described).
A simple solution would be to specify the whole path ... | How do I include a DTD in an XML file that will be loaded using getResourceAsStream()? | [
"",
"java",
"xml",
"xerces",
""
] |
Suppose you're maintaining an API that was originally released years ago (before java gained `enum` support) and it defines a class with enumeration values as ints:
```
public class VitaminType {
public static final int RETINOL = 0;
public static final int THIAMIN = 1;
public static final int RIBOFLAVIN = 2;
}
```
... | Personal opinion is that it's probably not worth the effort of trying to convert. For one thing, the "public static final int" idiom isn't going away any time soon, given that it's sprinkled liberally all over the JDK. For another, tracking down usages of the original ints is likely to be really unpleasant, given that ... | How likely is it that the API consumers are going to confuse VitaminType with NutrientType? If it is unlikely, then maybe it is better to maintain API design consistency, especially if the user base is established and you want to minimize the delta of work/learning required by customers. If confusion is likely, then Nu... | What's the best way to handle coexistence of the "int enum" pattern with java enums as an API evolves? | [
"",
"java",
"api",
"enums",
""
] |
I've got a JScript error on my page. I know where the error's happening, but I'm attempting to decipher the JScript on that page (to figure out where it came from -- it's on an ASPX page, so any number of user controls could have injected it).
It'd be easier if it was indented properly. Are there any free JScript refo... | You really should use Firebug or some similar debugging tool to actually *find* the problem, but, if you want to just format your JavaScript code, [here's a reformatter I found on Google](http://javascript.about.com/library/blformat.htm). | You can use [Aptana Studio](http://www.aptana.com/studio), its free and really good, and you can [customize your formatting preferences](http://www.aptana.com/docs/index.php/Customizing_your_formatting_preferences). | Reformatting JavaScript/JScript code? | [
"",
"javascript",
"pretty-print",
""
] |
I've noticed that boost.asio has a lot of examples involving sockets, serial ports, and all sorts of non-file examples. Google hasn't really turned up a lot for me that mentions if asio is a good or valid approach for doing asynchronous file i/o.
I've got gobs of data i'd like to write to disk asynchronously. This can... | ## Has boost.asio any kind of file support?
Starting with (I think) Boost 1.36 (which contains Asio 1.2.0) you can use [boost::asio::]windows::stream\_handle or windows::random\_access\_handle to wrap a HANDLE and perform asynchronous read and write methods on it that use the OVERLAPPED structure internally.
User Laz... | **boost::asio file i/o on Linux**
On Linux, asio uses the [`epoll`](http://linux.die.net/man/4/epoll) mechanism to detect if a socket/file descriptor is ready for reading/writing. If you attempt to use vanilla asio on a regular file on Linux you'll get an "operation not permitted" exception because [epoll does not sup... | What's the deal with boost.asio and file i/o? | [
"",
"c++",
"boost",
"file-io",
"boost-asio",
""
] |
I'm using PHP 5.2. I'd like to find a way to output a unique id for every object, so it's easy when looking over logs to see which objects are the same.
In Ruby, I'd just say object.object\_id to get Ruby's internal identifier for the object. There doesn't seem to be an obvious way to do this in PHP.
Is there is a bu... | Use [`spl_object_hash()`](http://php.net/manual/en/function.spl-object-hash.php) for that.
It returns an unique identifier for each object instance, and not the name of the class, so it seems more suitable for you.
**Edit:**
For PHP < 5.2.x users, see [this answer](https://stackoverflow.com/a/19250740/179104). | There is currently no way to do this in PHP, as of version 5.3.6.
spl\_object\_hash() does not do what you want - because it recycles the identifiers when objects get deleted, this will lead to errors in (for example) an object-relational mapper trying to keep track of objects in a session.
The description at the top... | How to find Object ID in PHP? | [
"",
"php",
"object",
""
] |
What would be the simplest way to create some graphical representations of the usage of electricity by month? | The best way is to use [JFreeChart](http://www.jfree.org/jfreechart/) to produce an image from your data, and then display the image in the jsp. | Easy solution for me was outputting numerical arrays in the backend and displaying with [flot](http://code.google.com/p/flot/) (google javascript library). All you need to do is generate your series of points
(e.g. something like ([1,0], [2,1.1], [3,1.4],[4, ] ... ). | JSP: Creating Graph | [
"",
"java",
"jsp",
"graphics",
"charts",
"graph",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.