Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a problem using the Java search function in Eclipse on a particular project.
When using the Java search on one particular project, I get an error message saying `Class file name must end with .class` (see stack trace below). This does not seem to be happening on all projects, just one particular one, so perhaps... | Two more general-purpose mechanisms for fixing some of Eclipse's idiosyncrasies:
* Close and open the project
* Delete the project (but not from disk!) and reimport it as an existing project
Failing that, [bugs.eclipse.org](https://bugs.eclipse.org/bugs/buglist.cgi?query_format=specific&order=relevance+desc&bug_statu... | Comment [#9 to bug 269820](https://bugs.eclipse.org/bugs/show_bug.cgi?id=269820#c9) explains how to delete the search index, which appears to be the solution to a corrupt index whose symptoms are the dreaded
> An internal error occurred during: "Items filtering".
> Class file name must end with .class
message box.
... | Class file name must end with .class exception in Java search | [
"",
"java",
"eclipse",
"search",
""
] |
I have several "ASP:TextBox" controls on a form (about 20).
When the form loads, the text boxes are populated from a database.
The user can change the populated values, and when they submit the form, I take the values posted to the server and conditionally save them (determined by some business logic).
All but 1 ... | Are you initially loading the data only when !Page.IsPostBack? Also, is view state enabled for the text box? | this happens to me all the time.
```
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// populate text boxes from database
}
}
``` | Form post doesn't contain textbox data [ASP.NET C#] | [
"",
"c#",
"asp.net",
""
] |
I'm trying to perform a SQL query through a linked SSAS server. The initial query works fine:
```
SELECT "Ugly OLAP name" as "Value"
FROM OpenQuery( OLAP, 'OLAP Query')
```
But if I try to add:
```
WHERE "Value" > 0
```
I get an error
> Invalid column name 'Value'
Any ideas what I might be doing wrong?
---
So ... | This should work:
```
SELECT A.Value
FROM (
SELECT "Ugly OLAP name" as "Value"
FROM OpenQuery( OLAP, 'OLAP Query')
) AS a
WHERE a.Value > 0
```
It's not that Value is a reserved word, the problem is that it's a column alias, not the column name. By making it an inline view, "Value" becomes the column name and can th... | You're using "Value" as a column alias, and I don't think the alias can appear in the where clause. It's simply used to name the returned column value. Your where clause should refer to the original column name:
```
SELECT "Ugly OLAP name" as "Value"
FROM OpenQuery( OLAP, 'OLAP Query')
WHERE "Ugly OLAP name" > 0
``` | "Invalid column name" error on SQL statement from OpenQuery results | [
"",
"sql",
"sql-server",
""
] |
Does anyone know of an easy way to escape HTML from strings in [jQuery](http://jquery.com/)? I need to be able to pass an arbitrary string and have it properly escaped for display in an HTML page (preventing JavaScript/HTML injection attacks). I'm sure it's possible to extend jQuery to do this, but I don't know enough ... | Since you're using [jQuery](https://jquery.com/), you can just set the element's [`text`](http://api.jquery.com/text/) property:
```
// before:
// <div class="someClass">text</div>
var someHtmlString = "<script>alert('hi!');</script>";
// set a DIV's text:
$("div.someClass").text(someHtmlString);
// after:
// <div c... | There is also [the solution from mustache.js](https://github.com/janl/mustache.js/blob/master/mustache.js#L73)
```
var entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
function escapeHtml (string) {
return String(string... | Escaping HTML strings with jQuery | [
"",
"javascript",
"jquery",
"string",
"escaping",
""
] |
Has anyone been able to get xinc to run correctly under OpenBSD's chrooted default Apache? I'd like to keep our development server running fully chrooted just like our Production server so that we make sure our code runs just fine chrooted. | Have you posted the issue on the Xinc [bug tracker](http://code.google.com/p/xinc/issues/list)? Xinc itself should run fine as it runs both as a daemon and as a web app. As you alluded to, the issue may be that the daemon is not running in a chroot'ed environment where as the web interface is, leading to either side no... | @dragonmantank
In Xinc's case, I hope you used PEAR to install it.
```
pear list-files xinc/Xinc
```
This should do it, and show you where your Xinc install put its files. So even though Xinc is "just" one big PHP script, it's still spread out into rc scripts and all those other things which are necessary to make an... | Running xinc on OpenBSD's Apache Server | [
"",
"php",
"continuous-integration",
"openbsd",
"xinc",
""
] |
I have some code for starting a thread on the .NET CF 2.0:
```
ThreadStart tStart = new ThreadStart(MyMethod);
Thread t = new Thread(tStart);
t.Start();
```
If I call this inside a loop the items completely out of order. How do introduce a wait after `t.Start()`, so that the work on the thread completes before the co... | How much order do you need to impose on the threads? If you just need all of the work started in the loop to finish before the code continues, but you don't care about the order the work within the loop finishes, then calling Join is the answer. To add more detail to [Kevin Kenny's answer,](https://stackoverflow.com/qu... | Another way of waiting for a thread to finish is using an `AutoResetEvent`.
```
private readonly AutoResetEvent mWaitForThread = new AutoResetEvent(false);
private void Blah()
{
ThreadStart tStart = new ThreadStart(MyMethod);
Thread t = new Thread(tStart);
t.Start();
//... (any other things)
mWai... | How to wait for thread complete before continuing? | [
"",
"c#",
"multithreading",
"compact-framework",
""
] |
To illustrate, assume that I have two tables as follows:
```
VehicleID Name
1 Chuck
2 Larry
LocationID VehicleID City
1 1 New York
2 1 Seattle
3 1 Vancouver
4 2 Los Angeles
5 2 Houston
```
I want to write a query to ... | If you're using SQL Server 2005, you could use the FOR XML PATH command.
```
SELECT [VehicleID]
, [Name]
, (STUFF((SELECT CAST(', ' + [City] AS VARCHAR(MAX))
FROM [Location]
WHERE (VehicleID = Vehicle.VehicleID)
FOR XML PATH ('')), 1, 2, '')) AS Locations
FROM [Vehicle]
```
It'... | Note that [Matt's code](https://stackoverflow.com/questions/6899/how-to-create-a-sql-server-function-to-join-multiple-rows-from-a-subquery-into#6961) will result in an extra comma at the end of the string; using COALESCE (or ISNULL for that matter) as shown in the link in Lance's post uses a similar method but doesn't ... | How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field? | [
"",
"sql",
"sql-server",
"string-concatenation",
""
] |
I'm trying to use the CoreCon API in Visual Studio 2008 to programmatically launch device emulators. When I call `device.Connect()`, I inexplicably get a DirectoryNotFoundException. I get it if I try it in PowerShell or in C# Console Application. Here's the code I'm using:
```
static void Main(string[] args)
{
Da... | It can be found at `<systemdrive>:\Program files\Common Files\Microsoft Shared\CoreCon\1.0\Bin`.
This is the path where you can get this dll, so add this dll to your project. | Installing VS 2008 SP 1 fixed it for me. | Getting DirectoryNotFoundException when trying to Connect to Device with CoreCon API | [
"",
"c#",
"visual-studio",
"windows-mobile",
"compact-framework",
"corecon",
""
] |
Is there a way to implement a singleton object in C++ that is:
1. Lazily constructed in a thread-safe manner (two threads might simultaneously be the first user of the singleton - it should still only be constructed once).
2. Doesn't rely on static variables being constructed beforehand (so the singleton object is its... | Basically, you're asking for synchronized creation of a singleton, without using any synchronization (previously-constructed variables). In general, no, this is not possible. You need something available for synchronization.
As for your other question, yes, static variables which can be statically initialized (i.e. no... | Here's [Meyer's singleton](https://en.wikipedia.org/wiki/Singleton_pattern), a very simple lazily constructed singleton getter:
```
Singleton &Singleton::self() {
static Singleton instance;
return instance;
}
```
This is lazy, and C++11 requires it to be thread-safe. In fact, I believe that at least g++ imple... | How do you lazily construct a singleton object thread-safely? | [
"",
"c++",
"multithreading",
"thread-safety",
"singleton",
"lazy-initialization",
""
] |
I have a WCF service that I have to reference from a .net 2.0 project.
I have tried to reference it using the "**add web reference**" method but it messes up the params.
For example, I have a method in the service that expects a `char[]` to be passed in, but when I add the web reference, the method expects an `int[]`... | One of those instances that you need to edit the WSDL. For a start a useful tool
<http://codeplex.com/storm> | What binding are you using - I think if you stick to the basicHttp binding you should be able to generate a proxy using the "add web reference" approach from a .net 2 project?
Perhaps if you post the contract/interface definition it might help?
Cheers
Richard | WCF Backward Compatibility Issue | [
"",
"c#",
".net",
"wcf",
""
] |
Let's say that I want to have a table that logs the date and the number of columns in some other table (or really any sort of math / string concat etc).
```
CREATE TABLE `log` (
`id` INTEGER NOT NULL AUTO_INCREMENT ,
`date` DATETIME NOT NULL ,
`count` INTEGER NOT NULL ,
PRIMARY KEY (`id`)
);
```
Is it possible to hav... | Triggers are the best tool for annotating data when a table is changed by insert, update or delete.
To automatically set the date column of a new row in the log with the current date, you'd create a trigger that looked something like this:
```
create trigger log_date before insert on log
for each row begin
set ne... | You definitly have to declare what to insert. This should be possible by using the [INSERT ... SELECT](http://dev.mysql.com/doc/refman/5.1/en/insert-select.html "INSERT .... SELECT") statement.
```
INSERT INTO log (date, count)
SELECT DATE() as date, count(id) as count
from foo;
```
Which should insert a new ... | Calculated columns in mysql on INSERT statements | [
"",
"sql",
"mysql",
"database",
""
] |
So I am writing a registration form and I need the display name to be only numbers, letters and underscores.
Have a look at my code and tell me what I'm doing wrong.
```
<form method="post" action="/" onsubmit="return check_form()">
<input type="text" id="display-name" name="display-name" maxlength="255" />
<... | Your regex
```
/^([a-zA-Z0-9_])+/
```
Looks for
1. Start of string(check), followed by
2. 1 or more letters, numbers, or underscore (check)
And then whatever comes after it doesn't matter. This regex will match anything at all so long as it begins with a letter, number, or underscore
If you put a `$` at the end, t... | My regexp would go along the lines of: `/^[a-zA-Z0-9_]+$/`
edit: I think it's the lack of a line end `$` that makes it fail. | What did I do wrong here? [Javascript Regex] | [
"",
"javascript",
"regex",
""
] |
When attempting to compile my C# project, I get the following error:
```
'C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\CleanerMenu\obj\Debug\CSC97.tmp' is not a valid Win32 resource file.
```
Having gone through many Google searches, I have determined that this is usually caused by a 256x256 ima... | I don't know if this will help, but from [this forum](http://forums.msdn.microsoft.com/en-US/csharplanguage/thread/4217bec6-ea65-465f-8510-757558b36094/):
> Add an .ico file to the application section of the properties page, and recieved the error thats been described, when I checked the Icon file with an icon editor,... | I had a similar issue with an "obj/debug/**\***.tmp" file erroring out in my build log. Turns out my C:\ drive was out of space. After clearing some space, my builds started working. | Invalid Resource File | [
"",
"c#",
"visual-studio",
"resources",
""
] |
[Project Darkstar](http://en.wikipedia.org/wiki/Project_Darkstar) was the topic of the monthly [JavaSIG](http://www.javasig.com/meeting/home.xhtml) meeting down at the Google offices in NYC last night. For those that don't know (probably everyone), Project Darkstar is a framework for massively multiplayer online games ... | **Edit: This was written before Oracle bought Sun and started a rampage to kill everything that does not make them a billion $ per day. See the comments for an OSS Fork.** *I still stand by my opinion that stuff like that (MMO Middleware) is realistic, you just need a company that doesn't suck behind it.*
The Market m... | Sounds like useless tech to me. The MMO world is controlled by a few big game companies that already have their own tech in place. Indie game developers love trying to build MMO's and sometimes they do, but those games rarely gain traction. Larger companies breaking into the MMO world would probably license "proven" te... | Is Project Darkstar Realistic? | [
"",
"java",
"concurrency",
"distributed",
""
] |
What options are there in the industry for enterprise reporting? I'm currently using SSRS 2005, and know that there is another version coming out with the new release of MSSQL.
But, it seems like it might also be a good time to investigate the market to see what else is out there.
What have you encountered? Do you li... | I've used Cognos Series 7, Cognos Series 8, Crystal Reports, Business Objects XI R2 WebIntelligence, Reporting Services 2000, Reporting Services 2005, and Reporting Services 2008. Here's my feedback on what I've learned:
**Reporting Services 2008/2005/2000**
PROS
1. Cost: Cheapest enterprise business intelligence so... | I'd like to make two contributions. One is very negative (CR is rubbish) and the other is very positive (SSRS is backing store independent and available at no cost).
On a side note, if you mod an answer down then add a comment explaining why you think the answer is wrong or counterproductive, unless someone else alrea... | Enterprise Reporting Solutions | [
"",
"sql",
"reporting-services",
"reporting",
""
] |
I'm trying to do a simple test php script for sessions. Basically it increments a counter (stored in `$_SESSION`) every time you refresh that page. That works, but I'm trying to have a link to destroy the session which reloads the page with the `?destroy=1` parameter. I've tried a couple of if statements to see if that... | I think you put
```
$_POST['destroy']
```
Instead of
```
$_GET['destroy']
```
You need to use a form if you'd like to use a $\_POST variable. $\_GET variables are stored in the URL. | By the way you can use
> $\_REQUEST['destroy']
which would work regardless if the data is passed in a POST or a GET request. | Accessing html parameter in PHP | [
"",
"php",
"session",
""
] |
I have a quad core machine and would like to write some code to parse a text file that takes advantage of all four cores. The text file basically contains one record per line.
Multithreading isn't my forte so I'm wondering if anyone could give me some patterns that I might be able to use to parse the file in an optima... | I'd go with your original idea. If you are concerned that the queue might get too large implement a buffer-zone for it (i.e. If is gets above 100 lines the stop reading the file and if it gets below 20 then start reading again. You'd need to do some testing to find the optimal barriers). Make it so that any of the thre... | Mark's answer is the simpler, more elegant solution. Why build a complex program with inter-thread communication if it's not necessary? Spawn 4 threads. Each thread calculates size-of-file/4 to determine it's start point (and stop point). Each thread can then work entirely independently.
The *only* reason to add a spe... | Multicore Text File Parsing | [
"",
"c#",
"multithreading",
""
] |
I have a data structure that represents a directed graph, and I want to render that dynamically on an HTML page. These graphs will usually be just a few nodes, maybe ten at the very upper end, so my guess is that performance isn't going to be a big deal. Ideally, I'd like to be able to hook it in with jQuery so that us... | I've just put together what you may be looking for: <http://www.graphdracula.net>
It's JavaScript with directed graph layouting, SVG and you can even drag the nodes around. Still needs some tweaking, but is totally usable. You create nodes and edges easily with JavaScript code like this:
```
var g = new Graph();
g.ad... | *Disclaimer: I'm a developer of Cytoscape.js*
Cytoscape.js is a HTML5 graph visualisation library. The API is sophisticated and follows jQuery conventions, including
* selectors for querying and filtering (`cy.elements("node[weight >= 50].someClass")` does much as you would expect),
* chaining (e.g. `cy.nodes().unsel... | Graph visualization library in JavaScript | [
"",
"javascript",
"jquery",
"data-structures",
"graph-layout",
""
] |
I need to periodically download, extract and save the contents of <http://data.dot.state.mn.us/dds/det_sample.xml.gz> to disk. Anyone have experience downloading gzipped files with C#? | To compress:
```
using (FileStream fStream = new FileStream(@"C:\test.docx.gzip",
FileMode.Create, FileAccess.Write)) {
using (GZipStream zipStream = new GZipStream(fStream,
CompressionMode.Compress)) {
byte[] inputfile = File.ReadAllBytes(@"c:\test.docx");
zipStream.Write(inputfile, 0, input... | You can use WebClient in System.Net to download:
```
WebClient Client = new WebClient ();
Client.DownloadFile("http://data.dot.state.mn.us/dds/det_sample.xml.gz", " C:\mygzipfile.gz");
```
then use [#ziplib](http://sharpdevelop.net/OpenSource/SharpZipLib/Default.aspx) to extract
Edit: or GZipStream... forgot about t... | How do you download and extract a gzipped file with C#? | [
"",
"c#",
".net",
"gzip",
""
] |
There are numerous libraries providing Linq capabilities to C# code interacting with a MySql database. Which one of them is the most stable and usable on Mono?
Background (mostly irrelevant): I have a simple C# (.Net 2.0) program updating values in a MySql database. It is executed nightly via a cron job and runs on a ... | The only (free) linq provider for MySql is [DbLinq](http://code2code.net/DB_Linq/), and I believe it is a long way from production-ready.
There is also [MyDirect.Net](http://www.devart.com/mysqlnet/) which is commercial, but I have heard mixed reviews of it's capability.
I've read that MySql will be implementing the ... | According to the [Mono roadmap](http://www.mono-project.com/Mono_Project_Roadmap) I'm not sure if Linq is available for mono?
At least some of Linq might be available in the very latest release, but Linq to DB is listed for Mono 2.4 (Feb 2009) | How can I use Linq with a MySql database on Mono? | [
"",
"c#",
"mysql",
"linux",
"linq",
"mono",
""
] |
I am creating a GUI for a machine that runs remote (WinXP) or on the machine itself (Windows CE 6.0).
Right now I've created a fast visualisation (read: very simple) of the machine itself. The goal is to make a bit more complex visualisation of the machine and for that I would need a lightweight 3d engine.
The engine... | Did you try [Irrlicht](http://irrlicht.sourceforge.net/).
> Recently Irrlicht has acquired official .NET bindings, allowing users to develop in .Net languages such as VB.NET, C# and Boo.
There is also [Ogre 3D](http://en.wikipedia.org/wiki/OGRE_3D) and also [Axiom Engine](http://en.wikipedia.org/wiki/Axiom_Engine) | It is a good question. I have looked as well, and not seen anything. It would be great to see some easy to access great visual effects for mobile, to somewhat compete with other platforms that are getting better looking.
Sometimes with Windows Mobile I feel like I am in the Windows 3.1 days! | Lightweight 3D Graphics Engine .NET (Compact and Full Framework) | [
"",
"c#",
"3d-engine",
""
] |
I need to import a csv file into **Firebird** and I've spent a couple of hours trying out some tools and none fit my needs.
The main problem is that all the tools I've been trying like [EMS Data Import](http://www.sqlmanager.net/products/ibfb/dataimport) and [Firebird Data Wizard](http://www.sqlmaestro.com/products/fi... | It's a bit crude - but for one off jobs, I sometimes use Excel.
If you import the CSV file into Excel, you can create a formula which creates an INSERT statement by using string concatenation in the formula. So - if your CSV file has 3 columns that appear in columns A, B, and C in Excel, you could write a formula like... | Well, if it's a CSV, and it this is a one time process, open up the file in Excel, and then write formulas to populate your data in any way you desire, and then write a simple Concat formula to construct your SQL, and then copy that formula for every row. You will get a large number of SQL statements which you can exec... | Generate insert SQL statements from a CSV file | [
"",
"sql",
"csv",
"insert",
"firebird",
""
] |
I'm using MSVE, and I have my own tiles I'm displaying in layers on top. Problem is, there's a ton of them, and they're on a network server. In certain directories, there are something on the order of 30,000+ files. Initially I called Directory.GetFiles, but once I started testing in a pseudo-real environment, it timed... | I've worked on a SAN system in the past with telephony audio recordings which had issues with numbers of files in a single folder - that system became unusable somewhere near 5,000 (on Windows 2000 Advanced Server with an application in C#.Net 1.1)- the only sensible solution that we came up with was to change the fold... | Definitely split them up. That said, stay as far away from the Indexing Service as you can. | Searching directories for tons of files? | [
"",
"c#",
"directory",
"file-management",
""
] |
So WPF doesn't support standard sorting or filtering behavior for views of CompositeCollections, so what would be a best practice for solving this problem.
There are two or more object collections of different types. You want to combine them into a single sortable and filterable collection (withing having to manually ... | Update: I found a much more elegant solution:
```
class MyCompositeObject
{
DateTime CreatedDate;
string SomeAttribute;
Object Obj1;
{
class MyCompositeObjects : List<MyCompositeObject> { }
```
I found that due to reflection, the specific type stored in Obj1 is resolved at runtime and the typ... | "Brute force" method you mention is actually ideal solution. Mind you, all objects are in RAM, there is no I/O bottleneck, so you can pretty much sort and filter millions of objects in less than a second on any modern computer.
The most elegant way to work with collections is System.Linq namespace in .NET 3.5
> Thank... | Sorting a composite collection | [
"",
"c#",
".net",
"wpf",
"data-binding",
"collections",
""
] |
I would like to automatically generate PDF documents from [WebObjects](https://en.wikipedia.org/wiki/WebObjects) based on mulitpage forms. Assuming I have a class which can assemble the related forms (java/wod files) is there a good way to then parse the individual forms into a PDF instead of going to the screen? | The canonical response when asked about PDFs from WebObjects has generally been [ReportMill](http://www.reportmill.com/). It's a PDF document generating framework that works a lot like WebObjects, and includes its own graphical PDF builder tool similar to WebObjects Builder and Interface Builder. You can bind elements ... | I'm not familiar with WebObjects, but I see you have java listed in there.
[iText](http://www.lowagie.com/iText/) is a java api for building pdfs. If you can access a java api from WebObjects you should be able to build pdfs that way. | Create PDFs from multipage forms in WebObjects | [
"",
"java",
"pdf",
"webobjects",
""
] |
What is the story behind XPath and support for namespaces? Did XPath as a specification precede namespaces? If I have a document where elements have been given a default namespace:
```
<foo xmlns="uri" />
```
It appears as though some of the XPath processor libraries won't recognize `//foo` because of the namespace w... | I tried something similar to what palehorse proposed and could not get it to work. Since I was getting data from a published service I couldn't change the xml. I ended up using XmlDocument and XmlNamespaceManager like so:
```
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlWithBogusNamespace);
XmlNames... | You need local-name():
<http://www.w3.org/TR/xpath#function-local-name>
To crib from <http://web.archive.org/web/20100810142303/http://jcooney.net:80/archive/2005/08/09/6517.aspx>:
```
<foo xmlns='urn:foo'>
<bar>
<asdf/>
</bar>
</foo>
```
This expression will match the “bar” element:
```
//*[... | XPATHS and Default Namespaces | [
"",
"c#",
"xml",
"xpath",
"namespaces",
""
] |
The following code doesn't compile with gcc, but does with Visual Studio:
```
template <typename T> class A {
public:
T foo;
};
template <typename T> class B: public A <T> {
public:
void bar() { cout << foo << endl; }
};
```
I get the error:
> test.cpp: In member function ‘void B::bar()’:
>
> test.cpp:11: e... | This changed in [gcc-3.4](http://gcc.gnu.org/gcc-3.4/changes.html#cplusplus). The C++ parser got much more strict in that release -- per the spec but still kinda annoying for people with legacy or multi-platform code bases. | David Joyner had the history, here is the reason.
The problem when compiling `B<T>` is that its base class `A<T>` is unknown from the compiler, being a template class, so no way for the compiler to know any members from the base class.
Earlier versions did some inference by actually parsing the base template class, b... | GCC issue: using a member of a base class that depends on a template argument | [
"",
"c++",
"templates",
"base-class",
"class-members",
"name-lookup",
""
] |
I've recently taken up learning some C# and wrote a Yahtzee clone. My next step (now that the game logic is in place and functioning correctly) is to integrate some method of keeping stats across all the games played.
My question is this, how should I go about storing this information? My first thought would be to use... | Here is one idea: use Xml Serialization. Design your GameStats data structure and optionally use Xml attributes to influence the schema as you like. I like to use this method for small data sets because its quick and easy and all I need to do is design and manipulate the data structure.
```
using (FileStream fs = new ... | A database would probably be overkill for something like this - start with storing your information in an XML doc (or series of XML docs, if there's a lot of data). You get all that nifty XCopy deployment stuff, you can still use LINQ, and it would be a smooth transition to a database if you decided later you really ne... | Store data from a C# application | [
"",
"c#",
".net",
""
] |
I want to create a draggable and resizable window in JavaScript for cross browser use, but I want to try and avoid using a framework if I can.
Has anyone got a link or some code that I can use? | JQuery is more focused on a lot of nice utility functions, and makes DOM manipulation a whole lot easier. Basically, I consider it to be Javascript as it should have been. It's a supremely helpful addition to the Javascript language itself.
ExtJS is a suite of GUI components with specific APIs... Use it if you want to... | [JQuery](http://jquery.com/) would be a good way to go. And with the [Jquery UI](http://ui.jquery.com/) plugins (such as [draggable](http://docs.jquery.com/UI/Draggables)), it's a breeze.. (there's a [demo](http://ui.jquery.com/repository/real-world/photo-manager/) here).
Not using a framework, to keep it 'pure', seem... | How do I create a draggable and resizable JavaScript popup window? | [
"",
"javascript",
"dialog",
""
] |
What's the **easiest**, **tersest**, and most **flexible** method or library for parsing Python command line arguments? | **This answer suggests `optparse` which is appropriate for older Python versions. For Python 2.7 and above, `argparse` replaces `optparse`. See [this answer](https://stackoverflow.com/questions/3217673/why-use-argparse-rather-than-optparse) for more information.**
As other people pointed out, you are better off going ... | [`argparse`](https://docs.python.org/library/argparse.html) is the way to go. Here is a short summary of how to use it:
**1) Initialize**
```
import argparse
# Instantiate the parser
parser = argparse.ArgumentParser(description='Optional app description')
```
**2) Add Arguments**
```
# Required positional argument... | What's the best way to parse command line arguments? | [
"",
"python",
"command-line",
"command-line-arguments",
""
] |
I want to include a batch file rename functionality in my application. A user can type a destination filename pattern and (after replacing some wildcards in the pattern) I need to check if it's going to be a legal filename under Windows. I've tried to use regular expression like `[a-zA-Z0-9_]+` but it doesn't include m... | You can get a list of invalid characters from [`Path.GetInvalidPathChars`](http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidpathchars.aspx) and [`GetInvalidFileNameChars`](http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx).
**UPD:** See [Steve Cooper's suggestion](http... | From [MSDN's "Naming a File or Directory,"](http://msdn.microsoft.com/en-us/library/aa365247.aspx "Naming a File or Directory") here are the general conventions for what a legal file name is under Windows:
You may use any character in the current code page (Unicode/ANSI above 127), except:
* `<` `>` `:` `"` `/` `\` `... | How do I check if a given string is a legal/valid file name under Windows? | [
"",
"c#",
"windows",
"file",
"filesystems",
""
] |
How do I implement a Copy menu item in a Windows application written in C#/.NET 2.0?
I want to let the user to mark some text in a control and then select the Copy menu item from an Edit menu in the menubar of the application and then do a Paste in for example Excel.
What makes my head spin is how to first determine ... | With the aid of some heavy pair programming a colleague of mine and I came up with this, feel free to refactor.
The code is placed in the main form. The copyToolStripMenuItem\_Click method handles the Click event on the Copy menu item in the Edit menu.
```
/// <summary>
/// Recursively traverse a tree of cont... | Why not extending the control, so the control itself provides the data which should be copied into the clipboard.
Take a look at [ApplicationCommands](http://msdn.microsoft.com/en-us/library/system.windows.input.applicationcommands.aspx) documentation. | How to implement the Edit -> Copy menu in c#/.net | [
"",
"c#",
".net",
"winforms",
"user-interface",
""
] |
At my work we are running a group of tests that consist of about 3,000 separate test cases. Previously we were running this entire test suite on one machine, which took about 24-72 hours to complete the entire test run. We now have created our own system for grouping and distributing the tests among about three separat... | I've seen some people having a play with [distributed JUnit](http://216.93.179.140:8080/wiki/display/GG15UG/Distributed+JUnit+Overview). I can't particularly vouch for how effective it is, but the other teams I've seen seemed to think it was straight forward enough. Hope that helps. | There's also [parallel-junit](https://parallel-junit.java.net/). Depending on how you currently execute your tests its convenience may vary - the idea is just to multithread on a single system that has multiple cores. I've played with it briefly, but it's a change from how we currently run our tests.
[Hudson](https://... | Test Distribution | [
"",
"java",
"testing",
"enterprise",
""
] |
It's fall of 2008, and I still hear developers say that you should not design a site that requires JavaScript.
I understand that you should develop sites that degrade gracefully when JS is not present/on. But at what point do you not include funcitonality that can only be powered by JS?
I guess the question comes dow... | 5% according to these statistics: <http://www.w3schools.com/browsers/browsers_stats.asp> | Just as long as you're aware of the accessibility limitations you might be introducing, ie for users of screen-reading software, etc.
It's one thing to exclude people because they choose to turn off JS or use a browser which doesn't support it, it's entirely another to exclude them because of a disability. | Should you design websites that require JavaScript in this day & age? | [
"",
"javascript",
""
] |
I've written PL/SQL code to denormalize a table into a much-easer-to-query form. The code uses a temporary table to do some of its work, merging some rows from the original table together.
The logic is written as a [pipelined table function](http://www.oreillynet.com/lpt/a/3136), following the pattern from the linked ... | I think a way to approach this is to use analytic functions...
I set up your test case using:
```
create table employee_job (
emp_id integer,
job_id integer,
status varchar2(1 char),
eff_date date
);
insert into employee_job values (1,10,'A',to_date('10-JAN-2008','DD-MON-YYYY'));
insert into em... | Rather than having the input parameter as a cursor, I would have a table variable (don't know if Oracle has such a thing I'm a TSQL guy) or populate another temp table with the ID values and join on it in the view/function or wherever you need to.
The only time for cursors in my honest opinion is when you *have* to lo... | Best way to encapsulate complex Oracle PL/SQL cursor logic as a view? | [
"",
"sql",
"oracle",
"plsql",
""
] |
Following on from my [previous question](https://stackoverflow.com/questions/19454/enforce-attribute-decoration-of-classesmethods) I have been working on getting my object model to serialize to XML. But I have now run into a problem (quelle surprise!).
The problem I have is that I have a collection, which is of a abst... | ## Problem Solved!
OK, so I finally got there (admittedly with a **lot** of help from [here](http://www.codeproject.com/KB/XML/xmlserializerforunknown.aspx)!).
So summarise:
### Goals:
* I didn't want to go down the *XmlInclude* route due to the maintenence headache.
* Once a solution was found, I wanted it to be q... | One thing to look at is the fact that in the XmlSerialiser constructor you can pass an array of types that the serialiser might be having difficulty resolving. I've had to use that quite a few times where a collection or complex set of datastructures needed to be serialised and those types lived in different assemblies... | XML Serialization and Inherited Types | [
"",
"c#",
"xml",
"inheritance",
"serialization",
"xml-serialization",
""
] |
I know in JavaScript, *objects* double as hashes, but I have been unable to find a built-in function to get the keys:
```
var h = {a:'b', c:'d'};
```
I want something like
```
var k = h.keys() ; // k = ['a', 'c'];
```
It is simple to write a function myself to iterate over the items and add the keys to an array tha... | There is function in modern JavaScript (ECMAScript 5) called [`Object.keys`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys) performing this operation:
```
var obj = { "a" : 1, "b" : 2, "c" : 3};
alert(Object.keys(obj)); // will output ["a", "b", "c"]
```
Compatibility details can be... | For production code requiring a large compatibility with client browsers I still suggest [Ivan Nevostruev's answer](https://stackoverflow.com/questions/18912/how-can-i-find-the-keys-of-a-hash/6921193#6921193) with shim to ensure `Object.keys` in older browsers. However, it's possible to get the exact functionality requ... | How can I find the keys of an object? | [
"",
"javascript",
"object",
"key",
""
] |
I'm using Eclipse 3.4 and have configured the Java code formatter with all of the options on the *Comments* tab enabled. The problem is that when I format a document comment that contains:
```
* @see <a href="test.html">test</a>
```
the code formatter inserts a space in the closing HTML, breaking it:
```
* @see <a h... | I can only assume it's a bug in Eclipse. It only happens with *@see* tags, it happens also for all 3 builtin code formatter settings.
There are some interesting bugs reported already in the neighbourhood, but I couldn't find this specific one. See for example a search for *@see* in the [Eclipse Bugzilla](https://bugs.... | Strict XML specifications require that the self closing tags should have a space before the closing slash like so:
```
<gcServer enabled="true" /> <!-- note the space just after "true" -->
```
I can only assume, like Bart said, that there is a bug in Eclipse's reformatter that thinks the closing tag is actually a sel... | Why does the Eclipse code formatter break </a> in a Javadoc @see tag? | [
"",
"java",
"eclipse",
"javadoc",
"eclipse-3.4",
""
] |
I'm using **Struts 2**.
I'd like to return from an Action to the page which invoked it.
Say I'm in page **x.jsp**, I invoke Visual action to change CSS preferences in the session; I want to return to **x.jsp** rather than to a fixed page (i.e. **home.jsp**)
Here's the relevant **struts.xml** fragment:
```
<action
... | You can use a dynamic result in struts.xml. For instance:
```
<action
name="Visual"
class="it.___.web.actions.VisualizationAction">
<result name="next">${next}</result>
</action>
```
Then in your action, you create a field called next. So to invoke the action you will pass the name of the page that you want ... | ```
return INPUT;
```
will do the trick. INPUT constant is defined in Action interface itself. It indicates that action needs more input.
By calling page if you meant the page that took you to the action input page, then your input page will have to store HTTP header "Referer" in the request scope for the Action. | Struts 2: return to calling page | [
"",
"java",
"struts2",
"struts",
""
] |
When we create stored procedures in Visual Studio (with the extension .sql) the file encoding is automatically set to 'Unicode (UTF-8 with signature) - Codepage 65001'.
This causes ours DBA's problems as their scripts don't like it.
We have to manually go in and change them to 'Western European (windows) - Codepage 1... | I think somebody faced a similar problem like yours and had the following workaround which is posted at
<http://connect.microsoft.com/VisualStudio/feedback/Workaround.aspx?FeedbackID=319830> | To summarise the link provided by Codeslayer (in case the page url changes)...
*Change the sql file templates to ANSI encoding by opening with notepad and then saving it as an ANSI file. You can do the same for files already created.
\Common7\Tools\Templates\Database Project Items*
You've just made our DBA's very hap... | SQL file encoding in Visual Studio | [
"",
"sql",
"visual-studio",
"stored-procedures",
""
] |
The following code illustrates an object literal being assigned, but with no semicolon afterwards:
```
var literal = {
say: function(msg) { alert(msg); }
}
literal.say("hello world!");
```
This appears to be legal, and doesn't issue a warning (at least in Firefox 3). Is this completely legal, or is there a strict... | Not technically, JavaScript has semicolons as optional in many situations.
But, as a general rule, use them at the end of any statement. Why? Because if you ever want to compress the script, it will save you from countless hours of frustration.
Automatic semicolon insertion is performed by the interpreter, so you *ca... | The YUI Compressor and dojo shrinksafe should work perfectly fine without semicolons since they're based on a full JavaScript parser. But Packer and JSMin won't.
The other reason to always use semi-colons at the end of statements is that occasionally you can accidentally combine two statements to create something very... | Are semicolons needed after an object literal assignment in JavaScript? | [
"",
"javascript",
""
] |
What is the best way people have found to do String to Lower case / Upper case in C++?
The issue is complicated by the fact that C++ isn't an English only programming language. Is there a good multilingual method? | ```
#include <algorithm>
std::string data = "Abc";
std::transform(data.begin(), data.end(), data.begin(), ::toupper);
```
<http://notfaq.wordpress.com/2007/08/04/cc-convert-string-to-upperlower-case/>
Also, CodeProject article for common string methods: <http://www.codeproject.com/KB/stl/STL_string_util.aspx> | ```
> std::string data = “Abc”;
> std::transform(data.begin(), data.end(), data.begin(), ::toupper);
```
This will work, but this will use the standard "C" locale. You can use facets if you need to get a tolower for another locale. The above code using facets would be:
```
locale loc("");
const ctype<char>& ct = use... | String To Lower/Upper in C++ | [
"",
"c++",
"string",
"unicode",
""
] |
I am messing around with [a toy interpreter in Java](http://code.google.com/p/zemscript/) and I was considering trying to write a simple compiler that can generate bytecode for the Java Virtual Machine. Which got me thinking, how much optimization needs to be done by compilers that target virtual machines such as JVM a... | I'm just gonna add two links which explain [Java's bytecode](http://www.ibm.com/developerworks/ibm/library/it-haggar_bytecode/) pretty well and some of the [various optimization](http://www.ibm.com/developerworks/java/library/j-benchmark1.html) of the JVM during runtime. | Optimisation is what makes JVMs viable as environments for long running applications, you can bet that SUN, IBM and friends are doing their best to ensure they can optimise your bytecode and JIT-compiled code in an efficient a manner as possible.
With that being said, if you think you can pre-optimise your bytecode th... | Virtual Machine Optimization | [
"",
"java",
"jvm",
"jit",
"cil",
""
] |
Our application is interfacing with a lot of web services these days. We have our own package that someone wrote a few years back using UTL\_HTTP and it generally works, but needs some hard-coding of the SOAP envelope to work with certain systems. I would like to make it more generic, but lack experience to know how ma... | I have used `UTL_HTTP` which is simple and works. If you face a challenge with your own package, you can probably find a solution in one of the many wrapper packages around UTL\_HTTP on the net (Google "consuming web services from pl/sql", leading you to e.g.
<http://www.oracle-base.com/articles/9i/ConsumingWebServices... | I had this challenge and found and installed the 'SOAP API' package that Sten suggests on Oracle-Base. It provides some good envelope-creation functionality on top of UTL\_HTTP.
However there were some limitations that pertain to your question. SOAP\_API assumes all requests are simple XML- i.e. only one layer tag hie... | Consuming web services from Oracle PL/SQL | [
"",
"sql",
"oracle",
"web-services",
"plsql",
""
] |
Is there any JavaScript method similar to the jQuery `delay()` or `wait()` (to delay the execution of a script for a specific amount of time)? | There is the following:
```
setTimeout(function, milliseconds);
```
function which can be passed the time after which the function will be executed.
See: [Window `setTimeout()` Method](https://www.w3schools.com/jsref/met_win_settimeout.asp). | Just to add to what everyone else have said about `setTimeout`:
If you want to call a function with a parameter in the future, you need to set up some anonymous function calls.
You need to pass the function as an argument for it to be called later. In effect this means without brackets behind the name. The following w... | Execute script after specific delay using JavaScript | [
"",
"javascript",
"settimeout",
""
] |
Every project invariably needs some type of reporting functionality. From a foreach loop in your language of choice to a full blow BI platform.
> To get the job done what tools, widgets, platforms has the group used with success, frustration and failure? | For knocking out fairly "run of the mill" reports, SQL Reporting Services is really quite impressive.
For complicated analysis, loading the data (maybe pre-aggregated) into an Excel Pivot table is usually adequate for most users.
I've found you can spend a lot of time (and money) building a comprehensive "ad-hoc" rep... | For most reports we use [BIRT](http://www.eclipse.org/birt/). | What is your reporting tool of choice? | [
"",
"sql",
"reporting",
"business-intelligence",
""
] |
How can I find any unused functions in a PHP project?
Are there features or APIs built into PHP that will allow me to analyse my codebase - for example [Reflection](http://ie.php.net/manual/en/language.oop5.reflection.php), [`token_get_all()`](http://php.net/manual/en/function.token-get-all.php)?
Are these APIs featu... | Thanks Greg and Dave for the feedback. Wasn't quite what I was looking for, but I decided to put a bit of time into researching it and came up with this quick and dirty solution:
```
<?php
$functions = array();
$path = "/path/to/my/php/project";
define_dir($path, $functions);
reference_dir($path, $func... | You can try Sebastian Bergmann's Dead Code Detector:
**Note:** *Dead Code Detector has been archived by the owner on Nov 9, 2017*
**Alternative tools**:
* <https://phpqa.io/>
* <https://github.com/phpmd/phpmd>
**Dead Code Detector:**
> `phpdcd` is a Dead Code Detector (DCD) for PHP code. It scans a PHP project for... | How can I find unused functions in a PHP project | [
"",
"php",
""
] |
How can you do a streaming read on a large XML file that contains a xs:sequence just below root element, without loading the whole file into a XDocument instance in memory? | Going with a SAX-style element parser and the [XmlTextReader](http://msdn.microsoft.com/en-us/library/system.xml.xmltextreader.aspx) class created with [XmlReader.Create](http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.create.aspx) would be a good idea, yes. Here's a slightly-modified code example from [Co... | I can't add a comment, since I just signed up but the code sample posted by Hirvox and currently selected as the answer has a bug in it. It should not have the `new` statement when using the static `Create` method.
Current:
```
using (var reader = new XmlReader.Create(strUrl))
```
Fixed:
```
using (var reader = Xml... | How to do streaming read of a large XML file in C# 3.5 | [
"",
"c#",
".net",
"xml",
".net-3.5",
"streaming",
""
] |
I would like to flash a success message on my page.
I am using the jQuery `fadeOut` method to fade and then remove the element. I can increase the duration to make it last longer, however this looks strange.
What I would like to happen is have the element be displayed for five seconds, then fade quickly, and finally ... | The new `delay()` function in jQuery 1.4 should do the trick.
```
$('#foo').fadeIn(200).delay(5000).fadeOut(200).remove();
``` | use `setTimeout(function(){$elem.hide();}, 5000);`
Where `$elem` is the element you wish to hide, and `5000` is the delay in milliseconds. You can actually use any function within the call to `setTimeout()`, that code just defines a small anonymous function for simplicity. | How do you pause before fading an element out using jQuery? | [
"",
"javascript",
"jquery",
"animation",
""
] |
I've used Apache CXF to expose about ten java classes as web services.
I've generated clients using CXF, Axis, and .NET.
In Axis and CXF a "Service" or "Locator" is generated.
From this service you can get a "Port".
The "Port" is used to make individual calls to the methods exposed by the web service.
In .NET the "S... | I'd hop over to <http://www.w3.org/TR/wsdl.html> which I think explains Port, Service and Endpoint reasonably well. A locator is an implementation specific mechanism that some WS stacks use to provide access to service endpoints. | I found the information based on Kevin Kenny's answer, but I figured I'd post it here for others.
A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format bindings. This ... | What is the difference between an endpoint, a service, and a port when working with webservices? | [
"",
"java",
".net",
"web-services",
"cxf",
"axis",
""
] |
`std::swap()` is used by many std containers (such as `std::list` and `std::vector`) during sorting and even assignment.
But the std implementation of `swap()` is very generalized and rather inefficient for custom types.
Thus efficiency can be gained by overloading `std::swap()` with a custom type specific implementa... | The right way to overload `std::swap`'s implemention (aka specializing it), is to write it in the same namespace as what you're swapping, so that it can be found via [argument-dependent lookup (ADL)](https://en.cppreference.com/w/cpp/language/adl). One particularly easy thing to do is:
```
class X
{
// ...
fri... | **Attention Mozza314**
Here is a simulation of the effects of a generic `std::algorithm` calling `std::swap`, and having the user provide their swap in namespace std. As this is an experiment, this simulation uses `namespace exp` instead of `namespace std`.
```
// simulate <algorithm>
#include <cstdio>
namespace ex... | How to overload std::swap() | [
"",
"c++",
"performance",
"optimization",
"stl",
"c++-faq",
""
] |
Is it necessary or advantageous to write custom connection pooling code when developing applications in .NET with an SQL Server database? I know that ADO.NET gives you the option to enable/disable connection pooling -- does that mean that it's built into the framework and I don't need to worry about it? Why do people t... | The connection pooling built-in to ADO.Net is robust and mature. I would recommend against attempting to write your own version. | I'm no *real* expert on this matter, but I know ADO.NET has its own connection pooling system, and as long as I've been using it it's been faultless.
My reaction would be that there's no point in reinventing the wheel... Just make sure you close your connections when you're finished with them and everything will be fi... | Connection Pooling in .NET/SQL Server? | [
"",
"c#",
".net",
"sql-server",
"connection-pooling",
""
] |
I could swear I've seen people typing function headers and then hitting some key combination to auto-create function braces and insert the cursor between them like so:
```
void foo()_
```
to
```
void foo()
{
_
}
```
Is this a built-in feature? | Check out [Resharper](http://www.jetbrains.com/resharper/documentation/feature_map.html) - it is a Visual Studio add-on with this feature, among many other development helps.
Also see [C# Completer](http://www.knowdotnet.com/articles/csharpcompleter.html), another add-on.
If you want to roll your own, check out [this... | The tools look nice (especially Resharper but at $200-350 ouch!) but I ended up just recording a macro and assigning it to ctrl+alt+[
Macro came out like this:
```
Sub FunctionBraces()
DTE.ActiveDocument.Selection.NewLine
DTE.ActiveDocument.Selection.Text = "{}"
DTE.ActiveDocument.Selection.CharLeft
D... | How do I make Visual Studio auto generate braces for a function block? | [
"",
"c#",
"visual-studio",
""
] |
I would like to monitor a log file that is being written to by an application. I want to process the file line by line as, or shortly after, it is written. I have not found a way of detecting that a file has been extended after reaching eof.
The code needs to work on Mac and PC, and can be in any language, though I am... | In Perl, the [File::Tail](http://search.cpan.org/dist/File-Tail/) module does exactly what you need. | A generic enough answer:
Most languages, on EOF, return that no data were read. You can re-try reading after an interval, and if the file has grown since, this time the operating system will return data. | Reading data from a log file as a separate application is writing to it | [
"",
"c++",
"perl",
"macos",
"file-io",
"logging",
""
] |
Is there an easy way to iterate over an associative array of this structure in PHP:
The array `$searches` has a numbered index, with between 4 and 5 associative parts. So I not only need to iterate over `$searches[0]` through `$searches[n]`, but also `$searches[0]["part0"]` through `$searches[n]["partn"]`. The hard pa... | Nest two [`foreach` loops](http://php.net/foreach):
```
foreach ($array as $i => $values) {
print "$i {\n";
foreach ($values as $key => $value) {
print " $key => $value\n";
}
print "}\n";
}
``` | I know it's question necromancy, but iterating over Multidimensional arrays is easy with Spl Iterators
```
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($iterator as $key=>$value) {
echo $key.' -- '.$value.'<br />';
}
```
See
* <http://php.net/manual/en/spl.iterators.php... | Iterating over a complex Associative Array in PHP | [
"",
"php",
"arrays",
"associative-array",
""
] |
I specifically want to add the style of `background-color` to the `<body>` tag of a master page, from the code behind (C#) of a content page that uses that master page.
I have different content pages that need to make the master page has different colors depending on which content page is loaded, so that the master pa... | What I would do for the particular case is:
i. Define the body as a server side control
```
<body runat="server" id="masterpageBody">
```
ii. In your content aspx page, register the MasterPage with the register:
```
<% MasterPageFile="..." %>
```
iii. In the Content Page, you can now simply use
```
Master.FindCon... | This is what I came up with:
In the page load function:
```
HtmlGenericControl body = (HtmlGenericControl)Master.FindControl("default_body");
body.Style.Add(HtmlTextWriterStyle.BackgroundColor, "#2E6095");
```
Where
> default\_body = the id of the body tag. | How can I change the background of a masterpage from the code behind of a content page? | [
"",
"c#",
"asp.net",
".net",
"master-pages",
""
] |
Is there an easy way in C# to create [Ordinals](http://en.wikipedia.org/wiki/Ordinal_numbers_%28linguistics%29) for a number? For example:
* 1 returns 1st
* 2 returns 2nd
* 3 returns 3rd
* ...etc
Can this be done through `String.Format()` or are there any functions available to do this? | This page gives you a complete listing of all custom numerical formatting rules:
[Custom numeric format strings](https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings)
As you can see, there is nothing in there about ordinals, so it can't be done using `String.Format`. However its ... | Remember internationalisation!
The solutions here only work for English. Things get a lot more complex if you need to support other languages.
For example, in Spanish "1st" would be written as "1.o", "1.a", "1.os" or "1.as" depending on whether the thing you're counting is masculine, feminine or plural!
So if your s... | Is there an easy way to create ordinals in C#? | [
"",
"c#",
".net",
"ordinals",
""
] |
Regarding the same program as [my question a few minutes ago](https://stackoverflow.com/questions/20061/store-data-from-a-c-application)... I added a setup project and built an MSI for the program (just to see if I could figure it out) and it works great except for one thing. When I tried to install it on my parent's l... | Indeed, boot from a clean CD (use a known good machine to build [BartPE](http://nu2.nu/pebuilder/) or something similar) and scan your machine thoroughly. Another good thing to check, though, would be exactly which virus Avast! thinks your program is. Once you know that, you should be able to look it up in one of the v... | I would do what jsight suggested and make sure that your machine did not have a virus. I would also submit the .msi file to [Avast's online scanner](http://onlinescan.avast.com/ "avast! Online Scanner") and see what they identified as being in your package. If that reports your file as containing a trojan, contact Avas... | C# application detected as a virus | [
"",
"c#",
".net",
"antivirus",
""
] |
This isn't a design question, really, though it may seem like it. (Well, okay, it's kind of a design question). What I'm wondering is why the C++ `std::fstream` classes don't take a `std::string` in their constructor or open methods. Everyone loves code examples so:
```
#include <iostream>
#include <fstream>
#include ... | By taking a C string the C++03 [`std::fstream`](http://en.cppreference.com/w/cpp/io/basic_fstream) class reduced dependency on the `std::string` class. In C++11, however, the `std::fstream` class does allow passing a `std::string` for its constructor parameter.
Now, you may wonder why isn't there a transparent convers... | There are several places where the C++ standard committee did not really optimize the interaction between facilities in the standard library.
`std::string` and its use in the library is one of these.
One other example is `std::swap`. Many containers have a swap member function, but no overload of std::swap is supplie... | Why don't the std::fstream classes take a std::string? | [
"",
"c++",
"stl",
"file-io",
"stdstring",
""
] |
I'm writing an application that on some stage performs low-level disk operations in Linux environment. The app actually consists of 2 parts, one runs on Windows and interacts with a user and another is a linux part that runs from a LiveCD. User makes a choice of Windows drive letters and then a linux part performs acti... | Partitions have UUIDs associated with them. I don't know how to find these in Windows but in linux you can find the UUID for each partition with:
> sudo vol\_id -u device (e.g. /dev/sda1)
If there is an equivilent function in Windows you could simply store the UUIDs for whatever partition they pick then iterate throu... | > Partitions have UUIDs associated with them
My knowledge of this is very shallow, but I thought that was only true for disks formatted with GPT (Guid Partition Table) partitions, rather than the old-style MBR format which 99% of the world is still stuck with? | How to match linux device path to windows drive name? | [
"",
"c++",
"linux",
"drives",
""
] |
I'm working on a website that will switch to a new style on a set date. The site's built-in semantic HTML and CSS, so the change should just require a CSS reference change. I'm working with a designer who will need to be able to see how it's looking, as well as a client who will need to be able to review content update... | In Asp.net 3.5, you should be able to set up the Link tag in the header as a server tag. Then in the codebehind you can set the href property for the link element, based on a cookie value, querystring, date, etc.
In your aspx file:
```
<head>
<link id="linkStyles" rel="stylesheet" type="text/css" runat="server" />
... | You should look into `ASP.NET` themes, that's exactly what they're used for. They also allow you to skin controls, which means give them a set of default attributes. | How to set up a CSS switcher | [
"",
"javascript",
"html",
"asp.net",
"css",
""
] |
I am using Java back end for creating an XML string which is passed to the browser. Currently I am using simple string manipulation to produce this XML. Is it essential that I use some XML library in Java to produce the XML string?
I find the libraries very difficult to use compared to what I need. | It's not essential, but advisable. However, if string manipulation works for you, then go for it! There are plenty of cases where small or simple XML text can be safely built by hand.
Just be aware that creating XML text is harder than it looks. Here's some criteria I would consider:
* First: how much *control* do yo... | Xml is hard. Parsing yourself is a bad idea, it's even a worse idea to generate content yourself. Have a look at the Xml 1.1 spec.
You have to deal with such things as proper encoding, attribute encoding (e.g., produces invalid xml), proper CDATA escaping, UTF encoding, custom DTD entities, and that's without throwing... | Is it essential that I use libraries to manipulate XML? | [
"",
"java",
"xml",
""
] |
I would like to display details of an xml error log to a user in a winforms application and am looking for the best control to do the job.
The error data contains all of the sever variables at the time that the error occurred. These have been formatted into an XML document that looks something to the effect of:
```
<... | You can transform your XML data using [XSLT](http://www.xml.com/pub/a/2002/08/14/dotnetxslt.html)
Another option is to use XLinq.
If you want concrete code example provide us with sample data
**EDIT**:
here is a sample XSLT transform for your XML file:
```
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.or... | You could try using the `DataGridView` control. To see an example, load an XML file in DevStudio and then right-click on the XML and select "View Data Grid". You'll need to read the API documentation on the control to use it. | Displaying XML data in a Winforms control | [
"",
"c#",
"xml",
"winforms",
"formatting",
""
] |
**Is there a way to utilise the GCC compiler whilst still being able to develop via the Visual Studio IDE?**
Our project is cross-platform, and I quite frequently get into trouble from my [colleague](https://stackoverflow.com/users/912/jkp) because I'm checking in code that's not standards compliant (this can be attri... | What I am about to suggest would still require a makefile, so I am partially repeating the advice from an earlier reply. Or, as was also mentioned earlier, maybe you already have a makefile, in which case you will have even fewer steps in order to accomplish what I am about to describe.
Once you know your specific win... | I don't think there is a simple switch, because gcc's command-line options are very different from VSs. In any case, just running the compiler will be non-trivial, as your build system probably sets a bunch of preprocessor defines and build variables that need to be set for the compile to succeed.
If your colleague is... | Using GCC from within VS 2005(8) IDE | [
"",
"c++",
"visual-studio",
"visual-c++",
"gcc",
"cross-platform",
""
] |
I have a collection of classes that inherit from an abstract class I created. I'd like to use the abstract class as a factory for creating instances of concrete implementations of my abstract class.
Is there any way to hide a constructor from all code except a parent class.
I'd like to do this basically
```
public a... | You can make the sub classes child classes, something like this:
```
public abstract class AbstractClass
{
public static AbstractClass MakeAbstractClass(string args)
{
if (args == "a")
return new ConcreteClassA();
if (args == "b")
return new ConcreteClassB();
}
... | > To me, the simplest solution is to
> make child classes as samjudson
> mentioned. I'd like to avoid this
> however since it would make my
> abstract class' file a lot bigger than
> I'd like it to be. I'd rather keep
> classes split out over a few files for
> organization.
No problem, just use **partial** keyword and... | Is there a way to make a constructor only visible to a parent class in C#? | [
"",
"c#",
"inheritance",
"oop",
""
] |
I'm using Visual C++ 2003 to debug a program remotely via TCP/IP.
I had set the Win32 exception c00000005, "Access violation," to break into the debugger when thrown. Then, I set it back to "Use parent setting." The setting for the parent, Win32 Exceptions, is to continue when the exception is thrown.
Now, when I deb... | I'd like to support [Will Dean's answer](https://stackoverflow.com/questions/8263/i-cant-get-my-debugger-to-stop-breaking-on-first-chance-exceptions#8304)
An access violation sounds like an actual bug in your code. It's not something I'd expect the underlying C/++ Runtime to be throwing and catching internally.
The '... | Is this an exception that your code would actually handle if you weren't running in the debugger? | I can't get my debugger to stop breaking on first-chance exceptions | [
"",
"c++",
"visual-studio",
"debugging",
"visual-studio-2003",
"first-chance-exception",
""
] |
I've done this before in C++ by including sqlite.h but is there a similarly easy way in C#? | [Microsoft.Data.Sqlite](https://www.nuget.org/packages/Microsoft.Data.Sqlite) by Microsoft has over 9000 downloads every day, so I think you are safe using that one.
Example usage from [the documentation](https://learn.microsoft.com/dotnet/standard/data/sqlite/):
```
using (var connection = new SqliteConnection("Data... | I'm with, Bruce. I AM using <http://system.data.sqlite.org/> with great success as well. Here's a simple class example that I created:
```
using System;
using System.Text;
using System.Data;
using System.Data.SQLite;
namespace MySqlLite
{
class DataClass
{
private SQLiteConnection sqlite;
... | What is the best way to connect and use a sqlite database from C# | [
"",
"c#",
"sqlite",
""
] |
I'm about to deploy a mediumsized site powered by Django. I have a dedicated Ubuntu Server.
I'm really confused over which serversoftware to use. So i thought to myself: why not ask stackoverflow.
What i'm looking for is:
* Easy to set up
* Fast and easy on resources
* Can serve mediafiles
* Able to serve multiple d... | Since I was looking for some more in-depth answers, I decided to research the issue myself in depth. Please let me know if I've misunderstood anything.
Some general recommendation are to use a separate webserver for handling media. By separate, I mean a webserver which is not running Django. This server can be for ins... | I'm using [Cherokee](http://www.cherokee-project.com/).
According to [their benchmarks](http://www.cherokee-project.com/benchmarks.html) (grain of salt with them), it handles load better than both Lighttpd and nginx... But that's not why I use it.
I use it because if you type `cherokee-admin`, it starts a new server ... | Cleanest & Fastest server setup for Django | [
"",
"python",
"django",
"apache",
"hosting",
""
] |
For my blog I am wanting to use the Output Cache to save a cached version of a perticular post for around 10 minutes, and thats fine...
```
<%@OutputCache Duration="600" VaryByParam="*" %>
```
However, if someone posts a comment, I want to clear the cache so that the page is refreshed and the comment can be seen.
Ho... | I've found the answer I was looking for:
```
HttpResponse.RemoveOutputCacheItem("/caching/CacheForever.aspx");
``` | The above are fine if you know what pages you want to clear the cache for. In my instance (ASP.NET MVC) I referenced the same data from all over. Therefore, when I did a [save] I wanted to clear cache site wide. This is what worked for me: <http://aspalliance.com/668>
This is done in the context of an OnActionExecutin... | Clearing Page Cache in ASP.NET | [
"",
"c#",
"asp.net",
"outputcache",
""
] |
I have inherited an old crusty `PHP application`, and I'd like to refactor it into something a little nicer to deal with, but in a gradual manner. In perl's CPAN, there is a series of classes around Class::DBI that allow you to use database rows as the basis for objects in your code, with the library generating `access... | It's now defunct but [phpdbi](http://phpdbi.sourceforge.net/web/) is possibly worth a look. If you're willing to let go of some of your caveats (the framework one), I've found that [Doctrine](http://www.phpdoctrine.org/) is a pretty neat way of accessing DBs in PHP. Worth investigating anyway. | I'm trying to get more feedback on my own projects, so I'll suggest my take on ORM: [ORMer](http://greaterscope.net/projects/ORMer)
Usage examples are [here](http://greaterscope.net/projects/ORMer/examples)
You can phase it in, it doesn't require you to adopt MVC, and it requires very little setup. | Class::DBI-like library for php? | [
"",
"php",
"perl",
"orm",
""
] |
What are the differences between these two, and which one should I use?
```
string s = "Hello world!";
String s = "Hello world!";
``` | [`string`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/string) is an alias in C# for [`System.String`](https://learn.microsoft.com/en-us/dotnet/api/system.string).
So technically, there is no difference. It's like [`int` *vs.* `System.Int32`](https://stackoverflow.com/questions/62503/c... | Just for the sake of completeness, here's a brain dump of related information...
As others have noted, `string` is an alias for `System.String`. Assuming your code using `String` compiles to `System.String` (i.e. you haven't got a using directive for some other namespace with a different `String` type), they compile t... | What is the difference between String and string in C#? | [
"",
"c#",
".net",
"string",
"types",
"alias",
""
] |
I need to prevent [Session Fixation](http://www.owasp.org/index.php/Session_Fixation), a particular type of session hijacking, in a Java web application running in JBoss. However, it appears that the standard idiom [doesn't work in JBoss](http://www.owasp.org/index.php/Session_Fixation_in_Java). Can this be worked arou... | [This defect](https://jira.jboss.org/jira/browse/JBAS-4436) (found [here](http://forum.springframework.org/showthread.php?t=54688)) points the way to the solution. The Tomcat instance that runs in JBoss is configured with emptySessionPath="true", rather than "false", which is the default. This can be modified in `.../d... | This problem and the specific case in which it occurs is a problem in Tomcat as well as JBoss. Tomcat shares the emptySessionPath="true" effect (and actually JBoss inherits it from Tomcat).
This really seems like a bug in Tomcat and JBoss when you are trying to prevent session fixation attacks but the servlet spec (at... | Resolving Session Fixation in JBoss | [
"",
"java",
"security",
"jboss",
""
] |
The `datepicker` function only works on the first input box that is created.
I'm trying to duplicate a datepicker by cloning the `div` that is containing it.
```
<a href="#" id="dupMe">click</a>
<div id="template">
input-text <input type="text" value="text1" id="txt" />
date time picker <input type="text" id="exa... | I'd recommend just using a common class name as well. However, if you're against this for some reason, you could also write a function to create date pickers for all text boxes in your template `div` (to be called after each duplication). Something like:
```
function makeDatePickers() {
$("#template input[type=text]... | I use a CSS class instead:
```
<input type="text" id="BeginDate" class="calendar" />
<input type="text" id="EndDate" class="calendar" />
```
Then, in your `document.ready` function:
```
$('.calendar').datepicker();
```
Using it that way for multiple calendar fields works for me. | duplicating jQuery datepicker | [
"",
"javascript",
"jquery",
""
] |
A researcher has created a small simulation in MATLAB and we want to make it accessible to others. My plan is to take the simulation, clean up a few things and turn it into a set of functions. Then I plan to compile it into a C library and use [SWIG](https://en.wikipedia.org/wiki/SWIG) to create a Python wrapper. At th... | I remember that I was able to wrap a MATLAB simulation into a [DLL file](https://en.wikipedia.org/wiki/Dynamic-link_library) and then call it from a [Delphi](https://en.wikipedia.org/wiki/Embarcadero_Delphi) application. It worked really well. | One thing to remember is that the MATLAB compiler does not actually compile the MATLAB code into native machine instructions. It simply wraps it into a stand-alone executable or a library with its own runtime engine that runs it. You would be able to run your code without MATLAB installed, and you would be able to inte... | Creating a shared library in MATLAB | [
"",
"python",
"c",
"matlab",
""
] |
This should be fine seeing as the CLR hasn't actually changed?
The boxes running the C# 2.0 code **have** had .NET 3.5 rolled out.
The background is that we have a windows service (.NET 2.0 exe built with VS2005, deployed to ~150 servers) that dynamically loads assemblies (almost like plug-ins) to complete various wo... | C#3 and .Net 3.5 adds new assemblies, but the IL is unchanged.
This means that with .Net 2 assemblies you can compile and use C#3, as long as you don't use Linq or anything else that references System.Linq or System.Core
`yield`, `var`, lambda syntax, anon types and initialisers are all compiler cleverness. The IL th... | > yield, var, lambda syntax, anon types
> and initialisers are all compiler
> cleverness. The IL they produce is
> cross-compatible.
Minor nit-picking point, but yield was a 2.0 feature anyway. | C# 2.0 code consuming assemblies compiled with C# 3.0 | [
"",
"c#",
".net",
".net-3.5",
""
] |
I'm looking to add a testing suite to my application, however I can't move to the newer testing frameworks for .NET 3.5.
Does anyone have a suggestion about good testing frameworks to use? | We use [MbUnit](http://www.mbunit.com/) and [Rihno Mocks](http://www.ayende.com/Blog/archive/2007/03/28/Rhino-Mocks-3.0-Released.aspx) and they prove to work very well together. When doing TDD you will almost certainly need to do some form of dependency injection, while this can be done manually, its worth looking at a... | NUnit and Rhino suit well and the [auto-mocking container](http://www.ayende.com/Blog/archive/2007/06/08/The-Auto-Mocking-Container.aspx) might be of interest.
If you're looking at BDD too then [NBehave](http://nbehave.org/) is probably a good choice. If however you just mean the style of BDD that relates to unit test... | What's the best way to implement BDD/TDD in .NET 2.0? | [
"",
"c#",
".net",
"testing",
"tdd",
"bdd",
""
] |
Imagine an object you are working with has a collection of other objects associated with it, for example, the Controls collection on a WinForm. You want to check for a certain object in the collection, but the collection doesn't have a `Contains()` method. There are several ways of dealing with this.
* Implement your ... | I would have to say that this is pretty bad practice. Whilst some people might be happy to say that looping through the collection is less efficient to throwing an exception, there is an overhead to throwing an exception. I would also question why you are using a collection to access an item by key when you would be be... | The general rule of thumb is to avoid using exceptions for control flow unless the circumstances that will trigger the exception are "exceptional" -- e.g., extremely rare!
If this is something that will happen normally and regularly it definitely should not be handled as an exception.
Exceptions are very, very slow d... | Using unhandled exceptions instead of Contains()? | [
"",
"c#",
".net",
"error-handling",
""
] |
I'm looking to create `favicon.ico` files programatically from Python, but PIL only has support for reading `ico` files. | According to [Wikipedia](http://en.wikipedia.org/wiki/Favicon) modern browsers can handle favicons in PNG format, so maybe you could just generate that?
Alternatively the [ICO article](http://en.wikipedia.org/wiki/ICO_(icon_image_file_format)) describes the format... | You can use [Pillow](http://pillow.readthedocs.org):
```
from PIL import Image
filename = r'logo.png'
img = Image.open(filename)
img.save('logo.ico')
```
Optionally, you may specify the icon sizes you want:
```
icon_sizes = [(16,16), (32, 32), (48, 48), (64,64)]
img.save('logo.ico', sizes=icon_sizes)
```
The [Pillo... | Is there a Python library for generating .ico files? | [
"",
"python",
"favicon",
""
] |
I'm trying to fix some JavaScript bugs. Firebug makes debugging these issues a lot easier when working in Firefox, but what do you do when the code works fine on Firefox but IE is complaining? | you can also check out the [IE Developer Toolbar](http://www.microsoft.com/downloads/en/details.aspx?FamilyID=95e06cbe-4940-4218-b75d-b8856fced535) which isn't a debugger but will help you analyze the contents of your code.
[Visual Studio](http://weblogs.asp.net/scottgu/archive/2007/07/19/vs-2008-javascript-debugging.... | You can try [Firebug Lite](http://getfirebug.com/lite.html) or use Visual Studio to debug the JavaScript. | Is there something like "Firebug for IE" (for debugging JavaScript)? | [
"",
"javascript",
"debugging",
"internet-explorer",
"firebug",
"javascript-debugger",
""
] |
Could someone write-up a step by step guide to developing a C++ based plugin for FireFox on Windows?
The links and examples on <http://www.mozilla.org/projects/plugins/> are all old and inaccurate - the "NEW" link was added to the page in 2004.
The example could be anything, but I was thinking a plugin that lets Java... | See also <http://developer.mozilla.org/en/Plugins> . And yes, NPAPI plugins should work in Google Chrome as well.
[edit 2015: Chrome removes support for NPAPI soon <http://blog.chromium.org/2014/11/the-final-countdown-for-npapi.html> ] | If you need something that works cross-browser (firefox and ie), you could look at firebreath: <http://www.firebreath.org>
For general "how to build a npapi plugin on windows" information, I have a few blog posts on the subject (linked to from some of the above sources as well)
<http://colonelpanic.net/2009/03/buildi... | How to write a C++ FireFox 3 plugin (not extension) on Windows? | [
"",
"c++",
"windows",
"firefox",
"plugins",
""
] |
I have over a million text files compressed into 40 zip files. I also have a list of about 500 model names of phones. I want to find out the number of times a particular model was mentioned in the text files.
Is there any python module which can do a regex match on the files without unzipping it. Is there a simple way... | There's nothing that will automatically do what you want.
However, there is a python zipfile module that will make this easy to do. Here's how to iterate over the lines in the file.
```
#!/usr/bin/python
import zipfile
f = zipfile.ZipFile('myfile.zip')
for subfile in f.namelist():
print subfile
data = f.rea... | Isn't it (at least theoretically) possible, to read in the ZIP's Huffman coding and then translate the regexp into the Huffman code? Might this be more efficient than first de-compressing the data, then running the regexp?
(Note: I know it wouldn't be quite that simple: you'd also have to deal with other aspects of th... | Is there a python module for regex matching in zip files | [
"",
"python",
"regex",
"zip",
"text-processing",
""
] |
I currently use a DataTable to get results from a database which I can use in my code.
However, many example on the web show using a DataSet instead and accessing the table(s) through the collections method.
Is there any advantage, performance wise or otherwise, of using DataSets or DataTables as a storage method for... | It really depends on the sort of data you're bringing back. Since a DataSet is (in effect) just a collection of DataTable objects, you can return multiple distinct sets of data into a single, and therefore more manageable, object.
Performance-wise, you're more likely to get inefficiency from unoptimized queries than f... | One major difference is that DataSets can hold multiple tables and you can define relationships between those tables.
If you are only returning a single result set though I would think a DataTable would be more optimized. I would think there has to be some overhead (granted small) to offer the functionality a DataSet ... | Datatable vs Dataset | [
"",
"c#",
"dataset",
"datatable",
""
] |
I just saw this mentioned in Stack Overflow question *[Best WYSIWYG CSS editor](http://web.archive.org/web/20090503103538/http://stackoverflow.com:80/questions/7975/best-css-editor)* and didn't know it could be done. I'm a Visual Studio newbie, so how do you do it?
Is there a separate debugger for JavaScript? I know h... | I prefer using [Firebug](http://en.wikipedia.org/wiki/Firebug_%28software%29) for projects I can't use [Visual Studio 2008](http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2008) on. | To debug in Visual Studio 2005, make sure that "disable script debugging" is unchecked. Then load your webpage in Internet Explorer. From the debug menu inside of Visual Studio 2005, select "Attach to process" and pick the instance of Internet Explorer that has your web page loaded.
Alternatively, the [Firebug](http:/... | How do I debug JavaScript in Visual Studio 2005? | [
"",
"javascript",
"visual-studio",
"visual-studio-2005",
"debugging",
""
] |
I would like to create a database backed interactive AJAX webapp which has a custom (specific kind of events, editing) calendaring system. This would involve quite a lot of JavaScript and AJAX, and I thought about Google Web Toolkit for the interface and Ruby on Rails for server side.
Is Google Web Toolkit reliable an... | RoR is actually one of the things the GWT is made to work well with, as long as you're using REST properly. It's in the Google Web Toolkit Applications book, and you can see a demo from the book using this kind of idea [here](http://www.gwtapps.com/?page_id=33). That's not to say that you won't have any problems, but I... | If you are looking to integrate GWT with non-Java backends such as ROR, PHP etc., you should bear in mind that GWT 1.5 now supports JavaScript Overlay types. This feature lets you write classes that can be mapped over the top of native JavaScript objects to easily provide accessor methods for properties of those object... | Should I use Google Web Toolkit for my new webapp? | [
"",
"javascript",
"ruby",
"gwt",
""
] |
From time to time I see an enum like the following:
```
[Flags]
public enum Options
{
None = 0,
Option1 = 1,
Option2 = 2,
Option3 = 4,
Option4 = 8
}
```
I don't understand what exactly the `[Flags]` attribute does.
Anyone have a good explanation or example they could post? | The `[Flags]` attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value. Such collections are often used with bitwise operators, for example:
```
var allowedColors = MyColor.Red | MyColor.Green | MyColor.Blue;
```
Note that the `[Flags]` attribute **doesn'... | You can also do this
```
[Flags]
public enum MyEnum
{
None = 0,
First = 1 << 0,
Second = 1 << 1,
Third = 1 << 2,
Fourth = 1 << 3
}
```
I find the bit-shifting easier than typing 4,8,16,32 and so on. It has no impact on your code because it's all done at compile time | What does the [Flags] Enum Attribute mean in C#? | [
"",
"c#",
"enums",
"flags",
""
] |
I want to create an allocator which provides memory with the following attributes:
* cannot be paged to disk.
* is incredibly hard to access through an attached debugger
The idea is that this will contain sensitive information (like licence information) which should be inaccessible to the user. I have done the usual ... | You can't really protect against memory access. You can probably prevent paging if you are running as an admin or as the system, but you cannot prevent the admin or system from reading your memory. Even if you could somehow completely block other processes from reading your memory (which you can't), another process cou... | On Unix systems you can use [mlock(2)](http://linux.die.net/man/2/mlock) to lock memory pages into RAM, preventing them being paged.
> mlock() and mlockall() respectively lock part or all of the calling
> process’s virtual address space into RAM, preventing that memory from
> being paged to the swap area.
There is a ... | Secure Memory Allocator in C++ | [
"",
"c++",
"security",
"memory",
"ram-scraping",
""
] |
I have an object that is mapped to a cookie as a serialized base-64 string. I only want to write out a new cookie if there are changes made to the object stored in the cookie on server-side.
What I want to do is get a hash code when the object is pulled from the cookie/initialized and compare the original hash code to... | At the end of the object's constructor you could serialize the object to a base 64 string just like the cookie stores it, and store this in a member variable.
When you want to check if the cookie needs recreating, re - serialize the object and compare this new base 64 string against the one stored in a member variable... | GetHashCode() should always be in sync with Equals(), and Equals() isn't necessarily guaranteed to check for *all* of the fields in your object (there's certain situations where you want that to not be the case).
Furthermore, GetHashCode() isn't guaranteed to return unique values for all possible object states. It's c... | What is the best way to tell if an object is modified? | [
"",
"c#",
".net",
""
] |
How can I use the Prototype library and create unobtrusive javascript to inject the onmouseover and onmouseout events to each row, rather than putting the javascript in each table row tag?
An answer utilizing the Prototype library (instead of mootools, jQuery, etc) would be most helpful. | ```
<table id="mytable">
<tbody>
<tr><td>Foo</td><td>Bar</td></tr>
<tr><td>Bork</td><td>Bork</td></tr>
</tbody>
</table>
<script type="text/javascript">
$$('#mytable tr').each(function(item) {
item.observe('mouseover', function() {
item.setStyle({ backgroundColor: '#ddd' });
}... | You can use Prototype's `addClassName` and `removeClassName` methods.
Create a CSS class "hilight" that you'll apply to the hilighted `<tr>`'s. Then run this code on page load:
```
var rows = $$('tbody tr');
for (var i = 0; i < rows.length; i++) {
rows[i].onmouseover = function() { $(this).addClassName('hilig... | How can I highlight a table row using Prototype? | [
"",
"javascript",
"ajax",
"prototypejs",
""
] |
Is it possible to write a `doctest` unit test that will check that an exception is raised?
For example, if I have a function `foo(x)` that is supposed to raise an exception if `x < 0`, how would I write the `doctest` for that? | Yes. You can do it. The [doctest module documentation](https://docs.python.org/3/library/doctest.html) and Wikipedia has an [example](http://en.wikipedia.org/wiki/Doctest#Example_2:_doctests_embedded_in_a_README.txt_file) of it.
```
>>> x
Traceback (most recent call last):
...
NameError: name 'x' is not ... | ```
>>> scope # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
NameError: name 'scope' is not defined
```
Don't know why the previous answers don't have the IGNORE\_EXCEPTION\_DETAIL. I need this for it to work. Py versioin: 3.7.3. | Can you check that an exception is thrown with doctest in Python? | [
"",
"python",
"doctest",
""
] |
Let's say I have a drive such as **C:\**, and I want to find out if it's shared and what it's share name (e.g. **C$**) is.
To find out if it's shared, I can use [NetShareCheck](https://learn.microsoft.com/en-us/windows/desktop/api/Lmshare/nf-lmshare-netsharecheck).
How do I then map the drive to its share name? I tho... | If all else fails, you could always use [NetShareEnum](https://learn.microsoft.com/en-us/windows/win32/api/lmshare/nf-lmshare-netshareenum) and call [NetShareGetInfo](https://learn.microsoft.com/windows/desktop/api/lmshare/nf-lmshare-netsharegetinfo) on each. | I believe you're looking for [WNetGetConnectionA](https://learn.microsoft.com/en-us/windows/win32/api/winnetwk/nf-winnetwk-wnetgetconnectiona) or [WNetGetConnectionW](https://learn.microsoft.com/en-us/windows/win32/api/winnetwk/nf-winnetwk-wnetgetconnectionw). | Windows/C++: How do I determine the share name associated with a shared drive? | [
"",
"c++",
"windows",
"networking",
"share",
""
] |
Every method I write to encode a string in Java using 3DES can't be decrypted back to the original string. Does anyone have a simple code snippet that can just encode and then decode the string back to the original string?
I know I'm making a very silly mistake somewhere in this code. Here's what I've been working wit... | Your code was fine except for the Base 64 encoding bit (which you mentioned was a test), the reason the output may not have made sense is that you were displaying a raw byte array (doing toString() on a byte array returns its internal Java reference, not the String representation of the **contents**). Here's a version ... | Here is a solution using the **javax.crypto** library and the apache commons codec library for encoding and decoding in Base64:
```
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import org.apac... | How do I use 3DES encryption/decryption in Java? | [
"",
"java",
"encryption",
"3des",
""
] |
I'm displaying a set of images as an overlay using Google Maps. Displaying these images should be in an endless loop but most most browsers detect this, and display a warning.
Is there a way to make a endless loop in JavaScript so that it isn't stopped or warned against by the browser? | Try [setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) or [setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/settimeout).
Here is an example:
```
(show = (o) => setTimeout(() => {
console.log(o)
show(++o)
}, 1000))(1);
... | You should use a timer to continuously bring new images instead of an infinite loop. Check the `setTimeout()` function. The caveat is that you should call it in a function that calls itself, for it to wait again. Example taken from [w3schools](http://www.w3schools.com/js/js_timing.asp):
```
var c = 0
var t;
functi... | Endless loop in JavaScript that does not trigger warning by browser | [
"",
"javascript",
"loops",
""
] |
I have a bunch of classes I want to rename. Some of them have names that are small and that name is reused in other class names, where I don't want that name changed. Most of this lives in Python code, but we also have some XML code that references class names.
Simple search and replace only gets me so far. In my case... | In the meantime, I've tried it two tools that have some sort of integration with vim.
The first is [Rope](https://github.com/python-rope/rope), a python refactoring library that comes with a Vim (and emacs) plug-in. I tried it for a few renames, and that definitely worked as expected. It allowed me to preview the refa... | I would strongly recommend [PyCharm](https://www.jetbrains.com/pycharm/) - not just for refactorings. Since the first PyCharm answer was posted here a few years ago the refactoring support in PyCharm has improved significantly.
[Python Refactorings available in PyCharm](https://www.jetbrains.com/pycharm/webhelp/refact... | What refactoring tools do you use for Python? | [
"",
"python",
"refactoring",
""
] |
If I call `finalize()` on an object from my program code, will the **JVM** still run the method again when the garbage collector processes this object?
This would be an approximate example:
```
MyObject m = new MyObject();
m.finalize();
m = null;
System.gc()
```
Would the explicit call to `finalize()` make the **... | According to this simple test program, the JVM will still make its call to finalize() even if you explicitly called it:
```
private static class Blah
{
public void finalize() { System.out.println("finalizing!"); }
}
private static void f() throws Throwable
{
Blah blah = new Blah();
blah.finalize();
}
public ... | One must understand the Garbage Collector(GC) Workflow to understand the function of finalize. calling .finalize() will not invoke the garbage collector, nor calling system.gc. Actually, What finalize will help the coder is to declare the reference of the object as "unreferenced".
GC forces a suspension on the running... | Java and manually executing finalize | [
"",
"java",
"garbage-collection",
"finalize",
""
] |
I have a little game written in C#. It uses a database as back-end. It's
a [trading card game](http://en.wikipedia.org/wiki/Collectible_card_game), and I wanted to implement the function of the cards as a script.
What I mean is that I essentially have an interface, `ICard`, which a card class implements (`public class... | [Oleg Shilo's C# Script solution (at The Code Project](https://www.codeproject.com/Articles/8656/C-Script-The-Missing-Puzzle-Piece)) really is a great introduction to providing script abilities in your application.
A different approach would be to consider a language that is specifically built for scripting, such as [... | You might be able to use IronRuby for that.
Otherwise I'd suggest you have a directory where you place precompiled assemblies. Then you could have a reference in the DB to the assembly and class, and use reflection to load the proper assemblies at runtime.
If you really want to compile at run-time you could use the C... | Adding scripting functionality to .NET applications | [
"",
"c#",
".net",
"scripting",
"compiler-construction",
""
] |
I'm looking for a tool which can generate a [Makefile](https://en.wikipedia.org/wiki/Make_(software)#Makefile) for a C/C++ project for different compilers ([GCC](https://en.wikipedia.org/wiki/GNU_Compiler_Collection), [Microsoft Visual C++](https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B), [C++Builder](https://e... | Other suggestions you may want to consider:
* [Scons](http://www.scons.org/) is a cross-platform, cross-compiler build library, uses Python scripting for the build systems. Used in a variety of large projects, and performs very well.
* If you're using [Qt](https://en.wikipedia.org/wiki/Qt_%28software%29), [QMake](http... | Try [Automatic Makefile Generator](http://www.robertnz.net/genmake.htm#Details).
It has support for the following compilers:
* Borland 3.1
* Borland 5.0
* Borland 5.0, 16 bit
* Borland 5.5
* Borland 5.6
* Borland 5.8
* CC
* GNU g++
* GNU g++, dynamic library
* Intel 5, 6, 7 for Linux
* Intel 5, 6, 7 for Linux, dynami... | Is there a good tool for Makefile generation? | [
"",
"c++",
"c",
"cross-platform",
"makefile",
""
] |
I often have to sort a dictionary (consisting of keys & values) by value. For example, I have a hash of words and respective frequencies that I want to order by frequency.
There is a `SortedList` which is good for a single value (say frequency), that I want to map back to the word.
[SortedDictionary](http://msdn.micr... | Use:
```
using System.Linq.Enumerable;
...
List<KeyValuePair<string, string>> myList = aDictionary.ToList();
myList.Sort(
delegate(KeyValuePair<string, string> pair1,
KeyValuePair<string, string> pair2)
{
return pair1.Value.CompareTo(pair2.Value);
}
);
```
Since you're targeting .NET 2.0 or a... | Use LINQ:
```
Dictionary<string, int> myDict = new Dictionary<string, int>();
myDict.Add("one", 1);
myDict.Add("four", 4);
myDict.Add("two", 2);
myDict.Add("three", 3);
var sortedDict = from entry in myDict orderby entry.Value ascending select entry;
```
This would also allow for great flexibility in that you can se... | How do you sort a dictionary by value? | [
"",
"c#",
".net",
"sorting",
"dictionary",
""
] |
I'm trying to compile over 100 java classes from different packages from a clean
directory (no incremental compiles) using the following ant tasks:
```
<target name="-main-src-depend">
<depend srcdir="${src.dir}"
destdir="${bin.dir}"
cache="${cache.dir}"
closure="true"/>
</tar... | > It will be nice to know; what can
> cause or causes a StackOverflowError
> during compilation of Java code?
It is probable that evaluating the long expression in your java file consumes lots of memory and because this is being done in conjunction with the compilation of other classes, the VM just runs out of stack s... | ```
<javac srcdir="gen" destdir="gen-bin" debug="on" fork="true">
<compilerarg value="-J-Xss10M" />
</javac>
```
from the [comment above](https://stackoverflow.com/questions/16935/ants-javac-tasks-throws-stackoverflowexception/19782#19782) is incorrect. You need a space between the -J and -X, like so:
```... | Ant's <javac> tasks throws StackOverflowException | [
"",
"java",
"ant",
""
] |
What is actually the difference between these two casts?
```
SomeClass sc = (SomeClass)SomeObject;
SomeClass sc2 = SomeObject as SomeClass;
```
Normally, shouldn't they both be explicit casts to the specified type? | The former will throw an exception if the source type can't be cast to the target type. The latter will result in sc2 being a null reference, but no exception.
[Edit]
My original answer is certainly the most pronounced difference, but as Eric Lippert [points out](http://blogs.msdn.com/ericlippert/archive/2009/10/08/w... | Also note that you can only use the as keyword with a reference type or a nullable type
ie:
```
double d = 5.34;
int i = d as int;
```
will not compile
```
double d = 5.34;
int i = (int)d;
```
will compile. | Casting: (NewType) vs. Object as NewType | [
"",
"c#",
".net",
""
] |
I'm currently designing a program that will involve some physics (nothing too fancy, a few balls crashing to each other)
What's the most exact datatype I can use to represent position (without a feeling of discrete jumps) in c#?
Also, what's the smallest ammount of time I can get between t and t+1? One tick?
EDIT: C... | In .Net a `decimal` will be the most precise datatype that you could use for position. I would just write a class for the position:
```
public class Position
{
decimal x;
decimal y;
decimal z;
}
```
As for time, your processor can't give you anything smaller than one tick.
Sounds like an fun project! Goo... | The Decimal data type although precise might not be the optimum choice depending on what you want to do. Generally Direct3D and GPUs use 32-bit floats, and vectors of 3 (total 96 bits) to represent a position in x,y,z.
This will usually give more than enough precision unless you need to mix both huge scale (planets) a... | Datatypes for physics | [
"",
"c#",
"types",
"physics",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.