Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Recently I have been investigating the possibilities of caching in ASP.NET.
I rolled my own "Cache", because I didn't know any better, it looked a bit like this:
```
public class DataManager
{
private static DataManager s_instance;
public static DataManager GetInstance()
{
}
private D... | I think the maxim "let the computer do it; it's smarter than you" applies here. Just like memory management and other complicated things, the computer is a lot more informed about what it's doing than your are; consequently, able to get more performance than you are.
Microsoft has had a team of engineers working on it... | The ASP.NET caching mechanism has been around for a while, so it's stable and well understood. There are lots of resources out there to help you make the most of it.
Rolling your own might be the right solution, depending on your requirements.
The hard part about caching is choosing what is safe to cache, and when. F... | ASP.NET Caching | [
"",
"asp.net",
"sql",
"caching",
""
] |
I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this differen... | * Tuples are used whenever you want to return multiple results from a function.
* Since they're immutable, they can be used as keys for a dictionary (lists can't). | Tuples make good dictionary keys when you need to combine more than one piece of data into your key and don't feel like making a class for it.
```
a = {}
a[(1,2,"bob")] = "hello!"
a[("Hello","en-US")] = "Hi There!"
```
I've used this feature primarily to create a dictionary with keys that are coordinates of the verti... | What is a tuple useful for? | [
"",
"python",
"tuples",
""
] |
Using ASP.NET MVC there are situations (such as form submission) that may require a `RedirectToAction`.
One such situation is when you encounter validation errors after a form submission and need to redirect back to the form, but would like the URL to reflect the URL of the form, not the action page it submits to.
As... | The solution is to use the TempData property to store the desired Request components.
For instance:
```
public ActionResult Send()
{
TempData["form"] = Request.Form;
return this.RedirectToAction(a => a.Form());
}
```
Then in your "Form" action you can go:
```
public ActionResult Form()
{
/* Declare view... | Keep in mind that TempData stores the form collection in session. If you don't like that behavior, you can implement the new ITempDataProvider interface and use some other mechanism for storing temp data. I wouldn't do that unless you know for a fact (via measurement and profiling) that the use of Session state is hurt... | How to RedirectToAction in ASP.NET MVC without losing request data | [
"",
"c#",
"asp.net-mvc",
""
] |
Is there any python module to convert PDF files into text? I tried [one piece of code](http://code.activestate.com/recipes/511465/) found in Activestate which uses pypdf but the text generated had no space between and was of no use. | Try [PDFMiner](http://www.unixuser.org/~euske/python/pdfminer/index.html). It can extract text from PDF files as HTML, SGML or "Tagged PDF" format.
The Tagged PDF format seems to be the cleanest, and stripping out the XML tags leaves just the bare text.
A Python 3 version is available under:
* <https://github.com/pd... | The [PDFMiner](http://www.unixuser.org/~euske/python/pdfminer/index.html) package has changed since [codeape](https://stackoverflow.com/users/3571/codeape) posted.
**EDIT (again):**
PDFMiner has been updated again in version `20100213`
You can check the version you have installed with the following:
```
>>> import ... | Python module for converting PDF to text | [
"",
"python",
"pdf",
"text-extraction",
"pdf-scraping",
""
] |
I am writing a client-side **Swing** application (graphical font designer) on **Java 5**. Recently, I am running into `java.lang.OutOfMemoryError: Java heap space` error because I am not being conservative on memory usage. The user can open unlimited number of files, and the program keeps the opened objects in the memo... | Ultimately you always have a finite max of heap to use no matter what platform you are running on. In Windows 32 bit this is around `2GB` (not specifically heap but total amount of memory per process). It just happens that Java chooses to make the default smaller (presumably so that the programmer can't create programs... | Run Java with the command-line option `-Xmx`, which sets the *maximum* size of the heap.
[See here for details](http://docs.oracle.com/javase/7/docs/technotes/tools/windows/java.html#nonstandard). | How to deal with "java.lang.OutOfMemoryError: Java heap space" error? | [
"",
"java",
"jvm",
"out-of-memory",
"heap-memory",
""
] |
I have my Wordpress install and MediaWiki [sharing the same login information](https://stackoverflow.com/questions/33745 "Thanks ceejayoz"). Unfortunately, users need to log into both separately, but at least they use the same credentials.
What I would like to do is cause a successful login on the Wordpress blog to al... | They both support [OpenId](http://openid.net/) now.
* [MediaWiki's extension](http://www.mediawiki.org/wiki/Extension:OpenID)
* [WordPress's plugin](http://wordpress.org/extend/plugins/openid/)
There are probably other options for using OpenId, but I think that is the best solution available. | The primary problem you are going to run into is that you'll have two login forms, and two logout methods. What you need to do is pick one of the login forms as the default, and redirect the other one over to it.
I've been able to [successfully integrate](http://www.howtogeek.com) bbPress + MediaWiki + WordPress + Wor... | Wordpress MediaWiki Cookie Integration | [
"",
"php",
"wordpress",
"lamp",
"mediawiki",
""
] |
If I create a class like so:
```
// B.h
#ifndef _B_H_
#define _B_H_
class B
{
private:
int x;
int y;
};
#endif // _B_H_
```
and use it like this:
```
// main.cpp
#include <iostream>
#include <vector>
class B; // Forward declaration.
class A
{
public:
A() {
std::cout << v.size() << std::endl;
... | The compiler needs to know how big "B" is before it can generate the appropriate layout information. If instead, you said `std::vector<B*>`, then the compiler wouldn't need to know how big B is because it knows how big a pointer is. | In fact your example would build if A's constructor were implemented in a compile unit that knows the type of B.
An std::vector instance has a fixed size, no matter what T is, since it contains, as others said before, only a pointer to T. But the vector's constructor depends on the concrete type. Your example doesn't ... | Why can't a forward declaration be used for a std::vector? | [
"",
"c++",
"stl",
""
] |
Is there a function like `document.getElementById("FirstDiv").clear()`? | To answer the original question - there are various ways to do this, but the following would be the simplest.
If you already have a handle to the child node that you want to remove, i.e. you have a JavaScript variable that holds a reference to it:
```
myChildNode.parentNode.removeChild(myChildNode);
```
Obviously, i... | If you want to clear the div and remove all child nodes, you could put:
```
var mydiv = document.getElementById('FirstDiv');
while(mydiv.firstChild) {
mydiv.removeChild(mydiv.firstChild);
}
``` | How can I remove a child node in HTML using JavaScript? | [
"",
"javascript",
"html",
"dom",
""
] |
We've just started using LINQ to SQL at work for our DAL & we haven't really come up with a standard for out caching model. Previously we had being using a base 'DAL' class that implemented a cache manager property that all our DAL classes inherited from, but now we don't have that. I'm wondering if anyone has come up ... | A quick answer: Use the Repository pattern (see Domain Driven Design by Evans) to fetch your entities. Each repository will cache the things it will hold, ideally by letting each instance of the repository access a singleton cache (each thread/request will instantiate a new repository but there can be only one cache).
... | My [LINQ query result cache](http://petemontgomery.wordpress.com/2008/08/07/caching-the-results-of-linq-queries/) is probably just what you're looking for.
```
var q = from c in context.Customers
where c.City == "London"
select new { c.Name, c.Phone };
var result = q.Take(10).FromCache();
```
Pete. | How do you implement caching in Linq to SQL? | [
"",
".net",
"sql",
"linq-to-sql",
"iis",
"caching",
""
] |
I have a website that plays mp3s in a flash player. If a user clicks 'play' the flash player automatically downloads an mp3 and starts playing it.
Is there an easy way to track how many times a particular song clip (or any binary file) has been downloaded?
---
> Is the play link a link to the actual
> mp3 file or to... | The funny thing is I wrote a php media gallery for all my musics 2 days ago. I had a similar problem. I'm using <http://musicplayer.sourceforge.net/> for the player. And the playlist is built via php. All music requests go to a script called xfer.php?file=WHATEVER
```
$filename = base64_url_decode($_REQUEST['file']);
... | Use your httpd log files. Install <http://awstats.sourceforge.net/> | How do I track file downloads | [
"",
"php",
"apache",
"logging",
"download",
"analytics",
""
] |
I was just wondering if there is an elegant way to set the maximum CPU load for a particular thread doing intensive calculations.
Right now I have located the most time-consuming loop in the thread (it does only compression) and use `GetTickCount()` and `Sleep()` with hardcoded values. It makes sure that the loop cont... | I am not aware of any API to do get the OS's scheduler to do what you want (even if your thread is idle-priority, if there are no higher-priority ready threads, yours will run). However, I think you can improvise a fairly elegant throttling function based on what you are already doing. Essentially (I don't have a Windo... | On linux, you can change the scheduling priority of a thread with nice(). | CPU throttling in C++ | [
"",
"c++",
"performance",
"cpu",
"throttling",
""
] |
In many places, `(1,2,3)` (a tuple) and `[1,2,3]` (a list) can be used interchangeably.
When should I use one or the other, and why? | From the [Python FAQ](http://www.python.org/doc/faq/general/#why-are-there-separate-tuple-and-list-data-types):
> Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of ... | The list `[1,2,3]` is dynamic and flexible but that flexibility comes at a speed cost.
The tuple `(1,2,3)` is fixed (immutable) and therefore faster. | Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each? | [
"",
"python",
"list",
"tuples",
""
] |
I've seen references to curried functions in several articles and blogs but I can't find a good explanation (or at least one that makes sense!) | Currying is when you break down a function that takes multiple arguments into a series of functions that each take only one argument. Here's an example in JavaScript:
```
function add (a, b) {
return a + b;
}
add(3, 4); // returns 7
```
This is a function that takes two arguments, a and b, and returns their sum. W... | In an algebra of functions, dealing with functions that take multiple arguments (or equivalent one argument that's an N-tuple) is somewhat inelegant -- but, as Moses Schönfinkel (and, independently, Haskell Curry) proved, it's not needed: all you need are functions that take one argument.
So how do you deal with somet... | What is 'Currying'? | [
"",
"javascript",
"functional-programming",
"terminology",
"definition",
"currying",
""
] |
It seems that a List object cannot be stored in a List variable in C#, and can't even be explicitly cast that way.
```
List<string> sl = new List<string>();
List<object> ol;
ol = sl;
```
results in Cannot implicitly convert type `System.Collections.Generic.List<string>` to `System.Collections.Generic.List<object>`
A... | Think of it this way, if you were to do such a cast, and then add an object of type Foo to the list, the list of strings is no longer consistent. If you were to iterate the first reference, you would get a class cast exception because once you hit the Foo instance, the Foo could not be converted to string!
As a side n... | If you're using .NET 3.5 have a look at the Enumerable.Cast method. It's an extension method so you can call it directly on the List.
```
List<string> sl = new List<string>();
IEnumerable<object> ol;
ol = sl.Cast<object>();
```
It's not exactly what you asked for but should do the trick.
Edit: As noted by Zooba, you... | In C#, why can't a List<string> object be stored in a List<object> variable | [
"",
"c#",
".net",
"generics",
"covariance",
"type-safety",
""
] |
I have a "Status" class in C#, used like this:
```
Status MyFunction()
{
if(...) // something bad
return new Status(false, "Something went wrong")
else
return new Status(true, "OK");
}
```
You get the idea.
All callers of MyFunction *should* check the returned Status:
```
Status myStatus = MyFunction... | I am fairly certain you can't get the effect you want as a return value from a method. C# just can't do some of the things C++ can. However, a somewhat ugly way to get a similar effect is the following:
```
using System;
public class Example
{
public class Toy
{
private bool inCupboard = false;
... | I know this doesn't answer your question directly, but if "something went wrong" within your function (unexpected circumstances) I think you should be throwing an exception rather than using status return codes.
Then leave it up to the caller to catch and handle this exception if it can, or allow it to propogate if th... | Enforcing required function call | [
"",
"c#",
"garbage-collection",
"dispose",
"destructor",
""
] |
I am currently working on a project with specific requirements. A brief overview of these are as follows:
* Data is retrieved from external webservices
* Data is stored in SQL 2005
* Data is manipulated via a web GUI
* The windows service that communicates with the web services has no coupling with our internal web UI... | Why not use a SQL Job instead of the Windows Service? You can encapsulate all of you db "trigger" code in Stored Procedures. Then your UI and SQL Job can call the same Stored Procedures and create the triggers the same way whether it's manually or at a time interval. | The way I see it is this.
You have a Windows Service, which is playing the role of a scheduler and in it there are some classes which simply call the webservices and put the data in your databases.
So, you can use these classes directly from the WebUI as well and import the data based on the WebUI trigger.
I don't l... | Timer-based event triggers | [
"",
"sql",
"web-services",
"service",
"triggers",
"timer",
""
] |
I have a web service that I created in C# and a test harness that was provided by my client. Unfortunately my web service doesn't seem to be parsing the objects created by the test harness. I believe the problem lies with serializing the soap packet.
Using TCPTrace I was able to get the soap packet passed to the web s... | A somewhat manual process would be to use the [Poster](http://code.google.com/p/poster-extension/) add-in for Firefox. There is also a java utility called [SoapUI](http://sourceforge.net/project/showfiles.php?group_id=136013&package_id=163662&release_id=500134) that has some discovery based automated templates that you... | By default, .Net will not allow you to connect a packet analyzer like TCPTrace or Fiddler (which I prefer) to localhost or 127.0.0.1 connections (for reasons that I forget now..)
Best way would be to reference your web services via a full IP address or FQDN where possible. That will allow you to trace the calls in the... | Debugging Web Service with SOAP Packet | [
"",
"c#",
"web-services",
"soap",
"tcptrace-pocketsoap",
""
] |
I'd like to have a java.utils.Timer with a resettable time in java.I need to set a once off event to occur in X seconds. If nothing happens in between the time the timer was created and X seconds, then the event occurs as normal.
If, however, before X seconds has elapsed, I decide that the event should occur after Y s... | According to the [`Timer`](http://java.sun.com/javase/6/docs/api/java/util/Timer.html) documentation, in Java 1.5 onwards, you should prefer the [`ScheduledThreadPoolExecutor`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html) instead. (You may like to create this executor usi... | If your `Timer` is only ever going to have one task to execute then I would suggest subclassing it:
```
import java.util.Timer;
import java.util.TimerTask;
public class ReschedulableTimer extends Timer
{
private Runnable task;
private TimerTask timerTask;
public void schedule(Runnable runnable, long del... | Resettable Java Timer | [
"",
"java",
"timer",
""
] |
I am trying to link two fields of a given table to the same field in another table.
I have done this before so I can't work out what is wrong this time.
Anyway:
```
Table1
- Id (Primary)
- FK-Table2a (Nullable, foreign key relationship in DB to Table2.Id)
- FK-Table2b (Nullable, foreign key relationship in DB to Tabl... | No idea on the cause, but I just reconstructed my .dbml from scratch and it fixed itself.
Oh for a "refresh" feature... | I see this problem when I try to create one-to-one relationships where one side of the relationship is nullable (so really, one-to-zero/one). LINQ-to-SQL doesn't seem to support this so it appears we are forced to a plural relationship and a collection that will contain zero or one items. Annoying. | LINQ to SQL Association - "Properties do not have matching types" | [
"",
"c#",
"asp.net",
"linq-to-sql",
"dynamic-data",
""
] |
I have a flag enum below.
```
[Flags]
public enum FlagTest
{
None = 0x0,
Flag1 = 0x1,
Flag2 = 0x2,
Flag3 = 0x4
}
```
I cannot make the if statement evaluate to true.
```
FlagTest testItem = FlagTest.Flag1 | FlagTest.Flag2;
if (testItem == FlagTest.Flag1)
{
// Do something,
// however This is... | In .NET 4 there is a new method [Enum.HasFlag](http://msdn.microsoft.com/en-us/library/system.enum.hasflag%28VS.100%29.aspx). This allows you to write:
```
if ( testItem.HasFlag( FlagTest.Flag1 ) )
{
// Do Stuff
}
```
which is much more readable, IMO.
The .NET source indicates that this performs the same logic a... | ```
if ((testItem & FlagTest.Flag1) == FlagTest.Flag1)
{
// Do something
}
```
`(testItem & FlagTest.Flag1)` is a bitwise AND operation.
`FlagTest.Flag1` is equivalent to `001` with OP's enum. Now let's say `testItem` has Flag1 and Flag2 (so it's bitwise `101`):
```
001
&101
----
001 == FlagTest.Flag1
``` | How to Compare Flags in C#? | [
"",
"c#",
".net",
"enums",
"attributes",
"flags",
""
] |
I have values stored as strings in a `DataTable` where each value could really represent an `int`, `double`, or `string` (they were all converted to strings during an import process from an external data source). I need to test and see what type each value really is.
What is more efficient for the application (or is t... | Would use double.TryParse, it has performance benefits. | I would say, don't worry so much about such micro performance. It is much better to just get something to work, and then make it as clear and concise and easy to read as possible. The worst thing you can do is sacrifice readability for an insignificant amount of performance.
In the end, the best way to deal with perfo... | Most Efficient Way to Test Object Type | [
"",
"c#",
".net",
"double",
"int",
""
] |
So I've got a `JPanel` implementing `MouseListener` and `MouseMotionListener`:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DisplayArea extends JPanel implements MouseListener, MouseMotionListener {
public DisplayArea(Rectangle bounds, Display display) {
setLayout(nu... | The *implements mouselistener, mousemotionlistener* just allows the displayArea class to listen to some, to be defined, Swing component's mouse events. You have to explicitly define what it should be listening at. So I suppose you could add something like this to the constructor:
```
this.addMouseListener(this);
this.... | I don't see anywhere in the code where you call addMouseListener(this) or addMouseMotionListener(this) for the DisplayArea in order for it to subscribe to those events. | My (Java/Swing) MouseListener isn't listening, help me figure out why | [
"",
"java",
"swing",
"actionlistener",
"mouselistener",
""
] |
I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have:
```
var data = '{"count" : 1, "stack" : "sometext\n\n"}';
var dataObj = eval('('+data+')');
```
This gives me an error:
```
unterminated string literal
```
With `JSON.parse(data)`, I see simil... | This is what you want:
```
var data = '{"count" : 1, "stack" : "sometext\\n\\n"}';
```
You need to escape the `\` in your string (turning it into a double-`\`), otherwise it will become a newline in the JSON source, not the JSON data. | You will need to have a function which replaces `\n` to `\\n` in case `data` is not a string literal.
```
function jsonEscape(str) {
return str.replace(/\n/g, "\\\\n").replace(/\r/g, "\\\\r").replace(/\t/g, "\\\\t");
}
var data = '{"count" : 1, "stack" : "sometext\n\n"}';
var dataObj = JSON.parse(jsonEscape(data... | How do I handle newlines in JSON? | [
"",
"javascript",
"json",
"newline",
""
] |
I am considering creating my own website using Java and am trying to decide what framework to use. However, doing a quick search for Java frameworks returns more than 50 to choose from!
My website is just going to be for my own enjoyment of building it in the beginning, but if it becomes popular, it would be good for ... | I've used [Tapestry 3](http://tapestry.apache.org/tapestry3/), [Wicket](http://wicket.apache.org/), [Echo](http://echo.nextapp.com/site/), and [JSF](http://www.oracle.com/technetwork/java/javaee/javaserverfaces-139869.html) fairly extensively. I'd really recommend you look those over and pick the one that appears the e... | My favorite is the Spring Framework. With 2.5 Spring MVC is soooo kick ass, with new annotations, convention over configuration features, etc.
If you're just doing something super simple you could also just try using the regular Servlet API and not bother with a framework. | What are the pros and cons of the assorted Java web frameworks? | [
"",
"java",
"web-frameworks",
"rich-internet-application",
""
] |
After reading the Head First Design Patterns book and using a number of other design patterns, I'm trying to understand the Observer pattern. Isn't this already implemented using Events in the .NET Framework? | Yes, it is. The observer pattern is also called the publish/subscribe pattern, which is exactly what events allow you to do. | I would say yes, it was Anders Heljsberg's intent to make the observer pattern a first-class language feature with events in C#, based on his experience with Delphi. Anders makes this and other design intentions clear in an excellent interview on [Software Engineering Radio](http://www.se-radio.net/podcast/2008-05/epis... | In C#, isn't the observer pattern already implemented using Events? | [
"",
"c#",
".net",
"design-patterns",
""
] |
Is it possible for the compiler to remove statements used for debugging purposes (such as logging) from production code? The debug statements would need to be marked somehow, maybe using annotations.
It's easy to set a property (debug = true) and check it at each debug statement, but this can reduce performance. It wo... | Two recommendations.
**First:**
for real logging, use a modern logging package like log4j or java's own built in logging. Don't worry about performance so much, the logging level check is on the order of nanoseconds. (it's an integer comparison).
And if you have more than a single log statement, guard the whole block... | ```
public abstract class Config
{
public static final boolean ENABLELOGGING = true;
}
```
---
```
import static Config.*;
public class MyClass
{
public myMethod()
{
System.out.println("Hello, non-logging world");
if (ENABLELOGGING)
{
log("Hello, logging world.");
... | How to remove debug statements from production code in Java | [
"",
"java",
"debugging",
"compiler-construction",
""
] |
I have a tree structure in memory that I would like to render in HTML using a Django template.
```
class Node():
name = "node name"
children = []
```
There will be some object `root` that is a `Node`, and `children` is a list of `Node`s. `root` will be passed in the content of the template.
I have found [this](h... | I think the canonical answer is: "Don't".
What you should probably do instead is unravel the thing in your *view* code, so it's just a matter of iterating over (in|de)dents in the template. I think I'd do it by appending indents and dedents to a list while recursing through the tree and then sending that "travelogue" ... | Using `with` template tag, I could do tree/recursive list.
Sample code:
main template: assuming 'all\_root\_elems' is list of one or more root of tree
```
<ul>
{%for node in all_root_elems %}
{%include "tree_view_template.html" %}
{%endfor%}
</ul>
```
tree\_view\_template.html renders the nested `ul`, `li` and... | How can I render a tree structure (recursive) using a django template? | [
"",
"python",
"django",
""
] |
What are some good steps to follow for a smooth migration from PHP4 to PHP5. What are some types of code that are likely to break? | I also once worked on an app which used PHP4's XML support quite heavily, and would have required quite a bit of work to move to PHP5.
One of the other significant changes I was looking at at the time was the change of the default handling of function parameters. In PHP4 if I remember, they were pass-by-copy unless yo... | The best advice I could give anyone working with PHP4 is this:
```
error_reporting( E_ALL );
```
It pretty much will tell you exactly what you need to do. | PHP4 to PHP5 Migration | [
"",
"php",
"migration",
""
] |
On a recent Java project, we needed a free Java based real-time data plotting utility. After much searching, we found this tool called the [Scientific Graphics Toolkit or SGT](http://www.epic.noaa.gov/java/sgt/) from NOAA. It seemed pretty robust, but we found out that it wasn't terribly configurable. Or at least not c... | I've had success using [JFreeChart](http://www.jfree.org/jfreechart/) on multiple projects. It is *very* configurable. JFreeChart is open source, but they charge for the [developer guide](http://www.jfree.org/jfreechart/devguide.html). If you're doing something simple, the sample code is probably good enough. Otherwise... | I just ran into a similar issue (displaying fast-updating data for engineering purposes), and I'm using [JChart2D](http://jchart2d.sourceforge.net/docs/javadoc/index.html). It's pretty minimalist and has a few quirks but it seems fairly fast: I'm running a benchmark speed test where it's adding 2331 points per second (... | Are there any decent free Java data plotting libraries out there? | [
"",
"java",
"plot",
"configuration",
""
] |
I've been developing a "Form Builder" in Javascript, and coming up to the part where I'll be sending the spec for the form back to the server to be stored. The builder maintains an internal data structure that represents the fields, label, options (for select/checkbox/radio), mandatory status, and the general sorting o... | Best practice on this dictates that if you are not planning to use the stored data for anything other than recreating the form then the best method is to send it back in some sort of native format (As mentioned above) With this then you can just load the data back in and requires the least processing of any method. | When making and processing requests with JavaScript, I live and breath [JSON](http://json.org/). It's easy to build on the client side and there are tons of parsers for the server side, so both ends get to use their native tongue as much as possible. | Communication between Javascript and the server | [
"",
"javascript",
"server",
""
] |
I would like to have an `iframe` take as much vertical space as it needs to display its content and not display a scrollbar. Is it at all possible ?
Are there any workarounds? | This should set the `IFRAME` height to its content's height:
```
<script type="text/javascript">
the_height = document.getElementById('the_iframe').contentWindow.document.body.scrollHeight;
document.getElementById('the_iframe').height = the_height;
</script>
```
You may want to add `scrolling="no"` to your `IFRAME` t... | This CSS snippet should remove the vertical scrollbar:
```
body {
overflow-x: hidden;
overflow-y: hidden;
}
```
I'm not sure yet about having it take up as much vertical space as it needs, but I'll see if I can't figure it out. | Making an iframe take vertical space | [
"",
"javascript",
"html",
"css",
"iframe",
""
] |
After changing the output directory of a visual studio project it started to fail to build with an error very much like:
```
C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\bin\sgen.exe /assembly:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryCaseManagement\obj\Release\EASDiscoveryCaseManagement.dll /proxytypes /... | see [msdn](http://msdn.microsoft.com/en-us/library/bk3w6240(VS.80).aspx) for the options to sgen.exe [you have the command line, you can play with it manually... delete your .XmlSerializers.dll or use /force though]
Today I also ran across how to more [manually specify the sgen options](http://www.kiwidude.com/blog/20... | If you are having this problem while building your VS.NET project in Release mode here is the solution:
Go to the project properties and click on the Build tab and set the value of the "Generate Serialization Assembly" dropdown to "Off".
Sgen.exe is "The XML Serializer Generator creates an XML serialization assembly ... | sgen.exe fails during build | [
"",
"c#",
"visual-studio",
"msbuild",
""
] |
What is the difference, if any, between these methods of indexing into a PHP array:
```
$array[$index]
$array["$index"]
$array["{$index}"]
```
I'm interested in both the performance and functional differences.
### Update:
(In response to @Jeremy) I'm not sure that's right. I ran this code:
```
$array = array(100... | see @svec and @jeremy above. All array indices are of type 'int' first, then type 'string', and will be cast to that as PHP sees fit.
Performance wise, $index should be faster than "$index" and "{$index}" (which are the same).
Once you start a double-quote string, PHP will go into interpolation mode and treat it as a... | I timed the 3 ways of using an index like this:
```
for ($ii = 0; $ii < 1000000; $ii++) {
// TEST 1
$array[$idx] = $ii;
// TEST 2
$array["$idx"] = $ii;
// TEST 3
$array["{$idx}"] = $ii;
}
```
The first set of tests used `$idx=0`, the second set used `$idx="0"`, and the third set used `$idx="blah"`. ... | PHP array indexing: $array[$index] vs $array["$index"] vs $array["{$index}"] | [
"",
"php",
"syntax",
""
] |
I have inherited some legacy PHP code what was written back when it was standard practice to use [`register_globals`](http://php.net/register_globals) (As of PHP 4.2.0, this directive defaults to off, released 22. Apr 2002).
We know now that it is bad for security to have it enabled. The problem is how do I find all t... | If you set error reporting to E\_ALL, it warns in the error log about undefined variables complete with filename and line number (assuming you are logging to a file). However, it will warn only if when it comes across an undefined variable, so I think you will have to test each code path. Running php from the command l... | I wrote a [script](http://pastebin.com/f6f379371) using the built-in [Tokenizer](http://au.php.net/manual/en/ref.tokenizer.php) functions. Its pretty rough but it worked for the code base I was working on. I believe you could also use [CodeSniffer](http://pear.php.net/manual/en/package.php.php-codesniffer.php). | Making code work with register_globals turned off | [
"",
"php",
"register-globals",
""
] |
I have a method which takes params object[] such as:
```
void Foo(params object[] items)
{
Console.WriteLine(items[0]);
}
```
When I pass two object arrays to this method, it works fine:
```
Foo(new object[]{ (object)"1", (object)"2" }, new object[]{ (object)"3", (object)"4" } );
// Output: System.Object[]
```
... | A simple typecast will ensure the compiler knows what you mean in this case.
```
Foo((object)new object[]{ (object)"1", (object)"2" }));
```
As an array is a subtype of object, this all works out. Bit of an odd solution though, I'll agree. | The `params` parameter modifier gives callers a shortcut syntax for passing multiple arguments to a method. There are two ways to call a method with a `params` parameter:
**1)** Calling with an array of the parameter type, in which case the `params` keyword has no effect and the array is passed directly to the method:... | How to pass a single object[] to a params object[] | [
"",
"c#",
"arrays",
""
] |
I've been working with [providers](http://msdn.microsoft.com/en-us/library/aa479030.aspx) a fair bit lately, and I came across an interesting situation where I wanted to have an abstract class that had an `abstract static` method. I read a few posts on the topic, and it sort of made sense, but is there a nice clear exp... | Static methods are not *instantiated* as such, they're just available without an object reference.
A call to a static method is done through the class name, not through an object reference, and the Intermediate Language (IL) code to call it will call the abstract method through the name of the class that defined it, n... | Static methods cannot be inherited or overridden, and that is why they can't be abstract. Since static methods are defined on the type, not the instance, of a class, they must be called explicitly on that type. So when you want to call a method on a child class, you need to use its name to call it. This makes inheritan... | Why can't I have abstract static methods in C#? | [
"",
"c#",
".net",
"language-design",
""
] |
I have a .exe and many plug-in .dll modules that the .exe loads. (I have source for both.) A cross-platform (with source) solution would be ideal, but the platform can be narrowed to WinXP and Visual Studio (7.1/2003 in my case).
The built-in VS leak detector only gives the line where new/malloc was called from, but I... | I personally use [Visual Leak Detector](https://kinddragon.github.io/vld/), though it can cause large delays when large blocks are leaked (it displays the contents of the entire leaked block). | If you don't want to recompile (as Visual Leak Detector requires) I would recommend [WinDbg](https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-download-tools), which is both powerful and fast (though it's not as easy to use as one could desire).
On the other hand, if you don't want to mess w... | What is the best free memory leak detector for a C/C++ program and its plug-in DLLs? | [
"",
"c++",
"c",
"visual-studio",
"memory-leaks",
""
] |
Ok, so PHP isn't the best language to be dealing with arbitrarily large integers in, considering that it only natively supports 32-bit signed integers. What I'm trying to do though is create a class that could represent an arbitrarily large binary number and be able to perform simple arithmetic operations on two of the... | The [PHP GMP extension](https://www.php.net/gmp) will be better for this. As an added bonus, you can use it to do your decimal-to-binary conversion, like so:
```
gmp_strval(gmp_init($n, 10), 2);
``` | There are already various [classes](http://www.pear.php.net/package/Crypt_DiffieHellman/docs/latest/Crypt_DiffieHellman/BigInteger/Crypt_DiffieHellman_Math_BigInteger_Interface.html) [available](http://pear.php.net/package/Math_BigInteger/docs/latest/Math_BigInteger/_Math_BigInteger-1.0.0RC3---BigInteger.php.html) for ... | Arithmetic with Arbitrarily Large Integers in PHP | [
"",
"php",
"integer",
""
] |
Using C# .NET 3.5 and WCF, I'm trying to write out some of the WCF configuration in a client application (the name of the server the client is connecting to).
The obvious way is to use `ConfigurationManager` to load the configuration section and write out the data I need.
```
var serviceModelSection = ConfigurationMa... | The [`<system.serviceModel>`](http://msdn.microsoft.com/en-us/library/ms731354%28v=vs.90%29.aspx) element is for a configuration section **group**, not a section. You'll need to use [`System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup()`](http://msdn.microsoft.com/en-us/library/system.servicemod... | <http://mostlytech.blogspot.com/2007/11/programmatically-enumerate-wcf.html>
```
// Automagically find all client endpoints defined in app.config
ClientSection clientSection =
ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;
ChannelEndpointElementCollection endpointCollection =
... | Loading System.ServiceModel configuration section using ConfigurationManager | [
"",
"c#",
".net",
"xml",
"wcf",
"configurationmanager",
""
] |
I am trying to implement string unescaping with Python regex and backreferences, and it doesn't seem to want to work very well. I'm sure it's something I'm doing wrong but I can't figure out what...
```
>>> import re
>>> mystring = r"This is \n a test \r"
>>> p = re.compile( "\\\\(\\S)" )
>>> p.sub( "\\1", mystring )
... | Isn't that what Anders' second example does?
In 2.5 there's also a `string-escape` encoding you can apply:
```
>>> mystring = r"This is \n a test \r"
>>> mystring.decode('string-escape')
'This is \n a test \r'
>>> print mystring.decode('string-escape')
This is
a test
>>>
``` | Well, I think you might have missed the r or miscounted the backslashes...
```
"\\n" == r"\n"
>>> import re
>>> mystring = r"This is \\n a test \\r"
>>> p = re.compile( r"[\\][\\](.)" )
>>> print p.sub( r"\\\1", mystring )
This is \n a test \r
>>>
```
Which, if I understood is what was requested.
I suspect the more... | Python Regular Expressions to implement string unescaping | [
"",
"python",
"regex",
"backreference",
""
] |
At work we are currently still using JUnit 3 to run our tests. We have been considering switching over to JUnit 4 for **new** tests being written but I have been keeping an eye on TestNG for a while now. What experiences have you all had with either JUnit 4 or TestNG, and which seems to work better for very large numbe... | I've used both, but I have to agree with Justin Standard that you shouldn't really consider rewriting your existing tests to any new format. Regardless of the decision, it is pretty trivial to run both. TestNG strives to be much more configurable than JUnit, but in the end they both work equally well.
TestNG has a nea... | First I would say, don't rewrite all your tests just to suit the latest fad. Junit3 works perfectly well, and the introduction of annotations in 4 doesn't buy you very much (in my opinion). It is much more important that you guys *write* tests, and it sounds like you do.
Use whatever seems most natural and helps you g... | JUnit vs TestNG | [
"",
"java",
"testing",
"junit",
"testng",
""
] |
My job would be easier, or at least less tedious if I could come up with an automated way (preferably in a Python script) to extract useful information from a FileMaker Pro database. I am working on Linux machine and the FileMaker database is on the same LAN running on an OS X machine. I can log into the webby interfac... | It has been a **really** long time since I did anything with FileMaker Pro, but I know that it does have capabilities for an ODBC (and JDBC) connection to be made to it (however, I don't know how, or if, that translates to the linux/perl/python world though).
This article shows how to share/expose your FileMaker data ... | You'll need the FileMaker Pro installation CD to get the drivers. [This document](http://www.filemaker.com/downloads/pdf/fm9_odbc_jdbc_guide_en.pdf) details the process for FMP 9 - it is similar for versions 7.x and 8.x as well. Versions 6.x and earlier are completely different and I wouldn't bother trying (xDBC suppor... | Best way to extract data from a FileMaker Pro database in a script? | [
"",
"python",
"linux",
"perl",
"scripting",
"filemaker",
""
] |
Let's say I have four tables: `PAGE`, `USER`, `TAG`, and `PAGE-TAG`:
```
Table | Fields
------------------------------------------
PAGE | ID, CONTENT
TAG | ID, NAME
USER | ID, NAME
PAGE-TAG | ID, PAGE-ID, TAG-ID, USER-ID
```
And let's say I have four pages:
```
PAGE#1 'Content page 1' t... | OK, so the key difference between this and kristof's answer is that you only want a count of 1 to show against page 1, because it has been tagged only with one tag from the set (even though two separate users both tagged it).
I would suggest this:
```
SELECT page.ID, page.content, count(*) AS uniquetags
FROM
( SE... | This might work:
```
select page.content, count(page-tag.tag-id) as tagcount
from page inner join page-tag on page-tag.page-id = page.id
group by page.content
having page-tag.tag-id in (1, 3, 8)
``` | How can I get the number of occurrences in a SQL IN clause? | [
"",
"sql",
""
] |
I have a recursive algorithm which steps through a string, character by character, and parses it to create a tree-like structure. I want to be able to keep track of the character index the parser is currently at (for error messages as much as anything else) but am not keen on implementing something like a tuple to hand... | Since you've already discovered the pseudo-mutable integer "hack," how about this option:
Does it make sense for you to make a separate Parser class? If you do this, you can store the current state in a member variable. You probably need to think about how you're going to handle any thread safety issues, and it might ... | It's kind of a hack, but sometimes I use an AtomicInteger, which is mutable, to do things like this. I've also seen cases where an int[] of size 1 is passed in. | How to keep a "things done" count in a recursive algorithm in Java? | [
"",
"java",
"recursion",
"coding-style",
"integer",
"final",
""
] |
I'm using `ByteBuffers` and `FileChannels` to write binary data to a file. When doing that for big files or successively for multiple files, I get an `OutOfMemoryError` exception.
I've read elsewhere that using `Bytebuffers` with NIO is broken and should be avoided. Does any of you already faced this kind of problem an... | I would say don't create a huge ByteBuffer that contains ALL of the data at once. Create a much smaller ByteBuffer, fill it with data, then write this data to the FileChannel. Then reset the ByteBuffer and continue until all the data is written. | Check out Java's **[Mapped Byte Buffers](http://java.sun.com/j2se/1.4.2/docs/api/java/nio/MappedByteBuffer.html)**, also known as 'direct buffers'. Basically, this mechanism uses the OS's virtual memory paging system to 'map' your buffer directly to disk. The OS will manage moving the bytes to/from disk and memory auto... | How to avoid OutOfMemoryError when using Bytebuffers and NIO? | [
"",
"java",
"nio",
"bytebuffer",
"filechannel",
""
] |
What is the simplest SQL query to find the second largest integer value in a specific column?
There are maybe duplicate values in the column. | ```
SELECT MAX( col )
FROM table
WHERE col < ( SELECT MAX( col )
FROM table )
``` | ```
SELECT MAX(col)
FROM table
WHERE col NOT IN ( SELECT MAX(col)
FROM table
);
``` | What is the simplest SQL Query to find the second largest value? | [
"",
"sql",
"puzzle",
""
] |
I'm aware of things like `onchange`, `onmousedown` and `onmouseup` but is there a good reference somewhere that lists all of them complete with possibly a list of the elements that they cover? | W3Schools seems to have a good Javascript events reference: [HTML DOM Events](http://www.w3schools.com/jsref/dom_obj_event.asp) | Quirksmode has a nice [event-compatibility table](http://quirksmode.org/dom/events/index.html) and an [introduction](http://quirksmode.org/js/introevents.html). | Reference that lists available JavaScript events? | [
"",
"javascript",
"browser",
"client-side",
""
] |
I'm looking for any way that I can improve the selector performance of a jQuery call. Specifically things like this:
Is `$("div.myclass")` faster than `$(".myclass")`
I would think it might be, but I don't know if jQuery is smart enough to limit the search by tag name first, etc. Anyone have any ideas for how to form... | There is no doubt that **filtering by tag name first is much faster** than filtering by classname.
This will be the case until all browsers implement getElementsByClassName natively, as is the case with getElementsByTagName. | In some cases, you can speed up a query by limiting its context. If you have an element reference, you can pass it as the second argument to limit the scope of the query:
```
$(".myclass", a_DOM_element);
```
should be faster than
```
$(".myclass");
```
if you already have a\_DOM\_element and it's significantly sma... | Good ways to improve jQuery selector performance? | [
"",
"javascript",
"jquery",
"performance",
"css-selectors",
""
] |
If I have a
```
<input id="uploadFile" type="file" />
```
tag, and a submit button, how do I determine, in IE6 (and above) if a file has been selected by the user.
In FF, I just do:
```
var selected = document.getElementById("uploadBox").files.length > 0;
```
But that doesn't work in IE. | This works in IE (and FF, I believe):
```
if(document.getElementById("uploadBox").value != "") {
// you have a file
}
``` | ```
var nme = document.getElementById("uploadFile");
if(nme.value.length < 4) {
alert('Must Select any of your photo for upload!');
nme.focus();
return false;
}
``` | How to determine if user selected a file for file upload? | [
"",
"javascript",
"html",
"upload",
""
] |
I have an Interface called `IStep` that can do some computation (See "[Execution in the Kingdom of Nouns](http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html)"). At runtime, I want to select the appropriate implementation by class name.
```
// use like this:
IStep step = GetStep(sName);
``` | Your question is very confusing...
If you want to find types that implement IStep, then do this:
```
foreach (Type t in Assembly.GetCallingAssembly().GetTypes())
{
if (!typeof(IStep).IsAssignableFrom(t)) continue;
Console.WriteLine(t.FullName + " implements " + typeof(IStep).FullName);
}
```
If you know already ... | If the implementation has a parameterless constructor, you can do this using the System.Activator class. You will need to specify the assembly name in addition to the class name:
```
IStep step = System.Activator.CreateInstance(sAssemblyName, sClassName).Unwrap() as IStep;
```
<http://msdn.microsoft.com/en-us/library... | How to find an implementation of a C# interface in the current assembly with a specific name? | [
"",
"c#",
"linq",
"reflection",
"linq-to-objects",
""
] |
This error just started popping up all over our site.
***Permission denied to call method to Location.toString***
I'm seeing google posts that suggest that this is related to flash and our crossdomain.xml. What caused this to occur and how do you fix? | Are you using javascript to communicate between frames/iframes which point to different domains? This is not permitted by the JS "same origin/domain" security policy. Ie, if you have
```
<iframe name="foo" src="foo.com/script.js">
<iframe name="bar" src="bar.com/script.js">
```
And the script on bar.com tries to acce... | You may have come across [this posting](http://willperone.net/Code/as3error.php), but it appears that a flash security update changed the behaviour of the crossdomain.xml, requiring you to specify a security policy to allow arbitrary headers to be sent from a remote domain. The Adobe knowledge base article (also refere... | What does this javascript error mean? Permission denied to call method to Location.toString | [
"",
"javascript",
"flash",
""
] |
I am trying to snoop on a log file that an application is writing to.
I have successfully hooked createfile with the detours library from MSR, but createfile never seems to be called with file I am interested in snooping on. I have also tried hooking openfile with the same results.
I am not an experienced Windows/C++... | You can use Sysinternal's [FileMon](http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx).
It is an excellent monitor that can tell you exactly which file-related system calls are being
made and what are the parameters.
I think that this approach is much easier than hooking API calls and much less intrusive. | Here's a link which might be of use:
[Guerilla-Style File Monitoring with C# and C++](http://www.codingthewheel.com/archives/how-i-built-a-working-online-poker-bot-6)
It is possible to create a file without touching CreateFile API but can I ask **what DLL injection method you're using**? If you're using something lik... | Any Windows APIs to get file handles besides createfile and openfile? | [
"",
"c++",
"windows",
"api",
"logfile",
""
] |
I need to set the height of every textbox on my form, some of which are nested within other controls. I thought I could do something like this:
```
private static IEnumerator<TextBox> FindTextBoxes(Control rootControl)
{
foreach (Control control in rootControl.Controls)
{
if (control.Controls.Count > 0... | As the compiler is telling you, you need to change your return type to IEnumerable. That is how the yield return syntax works. | Just to clarify
```
private static IEnumerator<TextBox> FindTextBoxes(Control rootControl)
```
Changes to
```
private static IEnumerable<TextBox> FindTextBoxes(Control rootControl)
```
That should be all :-) | Can I have a method returning IEnumerator<T> and use it in a foreach loop? | [
"",
"c#",
"foreach",
"ienumerable",
"ienumerator",
""
] |
Have you used VS.NET Architect Edition's Application and System diagrams to start designing a solution?
If so, did you find it useful?
Did the "automatic implementation" feature work ok? | I used to use it a lot. This designer worked good for stubbing out prototype projects, but ultimately I found myself wasting a lot of time moving the mouse around when I could be typing. It seemed like an awesome idea to be able to print out the class diagrams to show APIs to other developers while I was prototyping, b... | Yes, and no, it's not very useful in my opinion. It's not very stable, it's easy to get out of sync, and the "look how fast I generate this" advantage is virtually nil when compared to more mundane things such as code snippets.
Then again, I am a total "Architect" luddite, so take this with a grain of salt. | VS.NET Application Diagrams | [
"",
"c#",
".net",
"visual-studio",
"architecture",
"diagram",
""
] |
I have always thought that the .equals() method in java should be overridden to be made specific to the class you have created. In other words to look for equivalence of two different instances rather than two references to the same instance. However I have encountered other programmers who seem to think that the defau... | Overriding the equals method is necessary if you want to test equivalence in standard library classes (for example, ensuring a java.util.Set contains unique elements or using objects as keys in java.util.Map objects).
Note, if you override equals, ensure you honour the API contract as described in the documentation. F... | I would highly recommend picking up a copy of Effective Java and reading through item 7 obeying the [equals contract](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html). You need to be careful if you are overriding equals for mutable objects, as many of the collections such as Maps and Sets use equals to de... | Overriding the equals method vs creating a new method | [
"",
"java",
"oop",
""
] |
What I have so far is
```
#!/bin/sh
php_syntax_check()
{
retval=0
for i in $(git-diff-index --name-only --cached HEAD -- | grep -e '\.php$'); do
if [ -f $i ]; then
output=$(php -l $i)
retval=$?
if [ $retval -gt 0 ]; then
echo "=======================... | If the commit is a partial commit (not all the changes in the working tree are committed), then this make give incorrect results since it tests the working copy and not the staged copy.
One way to do this could be:
```
git diff --cached --name-only --diff-filter=ACMR | xargs git checkout-index --prefix=$TMPDIR/ --
fi... | I'm sorry if it's offtopic, but aren't you supposed to run some kind of automated tests (which would imply that the code has no syntax errors) before doing a commit? | Is there a better way of writing a git pre-commit hook to check any php file in a commit for parse errors? | [
"",
"php",
"git",
"version-control",
""
] |
How can I set the background color of an HTML element using css in JavaScript? | In general, CSS properties are converted to JavaScript by making them camelCase without any dashes. So `background-color` becomes `backgroundColor`.
```
function setColor(element, color)
{
element.style.backgroundColor = color;
}
// where el is the concerned element
var el = document.getElementById('elementId');
... | You might find your code is more maintainable if you keep all your styles, etc. in CSS and just set / unset class names in JavaScript.
Your CSS would obviously be something like:
```
.highlight {
background:#ff00aa;
}
```
Then in JavaScript:
```
element.className = element.className === 'highlight' ? '' : 'high... | How to set background color of HTML element using css properties in JavaScript | [
"",
"javascript",
"css",
"background-color",
""
] |
I'm trying to improve performance under high load and would like to implement opcode caching. Which of the following should I use?
* APC - [Installation Guide](http://www.howtoforge.com/apc-php5-apache2-debian-etch)
* eAccelerator - [Installation Guide](http://www.howtoforge.com/eaccelerator_php5_debian_etch)
* XCache... | I think the answer might depend on the type of web applications you are running. I had to make this decision myself two years ago and couldn't decide between Zend Optimizer and eAccelerator.
In order to make my decision, I used ab (apache bench) to test the server, and tested the three combinations (zend, eaccelerator... | I have run several [benchmarks with eAcclerator, APC, XCache](http://blogs.interdose.com/dominik/2008/04/11/benchmarking-php-eaccelerator-und-andere-opcode-caches/), and Zend Optimizer (even though Zend is an optimizer, not a cache).
[Benchmark Results http://blogs.interdose.com/dominik/wp-content/uploads/2008/04/opco... | Which PHP opcode cacher should I use to improve performance? | [
"",
"php",
"performance",
"caching",
""
] |
I am working on a project right now that involves receiving a message from another application, formatting the contents of that message, and sending it to a printer. The technology of choice is C# windows service. The output could be called a report, I suppose, but a reporting engine is not necessary. A simple templati... | Trust me, you will spend more money trying to search/develop a solution for this as compared to buying a third party component. Do not reinvent the wheel and go for the paid solution.
Printing is a complex problem and I would love to see the day when better framework support is added for this. | Printing from a Windows service is really painful. It seems to work... sometimes... but finally it craches or throws an exception from time to time, without any clear reason. It's really hopeless. Officially, it's even [not supported](http://msdn.microsoft.com/en-us/library/system.drawing.printing(VS.80).aspx), without... | Printing from a .NET Service | [
"",
"c#",
".net",
"windows-services",
"printing",
""
] |
I'm using the .NETCF (Windows Mobile) `Graphics` class and the `DrawString()` method to render a single character to the screen.
The problem is that I can't seem to get it centred properly. No matter what I set for the Y coordinate of the location of the string render, it always comes out lower than that and the large... | Through a combination of the suggestions I got, I came up with this:
```
private void DrawLetter()
{
Graphics g = this.CreateGraphics();
float width = ((float)this.ClientRectangle.Width);
float height = ((float)this.ClientRectangle.Width);
float emSize = height;
Font ... | I'd like to add another vote for the StringFormat object.
You can use this simply to specify "center, center" and the text will be drawn centrally in the rectangle or points provided:
```
StringFormat format = new StringFormat();
format.LineAlignment = StringAlignment.Center;
format.Alignment = StringAlignment.Center;... | Center text output from Graphics.DrawString() | [
"",
"c#",
"graphics",
"compact-framework",
""
] |
I joined a new company about a month ago. The company is rather small in size and has pretty strong "start-up" feel to it. I'm working as a Java developer on a team of 3 others. The company primarily sells a service to for businesses/business-type people to use in communicating with each other.
One of the main things ... | Your best bet is probably to refactor it slowly as you go along. Few us of have the resources that would be required to completely start from scratch with something that has so many business rules buried in it. Management really hates it when you spend months on developing an app that has more bugs than the one you rep... | First pick up a copy of Michael Feather's Working [Effectively with Legacy Code](https://rads.stackoverflow.com/amzn/click/com/0131177052). Then identify how best to test the existing code. The worst case is that you are stuck with just some high level regression tests (or nothing at all) and If you are lucky there wil... | What is the best way to migrate an existing messy webapp to elegant MVC? | [
"",
"java",
"model-view-controller",
"jsp",
"architecture",
""
] |
Why does Visual Studio declare new classes as private in C#? I almost always switch them over to public, am I the crazy one? | Private access by default seems like a reasonable design choice on the part of the C# language specifiers.
A good general design principle is to make all access levels as restrictive as possible, to minimize dependencies. You are less likely to end up with the wrong access level if you start as restrictive as possible... | I am not sure WHY it does that, but here's what you do in order to get Visual Studio to create the class as Public by default:
Go over to “Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033″, you will find a file called Class.zip, inside the .zip file open the file called Class.cs, th... | VS.NET defaults to private class | [
"",
"c#",
"visual-studio",
""
] |
I was looking at the API documentation for stl vector, and noticed there was no method on the vector class that allowed the removal of an element with a certain value. This seems like a common operation, and it seems odd that there's no built in way to do this. | `std::remove` does not actually erase elements from the container: it overwrites the elements that should not be removed at the beginning of the container, and returns the iterator pointing to the next element after them. This iterator can be passed to `container_type::erase` to do the actual removal of the extra eleme... | If you want to remove ***an*** item, the following will be a bit more efficient.
```
std::vector<int> v;
auto it = std::find(v.begin(), v.end(), 5);
if(it != v.end())
v.erase(it);
```
or you may avoid overhead of moving the items if the order does not matter to you:
```
std::vector<int> v;
auto it = std::find... | How do I remove an item from a stl vector with a certain value? | [
"",
"c++",
"stl",
""
] |
I want to get the MD5 Hash of a string value in SQL Server 2005. I do this with the following command:
```
SELECT HashBytes('MD5', 'HelloWorld')
```
However, this returns a VarBinary instead of a VarChar value. If I attempt to convert `0x68E109F0F40CA72A15E05CC22786F8E6` into a VarChar I get `há ðô§*à\Â'†øæ` instead ... | I have found the solution else where:
```
SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', 'HelloWorld')), 3, 32)
``` | ```
SELECT CONVERT(NVARCHAR(32),HashBytes('MD5', 'Hello World'),2)
``` | Convert HashBytes to VarChar | [
"",
"sql",
"sql-server",
""
] |
I am a web-developer working in PHP. I have some limited experience with using Test Driven Development in C# desktop applications. In that case we used nUnit for the unit testing framework.
I would like to start using TDD in new projects but I'm really not sure where to begin.
What recommendations do you have for a P... | I've used both PHPUnit & **[SimpleTest](http://simpletest.org/)** and I found **SimpleTest** to be easier to use.
As far as TDD goes, I haven't had much luck with it in the purest sense. I think that's mainly a time/discipline issue on my part though.
Adding tests after the fact has been somewhat useful but my favori... | I highly recommend [Test-Driven Development by Kent Beck (ISBN-10: 0321146530)](https://rads.stackoverflow.com/amzn/click/com/0321146530). It wasn't written specifically for PHP, but the concepts are there and should be easily translatable to PHP. | Test Driven Development in PHP | [
"",
"php",
"unit-testing",
"tdd",
""
] |
Is there a Regular Expression that can detect SQL in a string? Does anyone have a sample of something that they have used before to share? | Don't do it. You're practically guaranteed to fail. Use `PreparedStatement` (or its equivalent) instead. | Use stored procedures or prepared statements. How will you detect something like this?
BTW **do NOT run this:**
```
DECLARE%20@S%20VARCHAR(4000);SET%20@S=CAST(0x4445434C415 245204054205641524348415228323535292C40432056415243
4841522832353529204445434C415245205461626C655 F437572736F7220435552534F5220464F52205345... | RegEx to Detect SQL Injection | [
"",
"sql",
"regex",
"sql-injection",
""
] |
I assume that you can't use a JavaScript code snippet to validate if the browser user has turned off JavaScript. So what can I use instead? Can someone offer a code sample?
I'm looking to wrap an if/then statement around it.
I often code in CFML, if that helps. | Are we talking about something like this:
JavaScript:
```
<body>
...
...
<script type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
<noscript>Your browser does not support JavaScript!</noscript>
...
...
</body>
``` | this is a total hack but you could use an iframe inside the noscript tag to trigger an HTTP GET on a url to tell the server that a user doesn't have javascript enabled.
```
<body>
...
...
<noscript>
<iframe src ="/nojs.aspx?SOMEIDENTIFIER=XXXX&NOJS=TRUE" style="display: none;">
</iframe>
</noscript>
...
...
</... | How do I know if Javascript has been turned off inside browser? | [
"",
"javascript",
"browser",
""
] |
The new extensions in .Net 3.5 allow functionality to be split out from interfaces.
For instance in .Net 2.0
```
public interface IHaveChildren {
string ParentType { get; }
int ParentId { get; }
List<IChild> GetChildren()
}
```
Can (in 3.5) become:
```
public interface IHaveChildren {
string Parent... | I think the judicious use of extension methods put interfaces on a more equatable position with (abstract) base classes.
**Versioning.** One advantage base classes have over interfaces is that you can easily add new virtual members in a later version, whereas adding members to an interface will break implementers buil... | Extension methods should be used as just that: extensions. Any crucial structure/design related code or non-trivial operation should be put in an object that is composed into/inherited from a class or interface.
Once another object tries to use the extended one, they won't see the extensions and might have to reimplem... | Extension interface patterns | [
"",
"c#",
".net-3.5",
"extension-methods",
""
] |
I can set the PHP include path in the `php.ini`:
```
include_path = /path/to/site/includes/
```
But then other websites are affected so that is no good.
I can set the PHP include in the start of every file:
```
$path = '/path/to/site/includes/';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
```
Bu... | If you're using apache as a webserver you can override (if you allow it) settings using *.htaccess* files. See [the PHP manual](https://www.php.net/configuration.changes) for details.
Basically you put a file called *.htaccess* in your website root, which contains some PHP `ini` values. Provided you configured Apache ... | Erik Van Brakel gave, IMHO, one of the best answers.
More, if you're using Apache & Virtual hosts, you can set up includes directly in them. Using this method, you won't have to remember to leave php\_admin commands in your .htaccess. | Setting PHP Include Path on a per site basis? | [
"",
"php",
"include",
""
] |
I'm still new to the ASP.NET world, so I could be way off base here, but so far this is to the best of my (limited) knowledge!
Let's say I have a standard business object "Contact" in the *Business* namespace. I write a Web Service to retrieve a Contact's info from a database and return it. I then write a client appli... | You are on the right track. To get the data from the proxy object back into one of your own objects, you have to do left-hand-right-hand code. i.e. copy property values. I'll bet you that there is already a generic method out there that uses reflection.
Some people will use something other than a web service (.net rem... | You don't actually have to use the generated class that the WSDL gives you. If you take a look at the code that it generates, it's just making calls into some .NET framework classes to submit SOAP requests. In the past I have copied that code into a normal .cs file and edited it. Although I haven't tried this specifica... | ASP.NET Web Service Results, Proxy Classes and Type Conversion | [
"",
"c#",
"asp.net",
"web-services",
""
] |
I'm interested in learning some (ideally) database agnostic ways of selecting the *n*th row from a database table. It would also be interesting to see how this can be achieved using the native functionality of the following databases:
* SQL Server
* MySQL
* PostgreSQL
* SQLite
* Oracle
I am currently doing something ... | There are ways of doing this in optional parts of the standard, but a lot of databases support their own way of doing it.
A really good site that talks about this and other things is <http://troels.arvin.dk/db/rdbms/#select-limit>.
Basically, PostgreSQL and MySQL supports the non-standard:
```
SELECT...
LIMIT y OFFS... | PostgreSQL supports [windowing functions](https://www.postgresql.org/docs/current/tutorial-window.html) as defined by the SQL standard, but they're awkward, so most people use (the non-standard) [`LIMIT` / `OFFSET`](http://www.postgresql.org/docs/current/static/queries-limit.html):
```
SELECT
*
FROM
mytable
OR... | How to select the nth row in a SQL database table? | [
"",
"mysql",
"sql",
"database",
"oracle",
"postgresql",
""
] |
I am using a class library which represents some of its configuration in .xml. The configuration is read in using the `XmlSerializer`. Fortunately, the classes which represent the .xml use the `XmlAnyElement` attribute at which allows me to extend the configuration data for my own purposes without modifying the origina... | So you need to have your class contain custom configuration information, then serialize that class to XML, then make that serialized XML into an XML node: is that right?
Could you just take the string created by the XMLSerializer and wrap that in it's own XML tags?
```
XmlSerializer xs = new XmlSerializer(typeof(MyCo... | It took a bit of work, but the XPathNavigator route does work... just remember to call .Close on the XmlWriter, .Flush() doesn't do anything:
```
//DataContractSerializer serializer = new DataContractSerializer(typeof(foo));
XmlSerializer serializer = new XmlSerializer(typeof(foo));
XmlDocument doc = new XmlDocument(... | How do I create an XmlNode from a call to XmlSerializer.Serialize? | [
"",
"c#",
"xml",
""
] |
What is a good way to remove the code from display pages when developing with PHP. Often the pages I work on need to be editted by an outside person. This person is often confused by lots of blocks of PHP, and also likes to break my code.
I've tried moving blocks of code out into functions, so now there are functions ... | You don't need a "system" to do templating.
You can do it on your own by keeping presentation & logic separate.
This way the designer can screw up the display, but not the logic behind it.
Here's a simple example:
```
<?php
$people = array('derek','joel','jeff');
$people[0] = 'martin'; // all your logic goes here
in... | Take a look at how some of the popular PHP frameworks use templating. Examples include cakePHP, Zend Framework, and Code Igniter. Even if you are not going to base your site on these frameworks, the template design pattern is a good way to keep php code away from your web designers, so they can focus on layout and not ... | PHP best practices? | [
"",
"php",
""
] |
Is there any way, in any language, to hook my program when a user renames a file?
For example:
A user renames a file and presses enter (or clicks away) to confirm the rename action. BEFORE the file is actually renamed, my program "listens" to this event and pops up a message saying "Are you sure you want to rename C:\... | You can probably solve this by using the [FileSystemWatcher class](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx) in .NET framework.
From the class remarks:
> You can watch for renaming, deletion,
> or creation of files or directories.
> For example, to watch for renaming of
> text files, s... | My guess is that this is *not* possible, I did find [this](http://msdn.microsoft.com/en-us/library/bb776794(VS.85).aspx) which is for monitoring operations (including rename) on a folder, but there does not appear to be a similar method for files.
@Richard, FileSystemWatcher is good if you only need to monitor changes... | Hooking my program with windows explorer's rename event | [
"",
"c#",
".net",
"file",
"io",
""
] |
My current preferred C++ environment is the free and largely excellent Microsoft Visual Studio 2005 Express edition. From time to time I have sent release .exe files to other people with pleasing results. However recently I made the disturbing discovery that the pleasing results were based on more luck that I would lik... | For the C-runtime go to the project settings, choose C/C++ then 'Code Generation'. Change the 'runtime library' setting to 'multithreaded' instead of 'multithreaded dll'.
If you are using any other libraries you may need to tell the linker to ignore the dynamically linked CRT explicitly. | My experience in Visual Studio 2010 is that there are two changes needed so as to not need DLL's. From the project property page (right click on the project name in the Solution Explorer window):
1. Under Configuration Properties --> General, change the "Use of MFC" field to "Use MFC in a Static Library".
2. Under Con... | How do I make a fully statically linked .exe with Visual Studio Express 2005? | [
"",
"c++",
"visual-studio",
"linker",
""
] |
Instead of writing my ASP.NET C# applications in Visual Studio, I used my favorite text editor UltraEdit32.
Is there any way I can implement MVC without the use of VS? | There is nothing VS specific with the MVC framework - it is just a bunch of DLLs that you can use. The wizards in VS just build you a quick-start framework.
ASP.NET MVC is "bin-deployable" - there is nothing too clever to set up on the server either - just point the wildcard ISAPI filter to ASP.NET | Assuming you have the correct assemblies and a C# compiler you in theory can use whatever you want to edit the code and then just run the compiler by hand or using a build script. That being said it is a real pain doing .NET development without Visual Studio/SharpEdit/Monodevelop in my opinion. | Developing for ASP.NET-MVC without Visual Studio | [
"",
"c#",
"asp.net-mvc",
"visual-studio",
""
] |
Is there a way to create a `JButton` with your own button graphic and not just with an image inside the button?
If not, is there another way to create a custom `JButton` in java? | When I was first learning Java we had to make Yahtzee and I thought it would be cool to create custom Swing components and containers instead of just drawing everything on one `JPanel`. The benefit of extending `Swing` components, of course, is to have the ability to add support for keyboard shortcuts and other accessi... | Yes, this is possible. One of the main pros for using Swing is the ease with which the abstract controls can be created and manipulates.
Here is a quick and dirty way to extend the existing JButton class to draw a circle to the right of the text.
```
package test;
import java.awt.Color;
import java.awt.Container;
im... | Creating a custom JButton in Java | [
"",
"java",
"swing",
"jbutton",
""
] |
The following **C++** code uses a **ifstream** object to read integers from a text file (which has one number per line) until it hits **EOF**. Why does it read the integer on the last line twice? How to fix this?
**Code:**
```
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream iFil... | Just follow closely the chain of events.
* Grab 10
* Grab 20
* Grab 30
* Grab EOF
Look at the second-to-last iteration. You grabbed 30, then carried on to check for EOF. You haven't reached EOF because the EOF mark hasn't been read yet ("binarically" speaking, its conceptual location is just after the 30 line). There... | I like this example, which for now, leaves out the check which you could add inside the while block:
```
ifstream iFile("input.txt"); // input.txt has integers, one per line
int x;
while (iFile >> x)
{
cerr << x << endl;
}
```
Not sure how safe it is... | Reading from text file until EOF repeats last line | [
"",
"c++",
"iostream",
"fstream",
""
] |
I am getting C++ Compiler error C2371 when I include a header file that itself includes odbcss.h. My project is set to MBCS.
> C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\odbcss.h(430) :
> error C2371: 'WCHAR' : redefinition; different basic types 1>
> C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\... | This is a known bug - see the Microsoft Connect website:
<http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98699>
The error doesn't occur if you compile your app as Unicode instead of MBCS. | There are a half-dozen posts on various forums around the web about this - it seems to potentially be an issue when odbcss.h is used in the presence of MFC. Most of the answers involve changing the order of included headers (voodoo debugging). The header that includes odbcss.h compiles fine in it's native project, but ... | C++ Compiler Error C2371 - Redefinition of WCHAR | [
"",
"c++",
"visual-studio",
""
] |
I'm in the process of weeding out all hardcoded values in a Java library and was wondering what framework would be the best (in terms of zero- or close-to-zero configuration) to handle run-time configuration? I would prefer XML-based configuration files, but it's not essential.
Please do only reply if you have practic... | If your hardcoded values are just simple key-value pairs, you should look at [java.util.Properties](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Properties.html). It's a lot simpler than xml, easier to use, and mind-numbingly trivial to implement.
If you are working with Java and the data you are storing or retri... | [Apache Commons Configuration](http://commons.apache.org/configuration/) works great. It supports having the configuration stored in a wide range of formats on the backend including properties, XML, JNDI, and more. It is easy to use and to extend. To get the most flexibility out of it use a [factory](http://en.wikipedi... | Java configuration framework | [
"",
"java",
"xml",
"configuration",
"frameworks",
"configurationmanager",
""
] |
I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them. | [Closure on closures](http://mrevelle.blogspot.com/2006/10/closure-on-closures.html)
> Objects are data with methods
> attached, closures are functions with
> data attached.
```
def make_counter():
i = 0
def counter(): # counter() is a closure
nonlocal i
i += 1
return i
return coun... | It's simple: A function that references variables from a containing scope, potentially after flow-of-control has left that scope. That last bit is very useful:
```
>>> def makeConstantAdder(x):
... constant = x
... def adder(y):
... return y + constant
... return adder
...
>>> f = makeConstantAdde... | Can you explain closures (as they relate to Python)? | [
"",
"python",
"functional-programming",
"closures",
""
] |
.NET Framework: 2.0
Preferred Language: C#
I am new to TDD (Test Driven Development).
First of all, is it even possible to unit test Windows Service?
Windows service class is derived from ServiceBase, which has overridable methods,
1. OnStart
2. OnStop
How can I trigger those methods to be called as if unit test i... | I'd probably recommend designing your app so the "OnStart" and "OnStop" overrides in the Windows Service just call methods on a class library assembly. That way you can automate unit tests against the class library methods, and the design also abstracts your business logic from the implementation of a Windows Service.
... | I have unit tested windows services by not testing the service directly, but rather testing what the service does.
Typically I create one assembly for the service and another for what the service does. Then I write unit tests against the second assembly.
The nice thing about this approach is that your service is very... | How can I unit test a Windows Service? | [
"",
"c#",
".net",
"unit-testing",
"windows-services",
""
] |
I would like to be able to use the `Tab` key within a text box to tab over four spaces. The way it is now, the Tab key jumps my cursor to the next input.
Is there some JavaScript that will capture the Tab key in the text box before it bubbles up to the UI?
I understand some browsers (i.e. FireFox) may not allow this.... | Even if you capture the `keydown`/`keyup` event, those are the only events that the tab key fires, you still need some way to prevent the default action, moving to the next item in the tab order, from occurring.
In Firefox you can call the `preventDefault()` method on the event object passed to your event handler. In ... | I'd rather tab indentation not work than breaking tabbing between form items.
If you want to indent to put in code in the Markdown box, use `Ctrl`+`K` (or ⌘K on a Mac).
In terms of actually stopping the action, jQuery (which Stack Overflow uses) will stop an event from bubbling when you return false from an event cal... | Capturing TAB key in text box | [
"",
"javascript",
"user-interface",
""
] |
I know that we can get the MAC address of a user via IE (ActiveX objects).
Is there a way to obtain a user's MAC address using JavaScript? | I concur with all the previous answers that it would be a privacy/security vulnerability if you would be able to do this directly from Javascript. There are two things I can think of:
* Using Java (with a signed applet)
* Using signed Javascript, which in FF (and Mozilla in general) gets higher privileges than normal ... | The quick and simple answer is No.
Javascript is quite a high level language and does not have access to this sort of information. | MAC addresses in JavaScript | [
"",
"javascript",
"mac-address",
""
] |
Is there a programmatic way to build *htpasswd* files, without depending on OS specific functions (i.e. `exec()`, `passthru()`)? | .httpasswd files are just text files with a specific format depending on the hash function specified. If you are using MD5 they look like this:
```
foo:$apr1$y1cXxW5l$3vapv2yyCXaYz8zGoXj241
```
That's the login, a colon, ,$apr1$, the salt and 1000 times md5 encoded as base64. If you select SHA1 they look like this:
... | From what it says on the PHP website, you can use crypt() in the following method:
```
<?php
// Set the password & username
$username = 'user';
$password = 'mypassword';
// Get the hash, letting the salt be automatically generated
$hash = crypt($password);
// write to a file
file_set_contents('.htpasswd', $username... | Programmatically building htpasswd | [
"",
"php",
"automation",
".htpasswd",
""
] |
I have a script that retrieves objects from a remote server through an Ajax call. The server returns objects in JSON notation.... | You can find a [JSON parser written in JavaScript here](http://www.JSON.org/js.html) ([source code here](https://github.com/douglascrockford/JSON-js/blob/master/json2.js)). You can also use the as3corelib JSON parser from JavaScript, there's [a description of how to access ActionScript libraries from JavaScript here](h... | The current AIR release (v2.5) bundles a newer WebKit that has native JSON support, via JSON.stringify() and JSON.parse(). | Adobe AIR: Handling JSON objects from server | [
"",
"javascript",
"ajax",
"json",
"air",
""
] |
I have one field that I need to sum lets say named items
However that field can be part of group a or b
In the end I need to have all of the items summed for group a and group b
when I say grouped I mean there is a LEFT OUTER JOIN to another table the previous table has a type for the items and the one being joined ha... | Maybe I'm not understanding the complexity of what you're asking but... shouldn't this do?
```
SELECT groupname, SUM(value)
FROM items
WHERE groupname IN ('a', 'b')
GROUP BY groupname
```
And if you don't care which of a or b the item belongs to then this will do:
```
SELECT SUM(value)
FROM items
WHERE groupname IN ... | You want something like
```
SELECT column,SUM( column ) FROM table GROUP BY column
``` | Returning the sum of items depending on which type it is | [
"",
"sql",
"sql-server",
""
] |
I haven't used `C++` since college. Even though I've wanted to I haven't needed to do any until I started wanting to write plugins for `Launchy`.
> Is there a good book to read to get back into it?
My experience since college is mainly `C#` and recently `ruby`. I bought some book for `C#` developers and it ended up b... | The best way to get back into C++ is to jump in. You can't learn a real language without spending any serious time in a country where they speak it. I wouldn't try to learn a programming language without spending time coding in it either.
I wouldn't recommend learning C first though. That's a good way to pick up some ... | My favorites are Effective C++, More Effective C++, and Effective STL by Scott Meyers. Also C++ Coding Standards by Sutter and Alexandrescu. | Get back to basics. How do I get back into C++? | [
"",
"c++",
""
] |
I searched for this subject on Google and got some website about an experts exchange...so I figured I should just ask here instead.
How do you embed a `JApplet` in HTML on a webpage? | Here is an example from [sun's website](http://java.sun.com/docs/books/tutorial/uiswing/components/applet.html):
```
<applet code="TumbleItem.class"
codebase="examples/"
archive="tumbleClasses.jar, tumbleImages.jar"
width="600" height="95">
<param name="maxwidth" value="120">
<param na... | Although you didn't say so, just in case you were using JSPs, you also have the option of the [jsp:plugin](http://java.sun.com/products/jsp/tags/syntaxref.fm12.html) tag? | Java: JApplet, How do you embed it in a webpage? | [
"",
"java",
"html",
"web-applications",
""
] |
I'm going to guess that the answer is "no" based on the below error message (and [this Google result](http://archives.postgresql.org/pgsql-sql/2004-08/msg00076.php)), but is there anyway to perform a cross-database query using PostgreSQL?
```
databaseA=# select * from databaseB.public.someTableName;
ERROR: cross-data... | *Note: As the original asker implied, if you are setting up two databases on the same machine you probably want to make two [schemas](https://www.postgresql.org/docs/current/static/ddl-schemas.html) instead - in that case you don't need anything special to query across them.*
## `postgres_fdw`
Use [`postgres_fdw`](ht... | # [dblink()](http://www.postgresql.org/docs/current/interactive/dblink.html) -- executes a query in a remote database
> dblink executes a query (usually a SELECT, but it can be any SQL
> statement that returns rows) in a remote database.
>
> When two text arguments are given, the first one is first looked up as
> a pe... | Possible to perform cross-database queries with PostgreSQL? | [
"",
"sql",
"postgresql",
""
] |
Why are SQL distributions so non-standard despite an ANSI standard existing for SQL? Are there really that many meaningful differences in the way SQL databases work or is it just the two databases with which I have been working: MS-SQL and PostgreSQL? Why do these differences arise? | It's a form of "Stealth lock-in". Joel goes into great detail here:
* <http://www.joelonsoftware.com/articles/fog0000000056.html>
* <http://www.joelonsoftware.com/articles/fog0000000052.html>
Companies end up tying their business functionality to non-standard or weird unsupported functionality in their implementation... | The ANSI standard specifies only a limited set of commands and data types. Once you go beyond those, the implementors are on their own. And some very important concepts aren't specified at all, such as auto-incrementing columns. SQLite just picks the first non-null integer, MySQL requires `AUTO INCREMENT`, PostgreSQL u... | Reasons for SQL differences | [
"",
"sql",
"sql-server",
"postgresql",
""
] |
I've used the StAX API in Java quite a bit, and find it quite a clean way of dealing with XML files. Is there any equivalent library I could use for performing similar processing in C? | [libxml](http://xmlsoft.org/) is a heavily used and documented XML library for C, which provides a SAX API. [Expat](http://expat.sourceforge.net/) is another, but in my experience is not as well documented. | I have used Expat pretty extensively - I like it for its simplicity and small footprint. | Equivalent to StAX for C | [
"",
"java",
"c",
"xml",
""
] |
Does anyone have the secret formula to resizing transparent images (mainly GIFs) *without* ANY quality loss - what so ever?
I've tried a bunch of stuff, the closest I get is not good enough.
Take a look at my main image:
<http://www.thewallcompany.dk/test/main.gif>
And then the scaled image:
<http://www.thewallcom... | If there's no requirement on preserving file type after scaling I'd recommend the following approach.
```
using (Image src = Image.FromFile("main.gif"))
using (Bitmap dst = new Bitmap(100, 129))
using (Graphics g = Graphics.FromImage(dst))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = Interp... | This is a basic resize function I've used for a few of my applications that leverages GDI+
```
/// <summary>
/// Resize image with GDI+ so that image is nice and clear with required size.
/// </summary>
/// <param name="SourceImage">Image to resize</param>
/// <param name="NewHeight">New height to resize to.</param... | Resize transparent images using C# | [
"",
"c#",
".net",
"image",
"resize",
"image-scaling",
""
] |
I use Firebug and the Mozilla JS console heavily, but every now and then I run into an IE-only JavaScript bug, which is really hard to locate (ex: *error on line 724*, when the source HTML only has 200 lines).
I would love to have a lightweight JS tool (*a la* firebug) for Internet Explorer, something I can install in... | You might find [Firebug Lite](http://getfirebug.com/lite.html) useful for that.
Its bookmarklet should be especially useful when debugging on a user's machine. | Since Internet Explorer 8, IE has been shipping with a pretty impressive set of tools for JavaScript debugging, profiling, and more. Like most other browsers, the developer tools are accessible by pressing F12 on your keyboard.
### Script Tab
The Script tab is likely what you'll be interested in, though the Console, ... | JavaScript Troubleshooting Tools in Internet Explorer | [
"",
"javascript",
"internet-explorer",
"debugging",
""
] |
If I use `assert()` and the assertion fails then `assert()` will call `abort()`, ending the running program abruptly. I can't afford that in my production code. Is there a way to assert in runtime yet be able to catch failed assertions so I have the chance to handle them gracefully? | Yes, as a matter of fact there is. You will need to write a custom assert function yourself, as C++'s `assert()` is exactly C's `assert()`, with the `abort()` "feature" bundled in. Fortunately, this is surprisingly straightforward.
*Assert.hh*
```
template <typename X, typename A>
inline void Assert(A assertion)
{
... | [glib's error reporting functions](http://library.gnome.org/devel/glib/unstable/glib-Warnings-and-Assertions.html "glib documentation for error reporting functions") take the approach of continuing after an assert. glib is the underlying platform independence library that Gnome (via GTK) uses. Here's a macro that check... | How can I assert() without using abort()? | [
"",
"c++",
"exception",
"assert",
""
] |
Below I have a very simple example of what I'm trying to do. I want to be able to use HTMLDecorator with any other class. Ignore the fact it's called decorator, it's just a name.
```
import cgi
class ClassX(object):
pass # ... with own __repr__
class ClassY(object):
pass # ... with own __repr__
inst_x=ClassX()
... | > Very close, but then I lose everything from ClassX. Below is something a collegue gave me that does do the trick, but it's hideous. There has to be a better way.
Looks like you're trying to set up some sort of proxy object scheme. That's doable, and there are better solutions than your colleague's, but first conside... | Both of John's solutions would work. Another option that allows HTMLDecorator to remain very simple and clean is to monkey-patch it in as a base class. This also works only for user-defined classes, not builtin types:
```
import cgi
class ClassX(object):
pass # ... with own __repr__
class ClassY(object):
pas... | How can I simply inherit methods from an existing instance? | [
"",
"python",
"oop",
"inheritance",
"object",
""
] |
Because regular expressions scare me, I'm trying to find a way to remove all HTML tags and resolve HTML entities from a string in Python. | Use [lxml](http://lxml.de/) which is the best xml/html library for python.
```
import lxml.html
t = lxml.html.fromstring("...")
t.text_content()
```
And if you just want to sanitize the html look at the lxml.html.clean [module](http://lxml.de/lxmlhtml.html#cleaning-up-html) | Use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/)! It's perfect for this, where you have incoming markup of dubious virtue and need to get something reasonable out of it. Just pass in the original text, extract all the string tags, and join them. | Filter out HTML tags and resolve entities in python | [
"",
"python",
"html",
""
] |
What is the quickest way to get a large amount of data (think golf) and the most efficient (think performance) to get a large amount of data from a MySQL database to a session without having to continue doing what I already have:
```
$sql = "SELECT * FROM users WHERE username='" . mysql_escape_string($_POST['username'... | I came up with this and it appears to work.
```
while($row = mysql_fetch_assoc($result))
{
$_SESSION = array_merge_recursive($_SESSION, $row);
}
``` | Most efficient:
```
$get = mysql_query("SELECT * FROM table_name WHERE field_name=$something") or die(mysql_error());
$_SESSION['data'] = mysql_fetch_assoc($get);
```
Done.
This is now stored in an array. So say a field is username you just do:
```
echo $_SESSION['data']['username'];
```
Data is the name of the a... | Most efficient way to get data from the database to session | [
"",
"php",
"mysql",
"session",
""
] |
Do you use ILMerge? Do you use ILMerge to merge multiple assemblies to ease deployment of dll's? Have you found problems with deployment/versioning in production after ILMerging assemblies together?
I'm looking for some advice in regards to using ILMerge to reduce deployment friction, if that is even possible. | I use ILMerge for almost all of my different applications. I have it integrated right into the release build process so what I end up with is one exe per application with no extra dll's.
You can't ILMerge any C++ assemblies that have native code.
You also can't ILMerge any assemblies that contain XAML for WPF (at leas... | ## Introduction
This post shows how to replace all `.exe + .dll files` with a single `combined .exe`. It also keeps the debugging `.pdb` file intact.
## For Console Apps
Here is the basic `Post Build String` for Visual Studio 2010 SP1, using .NET 4.0. I am building a console .exe with all of the sub-.dll files inclu... | ILMerge Best Practices | [
"",
"c#",
".net",
"deployment",
"ilmerge",
""
] |
Before you answer this I have never developed anything popular enough to attain high server loads. Treat me as (sigh) an alien that has just landed on the planet, albeit one that knows PHP and a few optimisation techniques.
---
I'm developing a tool in **PHP** that could attain quite a lot of users, if it works out r... | No two sites are alike. You really need to get a tool like [jmeter](http://jakarta.apache.org/jmeter/) and benchmark to see where your problem points will be. You can spend a lot of time guessing and improving, but you won't see real results until you measure and compare your changes.
For example, for many years, the ... | I'm a lead developer on a site with over 15M users. We have had very little scaling problems because we planned for it EARLY and scaled thoughtfully. Here are some of the strategies I can suggest from my experience.
**SCHEMA**
First off, denormalize your schemas. This means that rather than to have multiple relational... | Tactics for using PHP in a high-load site | [
"",
"php",
"performance",
"high-load",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.