Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I want to use implicit linking in my project , and nmake really wants a .def file . The problem is , that this is a class , and I don't know what to write in the exports section .
Could anyone point me in the right direction ?
The error message is the following :
**NMAKE : U1073: don't know how to make 'DLLCLASS.def'... | You can always find the decorated name for the member function by using [dumpbin](http://msdn.microsoft.com/en-us/library/c1h23y6c(VS.80).aspx) /symbols myclass.obj
in my case
```
class A {
public:
A( int ){}
};
```
the `dumpbin` dump showed the symbol `??0A@@QAE@H@Z (public: __thiscall A::A(int))`
Putting ... | If I recall correctly, you can use `__declspec(dllexport)` on the *class*, and VC++ will automatically create exports for all the symbols related to the class (constructors/destructor, methods, vtable, typeinfo, etc).
Microsoft has more information on this [here](http://msdn.microsoft.com/en-us/library/81h27t8c(VS.80)... | Exporting DLL C++ Class , question about .def file | [
"",
"c++",
"build",
"windows-ce",
"nmake",
"function",
""
] |
Are there any "all-in-one" installers for php + mysql on iis? Preferably with a gui configuration interface. | The PHP part is easy with Web Platform Installer:
<http://php.iis.net/>
MySQL is a breeze to install on Windows:
<http://dev.mysql.com/downloads/mysql/5.1.html#win32> | I don't know of any all-in-one installers for both MySql and PHP, but PHP itself comes with an automated installer that will attach itself to IIS - but the preferred method is still manual (the automated procedure only uses CGI). There are plenty of how-to pages on the web that give you the step-by-step procedure requi... | Easy IIS install of php | [
"",
"php",
"iis",
""
] |
I've got a "Schroedinger's Cat" type of problem here -- my program (actually the test suite for my program, but a program nonetheless) is crashing, but only when built in release mode, and only when launched from the command line. Through caveman debugging (ie, nasty printf() messages all over the place), I have determ... | In 100% of the cases I've seen or heard of, where a C or C++ program runs fine in the debugger but fails when run outside, the cause has been writing past the end of a function local array. (The debugger puts more on the stack, so you're less likely to overwrite something important.) | When I have encountered problems like this before it has generally been due to variable initialization. In debug mode, variables and pointers get initialized to zero automatically but in release mode they do not. Therefore, if you have code like this
```
int* p;
....
if (p == 0) { // do stuff }
```
In debug mode the ... | Program only crashes as release build -- how to debug? | [
"",
"c++",
"debugging",
""
] |
I am working on a project that is built on an extended version of the default PDO and PDOStatement classes and as such it uses PDO style named parameters instead of the "?" placeholder for variables.
However, the client is now requesting that we look into using a different driver because their version OS X Web Server ... | PDO and ADODB both support prepared statements, but the API is not great. Most frameworks provide an abstraction to one of those.
I'm using Zend\_Db from the Zend Framework and I highly recommend it. It has a select class for composing queries (which turn into prepared statements when queried against the database adap... | I've used PEAR::MDB2 as well as PDO. MDB2's documentation is a little shaky, but once you get it all working its a dream to work with.
<http://pear.php.net/package/MDB2> | What PHP / MySQL drivers or Database Abstraction Layers Support Prepared Statements? | [
"",
"php",
"pdo",
"prepared-statement",
"database-abstraction",
""
] |
Does anyone have C# code handy for doing a ping and traceroute to a target computer? I am looking for a pure code solution, not what I'm doing now, which is invoking the ping.exe and tracert.exe program and parsing the output. I would like something more robust. | Although the Base Class Library includes [Ping](http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping.aspx), the BCL does not include any tracert functionality.
However, a quick search reveals two open-source attempts, the first in C# the second in C++:
* <http://www.codeproject.com/KB/IP/tracert... | Given that I had to write a TraceRoute class today I figured I might as well share the source code.
```
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Text;
using System.Net;
namespace Answer
{
public class TraceRoute
{
private const string Data = "aaaaaaaaaaaaaaaaaaaaaa... | TraceRoute and Ping in C# | [
"",
"c#",
".net",
"networking",
"ping",
"traceroute",
""
] |
I have a C# method which accepts a Predicate<Foo> and returns a list of matching items...
```
public static List<Foo> FindAll( Predicate<Foo> filter )
{
...
}
```
The filter will often be one of a common set...
```
public static class FooPredicates
{
public static readonly Predicate<Foo> IsEligible = ( foo =... | To perform your caching task, you can follow the other suggestions and create a Dictionary<Predicate<Foo>,List<Foo>> (static for global, or member field otherwise) that caches the results. Before actually executing the Predicate<Foo>, you would need to check if the result already exists in the dictionary.
The general ... | Delegate equality looks at each invocation in the invocation list, testing for equality of method to be invoked, and target of method.
The method is a simple piece of the cache key, but the target of the method (the instance to call it on - assuming an instance method) could be impossible to cache in a serializable wa... | Caching delegate results | [
"",
"c#",
".net",
"asp.net",
"delegates",
"memoization",
""
] |
I'm having trouble wrapping my head around this. Right now I have some models that looks kind of like this:
```
def Review(models.Model)
...fields...
overall_score = models.FloatField(blank=True)
def Score(models.Model)
review = models.ForeignKey(Review)
question = models.TextField()
grade = mode... | Save/delete signals are generally favourable in situations where you need to make changes which aren't completely specific to the model in question, or could be applied to models which have something in common, or could be configured for use across models.
One common task in overridden `save` methods is automated gene... | You asked:
*Would there be any benefits to using Django's signal dispatcher?*
I found this in the django docs:
> Overridden model methods are not called on bulk operations
>
> Note that the delete() method for an object is not necessarily called
> when deleting objects in bulk using a QuerySet or as a result of a
> ... | Django signals vs. overriding save method | [
"",
"python",
"django",
"django-models",
"django-signals",
""
] |
my java application has a loading task which requires two server calls which can be parallelized. So I launch a Thread t1 (doing **task1**) and a Thread t2 (for **task2**).
I want then to do a specific task, **task3** when both other tasks (1 & 2) are over. Naturally I can't tell which of **task1** and **task2** will f... | You've got several options:
1. If task3 is on a separate thread AND task1 and task2 threads are exclusive to their tasks (no thread pooling) and finish when the task finish, you can use {T1.join(); T2.join();} to wait for both threads. Pros: Easy. Cons: The situation is rarely that simple.
2. If task3 is on a separate... | You can [`join`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#join()) both `t1` and `t2` (in either order), then run task3 after the join. | Thread synchronization question (in java) | [
"",
"java",
"multithreading",
"concurrency",
"synchronization",
""
] |
Apparently ;-) the standard containers provide some form of guarantees.
What type of guarantees and what exactly are the differences between the different types of container?
Working from [the SGI page](http://www.sgi.com/tech/stl/) (about [STL](http://en.wikipedia.org/wiki/Standard_Template_Library)) I have come up ... | I found the nice resource *[Standard C++ Containers](http://www.cs.northwestern.edu/~riesbeck/programming/c++/stl-summary.html)*. Probably this is what you all looking for.
**VECTOR**
**Constructors**
```
vector<T> v; Make an empty vector. O(1)
vector<T> v(n); ... | I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).
Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet poi... | What are the complexity guarantees of the standard containers? | [
"",
"c++",
"stl",
"containers",
"big-o",
""
] |
I'm working on a control to tie together the view from one ListView to another so that when the master ListView is scrolled, the child ListView view is updated to match.
So far I've been able to get the child ListViews to update their view when the master scrollbar buttons are clicked. The problem is that when clickin... | I wanted to do the same thing, and after searching around I found your code here, which helped, but of course didn't solve the problem. But after playing around with it, I have found a solution.
The key came when I realized that since the scroll buttons work, that you can use that to make the slider work. In other wor... | This is conjecture just to get the mental juices flowing so take it as you will:
In the scroll handler for the master list, can you call the scroll handler for the child list (passing the sender and eventargs from the master)?
Add this to your Form load:
```
masterList.Scroll += new ScrollEventHandler(this.masterList... | Synchronized ListViews in .Net | [
"",
"c#",
".net",
"winforms",
"winapi",
"listview",
""
] |
I'm wondering what the best practices are for storing a relational data structure in XML. Particulary, I am wondering about best practices for enforcing node order. For example, say I have three objects: `School`, `Course`, and `Student`, which are defined as follows:
```
class School
{
List<Course> Courses;
L... | Don't think in SQL or relational when working with XML, because there are no order constraints.
You can however query using XPath to any portion of the XML document at any time. You want the courses first, then "//Courses/Course". You want the students enrollments next, then "//Students/Student/EnrolledIn/Course".
Th... | While you can specify order of child elements using a <xsd:sequence>, by requiring child objects to come in specific order you make your system less flexible (i.e., harder to update using notepad).
Best thing to do is to parse out all your data, then perform what actions you need to do. Don't act during the parse.
--... | Storing Relational Data in XML | [
"",
"c#",
"xml",
""
] |
How can I make my window not have a title bar but appear in the task bar with some descriptive text?
If you set the Form's .Text property then .net gives it a title bar, which I don't want.
```
this.ControlBox = false;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
thi... | One approach to look into might be to set the `FormBorderStyle` property of your `Form` to `None` (instead of `FixedDialog`).
The drawback to this approach is that you lose the borders of your window as well as the Titlebar. A result of this is that you lose the form repositioning/resizing logic that you normally get ... | In my case I have a Form with `FormBorderStyle = FormBorderStyle.SizableToolWindow` and the following `CreateParams` override did the trick (i.e. I now have a form without caption and without additional margin for the title, but it keeps the title in the task bar):
```
protected override System.Windows.Forms.CreatePar... | How to make a window have taskbar text but no title bar | [
"",
"c#",
".net",
"winforms",
""
] |
What Javascript libraries can you recommend for syntax highlighting <code> blocks in HTML?
(One suggestion per answer please). | StackOverflow uses the [Prettify](https://github.com/google/code-prettify) library. | I recently developed one called rainbow.
The main design goal was to make the core library really small and make it really easy for developers to extend.
See <http://rainbowco.de>. | Syntax highlighting code with Javascript | [
"",
"javascript",
"html",
"syntax",
"syntax-highlighting",
""
] |
I personally like the *exclusive or*, `^`, operator when it makes sense in the context of boolean checks because of its conciseness. I much prefer to write
```
if (boolean1 ^ boolean2)
{
//do it
}
```
than
```
if((boolean1 && !boolean2) || (boolean2 && !boolean1))
{
//do it
}
```
but I often get confused looks ... | You can simply use `!=` instead. | I think you've answered your own question - if you get strange looks from people, it's probably safer to go with the more explicit option.
If you need to comment it, then you're probably better off replacing it with the more verbose version and not making people ask the question in the first place. | Is it good practice to use the xor operator for boolean checks? | [
"",
"java",
"conditional-statements",
"bitwise-operators",
"logical-operators",
"xor",
""
] |
I have an *index.php* file which has to process many different file types. How do I guess the filetype based on the `REQUEST_URI`?
If I request `http://site/image.jpg`, and all requests redirect through *index.php*, which looks like this
```
<?php
include('/www/site'.$_SERVER['REQUEST_URI']);
?>
```
How would I m... | If you are sure you're only ever working with images, you can check out the [exif\_imagetype()](https://www.php.net/manual/en/function.exif-imagetype.php) PHP function, which attempts to return the image MIME type.
If you don't mind external dependencies, you can also check out the excellent [getID3](http://getid3.sou... | *mime\_content\_type()* is deprecated, so you won't be able to count on it working in the future. There is a "fileinfo" PECL extension, but I haven't heard good things about it.
If you are running on a Unix-like server, you can do the following, which has worked fine for me:
```
$file = escapeshellarg($filename);
$mi... | How do I find the MIME type of a file with PHP? | [
"",
"php",
"filesystems",
"http-headers",
"content-type",
""
] |
This is the way I read file:
```
public static string readFile(string path)
{
StringBuilder stringFromFile = new StringBuilder();
StreamReader SR;
string S;
SR = File.OpenText(path);
S = SR.ReadLine();
while (S != null)
{
stringFromFile.Append... | Leaving aside the horrible variable names and the lack of a using statement (you won't close the file if there are any exceptions) that should be okay, and *certainly* shouldn't take 5 minutes to read 2.5 megs.
Where does the file live? Is it on a flaky network share?
By the way, the only difference between what you'... | ```
S = SR.ReadLine();
while (S != null)
{
stringFromFile.Append(SR.ReadLine());
}
```
Of note here, `S` is never set after that initial `ReadLine()`, so the `S != null` condition never triggers if you enter the while loop. Try:
```
S = SR.ReadLine();
while (S != null)
{
stringFromFile.Append(S = SR.ReadLine(... | Reading from file not fast enough, how would I speed it up? | [
"",
"c#",
".net",
"optimization",
".net-2.0",
"io",
""
] |
As a test engineer, I often engage in exploratory testing. When I encounter a bug, it is not always immediately clear which steps led to the problem. So, obviously, I have to find the required steps to reproduce the problem. Depending on the situation, this can take a large amount of time.
What would be really helpful... | You may want to check out [BB Test Assistant](http://www.bbsoftware.co.uk/BBTestAssistant.aspx). I saw a very early version of this and was impressed. I've also heard good things from people who have used it since then. | [This question](https://stackoverflow.com/questions/7440/what-do-you-use-to-unit-test-your-web-ui) lists tools that can be used test web applications. Some of the answers may be useful.
One for example is Selenium - a mozilla plugin that records your actions and can be replayed later. | Are there tools that log user actions to help reproduce bugs? | [
"",
"java",
"testing",
"logging",
"manual-testing",
"exploratory",
""
] |
What is currying?
How can currying be done in C++?
Please Explain binders in STL container? | In short, currying takes a function `f(x, y)` and given a fixed `Y`, gives a new function `g(x)` where
```
g(x) == f(x, Y)
```
This new function may be called in situations where only one argument is supplied, and passes the call on to the original `f` function with the fixed `Y` argument.
The binders in the STL all... | # 1. What is currying?
Currying simply means a transformation of a function of several arguments to a function of a single argument. This is most easily illustrated using an example:
Take a function `f` that accepts three arguments:
```
int
f(int a,std::string b,float c)
{
// do something with a, b, and c
re... | How can currying be done in C++? | [
"",
"c++",
"stl",
"functional-programming",
"currying",
"binders",
""
] |
I've got a php script. Most of the time the script returns html, which is working fine, but on one occasion (parameter ?Format=XML) the script returns XML instead of HTML.
Is there any way to change the returned mime type of the php output on the fly from text/html to text/xml or application/xml? | ```
header('Content-type: application/xml');
```
More information available at the PHP documentation for [`header()`](http://php.net/manual/en/function.header.php) | Set the `Content-Type` header:
```
header('Content-Type: text/xml');
```
Though you should probably use "application/xml" instead. | change mime type of output in php | [
"",
"php",
"xml",
"mime-types",
""
] |
Say that I write an article or document about a certain topic, but the content is meant for readers with certain prior knowledge about the topic. To help people who don't have the "required" background information, I would like to add a note to the top of the page with an explanation and possibly a link to some referen... | You can build that portion of the content dynamically using Javascript.
For example:
```
<html>
<body>
<div id="dynContent">
</div>
Rest of the content here.
</body>
<script language='javascript' type='text/javascript'>
var dyn = document.getElementById('dynContent');
dyn.innerHTML = "Put the dynamic conte... | If you can use an iframe, then place the content on a static html page and use the meta tag in it's head to tell the search engines to ignore it. Since it's a seperate page, google etc.. should ignore it.
meta tag:
```
<meta name="robots" content="noindex, nofollow">
``` | How can I hide content in a HTML file from search engines? | [
"",
"javascript",
"search-engine",
""
] |
What is the best method for displaying major/minor versions in a C# console application?
The `System.Windows.Forms` namespace includes a `ProductVersion` class that can be used to display the name/version information set via the Visual Studio project properties (Assembly Information). As such, here is my current mecha... | ```
Assembly.GetExecutingAssembly().GetName().Version
```
Also, you can still use the class, you just have to reference the containing assembly. It's no biggie. | `Assembly.GetExecutingAssembly().GetName().Version` is not the same as `Application.ProductVersion` (but may be good enough depending on your environment.
As can be seen with Lutz Reflector, `Application.ProductVersion` first attempts to use the **AssemblyInformationalVersion** attribute from `Assembly.GetEntryAssembl... | Method for Application Version on a Console Utility App | [
"",
"c#",
".net",
"console",
""
] |
Let's say I have a model like this
```
class Foo(db.Model):
id = db.StringProperty()
bar = db.StringProperty()
baz = db.StringProperty()
```
And I'm going a GqlQuery like this
```
foos = db.GqlQuery("SELECT * FROM Foo")
```
**I want to take the results of the GqlQuery and turn into some sort of JSON str... | Take a look at [google.appengine.api.datastore](http://code.google.com/p/googleappengine/source/browse/trunk/google/appengine/api/datastore.py). It's the lower level datastore API that google.appengine.ext.db builds on, and it returns Entity objects, which subclass dict. You can query it using GQL with [google.appengin... | I can't do too much better than that, but here are a couple of ideas:
```
class Foo:
id = db.StringProperty() # etc.
json_attrs = 'id bar baz'.split()
# Depending on how easy it is to identify string properties, there
# might also be a way to assign json_attrs programmatically after the
# definition of Foo, l... | Turning a GqlQuery result set into a python dictionary | [
"",
"python",
"google-app-engine",
"gqlquery",
""
] |
I seem to only be able to write to the Apache error log via stderr. Anyone know of a more structured logging architecture that I could use from my python web project, like commons? | There isn't any built in support for mod\_python logging to Apache currently. If you really want to work within the Apache logs you can check out this thread (make sure you get the second version of the posted code, rather than the first):
* <http://www.dojoforum.com/node/13239>
* <http://www.modpython.org/pipermail/m... | This must have changed in the past four years. If you come across this question and want to do this then you can do it through the request object, i.e
```
def handler(req) :
req.log_error('Hello apache')
``` | How do I write to a log from mod_python under apache? | [
"",
"python",
"apache",
"logging",
""
] |
I'm looking for some good references for learning how to model 2d physics in games. I am **not** looking for a library to do it for me - I want to think and learn, not blindly use someone else's work.
I've done a good bit of Googling, and while I've found a few tutorials on GameDev, etc., I find their tutorials hard t... | Here are some resources I assembled a few years ago. Of note is the Verlet Integration.
I am also including links to some open source and commercial physics engines I found at that time. There is a stackoverflow article on this subject here: [2d game physics?](https://stackoverflow.com/questions/98628/2d-game-physics)
... | [](https://i.stack.imgur.com/dGkA7.gif)
(source: [oreilly.com](http://web.archive.org/web/20070225050059/http://www.oreilly.com:80/catalog/covers/0596000065_cat.gif))
[Physics for Game Developers](http://oreilly.com/catalog/9780596000066/) by O'Reilly | Resources for 2d game physics | [
"",
"c#",
"f#",
"2d",
"physics",
""
] |
If I have a class that needs to implement an interface but one or more of the methods on that interface don't make sense in the context of this particular class, what should I do?
For example, lets say I'm implementing an adapter pattern where I want to create a wrapper class that implements [java.util.Map](http://jav... | Any method that cannot be implemented according to the semantics of the interface should throw an [UnsupportedOperationException](http://java.sun.com/javase/6/docs/api/java/lang/UnsupportedOperationException.html). | That depends on your business case. 2 options:
* Do nothing.
* Throw an [`UnsupportedOperationException`](http://java.sun.com/javase/6/docs/api/java/lang/UnsupportedOperationException.html).
Use whichever makes more sense. If you do nothing, you are not obeying the contract of the interface. However, throwing a runti... | Correct behavior for interface methods that can't be implemented | [
"",
"java",
""
] |
I'm trying to create an access control system.
Here's a stripped down example of what the table I'm trying to control access to looks like:
```
things table:
id group_id name
1 1 thing 1
2 1 thing 2
3 1 thing 3
4 1 thing 4
5 2 thing 5
```
And the access... | I don't know the Postgres SQL dialect, but maybe something like:
```
select thing.*, coalesce ( ( select access
from access
where userid = 1
and type = 'thing'
and object_id = thing.id
... | I just read a paper last night on this. It has some ideas on how to do this. If you can't use the link on the title try using Google Scholar on [Limiting Disclosure in Hippocratic Databases.](http://portal.acm.org/citation.cfm?id=1316701) | How can I do access control via an SQL table? | [
"",
"sql",
"postgresql",
"access-control",
""
] |
.Net 3.5 doesn't support tuples. Too bad, But not sure whether the future version of .net will support tuples or not? | I've just read this article from the MSDN Magazine: [Building Tuple](http://msdn.microsoft.com/en-us/magazine/dd942829.aspx)
Here are excerpts:
> The upcoming 4.0 release of Microsoft
> .NET Framework introduces a new type
> called System.Tuple. System.Tuple is a
> fixed-size collection of
> heterogeneously typed dat... | ```
#region tuples
public class Tuple<T>
{
public Tuple(T first)
{
First = first;
}
public T First { get; set; }
}
public class Tuple<T, T2> : Tuple<T>
{
public Tuple(T first, T2 second)
: base(first)
{
Second = s... | Will a future version of .NET support tuples in C#? | [
"",
"c#",
".net",
"tuples",
"language-features",
""
] |
## Problem
Language: C# 2.0 or later
---
I would like to register context handlers to create menues when the user right clicks certain files (in my case \*.eic). What is the procedure to register, unregister (clean up) and handle events (clicks) from these menues?
I have a clue it's something to do with the windows... | Resist writing Shell Extensions in managed languages - there are a multitude of things that could go bang if you pursue this route.
Have a browse through this thread for more details. It contains links to do it if really want, and sagely advice of why it can be done, but shouldn't.
<http://social.msdn.microsoft.com/F... | This is not a good idea because of potential dependency issues between different versions of the .NET Framework. Your shell extension could be expecting one version, while a different version may have already been loaded by the application that's currently running.
[This thread](http://social.msdn.microsoft.com/Forums... | How can I create my custom Shell Context Handlers for Windows? | [
"",
"c#",
".net",
"windows-shell",
""
] |
I have a submission table that is very simple: userId, submissionGuid
I want to select the username (simple inner join to get it) of all the users who have more than 10 submissions in the table.
I would do this with embedded queries and a group by to count submissions... but is there a better way of doing it (without... | This is the simplest way, I believe:
```
select userId
from submission
group by userId
having count(submissionGuid) > 10
``` | ```
select userId, count(*)
from submissions
having count(*) > 10
group by userId
``` | How to select all users who made more than 10 submissions | [
"",
"sql",
""
] |
I want to be able to compare an image taken from a webcam to an image stored on my computer.
The library doesn't need to be one hundred percent accurate as it won't be used in anything mission critical (e.g. police investigation), I just want something OK I can work with.
I have tried a demonstration project for [Ima... | You could try this: <http://code.google.com/p/aforge/>
It includes a comparison analysis that will give you a score. There are many other great imaging features of all types included as well.
```
// The class also can be used to get similarity level between two image of the same size, which can be useful to get infor... | You can exactly use [EmguCV](http://www.emgu.com/wiki/index.php/Main_Page) for .NET. | Are there any OK image recognition libraries for .NET? | [
"",
"c#",
".net",
"vb.net",
"image",
"image-recognition",
""
] |
Someone asked me how familiar I am with VC++ and how familiar I am with C++. What is the difference? | C++ is the actual language, VC++ is Microsoft's Visual C++, an IDE for C++ development.
From [stason.org](http://stason.org/TULARC/webmaster/lang/c-cpp-faq/20-What-is-the-difference-between-C-and-Visual-C.html):
> C++ is the programming language, Visual C++ is Microsoft's implementation of it.
>
> When people talk ab... | C++ is the name of a programming language that has been approved by international standards committees (ANSI/ISO).
VC++ (“Visual C++”) is the product name of Microsoft's C++ compiler and sometimes, but not officially, the IDE it's shipped with (“Visual Studio”). | What is the difference between "VC++" and "C++"? | [
"",
"c++",
"visual-c++",
""
] |
What's the best/easiest to integrate templating system for PHP, and what are the benefits of using one?
I currently don't use one at all, and am thinking that it might help to seperate content from presentation a little more. | # [Smarty](http://www.smarty.net)
---
I've found it to be fast, easy to use, and easy to install (even in a shared-hosting environment). It also doesn't require that you use validating XHTML which is handy sometimes (although I think the template engines that **do** require valid XHTML are probably faster.)
It's rea... | PHP is a pretty good templating language by itself. Most leading PHP frameworks don't use a seperate templating langauge for just this reason.
Just make sure you use (something resemebling) MVC, and don't do any data access or business logic inside your view files.
I've also used Smarty extensively, but find it has l... | What's a good templating system for PHP? | [
"",
"php",
"templates",
""
] |
What is the purpose of the `Using` block in C#? How is it different from a local variable? | If the type implements IDisposable, it automatically disposes that type.
Given:
```
public class SomeDisposableType : IDisposable
{
...implmentation details...
}
```
These are equivalent:
```
SomeDisposableType t = new SomeDisposableType();
try {
OperateOnType(t);
}
finally {
if (t != null) {
((I... | `Using` calls `Dispose()` after the `using`-block is left, even if the code throws an exception.
So you usually use `using` for classes that require cleaning up after them, like IO.
So, this using block:
```
using (MyClass mine = new MyClass())
{
mine.Action();
}
```
would do the same as:
```
MyClass mine = new ... | What is the C# Using block and why should I use it? | [
"",
"c#",
".net",
"syntax",
"using",
"using-statement",
""
] |
I've been trying to track this one for literally a month now without any success. I have this piece of code on an car advertising website which basically allows thumbnails to rotate in search results given that a car has multiple pictures. You can see it in action at the following:
> [`http://www.abcavendre.com/450669... | A way to track memory leaks in Firefox is with the [Leak Monitor Addon](https://addons.mozilla.org/de/firefox/addon/2490). It shows memory leaks of javascript (including extension-scripts).
Please remind that the plugin will sometimes show leaked objects that will get cleaned up later by the garbage collection. If tha... | Try nulling elements variable array in the end of the initialize function
```
...
if (ads.length > 0)
{
this.imagesFx = new Fx.Elements(elements,
{
wait: false,
duration: 1000
});
this.moveNext.periodical(2500, this);
}
eleme... | How do I track and debug JavaScript memory leaks in Firefox? | [
"",
"javascript",
"memory-leaks",
"mootools",
""
] |
When I add a breakpoint and hit F5 to run in the debugger (I am using my debug build), a dialog pops up telling my my web.config file does not have debug=true in it (which is does) and I get 2 choices a) run without the debugger or b) let visual studio update my web.config file. If I choose b) the web.config is updated... | Open web.config manually and make sure the following line is in there
```
<compilation defaultLanguage="c#" debug="true" />
```
Now you should be able to debug from VS. If this does not work I suggest that you recreate the project.
EDIT: perhaps from what you say it could be that web.config is screwed up, e.g.contai... | In your project do a solution wide search for 'debug=' and if only one shows up then do a folder search. I've had it happen where there are multiple config files and this can cause problems. | Why can't I debug my asp.net web app | [
"",
"c#",
"asp.net",
"iis",
"visual-c++",
""
] |
I'm currently turning an array of pixel values (originally created with a java.awt.image.PixelGrabber object) into an Image object using the following code:
```
public Image getImageFromArray(int[] pixels, int width, int height) {
MemoryImageSource mis = new MemoryImageSource(width, height, pixels, 0, width);
... | You can create the image without using ImageIO. Just create a BufferedImage using an image type matching the contents of the pixel array.
```
public static Image getImageFromArray(int[] pixels, int width, int height) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
... | Using the raster I got an `ArrayIndexOutOfBoundsException` even when I created the `BufferedImage` with `TYPE_INT_ARGB`. However, using the `setRGB(...)` method of `BufferedImage` worked for me. | Turn an array of pixels into an Image object with Java's ImageIO? | [
"",
"java",
"image",
"awt",
"toolkit",
"javax.imageio",
""
] |
Since Python is a dynamic, interpreted language you don't have to compile your code before running it. Hence, it's very easy to simply write your code, run it, see what problems occur, and fix them. Using hotkeys or macros can make this incredibly quick.
So, because it's so easy to immediately see the output of your p... | I use pdb for basic python debugging. Some of the situations I use it are:
* When you have a loop iterating over 100,000 entries and want to break at a specific point, it becomes really helpful.(conditional breaks)
* Trace the control flow of someone else's code.
* Its always better to use a debugger than litter the c... | In 30 years of programming I've used a debugger exactly 4 times. All four times were to read the `core` file produced from a C program crashing to locate the traceback information that's buried in there.
I don't think debuggers help much, even in compiled languages. Many people like debuggers, there are some reasons f... | When to use the Python debugger | [
"",
"python",
"debugging",
""
] |
i need to get the color at a particular coordinate from a texture. There are 2 ways i can do this, by getting and looking at the raw png data, or by sampling my generated opengl texture. Is it possible to sample an opengl texture to get the color (RGBA) at a given UV or XY coord? If so, how? | Off the top of my head, your options are
1. Fetch the entire texture using glGetTexImage() and check the texel you're interested in.
2. Draw the texel you're interested in (eg. by rendering a GL\_POINTS primitive), then grab the pixel where you rendered it from the framebuffer by using glReadPixels.
3. Keep a copy of ... | The most efficient way I've found to do it is to access the texture data (you should have our PNG decoded to make into a texture anyway) and interpolate between the texels yourself. Assuming your texcoords are [0,1], multiply texwidth*u and texheight*v and then use that to find the position on the texture. If they're w... | Texture Sampling in Open GL | [
"",
"c++",
"opengl",
""
] |
Has anyone had luck with removing large amount of issues from a jira database instead of using the frontend? Deleting 60000 issues with the bulktools is not really feasible.
Last time I tried it, the jira went nuts because of its own way of doing indexes. | We got gutsy and did a truncate on the jiraissues table and then use the rebuild index feature on the frontend. It looks like it's working! | How about doing a backup to xml, editing the xml, and reimporting? | Using SQL for cleaning up JIRA database | [
"",
"sql",
"jira",
""
] |
What is the best way to secure an intranet website developed using `PHP` from outside attacks? | That's a stunningly thought-provoking question, and I'm surprised that you haven't received better answers.
## Summary
Everything you would do for an external-facing application, and then some.
## Thought Process
If I'm understanding you correctly, then you are asking a question which *very* few developers are aski... | If it is on an internal network, why is it even possible to get to the app from the outside? Firewall rules should be in place at the very least. | PHP - Security what is best way? | [
"",
"php",
"security",
""
] |
What are the pros and cons of using [Criteria](http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html/ch17.html) or [HQL](http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html/ch16.html)? The Criteria API is a nice object-oriented way to express queries in Hibernate, but sometimes Criteria Queries are more diffi... | I mostly prefer Criteria Queries for dynamic queries. For example it is much easier to add some ordering dynamically or leave some parts (e.g. restrictions) out depending on some parameter.
On the other hand I'm using HQL for static and complex queries, because it's much easier to understand/read HQL. Also, HQL is a b... | There is a difference in terms of performance between HQL and criteriaQuery, everytime you fire a query using criteriaQuery, it creates a new alias for the table name which does not reflect in the last queried cache for any DB. This leads to an overhead of compiling the generated SQL, taking more time to execute.
Rega... | JPA and Hibernate - Criteria vs. JPQL or HQL | [
"",
"java",
"hibernate",
"hql",
"criteria",
"hibernate-criteria",
""
] |
I need to enumerate all classes in a package and add them to a List. The non-dynamic version for a single class goes like this:
```
List allClasses = new ArrayList();
allClasses.add(String.class);
```
How can I do this dynamically to add all classes in a package and all its subpackages?
---
***Update:*** Having rea... | \*\*\*\*UPDATE 1 (2012)\*\*\*\*
OK, I've finally gotten around to cleaning up the code snippet below. I stuck it into it's own github project and even added tests.
<https://github.com/ddopson/java-class-enumerator>
\*\*\*\*UPDATE 2 (2016)\*\*\*\*
For an even more robust and feature-rich classpath scanner, see <http... | The most robust mechanism for listing all classes in a given package is currently [ClassGraph](https://github.com/classgraph/classgraph/wiki/Code-examples), because it handles the [widest possible array of classpath specification mechanisms](https://github.com/classgraph/classgraph/wiki/Classpath-Specification-Mechanis... | How can I enumerate all classes in a package and add them to a List? | [
"",
"java",
""
] |
I am using the jQuery library to implement drag and drop.
How do I get at the element that is being dragged when it is dropped?
I want to get the id of the image inside the div. The following element is dragged:
```
<div class="block">
<asp:Image ID="Image9" AlternateText="10/12/2008 - Retina" Width=81 Height=84... | Is it not the ui.draggable?
If you go here (in Firefox and assuming you have firebug) and look in the firebug console youll see I am doing a console.dir of the ui.draggable object which is the div being dragged
<http://jsbin.com/ixizi>
Therefore the code you need in the drop function is
```
drop: function(ev... | ```
$(ui.draggable).attr("id")
```
... | jQuery drag and drop - how to get at element being dragged | [
"",
"javascript",
"jquery",
"drag-and-drop",
""
] |
I got this bad feeling about how I insert larger amounts of HTML.
Lets assume we got:
`var html="<table>..<a-lot-of-other-tags />..</table>"`
and I want to put this into
`$("#mydiv")`
previously I did something like
`var html_obj = $(html);`
`$("#mydiv").append(html_obj);`
Is it correct that jQuery is parsing `ht... | innerHTML is remarkably fast, and in many cases you will get the best results just setting that (I would just use append).
**However, if there is much already in "mydiv" then you are forcing the browser to parse and render all of that content again (everything that was there before, plus all of your new content).** Yo... | Try the following:
```
$("#mydiv").append(html);
```
The other answers, including the accepted answer, are **slower** by **2-10x**: [jsperf](http://jsperf.com/jquery-append-html/1).
The accepted answer does not work in **IE 6, 7, and 8** because you can't set `innerHTML` of a `<table>` element, due to a bug in IE: [... | jquery: fastest DOM insertion? | [
"",
"javascript",
"jquery",
"dom",
""
] |
I've seen this is various codebases, and wanted to know if this generally frowned upon or not.
For example:
```
public class MyClass
{
public int Id;
public MyClass()
{
Id = new Database().GetIdFor(typeof(MyClass));
}
}
``` | There are several reasons this is not generally considered good design some of which like causing difficult unit testing and difficulty of handling errors have already been mentioned.
The main reason I would choose not to do so is that your object and the data access layer are now very tightly coupled which means that... | Well.. I wouldn't. But then again my approach usually involves the class NOT being responsible for retrieving its own data. | Is it OK to put a database initialization call in a C# constructor? | [
"",
"c#",
"database",
"constructor",
""
] |
I have a checkstyle suppression filter setup (e.g. ignore magic numbers in unit test code).
The suppression xml file resides in the same folder as the checkstyle xml file. However, where this file actually is varies:
on my windows dev box it is in d:\dev\shared\checkstyle\config
on the Linux CI server it will be in /r... | I had this same problem with the Checkstyle suppression configuration when I was going back and forth between Linux and Windows. Here's how I solved it in my Ant-based build system:
Basically, I inject the proper, platform-specific directory value into the main Checkstyle configuration file by configuring a Checkstyle... | In eclipse I put the following which did not require me to add any additional properties:
```
<module name="SuppressionFilter">
<property name="file" value="${samedir}/suppressions.xml"/>
</module>
``` | checkstyle + suppression filters | [
"",
"java",
"code-analysis",
"static-analysis",
"checkstyle",
""
] |
One of the major advantages with Javascript is said to be that it is a prototype based language.
But what does it mean that Javascript is prototype based, and why is that an advantage? | **Prototypal inheritance** is a form of object-oriented **code reuse**. Javascript is one of the only [mainstream] object-oriented languages to use prototypal inheritance. Almost all other object-oriented languages are classical.
In **classical inheritance**, the programmer writes a class, which defines an object. Mul... | A prototype-based language, does not make the distinction of classes vs objects: it simply has objects. A prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a new object. Any object can specify its own properties, either when you c... | What does it mean that Javascript is a prototype based language? | [
"",
"javascript",
"oop",
"inheritance",
"prototype-programming",
""
] |
If I am passing an object to a method, why should I use the ref keyword? Isn't this the default behaviour anyway?
For example:
```
class Program
{
static void Main(string[] args)
{
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(t);
Console.WriteLine(t.Something);
... | Pass a `ref` if you want to change what the object is:
```
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(ref t);
void DoSomething(ref TestRef x)
{
x = new TestRef();
x.Something = "Not just a changed TestRef, but a completely different TestRef object";
}
```
After calling DoSomething, `t` does not ... | You need to distinguish between "passing a reference by value", and "passing a parameter/argument by reference".
I've written a [reasonably long article on the subject](https://web.archive.org/web/20190303121828/http://jonskeet.uk/csharp/parameters.html) to avoid having to write carefully each time this comes up on ne... | Why use the 'ref' keyword when passing an object? | [
"",
"c#",
".net",
"pass-by-reference",
"ref",
""
] |
I am looking for the best way to test if a website is alive from a C# application.
### Background
My application consists of a *Winforms UI*, a backend *WCF service* and a *website* to publish content to the UI and other consumers. To prevent the situation where the UI starts up and fails to work properly because of ... | ```
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response == null || response.StatusCode != HttpStatusCode.OK)
```
As @Yanga mentioned, HttpClient is probably the more common way to do this now.
```
HttpClient client = new HttpClient();
var checkingResponse = await client.GetAsync(url);
if (... | While using WebResponse please make sure that you close the response stream ie (.close) else it would hang the machine after certain repeated execution.
Eg
```
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sURL);
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
// your code here
response.Close()... | Test if a website is alive from a C# application | [
"",
"c#",
"webrequest",
""
] |
I've read all the advice on const-correctness in C++ and that it is important (in part) because it helps the compiler to optimize your code. What I've never seen is a good explanation on how the compiler uses this information to optimize the code, not even the good books go on explaining what happens behind the curtain... | Let's disregard methods and look only at const objects; the compiler has much more opportunity for optimization here. If an object is declared const, then (ISO/IEC 14882:2003 7.1.5.1(4)):
> Except that any class member declared
> mutable (7.1.1) can be modified, any
> attempt to modify a const object
> during its life... | I think that the const keyword was primarily introduced for compilation checking of the program semantic, not for optimization.
Herb Sutter, in the [GotW #81 article](http://www.gotw.ca/gotw/081.htm), explains very well why the compiler can't optimize anything when passing parameters by const reference, or when declar... | Constants and compiler optimization in C++ | [
"",
"c++",
"optimization",
"compiler-construction",
"compiler-optimization",
"const-correctness",
""
] |
I am using Apache [HttpClient](http://hc.apache.org/httpclient-3.x/) and would like to communicate HTTP errors (400 Bad Request, 404 Not Found, 500 Server Error, etc.) via the Java exception mechanism to the calling code. Is there an exception in the Java standard library or in a widely used library that would be appro... | If it's not an Exception in HttpClient design philosophy, but an Exception in your code, then create your own Exception classes. ( As a subclass of org.apache.commons.httpclient.HttpException ) | ### Quick answer
In Spring you have **exactly** what you want:
* [HttpClientErrorException](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/HttpClientErrorException.html) - Exception thrown when an HTTP 4xx is received.
* [HttpServerErrorException](https://docs.spring.io/spring/d... | What Java exception class to use for HTTP errors? | [
"",
"java",
"http",
"exception",
""
] |
I wonder what the time complexity of the `pop` method of `list` objects is in Python (in CPython particulary). Also does the value of `N` for `list.pop(N)` affect the complexity? | `Pop()` for the last element ought to be O(1) since you only need to return the element referred to by the last element in the array and update the index of the last element. I would expect `pop()` for an arbitrary element to be O(N) and require on average N/2 operations since you would need to move any elements beyond... | Yes, it is O(1) to pop the *last* element of a Python list, and O(N) to pop an *arbitrary* element (since the whole rest of the list has to be shifted).
Here's a great article on how Python lists are stored and manipulated: <http://effbot.org/zone/python-list.htm> | What is the time complexity of popping elements from list in Python? | [
"",
"python",
"list",
"performance",
""
] |
I have a python module that makes use of a huge dictionary global variable, currently I put the computation code in the top section, every first time import or reload of the module takes more then one minute which is totally unacceptable. How can I save the computation result somewhere so that the next import/reload do... | Just to clarify: the code in the body of a module is *not* executed every time the module is imported - it is run only once, after which future imports find the already created module, rather than recreating it. Take a look at sys.modules to see the list of cached modules.
However, if your problem is the time it takes... | Calculate your global var on the first use.
```
class Proxy:
@property
def global_name(self):
# calculate your global var here, enable cache if needed
...
_proxy_object = Proxy()
GLOBAL_NAME = _proxy_object.global_name
```
Or better yet, access necessery data via special data object.
```
cla... | How to avoid computation every time a python module is reloaded | [
"",
"python",
"nltk",
""
] |
This was an interview question. Given Visual Studio 2008 and an icon saved as a .PNG file, they required the image as an embedded resource and to be used as the icon within the title bar of a form.
I'm looking for what would have been the model answer to this question, Both (working!) code and any Visual Studio tricks... | Fire up VS, start new Windows Application. Open the properties sheet, add the .png file as a resource (in this example: glider.png ). From hereon, you can access the resource as a Bitmap file as WindowsFormsApplication10.Properties.Resources.glider
Code for using it as an application icon:
```
public Form1()
... | `Icon.FromHandle` will cause problems with a PNG, because PNGs have more than one bit of transparency. This type of issue can be solved with a library like [IconLib](http://www.codeproject.com/KB/cs/IconLib.aspx "IconLib").
Chances are they didn't know how to do it and they were trying to squeeze the answer out of pot... | Got .PNG file. Want embeddded icon resource displayed as icon on form title bar | [
"",
"c#",
".net",
"winforms",
""
] |
Anyone know a simple way using Java calendar to subtract X days from a date?
I have not been able to find any function which allows me to directly subtract X days from a date in Java. Can someone point me to the right direction? | Taken from [the docs here](http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#add%28int,%20int%29):
> Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by cal... | You could use the `add` method and pass it a negative number. However, you could also write a simpler method that doesn't use the `Calendar` class such as the following
```
public static void addDays(Date d, int days)
{
d.setTime( d.getTime() + (long)days*1000*60*60*24 );
}
```
This gets the timestamp value of th... | How to subtract X days from a date using Java calendar? | [
"",
"java",
"calendar",
"subtraction",
""
] |
Provided I have admin access, I need a way to manage (Create, modify, remove) local accounts in a remote machine from an ASP.NET client.
I'm clueless in how to approach this. Is WMI a possibility (System.Management namespace)?
Any pointers? | Give this a try:
```
DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://ComputerName" & ",computer", "AdminUN", "AdminPW");
DirectoryEntry user = directoryEntry.Children.Add("username", "user");
user.Invoke("SetPassword", new object[] { "password"});
ser.CommitChanges();
```
If you do need to go the Active D... | I used System.DirectoryServices to get data from users in a n ActiveDirectory (LDAP).
I don't know if that's the kind of thing you're looking for.
Hope it helps. | Creating local users on remote windows server using c# | [
"",
"c#",
".net",
"windows",
""
] |
Sample code that shows how to create threads using MFC declares the thread function as both static and `__cdecl`. Why is the latter required? Boost threads don't bother with this convention, so is it just an anachronism?
For example (MFC):
```
static __cdecl UINT MyFunc(LPVOID pParam)
{
...
}
CWinThread* pThread = A... | \_\_cdecl tells the compiler to use the C calling convention (as opposed to the stdcall, fastcall or whatever other calling convention your compiler supports). I believe, VC++ uses stdcall by default.
The calling convention affects things such as how arguments are pushed onto the stack (or registers, in the case of fa... | Look at the prototype for [`AfxBeginThread()`](http://msdn.microsoft.com/en-us/library/s3w9x78e(VS.80).aspx):
```
CWinThread* AfxBeginThread(
AFX_THREADPROC pfnThreadProc,
LPVOID pParam,
int nPriority = THREAD_PRIORITY_NORMAL,
UINT nStackSize = 0,
DWORD dwCreateFlags = 0,
LPSECURITY_ATTRIBUTES lpSecu... | Why do thread functions need to be declared as '__cdecl'? | [
"",
"c++",
"multithreading",
"mfc",
"boost",
""
] |
I have a python script that analyzes a set of error messages and checks for each message if it matches a certain pattern (regular expression) in order to group these messages. For example "file x does not exist" and "file y does not exist" would match "file .\* does not exist" and be accounted as two occurrences of "fi... | You have two decent options:
1. Python standard config file format
using [ConfigParser](http://docs.python.org/lib/module-ConfigParser.html "ConfigParser")
2. [YAML](http://www.yaml.org/ "YAML") using a library like [PyYAML](http://pyyaml.org/ "PyYAML")
The standard Python configuration files look like INI files w... | I sometimes just write a python module (i.e. file) called `config.py` or something with following contents:
```
config = {
'name': 'hello',
'see?': 'world'
}
```
this can then be 'read' like so:
```
from config import config
config['name']
config['see?']
```
easy. | Configuration file with list of key-value pairs in python | [
"",
"python",
"configuration",
"serialization",
""
] |
I'm trying to catch a ClassCastException when deserializing an object from xml.
So,
```
try {
restoredItem = (T) decoder.readObject();
} catch (ClassCastException e){
//don't need to crash at this point,
//just let the user know that a wrong file has been passed.
}
```
And yet this won't as the exception ... | The code in the question should give you an unchecked cast warning. Listen to -Xlint.
All the compiler knows about T is its bounds, which it probably doesn't have (other than explicitly extending Object and a super of the null type). So effectively the cast at runtime is (Object) - not very useful.
What you can do is... | There will not be any ClassCastException, except when your T has some base:
```
public class GenericsTest
{
public static void main(String[] args)
{
System.out.println(cast(Integer.valueOf(0)));
System.out.println(GenericsTest.<Long> cast(Integer.valueOf(0)));
System.out.println(Generic... | How do I catch ClassCastException? | [
"",
"java",
"exception",
""
] |
My master page contains a list as shown here. What I'd like to do though, is add the "class=active" attribute to the list li thats currently active but I have no idea how to do this. I know that the code goes in the aspx page's page\_load event, but no idea how to access the li I need to add the attribute. Please enlig... | In order to access these controls from the server-side, you need to make them runat="server"
```
<ul id="nav" runat="server">
<li class="forcePadding"><img src="css/site-style-images/menu_corner_right.jpg" /></li>
<li id="screenshots"><a href="screenshots.aspx" title="Screenshots">Screenshots</a></l... | The code below can be used to find a named control anywhere within the control hierarchy:
```
public static Control FindControlRecursive(Control rootControl, string id)
{
if (rootControl != null)
{
if (rootControl.ID == id)
{
return rootControl;
}
for (int i = 0; i ... | C# - How to change HTML elements attributes | [
"",
"c#",
"html",
"asp.net",
""
] |
I need a way to bind POJO objects to an external entity, that could be XML, YAML, structured text or anything easy to write and maintain in order to create Mock data for unit testing and TDD. Below are some libraries I tried, but the main problems with them were that I am stuck (for at least more 3 months) to Java 1.4.... | If the objects to be populated are simple beans it may be a good idea to look at apache common's BeanUtils class. The populate() method might suit the described cases. Generally dependency injection frameworks like Spring can be very useful, but that might not be answer for the current problem. For input in form of xml... | Just use XStream (for XML or you could give a try to JSON).
But...
Man, I just can't avoid to think that put the test data outside the unit test itself will leads you to unreadable tests. You will need look two files when reading a test case, you will lose refactoring tools (when changing property's name). Jay Fields... | What libs can I use to bind POJOs to external files for TDD without much overhead? | [
"",
"java",
"binding",
"pojo",
""
] |
In Java, I have a subclass `Vertex` of the Java3D class `Point3f`. Now `Point3f` computes `equals()` based on the values of its coordinates, but for my `Vertex` class I want to be stricter: two vertices are only equal if they are the same object. So far, so good:
```
class Vertex extends Point3f {
// ...
pub... | Either use System.identityHashCode() or use an IdentityHashMap. | [`System.identityHashCode()`](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#identityHashCode(java.lang.Object)) returns the same hash code for the given object as would be returned by the default method `hashCode()`, whether or not the given object's class overrides `hashCode()`. | How to compute the hashCode() from the object's address? | [
"",
"java",
"hash",
"equals",
"hashcode",
""
] |
In a recent project the "lead" developer designed a database schema where "larger" tables would be split across two separate databases with a view on the main database which would union the two separate database-tables together. The main database is what the application was driven off of so these tables looked and felt... | I don't think that you are really going to gain anything by partitioning the table across multiple databases in a single server. All you have essentially done there is increased the overhead in working with the "table" in the first place by having several instances (i.e. open in two different DBs) of it under a single ... | Partitioning is not something to be undertaken lightly as there can be many subtle performance implications.
My first question is are you referring simply to placing larger table objects in separate filegroups (on separate spindles) or are you referring to data partitioning inside of a table object?
I suspect that th... | What is the best way to partition large tables in SQL Server? | [
"",
"sql",
"sql-server",
"partitioning",
""
] |
The `JPA` (Java Persistence API) specification has 2 different ways to specify entity composite keys: `@IdClass` and `@EmbeddedId`.
I'm using both annotations on my mapped entities, but it turns out to be a big mess to people who aren't very familiar with `JPA`.
I want to adopt only one way to specify composite keys.... | I consider that `@EmbeddedId` is probably more verbose because with `@IdClass` you cannot access the entire primary key object using any field access operator. Using the `@EmbeddedId` you can do like this:
```
@Embeddable class EmployeeId { name, dataOfBirth }
@Entity class Employee {
@EmbeddedId EmployeeId employee... | There are three strategies to use a compound primary key:
* Mark it as `@Embeddable` and add to your entity class a normal property for it, marked with `@Id`.
* Add to your entity class a normal property for it, marked with `@EmbeddedId`.
* Add properties to your entity class for all of its fields, mark them with `@Id... | Which annotation should I use: @IdClass or @EmbeddedId | [
"",
"java",
"jpa",
"annotations",
"java-persistence-api",
""
] |
I'm looking for a log viewer with similar capablilties as Chainsaw, in which I can tail Glassfish log files over for instance SSH/SCP. Does anyone know if such a tool exist? | From [other post](https://stackoverflow.com/questions/186968/map-ssh-drive-in-windows):
1. Configure putty to write out a log file from the connection.
2. Do the log analysis against the putty log file. | OtrosLogViewer user VFSFileSystems and can load logs from remote server (ftp, sftp, smb, http). It supports java.util.logging.XMLFormatter and java.util.logging.SimpleFormatter. See:
<http://code.google.com/p/otroslogviewer/> | Remote log viewer for Java/Glassfish log files | [
"",
"java",
"logging",
""
] |
I have been learning about the basics of C# but haven't come across a good explanation of what this is:
```
var l = new List<string>();
```
I don't know what the `<string>` is doing or if it's the `List` that is doing the magic. I have also seen objects been thrown within the `< >` tags.
Can someone explain this to ... | That is the generic syntax for C#.
The basic concept is that it allows you to use a Type placeholder and substitute the actual real type in at compile time.
For example, the old way:
```
ArrayList foos = new Arraylist();
foos.Add("Test");
```
worked by making ArrayList store a list of System.Objects (The base type ... | It's *generics* - it's a form of type parameterisation. In your example, it's making l refer to a list of strings - the list will only ever contain strings: the compiler treats it (pretty much) as if everywhere that the API docs mention "T" it actually says "string". So, you can only add strings to it, and if you use t... | What is the "< >" syntax within C# | [
"",
"c#",
".net",
""
] |
What are the most common browser compatibility issues across the major desktop browsers?
No dups please. Up-vote problems you've run into. I'm hoping for the list to self-sort. "IE sux" is not a pitfall, but a call for down-vote.
[Edit] Yes, I know it's a poll - I'm not posting answers in this to gather points - I'm ... | [Quirksmode](http://quirksmode.org/) has a comprehensive list of a lot of differencies requiring attention !-)
-- but he is, like most other sites and bloggers on the net, focused in his way, and that results in some minor or major bugs and inconsistencies ... | Transparent PNGs in Internet Explorer 6, especially because the common, JavaScript-less workaround of using the AlphaImageLoader can have the side effect of [locking up IE6](http://blogs.cozi.com/tech/2008/03/transparent-png.html). | Typical pitfalls of cross-browser compatibility | [
"",
"javascript",
"html",
"css",
"cross-browser",
""
] |
In many C/C++ macros I'm seeing the code of the macro wrapped in what seems like a meaningless `do while` loop. Here are examples.
```
#define FOO(X) do { f(X); g(X); } while (0)
#define FOO(X) if (1) { f(X); g(X); } else
```
I can't see what the `do while` is doing. Why not just write this without it?
```
#define F... | The `do ... while` and `if ... else` are there to make it so that a
semicolon after your macro always means the same thing. Let's say you
had something like your second macro.
```
#define BAR(X) f(x); g(x)
```
Now if you were to use `BAR(X);` in an `if ... else` statement, where the bodies of the if statement were no... | Macros are copy/pasted pieces of text the pre-processor will put in the genuine code; the macro's author hopes the replacement will produce valid code.
There are three good "tips" to succeed in that:
## Help the macro behave like genuine code
Normal code is usually ended by a semi-colon. Should the user view code no... | Why use apparently meaningless do-while and if-else statements in macros? | [
"",
"c++",
"c",
"c-preprocessor",
"c++-faq",
""
] |
I have this script:
```
select name,create_date,modify_date from sys.procedures order by modify_date desc
```
I can see what procedures were modified lately.
I will add a "where modify\_date >= "
And I'd like to use some system stored procedure, that will generate me :
drop + create scripts for the (let's say 5 match... | This ain't pretty, but it works. Run the output from it manually or execute it with sp\_executesql.
```
SELECT OBJECT_DEFINITION(object_id), 'drop procedure [' + name + ']'
FROM sys.procedures
WHERE modify_date >= @date
```
You will have to worry about lost rights as well. | No cursor necessary (modify as desired for schemas, etc):
```
DECLARE @dt AS datetime
SET @dt = '10/1/2008'
DECLARE @sql AS varchar(max)
SELECT @sql = COALESCE(@sql, '')
+ '-- ' + o.name + CHAR(13) + CHAR(10)
+ 'DROP PROCEDURE ' + o.name + CHAR(13) + CHAR(10)
+ 'GO' + CHAR(13) + CHAR(10)
+ m.definiti... | Generate Multiple and Filtered Drop + Create Stored Procedures | [
"",
"sql",
"sql-server",
"stored-procedures",
"system-stored-procedures",
""
] |
What good profilers do you know?
What is a good way to measure and tweak the performance of a C++ MFC application?
Is Analysis of algorithms really neccesary? <http://en.wikipedia.org/wiki/Algorithm_analysis> | I strongly recommend [AQTime](http://www.automatedqa.com) if you are staying on the Windows platform. It comes with a load of profilers, including static code analysis, and works with most important Windows compilers and systems, including Visual C++, .NET, Delphi, Borland C++, Intel C++ and even gcc. And it integrates... | If you're (still) using Visual C++ 6.0, I suggest using the built-in profiler. For more recent versions you could try [Compuware DevPartner Performance Analysis Community Edition](http://www.compuware.com/media.asp?cid=701000000004ej0). | How to measure performance in a C++ (MFC) application? | [
"",
"c++",
"performance",
"optimization",
"mfc",
""
] |
I've been working on a very simple crud generator for pylons. I came up with something that inspects
```
SomeClass._sa_class_manager.mapper.c
```
Is it ok to inspect this (or to call methods begining with underscore)? I always kind of assumed this is legal though frowned upon as it relies heavily on the internal stru... | It is intentional (in Python) that there are no "private" scopes. It is a convention that anything that starts with an underscore should not ideally be used, and hence you may not complain if its behavior or definition changes in a next version. | In general, this usually indicates that the method is effectively internal, rather than part of the documented interface, and should not be relied on. Future versions of the library are free to rename or remove such methods, so if you care about future compatability without having to rewrite, avoid doing it. | Is it OK to inspect properties beginning with underscore? | [
"",
"python",
"sqlalchemy",
"pylons",
""
] |
I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.
For example, let's say I have three files. Using [execfile](http://docs.python.org/library/functions.html#execfile):
* `script_1.py` calls `script_2.py`.
* In turn, `script_2.py` calls `s... | p1.py:
```
execfile("p2.py")
```
p2.py:
```
import inspect, os
print (inspect.getfile(inspect.currentframe())) # script filename (usually with path)
print (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) # script directory
``` | ```
__file__
```
as others have said. You may also want to use [os.path.realpath](https://docs.python.org/3/library/os.path.html#os.path.realpath) to eliminate symlinks:
```
import os
os.path.realpath(__file__)
``` | How do I get the path and name of the python file that is currently executing? | [
"",
"python",
"file",
"reflection",
"scripting",
"filesystems",
""
] |
Where can I find a free, very quick, and reliable implementation of FFT in C#?
That can be used in a product? Or are there any restrictions? | [AForge.net](http://code.google.com/p/aforge/) is a free (open-source) library with Fast Fourier Transform support. (See Sources/Imaging/[ComplexImage.cs](https://github.com/andrewkirillov/AForge.NET/blob/master/Sources/Imaging/ComplexImage.cs) for usage, Sources/Math/[FourierTransform.cs](https://github.com/andrewkiri... | The guy that did AForge did a fairly good job but it's not commercial quality. It's great to learn from but you can tell he was learning too so he has some pretty serious mistakes like assuming the size of an image instead of using the correct bits per pixel.
I'm not knocking the guy, I respect the heck out of him for... | An implementation of the fast Fourier transform (FFT) in C# | [
"",
"c#",
"signal-processing",
"fft",
""
] |
Does anybody know a way with JavaScript or CSS to basically grey out a certain part of a form/div in HTML?
I have a '*User Profile*' form where I want to disable part of it for a '*Non-Premium*' member, but want the user to see what is behind the form and place a '*Call to Action*' on top of it.
Does anybody know an ... | You might try the jQuery [BlockUI](http://malsup.com/jquery/block/) plugin. It's quite flexible and is very easy to use, if you don't mind the dependency on jQuery. It supports [element-level](http://malsup.com/jquery/block/#element) blocking as well an overlay message, which seems to be what you need.
The code to use... | Add this to your HTML:
```
<div id="darkLayer" class="darkClass" style="display:none"></div>
```
And this to your CSS:
```
.darkClass
{
background-color: white;
filter:alpha(opacity=50); /* IE */
opacity: 0.5; /* Safari, Opera */
-moz-opacity:0.50; /* FireFox */
z-index: 20;
height: 100%;
... | CSS/JavaScript Use Div to grey out section of page | [
"",
"javascript",
"css",
""
] |
I'm slowly moving all of my LAMP websites from mysql\_ functions to PDO functions and I've hit my first brick wall. I don't know how to loop through results with a parameter. I am fine with the following:
```
foreach ($database->query("SELECT * FROM widgets") as $results)
{
echo $results["widget_name"];
}
```
Howe... | Here is an example for using PDO to connect to a DB, to tell it to throw Exceptions instead of php errors (will help with your debugging), and using parameterised statements instead of substituting dynamic values into the query yourself (highly recommended):
```
// connect to PDO
$pdo = new PDO("mysql:host=localhost;d... | According to the [PHP documentation](https://www.php.net/manual/en/pdo.query.php) is says you should be able to to do the following:
```
$sql = "SELECT * FROM widgets WHERE something='something else'";
foreach ($database->query($sql) as $row) {
echo $row["widget_name"];
}
``` | How do I loop through a MySQL query via PDO in PHP? | [
"",
"php",
"mysql",
"pdo",
""
] |
I need to set a dependency property on a control (Slider.Value) in my code without it triggering a ValueChanged event (since I set the value, not the user). What is the best way to handle this situation in WPF?
For clarification, what I am trying to do is hook up WPF sliders to a WinForms User Control. Currently in my... | Here's a simply workaround/hack. Add a boolean to keep track whether you changed the setting, let's say "IsChangedByMe". When you change the dependency property in code, set the bool to true. In the ValueChanged event, if IsChangedByMe is true, don't do anything. | Are you sure you really want to do that? If there's a piece of UI databound to that property and you allow for changing the value without triggering the ValueChanged event you'd quickly end up with your UI no longer synchronized with the data.
In the case of your slider, imagine the user places it at 75%. Now your cod... | Setting WPF dependency property without triggering events | [
"",
"c#",
"wpf",
"events",
"dependency-properties",
""
] |
I've got a Java client that needs to access a remote database. It is the goal to hide database credentials from the user and not hardcode any credentials within the code. Therefore, the database access will probably have to be on the server side.
I'm restricted to use Ibatis as a data abstraction framework. Apart from... | Build a Service Layer and expose it over RMI - possibly as EJB3 stateless session beans as you have JBoss, possibly as pure RMI. I wouldn't bother with web services unless you have a specific need. RMI will take case of serialisation for you.
Your service layer needs to expose a method to authenticate users using thei... | As has been already said, you have to connect to a server which handles the database connection. There is no way to effectively prevent someone from breaking your security, with 30 minutes of effort.
If the clients are connecting somewhat locally, within an intranet, using EJB's on your appserver is probably the best ... | JAVA Swing client, Data Access to Remote Database; Ibatis | [
"",
"java",
"jboss",
"data-access-layer",
"ibatis",
"data-access",
""
] |
Unfortunately, sometimes the only way to debug a program is by going through its long log files.
I searched for a decent log viewer for a while now, and haven't found a real solution. The only program that seemed to be most appropriate was [Chainsaw](http://logging.apache.org/chainsaw/2.x/download.html) with its Socke... | You didn't mention an OS, so I'll mention this though it is only on Windows.
**Bare Metal Software makes a product called [BareTail](http://www.baremetalsoft.com/baretail/)** that has a nice interface and works well. They have a free version with a startup nag screen, a licensed version with no nag, and a pro version ... | Just wanted to say that I've finally found a tool that I can get along with just fine...
It's called LogExpert (see <http://www.log-expert.de/>) and is free. Besides the usual tail function, it also has a filter and a search function - two crucial things that are missing from BareTail. And if you happen to want to cus... | Java Log Viewer | [
"",
"java",
"log4j",
"viewer",
""
] |
Recently I have started playing with jQuery, and have been following a couple of tutorials. Now I feel slightly competent with using it (it's pretty easy), and I thought it would be cool if I were able to make a 'console' on my webpage (as in, you press the ` key like you do in [FPS](http://en.wiktionary.org/wiki/first... | Why would you want to convert key strokes to text? Add a button that sends the text inside the textarea to the server when clicked. You can get the text using the value attribute as the poster before has pointed out, or using jQuery's API:
```
$('input#mybutton').click(function() {
var text = $('textarea#mytextare... | Where it is often the text function you use (e.g. in divs etc) then for text area it is val
get:
```
$('#myTextBox').val();
```
set:
```
$('#myTextBox').val('new value');
``` | jQuery get textarea text | [
"",
"javascript",
"jquery",
"ajax",
""
] |
I'm trying to generate some code at runtime where I put in some boiler-plate stuff and the user is allowed to enter the actual working code. My boiler-plate code looks something like this:
```
using System;
public class ClassName
{
public double TheFunction(double input)
{
// user entered code here
... | Escape them by doubling them up:
```
string s = String.Format("{{ hello to all }}");
Console.WriteLine(s); //prints '{ hello to all }'
```
From <http://msdn.microsoft.com/en-us/netframework/aa569608.aspx#Question1> | "{{" and "}}" | How do you put { and } in a format string | [
"",
"c#",
".net",
"string",
"formatting",
""
] |
I have a list of Date objects, and a target Date. I want to find the date in the list that's nearest to the target date, but only dates that are before the target date.
Example:
2008-10-1
2008-10-2
2008-10-4
With a target date of 2008-10-3, I want to get 2008-10-2
What is the best way to do it? | Sietse de Kaper solution assumes a *reverse* sorted list, definitely not the most natural thing to have around
The natural sort order in java is following the ascending natural ordering. (see Collection.sort <http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#sort(java.util.List)> documentation)
From ... | ```
private Date getDateNearest(List<Date> dates, Date targetDate){
return new TreeSet<Date>(dates).lower(targetDate);
}
```
Doesn't require a pre-sorted list, TreeSort fixes that. It'll return null if it can't find one though, so you will have to modify it if that's a problem. Not sure of the efficency either :P | Best way to find date nearest to target in a list of dates? | [
"",
"java",
"date",
""
] |
Ok, this is a bit of a cheeky question. I want to build a simple text editor (using my own text mode screen handling). I just want a good example of data structures that can be used to represent the text buffer, and some simple examples of char/text insertion/deletion. I can handle all the rest of the code myself (file... | This is 2008. Don't write a text editor; you're reinventing fire.
Still here? I'm not sure if this applies or what platforms you plan to support, but the [Neatpad series of tutorials](http://www.catch22.net/tuts/neatpad/) is a great place to start thinking about writing a text editor. They focus on Win32 as the basic ... | I used to work for a company whose main product was a text editor. While I mainly worked on the scripting language for it, the internal design of the editor itself was naturally a major topic of discussion.
It seemed like it broke down into two general trains of thought. One was that you stored each line by itself, an... | Editing a text buffer | [
"",
"c++",
"c",
"open-source",
"editor",
""
] |
I tried:
```
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(f);
Node mapNode = getMapNode(doc);
System.out.print("\r\n elementName "+ mapNode.getNodeName());//This works fine.
Element e = (Element) mapNode; //This is where the... | I was using a different dtd file on the server. That was causing the issue. | Might the first child be a whitespace only text node or suchlike?
Try:
```
System.out.println(doc.getFirstChild().getClass().getName());
```
EDIT:
Just looked it up in my own code, you need:
```
doc.getDocumentElement().getChildNodes();
```
Or:
```
NodeList nodes = doc.getElementsByTagName("MyTag");
``` | How to add an attribute to an XML node in Java 1.4 | [
"",
"java",
"xml",
""
] |
Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures.
Some limitations are mentioned in the [Closures in Python](http://ivan.truemesh.com/archives/000411.html) (compared to Ruby's closures), but the article is old and many limitations do not exist ... | The most important limitation, currently, is that you cannot assign to an outer-scope variable. In other words, closures are read-only:
```
>>> def outer(x):
... def inner_reads():
... # Will return outer's 'x'.
... return x
... def inner_writes(y):
... # Will assign to a local 'x', no... | The only difficulty I've seen people encounter with Python's in particular is when they try to mix non-functional features like variable reassignment with closures, and are surprised when this doesn't work:
```
def outer ():
x = 1
def inner ():
print x
x = 2
return inner
outer () ()
```
Us... | What limitations have closures in Python compared to language X closures? | [
"",
"python",
"closures",
""
] |
> **Possible Duplicate:**
> [C#: How to enumerate an enum?](https://stackoverflow.com/questions/105372/c-how-to-enumerate-an-enum)
The subject says all. I want to use that to add the values of an enum in a combobox.
Thanks
vIceBerg | ```
string[] names = Enum.GetNames (typeof(MyEnum));
```
Then just populate the dropdown withe the array | I know others have already answered with a correct answer, however, if you're wanting to use the enumerations in a combo box, you may want to go the extra yard and associate strings to the enum so that you can provide more detail in the displayed string (such as spaces between words or display strings using casing that... | Is there a way to iterate through all enum values? | [
"",
"c#",
"enumeration",
""
] |
Currently, primary keys in our system are 10 digits longs, just over the limit for Java Integers. I want to avoid any maintenance problems down the road caused by numeric overflow in these keys, but at the same time I do not want to sacrifice much system performance to store infinitely large numbers that I will never n... | I've always gone with long keys (number(18,0) in database) because they simply remove the possibility of this situation happening in pretty much all situations (extreme data hoarding style applications aside). Having the same data-type across all tables for the key means you can share that field across all of your mode... | It seems like the answer depends on how likely you are to overflow the Java integers with your data. And there's no way to know that without some idea of what your data is. | What is the proper size for a sequence-generated primary key? | [
"",
"java",
"database",
"integer",
"primary-key",
"long-integer",
""
] |
I'd like all queries like
```
http://mysite.com/something/otherthing?foo=bar&x=y
```
to be rewritten as
```
http://mysite.com/something/otherthing.php?foo=bar&x=y
```
In other words, just make the .php extension optional, universally. | I would do it this way. Basically, if file doesn't exist, try adding .php to it.
```
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ $1.php [QSA,L]
``` | This works:
```
RewriteCond %{QUERY_STRING} ^.+$
RewriteRule ^/?([^/\.]+)$ /$1.php [L]
```
The idea is to make sure there's a query string (question mark plus stuff) and if so check if the stuff before the question mark has no extension and if so, append .php. | Rewrite all queries to not need the .php extension using a mod_rewrite RewriteRule | [
"",
"php",
"url",
"mod-rewrite",
"friendly-url",
""
] |
I have a class that has a Generic type "G"
In my class model i have
```
public class DetailElement : ElementDefinition
```
Let's say i have a method like this
```
public void DoSomething<G>(G generic)
where G : ElementDefinition
{
if (generic is DetailElement)
{
... | If `G` was constrained to be a `DetailElement` (`where G : DetailElement`) then you can go ahead and cast `G` to ElementDefinition, i.e., "`(ElementDefinition) generic`". But because `G` might be another subclass of `ElementDefinition` other than `DetailElement` at run-time it won't allow it at compile-time where the t... | Shouldn't your where clause be "where G : DetailElement"?
In the code you've written, a DetailElement is an ElementDefinition, but an ElementDefinition is not necessarily a DetailElement. So the implicit conversion is illegal.
Are there other types of ElementDefinition that you might pass into this method? If so, the... | Compiler fails converting a constrained generic type | [
"",
"c#",
"generics",
"casting",
"constraints",
""
] |
Everything I read about better PHP coding practices keeps saying don't use `require_once` because of speed.
Why is this?
What is the proper/better way to do the same thing as `require_once`? If it matters, I'm using PHP 5. | `require_once` and `include_once` both require that the system keeps a log of what's already been included/required. Every `*_once` call means checking that log. So there's definitely *some* extra work being done there but enough to detriment the speed of the whole app?
... I really doubt it... Not unless you're on *r... | This thread makes me cringe, because there's already been a "solution posted", and it's, for all intents and purposes, wrong. Let's enumerate:
1. Defines are **really** expensive in PHP. You can [look it up](http://bugs.php.net/bug.php?id=40165) or test it yourself, but the only efficient way of defining a global cons... | Why is require_once so bad to use? | [
"",
"php",
"performance",
"require-once",
""
] |
I have a HTML select list with quite a few (1000+) names. I have a javascript in place which will select the first matching name if someone starts typing. This matching looks at the start of the item:
```
var optionsLength = dropdownlist.options.length;
for (var n=0; n < optionsLength; n++)
{
var optionText = ... | use this filter script
<http://www.barelyfitz.com/projects/filterlist/> | Change
```
if (optionText.indexOf(dropdownlist.keypressBuffer,0) == 0)
```
to
```
if (optionText.indexOf(dropdownlist.keypressBuffer) > 0)
```
To find `dropdownlist.keypressBuffer` anywhere in the `optionText`. | How can I auto filter a HTML selectlist? | [
"",
"javascript",
"asp.net",
"autosuggest",
"autofilter",
""
] |
I am attempting to write an application that uses libCurl to post soap requests to a secure web service. This Windows application is built against libCurl version 7.19.0 which, in turn, is built against openssl-0.9.8i. The pertinent curl related code follows:
> ```
> FILE *input_file = fopen(current->post_file_name.c_... | After further investigation, I found that this error was due to a failure to initialise the openSSL library by calling SSL\_library\_init(). | I had the same problem, just thought I'd add the note that rather than calling the OpenSsl export SSL\_library\_init directly it can be fixed by adding the flag CURL\_GLOBAL\_SSL to [curl\_global\_init](http://curl.haxx.se/libcurl/c/curl_global_init.html) | "CURLE_OUT_OF_MEMORY" error when posting via https | [
"",
"c++",
"curl",
"https",
"openssl",
""
] |
Which is the best timer approach for a C# console batch application that has to process as follows:
1. Connect to datasources
2. process batch until timeout occurs or processing complete. "Do something with datasources"
3. stop console app gracefully.
related question: [How do you add a timer to a C# console applicat... | Sorry for this being an entire console app... but here's a complete console app that will get you started. Again, I appologize for so much code, but everyone else seems to be giving a "oh, all you have to do is do it" answer :)
```
using System;
using System.Collections.Generic;
using System.Threading;
namespace Cons... | It depends on how accurate do you want your stopping time to be. If your tasks in the batch are reasonably quick and you don't need to be very accurate, then I would try to make it single threaded:
```
DateTime runUntil = DataTime.Now.Add(timeout);
forech(Task task in tasks)
{
if(DateTime.Now >= runUntil)
{
... | Best Timer approach in C# console batch application | [
"",
"c#",
"batch-file",
"console",
"timer",
""
] |
In the Google C++ Style Guide, there's a section on [Operator Overloading](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Operator_Overloading) that has a curious statement:
> Overloading also has surprising
> ramifications. For instance, you can't
> forward declare classes that overload
> `operator&`.... | 5.3.1 of the Standard has "The address of an object of incomplete type can be taken, but if the complete type of that object is a class type that declares operator&() as a member function, then the behavior is undefined (and no diagnostic is required)."
I didn't know this either, but as another poster has pointed out,... | I hadn't heard of it either, but this gives potentially confusing results for the same code before and after the overload:
```
#include <iostream>
class Foo;
void bar (Foo& foo) {
std::cout << &foo << std::endl;
}
class Foo {
public:
bool operator & () { return true; }
};
void baz (Foo& foo) {
std::cou... | "You can't forward declare classes that overload operator&"? | [
"",
"c++",
"gcc",
""
] |
I have few asynchronous tasks running and I need to wait until at least one of them is finished (in the future probably I'll need to wait util M out of N tasks are finished).
Currently they are presented as Future, so I need something like
```
/**
* Blocks current thread until one of specified futures is done and ret... | As far as I know, Java has no analogous structure to the `WaitHandle.WaitAny` method.
It seems to me that this could be achieved through a "WaitableFuture" decorator:
```
public WaitableFuture<T>
extends Future<T>
{
private CountDownLatch countDownLatch;
WaitableFuture(CountDownLatch countDownLatch)
... | simple, check out [ExecutorCompletionService](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorCompletionService.html). | Wait until any of Future<T> is done | [
"",
"java",
"multithreading",
"concurrency",
""
] |
Many database systems don't allow comments or descriptions of tables and fields, so how do you go about documenting the purpose of a table/field apart from the obvious of having good naming conventions?
(Let's assume for now that "excellent" table and field names are not enough to document the full meaning of every ta... | MySQL [allows](http://dev.mysql.com/doc/refman/5.0/en/create-table.html) comments on tables and rows. PostgreSQL [does](http://www.postgresql.org/docs/7.4/interactive/sql-comment.html) as well. From other answers, Oracle and MSSQL have comments too.
For me, a combination of UML diagram for a quick refresher on field n... | Late one but hopefully useful…
Here is a process we used when developing relatively large database (around 100 tables and around 350 objects in total)
* Developers were required to use extended properties to add details to all objects.
* Admins rejected any DDL that didn’t have extended properties
* Third party tool w... | How do you document your database structure? | [
"",
"sql",
"database",
"documentation",
"relational",
""
] |
Ok, let's see if I can make this make sense.
I have a program written that parses an Excel file and it works just fine. I use the following to get into the file:
```
string FileToConvert = Server.MapPath(".") + "\\App_Data\\CP-ARFJN-FLAG.XLS";
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" ... | It sounds like the XLS file generated by your third-party app may not really be in Excel format - it might actually be a tab-delimited text file with an .xls extension.
Try opening it with a text editor and see.
If it is tab delimited, you can ditch the OleDB adapter and open/parse it as a standard text file. | If the format of the generated file is likely to change in future (perhaps when you upgrade the third-party app), you may prefer to use the [Office Primary Interop Assemblies](http://www.microsoft.com/downloads/details.aspx?familyid=59DAEBAA-BED4-4282-A28C-B864D8BFA513&displaylang=en). These will load any version or fo... | Problem parsing an XLS file with C# | [
"",
"c#",
"excel",
""
] |
Do you know what may cause memory leaks in JavaScript?
I am interested in browsers: IE 7, FireFox 3, Safari 3 | There is a nice article about [**JavaScript and memory leaks**](http://www.javascriptkit.com/javatutors/closuresleak/index.shtml). It does not specific about on browser, it rather describes the whole problematic of memory leaks and JavaScript.
* [JavaScript and memory leaks](http://www.javascriptkit.com/javatutors/clo... | Here is a classic memory leak in IE:-
```
function body_onload()
{
var elem = document.getElementById('someElementId');
// do stuff with elem
elem.onclick = function() {
//Some code that doesn't need the elem variable
}
}
```
After this code has run there is circular reference because an elem... | Do you know what may cause memory leaks in JavaScript? | [
"",
"javascript",
"memory-leaks",
""
] |
I frequently run into problems of this form and haven't found a good solution yet:
Assume we have two database tables representing an e-commerce system.
```
userData (userId, name, ...)
orderData (orderId, userId, orderType, createDate, ...)
```
For all users in the system, select their user information, their most ... | This should work, you'll have to adjust the table / column names:
```
select ud.name,
order1.order_id,
order1.order_type,
order1.create_date,
order2.order_id,
order2.order_type,
order2.create_date
from user_data ud,
order_data order1,
order_data order2
where u... | I have provided three different approaches for solving this problem:
1. Using Pivots
2. Using Case Statements
3. Using inline queries in the where clause
All of the solutions assume we are determining the "most recent" order based on the `orderId` column. Using the `createDate` column would add complexity due to time... | How to join the newest rows from a table? | [
"",
"sql",
"aggregate",
"pivot",
""
] |
How do I create subdomain like `http://user.mywebsite.example`? Do I have to access `.htaccess` somehow? Is it actually simply possible to create it via pure PHP code or I need to use some external script-server side language?
To those who answered: Well, then, should I ask my hosting if they provide some sort of DNS ... | You're looking to create a custom **A record**.
I'm pretty sure that you can use wildcards when specifying A records which would let you do something like this:
```
*.mywebsite.example IN A 127.0.0.1
```
*`127.0.0.1` would be the IP address of your webserver. The method of actually adding the record wil... | The feature you are after is called [Wildcard Subdomains](http://www.google.com.au/search?sourceid=chrome&ie=UTF-8&q=wildcard+subdomains). It allows you not have to setup DNS for each subdomain, and instead use Apache rewrites for the redirection. You can find a nice tutorial [here](http://steinsoft.net/static/archive/... | How to let PHP to create subdomain automatically for each user? | [
"",
"php",
"subdomain",
""
] |
```
Foo* set = new Foo[100];
// ...
delete [] set;
```
You don't pass the array's boundaries to `delete[]`. But where is that information stored? Is it standardised? | When you allocate memory on the heap, your allocator will keep track of how much memory you have allocated. This is usually stored in a "head" segment just before the memory that you get allocated. That way when it's time to free the memory, the de-allocator knows exactly how much memory to free. | ONE OF THE approaches for compilers is to allocate a little more memory and to store a count of elements in a head element.
Example how it could be done:
Here
```
int* i = new int[4];
```
compiler will allocate `sizeof(int)*5` bytes.
```
int *temp = malloc(sizeof(int)*5)
```
Will store "4" in the first `sizeof(in... | How does delete[] "know" the size of the operand array? | [
"",
"c++",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.