Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
For our school project, we are tasked to define a design document describing the architecture of a PHP application.
We are free te decide what to include in the document.
Our professor suggested, lots of (UML) diagrams.
He also asked us to consider class diagrams, but with care, as PHP is not fully object oriented.
... | IMHO it's pretty difficult to describe the architecture of any application without knowing what the application is supposed to do. All applications (PHP or otherwise) of any complexity look different.
Secondly, PHP5 gives you classes/objects and the usual plethora of OO gubbings - so to describe it as 'not fully objec... | PHP can nowadays be described as fully object oriented by choice. It offers everything you need but you are not forced to write OO code.
There are two books which helped me a lot in understanding the OO principles in relation to PHP:
* PHP in Action (Manning)
* Zend Study Guide for PHP5 (Zend) | Object Oriented design for PHP application | [
"",
"php",
"oop",
""
] |
I'm trying to run PHPDocumentor on my WAMPServer setup. It runs fine, but I'd like to exclude certain directories, such as \sqlbuddy\ which don't contain my own code. Ironically, PHPDocumentor appears to be ignoring my --ignore switch. I've tried several ways of expressing the same thing, but with the same result. Belo... | Which version of phpDocumentor are you using?
Because the [phpDocumentor 1.4.2 release notes](http://phpdoc.org/news.php?id=57) states:
> This release fixes two
> Windows-specific bugs, one involving
> usage of the "--ignore" option, and
> one involving usage of the @filesource
> tag. | I had the same problem, but different cause: ignoring more than one directory requires passing a comma-separated list i.e:
`--ignore sqlbuddy/,docs/` | Unable to exclude directories from PHPDocumentor | [
"",
"php",
"documentation",
"phpdoc",
""
] |
I have a big red button and I'm trying to use javascript to perform the following: -
1. OnMouseDown change image so the button looks depressed
2. OnMouseUp return to the initial image AND reveal a hidden div
I can get the onMouse Down and onMouseUp image changes part to work.
I can also get the hidden div to reveal ... | You can use semicolons to separate multiple script statements in an event:
```
<img src="..." alt="..."
onmousedown="depressed();"
onmouseup="undepressed(); revealDiv();" />
```
Also, I believe most browsers support the onclick event:
```
<img src="..." alt="..."
onmousedown="depressed();"
onmouseup="undepre... | It's never recommended to attach events to elements using the attribute notation directly to an html element's tag.
It is a **much better practice to seperate the view (being the rendered html) from the controller (the actions happening)**
The best way to attach an event is like such:
```
<img id="abut" />
<script>... | Javascript button click + reveal | [
"",
"javascript",
"onclick",
"onmousedown",
"onmouseup",
""
] |
I am using Eclipse IDE with few plug-ins for PHP dev. I am using PHPEclipse plug-in and I know there are lotsa other plugins like EasyEclipse.But is there an IDE like Visual Studio with cool drag and drop stuff for PHP? | I use APTANA.
You can get it here <http://www.aptana.com/>
It's my web IDE of choice. | If you're on Windows you might want to take a look at the (somewhat unfortunately named) "[Delphi for PHP](http://www.codegear.com/products/delphi/php)" from CodeGear / Emabarcadero which I hear mostly good things about - at least for new development that is as it's rather closely tied to a specific framework ([VCL for... | Is there any IDE for fast drag and drop php development? | [
"",
"php",
"ide",
""
] |
I've done a lot of research on this,but I'm unable to solve this problem. I've got a Div with several Divs within it that I want to hide before switching on a TinyMCE instance.
I'm doing this via jQuery -
```
$(".drop").hide()
```
This works fine, and every browser engine except Trident (IE) hides them. If I inspect... | This is because inside an editable element IE makes everything, including elements hidden with display: none, editable. There's nothing you can do about it except remove the elements you wish to hide from the page's DOM.
There's a reference to this behaviour of IE here: <http://msdn.microsoft.com/en-us/library/aa77002... | You could try applying a style that sets the display to something other than none, for example:
```
.drop
{
display: block; // or inline
}
```
This sounds like its being caused by IE's need for the element to "have layout" in order to do certain operations on it, hiding being one of them. Elements given a display... | IE designMode Showing display:none Divs | [
"",
"javascript",
"jquery",
"internet-explorer",
"tinymce",
"designmode",
""
] |
I recently read a question on here about static and dynamic linking, which reminded me of some questions I've had about it. From that post, I can see what the technical difference is (including object file contents directly instead of merely pointing to it), but I'd like to know a bit more about the pros/cons of doing ... | I am not sure if static linking is a really good idea in C# to be honest, for a million reasons. One reason is that, as opposed to languages like C or C++, C# has the concept of assemblies, which are basically executable files or DLLs.
Now if you want link things statically in .NET, you either
* Merge classes from mu... | The advantage of static linking is that it removes external dependency on libraries - i.e. the behaviour of the library you're using is never going to change because someone changed the libraryon the disk. That's also one of the disadvantages of static linking; if the OS changes and a new version of the library is need... | Static linking advantages | [
"",
"c#",
"linker",
""
] |
What's pros and cons of using Enterprise Library Unity vs other IoC containers (Windsor, Spring.Net, Autofac ..)? | I am preparing a presentation for a usergroup. As such I just went through a bunch of them. Namely: AutoFac, MEF, Ninject, Spring.Net, StructureMap, Unity, and Windsor.
I wanted to show off the 90% case (constructor injection, which is mainly what people use an IOC for anyway).
[You can check out the solution here (VS... | As far as I've seen they are pretty much the same, except for a few implementation details here and there. The biggest advantage that Unity has over the competition is that it is provided by Microsoft, there are lots of companies out there that are afraid of OSS.
One disadvantage is that it's rather new so it might ha... | Enterprise Library Unity vs Other IoC Containers | [
"",
"c#",
".net",
"inversion-of-control",
"unity-container",
"enterprise-library",
""
] |
I have read the following properties from AD,
```
TerminalServicesProfilePath
TerminalServicesHomeDirectory
TerminalServicesHomeDrive
```
I've tried DirectoryEntry and DirectorySearcher. But they does not include the properties.
I found some example in vbscript and VC to read them.
However I failed to make it workin... | I don't remember exactly, but it's something like this:
```
//user is a DirectoryEntry
IADsTSUserEx adsiUser = (IADsTSUserEx)user.NativeObject;
```
then you can get the TerminalServices properties you want via adsiUser.
From my experience you're better off developing on a Windows Server with access to AD due to the ... | I think you can use the `InvokeGet` method on your `DirectoryEntry`, passing in the name of the property you want to read.
*2008-12-10 11:50 CET — Edited in response to the comment*
If I specify a garbage property name, I get the same COM exception. Are you sure the properties you're trying to retrieve are part of th... | How to read TermainsServices IADsTSUserEx Property from LDAP in C#? | [
"",
"c#",
"ldap",
"c#-2.0",
"terminal-services",
"iadstsuserex",
""
] |
Sorry about the vague subject but I couldn't think what to put.
Here's my problem, I'm doing a query on a table that returns me a count of items related to a day. I want to make sure that if I do a query on the DB, I always get a set number of rows. For example, imagine I have the following table that contains a log o... | > I imagine I could do this if I set up a table containing all the dates in a year and then using a left/right join but that's really messy way of doing it.
Nope. That's pretty much how to do it. On the other hand, you can use a temporary table and populate it with just the date range required.
If only MS SQL had vir... | To do this you would need to write a stored procedure that returns a table result.
It would use a loop that would step thru each day and get the count and store it in a row of a temp table, then return that table as the resultset.
Here is a MS SQL server example of a loop:
<http://www.databasejournal.com/features/ms... | Filling In The Blanks On A SQL Query | [
"",
"sql",
"mysql",
""
] |
Is there local file manipulation that's been done with JavaScript? I'm looking for a solution that can be accomplished with no install footprint like requiring [Adobe AIR](http://en.wikipedia.org/wiki/Adobe_Integrated_Runtime).
Specifically, I'd like to read the contents from a file and write those contents to another... | If the user selects a file via `<input type="file">`, you can [read](https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications) and [process](http://www.html5rocks.com/en/tutorials/file/dndfiles/) that file using the [File API](https://www.w3.org/TR/FileAPI/).
Reading or writing arbitrary files is not... | Just an update of the HTML5 features is in <http://www.html5rocks.com/en/tutorials/file/dndfiles/>. This excellent article will explain in detail the local file access in JavaScript. Summary from the mentioned article:
The specification provides several interfaces for [accessing files from a 'local' filesystem](http:/... | Local file access with JavaScript | [
"",
"javascript",
"file-access",
""
] |
If I have a few UNION Statements as a contrived example:
```
SELECT * FROM xxx WHERE z = 1
UNION
SELECT * FROM xxx WHERE z = 2
UNION
SELECT * FROM xxx WHERE z = 3
```
**What is the default `order by` behaviour?**
The test data I'm seeing essentially does not return the data in the order that is specified above. I.e... | There is no default order.
Without an **Order By** clause the order returned is undefined. That means SQL Server can bring them back in any order it likes.
EDIT:
Based on what I have seen, without an Order By, the order that the results come back in depends on the query plan. So if there is an index that it is using,... | In regards to adding an ORDER BY clause:
This is probably elementary to most here but I thought I add this.
Sometimes you don't want the results mixed, so you want the first query's results then the second and so on. To do that I just add a dummy first column and order by that. Because of possible issues with forgetti... | SQL Server UNION - What is the default ORDER BY Behaviour | [
"",
"sql",
"sql-server",
"union",
"sql-order-by",
""
] |
Having read up on quite a few articles on Artificial Life (A subject I find very interesting) along with several questions right here on SO, I've begun to toy with the idea of designing a (Very, very, very) simple simulator. No graphics required, even. If I've overlooked a question, please feel free to point it out to ... | If you were doing this as a hard-core development project, I'd suggest using the equivalent of Java reflection (substitute the language of your choice there). If you want to do a toy project as a starter effort, I'd suggest at least rolling your own simple version of reflection, per the following rationale.
Each artif... | To the first question:
My understanding is that you have one-to-possibly-many relationship. So yes, a multimap seems appropriate to me.
To the second question:
Yes, I believe a generic interface for objects is appropriate. Perhaps use something similar to [REST](http://en.wikipedia.org/wiki/REST) to manipulate objec... | Efficient Methods for a Life Simulation | [
"",
"c++",
"performance",
"artificial-life",
""
] |
I have been programming in Java since 2004, mostly enterprise and web applications. But I have never used *short* or *byte*, other than a toy program just to know how these types work. Even in a *for loop* of 100 times, we usually go with *int*. And I don't remember if I have ever came across any code which made use of... | Keep in mind that Java is also used on mobile devices, where memory is much more limited. | I use byte a lot. Usually in the form of byte arrays or ByteBuffer, for network communications of binary data.
I rarely use float or double, and I don't think I've ever used short. | Anyone using short and byte primitive types, in real apps? | [
"",
"java",
"types",
"primitive",
""
] |
How are you supposed to unit test a web service in C# with Visual Studio 2008? When I generate a unit test it adds an actual reference to the web service class instead of a web reference. It sets the attributes specified in:
<http://msdn.microsoft.com/en-us/library/ms243399(VS.80).aspx#TestingWebServiceLocally>
Yet, ... | What I usually do is not test directly against the web-service, but to try and put as little code as possible in the service, and call a different class which does all the real work. Then I write unit tests for that other class. It turns out that class can sometimes be useful outside of the web-service context, so this... | If you are writing a web service, try to put all logic in another (testable) layer. Each Web method should have a little code as possible. Then you will have little reason to test the web method directly because you can test the underlying layers.
```
[WebMethod]
public void DoSomething()
{
hander.DoSomething();
}... | How to unit test C# Web Service with Visual Studio 2008 | [
"",
"c#",
"web-services",
"unit-testing",
""
] |
This is a subjective question.
I worked in Visual Basic 6.0 before coming into the .NET space.
One thing I see that there are a lot of things, for which there is a need to deal with the Win32 API. As a Visual Basic 6.0 developer, there were a lot of limitations. .NET fixes some of the old problems however the need to... | It can't go away any time soon, but in Windows, at least, new projects are going less and less with C/C++. You can even see examples of Microsoft starting to eat their own dog food.
A great example of this is the C# compiler. Currently, it is written in C/C++. The C# team is currently working on re-writing it purely i... | Not any time soon. They aren't going to re-write the kernel and the core APIs in .NET in the near future, if ever. People have been expecting C to go away for a very long time, I just don't see it happening. | Will .NET take over C/C++ any time? | [
"",
".net",
"c++",
"c",
""
] |
I am trying to insert a very long text string into a MySQL Blob column, but MySQL is only saving 64kB of the data. The string is 75360 characters long. I am connecting with PHP's `mysql_connect()`.
Any ideas?
Does it make a difference if it's Blob or Text. I originally had it as a Text but changed it with no affect. | Because that's the [maximum size](http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html) of a BLOB column. You need to use MEDIUMBLOB/LONGBLOB or MEDIUMTEXT/LONGTEXT. | A `BLOB` type in MySQL can store up to 65,534 bytes, if you try to store more than this much data MySQL will truncate the data. `MEDIUMBLOB` can store up to 16,777,213 bytes, and `LONGBLOB` can store up to 4,294,967,292 bytes.
If you enable strict SQL mode ([MySQL modes](http://dev.mysql.com/doc/refman/5.0/en/server-s... | Why is only 64kB of data being saved in my MySQL data column? | [
"",
"php",
"mysql",
"text",
"blob",
""
] |
I have a structure which I create a custom constructor to initialize the members to 0's. I've seen in older compilers that when in release mode, without doing a memset to 0, the values are not initialized.
I now want to use this structure in a union, but get errors because it has a non-trivial constructor.
So, questi... | Question 1: Default constructors do initialize POD members to 0 according to the C++ standard. See the quoted text below.
Question 2: If a constructor must be specified in a base class, then that class cannot be part of a union.
Finally, you can provide a constructor for your union:
```
union U
{
A a;
B b;
... | **Things changed for the better in C++11.**
You can now legally do this, as [described by Stroustrup](http://www.stroustrup.com/C++11FAQ.html#unions) himself (I reached that link from the [Wikipedia article on C++11](https://en.wikipedia.org/wiki/C%2B%2B11#Unrestricted_unions)).
The example on Wikipedia is as follows... | Initializing a union with a non-trivial constructor | [
"",
"c++",
"constructor",
"multiplatform",
""
] |
I am working with a set of data that I have converted to a list of dictionaries
For example one item in my list is
```
{'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2005',
'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Bananas'}
```
Per request
The second item in my list... | So what's wrong with pickle? If you structure your data as a list of dicts, then everything should work as you want it to (if I understand your problem).
```
>>> import pickle
>>> d1 = {1:'one', 2:'two', 3:'three'}
>>> d2 = {1:'eleven', 2:'twelve', 3:'thirteen'}
>>> d3 = {1:'twenty-one', 2:'twenty-two', 3:'twenty-thre... | Python does not retain order in dictionaries.
However, there is the [OrderedDict](http://docs.python.org/2/library/collections.html?highlight=collections#ordereddict-objects) class in the *collections* module.
Another option would be to use a list of tuples:
```
[('reportDate', u'R20080501'), ('idnum', u'1078099'),... | Does anyone know where there is a recipe for serializing data and preserving its order in the output? | [
"",
"python",
"serialization",
""
] |
I doubt I am the only one who has come up with this solution, but if you have a better one please post it here. I simply want to leave this question here so I and others can search it later.
I needed to tell whether a valid date had been entered into a text box and this is the code that I came up with. I fire this whe... | ```
DateTime.TryParse
```
This I believe is faster and it means you dont have to use ugly try/catches :)
e.g
```
DateTime temp;
if(DateTime.TryParse(startDateTextBox.Text, out temp))
{
// Yay :)
}
else
{
// Aww.. :(
}
``` | Don't use exceptions for flow control. Use [DateTime.TryParse](http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx) and [DateTime.TryParseExact](http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact.aspx). Personally I prefer TryParseExact with a specific format, but I guess there are ... | How to Validate a DateTime in C#? | [
"",
"c#",
"datetime",
"validation",
""
] |
I'm using php and I have the following code to convert an absolute path to a url.
```
function make_url($path, $secure = false){
return (!$secure ? 'http://' : 'https://').str_replace($_SERVER['DOCUMENT_ROOT'], $_SERVER['HTTP_HOST'], $path);
}
```
My question is basically, is there a better way to do this in term... | The [HTTP\_HOST variable is not a reliable or secure value](http://shiflett.org/blog/2006/mar/server-name-versus-http-host) as it is also being sent by the client. So be sure to validate its value before using it. | I don't think security is going to be effected, simply because this is a url, being printed to a browser... the worst that can happen is exposing the full directory path to the file, and potentially creating a broken link.
As a little side note, if this is being printed in a HTML document, I presume you are passing th... | Converting a filepath to a url securely and reliably | [
"",
"php",
"security",
"url",
"robustness",
""
] |
I am using google's appengine api
```
from google.appengine.api import urlfetch
```
to fetch a webpage. The result of
```
result = urlfetch.fetch("http://www.example.com/index.html")
```
is a string of the html content (in result.content). The problem is the data that I want to parse is not really in HTML form, so ... | I understand that the format of the document is the one you have posted. In that case, I agree that a parser like [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) may not be a good solution.
I assume that you are already getting the interesting data (between the BODY tags) with a regular expression like... | Only suggestion I can think of is to parse it as if it has fixed width columns. Newlines are not taken into consideration for HTML.
If you have control of the source data, put it into a text file rather than HTML. | Parsing fixed-format data embedded in HTML in python | [
"",
"python",
"html",
"google-app-engine",
"parsing",
"html-content-extraction",
""
] |
[Medicare Eligibility EDI Example Responses](https://medifacd.relayhealth.com/Pharmacies/MediFacD_Pharmacies_PayerSheet_E1December2006.htm#Examples "Medicare Eligibility EDI Example Responses") is what I'm trying to match.
I have a string that looks like this:
```
LN:SMITHbbbbbbbbFN:SAMANTHAbbBD:19400515PD:1BN:123456... | I think what you want is positive lookahead, not negative, so that you find the key-colon combo ahead of the current position, but you don't consume it. This appears to work for your test example:
```
([\w]{2})\:(.+?)(?=[\w]{2}\:|$)
```
Yielding:
```
LN: SMITHbbbbbbbb
FN: SAMANTHAbb
BD: 19400515
PD: 1
BN: 123456
PN:... | Looking at the link each field is of a fixed length, so you could do something like this:
```
int pos = 0;
Dictionary<string, string> parsedResults = new Dictionary<string, string>();
foreach (int length in new int[] { 13, 10, 8, 1, 6, 10, 15, 20, 3, 10, 6, 3, 8, 8, 1, 8, 8, 8, })
{
string fieldId = message.Subst... | RegEx matching with no single letter delimiter | [
"",
"c#",
"regex",
"regex-lookarounds",
""
] |
I recently saw a bit of code that looked like this (with sock being a socket object of course):
```
sock.shutdown(socket.SHUT_RDWR)
sock.close()
```
What exactly is the purpose of calling shutdown on the socket and then closing it? If it makes a difference, this socket is being used for non-blocking IO. | Here's one [explanation](http://publib.boulder.ibm.com/infocenter/systems/index.jsp?topic=/com.ibm.aix.progcomm/doc/progcomc/skt_shutdn.htm):
> Once a socket is no longer required,
> the calling program can discard the
> socket by applying a close subroutine
> to the socket descriptor. If a
> reliable delivery socket ... | Calling `close` and `shutdown` have two different effects on the underlying socket.
The first thing to point out is that the socket is a resource in the underlying OS and **multiple processes can have a handle for the same underlying socket.**
When you call `close` it decrements the handle count by one and if the han... | socket.shutdown vs socket.close | [
"",
"python",
"sockets",
"asynchronous",
""
] |
I'm writing a GUI application in Python using wxPython and I want to display an image in a static control (`wx.StaticBitmap`).
I can use [`wx.ImageFromStream`](http://www.wxpython.org/docs/api/wx-module.html#ImageFromStream) to load an image from a file, and this works OK:
```
static_bitmap = wx.StaticBitmap(parent, ... | You should be able to use `StringIO` to wrap the buffer in a memory file object.
```
...
import StringIO
buf = open("test.jpg", "rb").read()
# buf = get_image_data()
sbuf = StringIO.StringIO(buf)
image = wx.ImageFromStream(sbuf)
...
```
`buf` can be replaced with any data string. | Since in Python you use Duck Typing you can write your own stream class and hand an instance of that class to ImageFromStream. I think you only need to implement the read method and make it return your data. | How do I create a wx.Image object from in-memory data? | [
"",
"python",
"wxpython",
"wxwidgets",
""
] |
As the topic suggests I wish to be able to pass table names as parameters using .NET (doesn't matter which language really) and SQL Server.
I know how to do this for values, e.g. `command.Parameters.AddWithValue("whatever", whatever)` using `@whatever` in the query to denote the parameter. The thing is I am in a situa... | I don't *think* I've ever seen this capability in any SQL dialect I've seen, but it's not an area of expertise.
I would suggest restricting the characters to A-Z, a-z, 0-9, '.', '\_' and ' ' - and then use whatever the appropriate bracketing is for the database (e.g. [] for SQL Server, I believe) to wrap round the who... | You cannot directly parameterize the table name. You can do it indirectly via `sp_ExecuteSQL`, but you might just as well build the (parameterized) TSQL in C# (concatenating the table-name but not the other values) and send it down as a command. You get the same security model (i.e. you need explicit SELECT etc, and as... | Parameterise table name in .NET/SQL? | [
"",
"sql",
".net",
"sql-server",
"parameters",
""
] |
Or any open source project which utilize collective intelligence extensively?. | There's a new book out from Manning, ["Collective Intelligence in Action"](http://www.manning.com/alag/). There are also code samples available written in Java. I also recommend the Toby Segaran book. Coming from a Java background I was able to follow the Python code without a problem. | Take a look at the book [Collective Intelligence](https://rads.stackoverflow.com/amzn/click/com/0596529325) by Toby Segaran. It covers lots of topics, such as how Amazon generates recommendations etc etc. There's lots of source code in the book written in Python, which should be easy to port to Java/.Net | Which are the good open source libraries for Collective Intelligence in .net/java? | [
"",
"java",
".net",
"collective-intelligence",
""
] |
Okay, what is it, and why does it occur on Win2003 server, but not on WinXP.
It doesn't seem to affect my application at all, but I get this error message when I close the application. And it's annoying (as errors messages should be).
I am using pyOpenGl and wxPython to do the graphics stuff. Unfortunately, I'm a C# ... | Looks like OpenGL is trying to report some error on Win2003, however you've not configured your system where to output logging info.
You can add the following to the beginning of your program and you'll see details of the error in stderr.
```
import logging
logging.basicConfig()
```
Checkout documentation on [loggin... | The [proper way](https://github.com/techtonik/rainforce/blob/master/WartsOfPython.wiki#logging) to get rid of this message is to configure NullHandler for the root level logger of your library (OpenGL). | Python - No handlers could be found for logger "OpenGL.error" | [
"",
"python",
"logging",
"opengl",
"wxpython",
"pyopengl",
""
] |
Can we convert a hex string to a byte array using a built-in function in C# or do I have to make a custom method for this? | Here's a nice fun LINQ example.
```
public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
``` | I did some research and found out that byte.Parse is even slower than Convert.ToByte.
The fastest conversion I could come up with uses approximately 15 ticks per byte.
```
public static byte[] StringToByteArrayFastest(string hex) {
if (hex.Length % 2 == 1)
throw new Exception("The binary key ca... | How can I convert a hex string to a byte array? | [
"",
"c#",
"encoding",
"hex",
""
] |
I want to register a specific instance of an object for a type in structuremap, how can I do that?
For example,
When I do:
```
var myObj = ObjectFactory.GetInstance(typeof(MyAbstractClass));
```
i would like it to return a previously constructed concrete class, which i created like this:
```
var myClass = new MyCo... | I believe you would do this in you initialization
```
ObjectFactory.Initialize(x =>
{
x.ForRequestedType<MyAbstractClass>().TheDefault.IsThis(myClass);
});
```
Where myClass is the instance of the object you want to return. | You can inject a concrete instance as the default by
```
ObjectFactory.Inject(typeof(MyAbstractClass), myClass);
``` | How to get StructureMap to return a specific instance for a requested type | [
"",
"c#",
"structuremap",
""
] |
What is the difference between abstract class and interface in Python? | What you'll see sometimes is the following:
```
class Abstract1:
"""Some description that tells you it's abstract,
often listing the methods you're expected to supply."""
def aMethod(self):
raise NotImplementedError("Should have implemented this")
```
Because Python doesn't have (and doesn't need... | > # What is the difference between abstract class and interface in Python?
An interface, for an object, is a set of methods and attributes on that object.
In Python, we can use an abstract base class to define and enforce an interface.
## Using an Abstract Base Class
For example, say we want to use one of the abstr... | Difference between abstract class and interface in Python | [
"",
"python",
"interface",
"abstract-class",
""
] |
I'm trying to implement a comet style, long polling connection using an XMLHttpResponse object.
The idea is to maintain an open connection to a server which sends data when it is available (faking push). As soon as the XHR object completes, I need to spawn a new one to wait for any fresh data.
Below is a snippet of co... | Just use jquery and do something like this:
```
function getData() {
$.getJSON(someUrl, gotData);
}
// Whenever a query stops, start a new one.
$(document).ajaxStop(getData, 0);
// Start the first query.
getData();
```
My [slosh](http://github.com/dustin/slosh) examples do this (since it's pretty muc... | What you're doing is effectively polling, why make it more complex than it needs to be, and just poll every few seconds? Or every second, how much time are you really saving and is it really that important, and you're going to be tying up an awful lot of sockets on the server end if you have a lot of users. | Implementing a self resetting XMLHttpRequest object | [
"",
"javascript",
"ajax",
"xmlhttprequest",
""
] |
I'm new to the Mac OS X, and I'm just about ready to throw my brand new [MacBook Pro](http://en.wikipedia.org/wiki/MacBook_Pro) out the window. Every tutorial on setting up a Django development environment on [Mac OS X Leopard](http://en.wikipedia.org/wiki/Mac_OS_X_Leopard) is insidiously wrong. They are all skipping o... | Did the MySQL and MySQL-dev installations go smoothly? Can you run MySQL, connect to it and so on? Does `/usr/local/mysql/include` contain lots of header files? (I've got 46 header files there, for reference).
If so, MySQL should be good to go. There are still a few manual steps required to compile MySQL-python, howev... | You can use the BSD-alike(?) <http://macports.org>, which provides gentoo-like build-it-yourself installations of a wide swath of software you'd expect to find in a Linux distro.
Alternatively you could just run Ubuntu in a virtual machine as your test stage.
It's honestly a simple
`# port install <pkgname>` | How do I install MySQL and the Python MySQL package on OS X Leopard? Or how do I learn about being a web developer using OS X? | [
"",
"python",
"mysql",
"django",
"macos",
"system-administration",
""
] |
I'm adding some lazy initialization logic to a const method, which makes the method in fact not const. Is there a way for me to do this without having to remove the "const" from the public interface?
```
int MyClass::GetSomeInt() const
{
// lazy logic
if (m_bFirstTime)
{
m_bFirstTime = false;
... | Make m\_bFirstTime mutable:
```
class MyClass
{
: :
mutable bool m_bFirstTime;
};
```
...but this is also very often an indication of a design flaw. So beware. | Actually, you said that you didn't want to change the header file. So your only option is to cast away the constness of the this pointer...
```
int MyClass::GetSomeInt() const
{
MyClass* that = const_cast<MyClass*>(this);
// lazy logic
if (that->m_bFirstTime)
{
that->m_bFirstTime = false;
... | In C++, I want my interface, .h to say int GetSomeInt() const;.... but actually the method *DOES* update "this". | [
"",
"c++",
"constants",
""
] |
I've got a MenuItem whos ItemsSource is databound to a simple list of strings, its showing correctly, but I'm struggling to see how I can handle click events for them!
Here's a simple app that demonstrates it:
```
<Window x:Class="WPFDataBoundMenu.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentat... | ```
<MenuItem Header="My Items" ItemsSource="{Binding Path=MyMenuItems}" Click="DataBoundMenuItem_Click" />
```
Code behind..
```
private void DataBoundMenuItem_Click(object sender, RoutedEventArgs e)
{
MenuItem obMenuItem = e.OriginalSource as MenuItem;
MessageBox.Show( String.Format("{0} just said Hi!", obMen... | You could have each menu item execute the same command, thus handling the execution centrally. If you need to distinguish menu items beyond the actual object instance, you can bind the command parameter too:
```
<MenuItem Header="My Items" ItemsSource="{Binding Path=MyMenuItems}">
<MenuItem.ItemContainerStyle>
... | How do I handle click events in a data bound menu in WPF | [
"",
"c#",
"wpf",
"data-binding",
""
] |
I'm using PHP to generate thumbnails. The problem is that I have a set width and height the thumbnails need to be and often times the images are stretched.
What I'd like is the image to remain at the same proportions and just have black filler (or any color) either on the left & right for tall images or top & bottom f... | You'll need to calculate the new width & height to keep the image proportionat. Check out example 2 on this page:
<https://www.php.net/imagecopyresampled> | Okay got it working, here's what I ended up doing:
```
$filename = "http://www.example.com/image.jpg";
list($width,$height) = getimagesize($filename);
$width_ratio = 166 / $width;
if ($height * $width_ratio <= 103)
{
$adjusted_width = 166;
$adjusted_height = $height * $width_ratio;
}
else
{
$height_ratio... | Having issues with GD thumbnail generator | [
"",
"php",
"gd",
""
] |
If I want to loop over a Dictionary(Key, Value)... why cant I add a new key-value pair in the loop?
```
Dictionary<string, string> persons = new Dictionary<string, string>();
persons.Add("roger", "12");
persons.Add("mary", "13");
foreach (KeyValuePair<string,string> person in persons)
{
Console.WriteLine("Name: " +... | If you want to do this you should get a copy of the Dictionary Object (can be done in many ways) then enumerate it, add what you want to the original.
Simply you can't add new items while enumerating an Dictionary. | It's because of the way the enumerator is constructed.
From MSDN [Dictionary.Enumerator](http://msdn.microsoft.com/en-us/library/k3z2hhax.aspx):
> An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumer... | Why can't I .add a Dictionary(Key, Value) in a foreach? | [
"",
"c#",
"dictionary",
"foreach",
""
] |
How do I check to see if a particular value has already been assigned to Smarty and if not assign a (default) value?
Answer:
```
if ($this->cismarty->get_template_vars('test') === null) {
$this->cismarty->assign('test', 'Default value');
}
``` | **Smarty 2**
```
if ($smarty->get_template_vars('foo') === null)
{
$smarty->assign('foo', 'some value');
}
```
**Smarty 3**
```
if ($smarty->getTemplateVars('foo') === null)
{
$smarty->assign('foo', 'some value');
}
```
Note that for **Smarty 3**, you will have to use `$smarty->getTemplateVars` instead. | `get_template_vars()` will return null if you haven't set a variable, so you can do
```
if ($smarty->get_template_vars('test') === null) {
echo "'test' is not assigned or is null";
}
```
However that check will fail if you have a variable assigned but set as null, in which case you could do
```
$tmp = $smarty->g... | How do I check to see if a Smarty variable is already assigned? | [
"",
"php",
"smarty",
"template-engine",
""
] |
I was browsing the SGI STL documentation and ran into [`project1st<Arg1, Arg2>`](http://www.sgi.com/tech/stl/project1st.html). I understand its definition, but I am having a hard time imagining a practical usage.
Have you ever used project1st or can you imagine a scenario? | My guess is that if you were using the strategy pattern and had a situation where you needed to pass an identity object, this would be a good choice. For example, there might be a case where an algorithm takes several such objects, and perhaps it is possible that you want one of them to do nothing under some situation. | A variant of project1st (taking a `std::pair`, and returning `.first`) is quite useful. You can use it in combination with `std::transform` to copy the keys from a `std::map<K,V>` to a `std::vector<K>`. Similarly, a variant of `project2nd` can be used to copy the values from a map to a `vector<V>`.
As it happens, none... | What is the usefulness of project1st<Arg1, Arg2> in the STL? | [
"",
"c++",
"stl",
"functional-programming",
""
] |
I'm aware that Python 3 fixes a lot of UTF issues, I am not however able to use Python 3, I am using 2.5.1
I'm trying to regex a document but the document has UTF hyphens in it – rather than -. Python can't match these and if I put them in the regex it throws a wobbly.
How can I force Python to use a UTF string or in... | After a quick test and visit to [PEP 0264: Defining Python Source Code Encodings](http://www.python.org/dev/peps/pep-0263/), I see you may need to tell Python the whole file is UTF-8 encoded by adding adding a comment like this to the first line.
```
# encoding: utf-8
```
Here's the test file I created and ran on Pyt... | You have to escape the character in question (–) and put a u in front of the string literal to make it a unicode string.
So, for example, this:
```
re.compile("–")
```
becomes this:
```
re.compile(u"\u2013")
``` | UTF in Python Regex | [
"",
"python",
"regex",
""
] |
I am building a CMS and the naming convention for classes has been debated between the other developer involved and myself. The problem arises specifically with "Page", as it is a public class available in a typical library.
A natural response would be to call it MVCMSPage (where MVCMS is the to-be name of the cms) or... | I'd go with something other than '`Page`'. The '`Page`' class that is built into .NET is a very generic class that is commonly known as part of ASP.NET. You could easily confuse other developers (or even yourself, a few months down the road if you don't look at it for a while).
I usually go with a naming convention su... | I think the term you were looking for is `namespace`.
I don't think I would rely on namespace differentiation for such a fundamental class in the System.Web space. If you were writing a console-based notification mechanism then it might be ok, but since you're working in the web arena, I'd avoid it. My vote would be t... | Quick question about a naming convention for a C# CMS | [
"",
"c#",
"content-management-system",
"naming-conventions",
""
] |
If I had a dictionary `dict` and I wanted to check for `dict['key']` I could either do so in a `try` block (bleh!) or use the `get()` method, with `False` as a default value.
I'd like to do the same thing for `object.attribute`. That is, I already have object to return `False` if it hasn't been set, but then that give... | A more direct analogue to `dict.get(key, default)` than `hasattr` is `getattr`.
```
val = getattr(obj, 'attr_to_check', default_value)
```
(Where `default_value` is optional, raising an exception on no attribute if not found.)
For your example, you would pass `False`. | Do you mean `hasattr()` perhaps?
```
hasattr(object, "attribute name") #Returns True or False
```
[Python.org doc - Built in functions - hasattr()](http://docs.python.org/library/functions.html#hasattr)
You can also do this, which is a bit more cluttered and doesn't work for methods.
```
"attribute" in obj.__dict__... | A get() like method for checking for Python attributes | [
"",
"python",
"attributes",
""
] |
At work today we were trying to come up with any reason you would use [strspn](http://www.php.net/strspn).
I searched google code to see if it's ever been implemented in a useful way and came up blank. I just can't imagine a situation in which I would really need to know the length of the first segment of a string tha... | Although you link to the PHP manual, the `strspn()` function comes from C libraries, along with `strlen()`, `strcpy()`, `strcmp()`, etc.
`strspn()` is a convenient alternative to picking through a string character by character, testing if the characters match one of a set of values. It's useful when writing tokenizers... | It's based on the the ANSI C function `strspn()`. It can be useful in low-level C parsing code, where there is no high-level string class. It's considerably less useful in PHP, which has lots of useful string parsing functions. | What's the point of strspn? | [
"",
"php",
"function",
"built-in",
""
] |
How do I split a list of arbitrary length into equal sized chunks?
---
See also: [How to iterate over a list in chunks](https://stackoverflow.com/q/434287).
To chunk strings, see [Split string every nth character?](https://stackoverflow.com/questions/9475241). | Here's a generator that yields evenly-sized chunks:
```
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
```
```
import pprint
pprint.pprint(list(chunks(range(10, 75), 10)))
[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 2... | Something super simple:
```
def chunks(xs, n):
n = max(1, n)
return (xs[i:i+n] for i in range(0, len(xs), n))
```
For Python 2, use `xrange()` instead of `range()`. | How do I split a list into equally-sized chunks? | [
"",
"python",
"list",
"split",
"chunks",
""
] |
Suppose I have this code:
```
var myArray = new Object();
myArray["firstname"] = "Bob";
myArray["lastname"] = "Smith";
myArray["age"] = 25;
```
Now if I wanted to remove "lastname"?....is there some equivalent of
`myArray["lastname"].remove()`?
(I need the element gone because the number of elements is important and... | Objects in JavaScript can be thought of as associative arrays, mapping keys (properties) to values.
To remove a property from an object in JavaScript you use the [`delete`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete) operator:
```
const o = { lastName: 'foo' }
o.hasOwnProperty(... | All objects in JavaScript are implemented as hashtables/associative arrays. So, the following are the equivalent:
```
alert(myObj["SomeProperty"]);
alert(myObj.SomeProperty);
```
And, as already indicated, you "remove" a property from an object via the `delete` keyword, which you can use in two ways:
```
delete myOb... | How do I remove objects from a JavaScript associative array? | [
"",
"javascript",
"arrays",
"associative-array",
"associative",
""
] |
Can any one tell the bit size of **boolean** in Java? | It's virtual machine dependent. | It depends on the virtual machine, but it's easy to adapt the code from a [similar question asking about bytes in Java](https://stackoverflow.com/questions/229886):
```
class LotsOfBooleans
{
boolean a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, ac, ad, ae, af;
boolean b0, b1, b2, b3, b4, b5, b6, b7, b8, b9,... | What is the size of a boolean variable in Java? | [
"",
"java",
"boolean",
""
] |
I'm using Python to **infinitely** iterate over a list, repeating each element in the list a number of times. For example given the list:
```
l = [1, 2, 3, 4]
```
I would like to output each element two times and then repeat the cycle:
```
1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 2, 2 ...
```
I've got an idea of where to star... | How about this:
```
import itertools
def bicycle(iterable, repeat=1):
for item in itertools.cycle(iterable):
for _ in xrange(repeat):
yield item
c = bicycle([1,2,3,4], 2)
print [c.next() for _ in xrange(10)]
```
EDIT: incorporated [bishanty's](https://stackoverflow.com/users/37522/bishanty) ... | You could do it with a generator pretty easily:
```
def cycle(iterable):
while True:
for item in iterable:
yield item
yield item
x=[1,2,3]
c=cycle(x)
print [c.next() for i in range(10)] // prints out [1,1,2,2,3,3,1,1,2,2]
``` | How to iterate over a list repeating each element in Python | [
"",
"python",
"iterator",
""
] |
In Java, arrays don't override `toString()`, so if you try to print one directly, you get the `className` + '@' + the hex of the [`hashCode`](https://en.wikipedia.org/wiki/Java_hashCode()) of the array, as defined by `Object.toString()`:
```
int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(intArray); // ... | Since Java 5 you can use [`Arrays.toString(arr)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Arrays.html#toString(int%5B%5D)) or [`Arrays.deepToString(arr)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Arrays.html#deepToString(java.lang.Object%5B%5D)) for arrays wi... | Always check the standard libraries first.
```
import java.util.Arrays;
```
Then try:
```
System.out.println(Arrays.toString(array));
```
or if your array contains other arrays as elements:
```
System.out.println(Arrays.deepToString(array));
``` | What's the simplest way to print a Java array? | [
"",
"java",
"arrays",
"printing",
"tostring",
""
] |
I have two arrays in PHP. The first array ($author\_array) is comprised of user\_ids in a particular order, like so: (8, 1, 6)
The second array ($user\_results) is comprised of an array of objects like so:
```
Array
(
[0] => stdClass Object
(
[ID] => 1
[user_login] => user1
... | Use [usort](http://php.net/uksort) and provide a custom comparison function which uses the position of the key in your "ordering" array to determine the sort order, e.g. something like:
```
function cmp($a, $b)
{
global $author_array;
$pos1=array_search ($a->ID, $author_array);
$pos2=array_search ($b->ID, $... | I'm not sure whether this will be significantly slower than other examples, but it seems simpler. It may be that you could build the $user\_results array as an associative one to start with, using ID as the key, then you can easily do lookups.
```
$hash = array();
$result = array();
foreach ($user_results as $obj) {
... | Sorting an Array of Objects in PHP In a Specific Order | [
"",
"php",
"arrays",
"object",
""
] |
I have a client with a LAMP website serving mostly video. He is currently on one server with all components. He is having some scaling problems. What are some of the techniques that can be used to help.
I used separating out the DB to another server with a GB Ethernet between it and the webserver. Maybe adding more we... | The advice about CloudFront and MemCache etc. is all good, assuming those address the root of your performance issues.
On the database side: Profile, profile, profile. Moving the DB to a separate server was (probably) a good step, but if you haven't profiled the queries being run on this DB instance, you don't know wh... | First off, I agree that you must know what the bottleneck is before attempting to scale. Here some run of the mill suggestions to get you started:
1. Get video out of the database. I don't see how this would make sense in any situation.
2. Add one more server to only server the video content and leave the HTML/applica... | Scaling LAMP | [
"",
"php",
"mysql",
"lamp",
""
] |
I'm going to start maintaining an Eclipse RCP application for my current employer soon.
What are your experiences with this platform? What are the pros, what are the cons, what are the caveats that I should be aware of?
Also, what reading materials (books, tutorials) can you recommend? Most of the tutorials I found... | * [Eclipse Rich Client Platform (RCP) with Eclipse Ganymede (3.4) - Tutorial](http://www.vogella.de/articles/RichClientPlatform/article.html)
* [JFace examples](http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/CatalogSWT-JFace-Eclipse.htm)
* [Make your Eclipse applications richer with view linking](http://www-128.ibm.... | There are many good online references included on the Eclipse Resources page, and on the Eclipse Wiki. There is also quite a bit of good material on Eclipse Live <http://live.eclipse.org/> in the form of tutorials and other presentations, some of which come from the eclipsecon conferences.
I recommend starting with th... | Starting working with Eclipse RCP | [
"",
"java",
"eclipse",
"eclipse-plugin",
"eclipse-rcp",
""
] |
While considering the JS framework for my next project, I can see the scale clearly tipping towards jQuery, however, Prototype is getting good reviews, too.
The issue I am thinking of is how to **downscale these to have only the functionality I REALLY need.** The latest jQuery seems to be 55k compressed, for instance,... | Check these Frameworks out:
* [Midori](http://www.midorijs.com/) (*45KB uncompressed*)
* [SimpleJS](http://simplejs.bleebot.com/) (*Core File: 4KB)*
* [DOMAssistant](http://www.domassistant.com/) (*7KB gzipped)*
If you want a complete but light weight solution, I'd suggest you go with *Midori* or *DOMAssistant*.
Fin... | jQuery is about 10k compressed and minified with YUI compressor:
<http://www.julienlecomte.net/blog/2007/08/13/>
That is *incredibly* tiny for the amount of functionality you get in jQuery. | Downscaled versions of jQuery or Prototype - JS framework selection | [
"",
"javascript",
"jquery",
"ajax",
"prototypejs",
"javascript-framework",
""
] |
I am using XML minidom (xml.dom.minidom) in Python, but any error in the XML will kill the parser.
Is it possible to ignore them, like a browser for example?
I am trying to write a browser in Python, but it just throws an exception if the tags aren't fully compatible. | There is a library called [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/), I think it's what you're looking for.
As you're trying to parse a invalid XML, the normal XML parser won't work. BeautifulSoup is more fail-tolerant, it can still extract information from invalid XML.
> Beautiful Soup is a Python... | It should be noted that while HTML looks like XML it is not XML. XHTML is an XML form of HTML. | Ignoring XML errors in Python | [
"",
"python",
"xml",
"minidom",
""
] |
How do I get started doing unit testing in C++ ?
I have used Junit when coding in Java and found it very useful.
Is there something similar in C++ ? What do you recommend ? | Here are similar questions that you may want to look at:
* [Unit testing for C++ code - Tools and methodology](https://stackoverflow.com/questions/91384/unit-testing-for-c-code-tools-and-methodology)
* [C++ unit testing framework](https://stackoverflow.com/questions/87794/c-unit-testing-framework)
I recommend you che... | I recently wrote a 5-part series of blog posts covering unit testing in C++ with boost. It gives step by step instructions for how to do this in Visual Studio.
* [Part 1](http://legalizeadulthood.wordpress.com/2009/07/04/c-unit-tests-with-boost-test-part-1/): how to start making unit tests in C++ with Boost.Test.
* [P... | Unit testing in C++ | [
"",
"c++",
"unit-testing",
""
] |
I like Django, but for a particular application I would like to use only parts of it, but I'm not familiar enough with how Django works on the inside, so maybe someone can point me into the right direction as to what I have to check out.
Specifically, I *want to use*:
* The models and database abstraction
* The [cach... | I myself use Django for its object/db mapping without using its urlconfigs. Simply create a file called `djangosettings.py` and insert the necessary configuration, for example:
```
DATABASE_ENGINE = 'oracle'
DATABASE_HOST = 'localhost'
DATABASE_NAME = 'ORCL'
DATABASE_USER = 'scott'
DATABASE_PASSWORD = '... | Django, being a web framework, is extremely efficient at creating websites. However, it's also equally well-suited to tackling problems off the web. This is the *loose coupling* that the project prides itself on. Nothing stops you from installing a complete version of Django, and just using what you need. As a rule, ve... | Use only some parts of Django? | [
"",
"python",
"django",
""
] |
Given a java.util.Date object how do I go about finding what Quarter it's in?
Assuming Q1 = Jan Feb Mar, Q2 = Apr, May, Jun, etc. | Since Java 8, the quarter is accessible as a field using classes in the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) package.
```
import java.time.LocalDate;
import java.time.temporal.IsoFields;
LocalDate myLocal = LocalDate.now();
int quarter = myLocal.get(IsoFields.QUARTER_O... | In Java 8 and later, the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes have a more simple version of it. Use [`LocalDate`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html) and [`IsoFields`](https://docs.oracle.com/javase/8/docs/api/java/time/temporal/Is... | How do I discover the Quarter of a given Date? | [
"",
"java",
"calendar",
""
] |
Is there a difference between `Cursor.Current` and `this.Cursor` (where `this` is a WinForm) in .Net? I've always used `this.Cursor` and have had very good luck with it but I've recently started using CodeRush and just embedded some code in a "Wait Cursor" block and CodeRush used the `Cursor.Current` property. I've see... | Windows sends the window that contains the mouse cursor the WM\_SETCURSOR message, giving it an opportunity to change the cursor shape. A control like TextBox takes advantage of that, changing the cursor into a I-bar. The Control.Cursor property determines what shape will be used.
The Cursor.Current property changes t... | I believe that Cursor.Current is the mouse cursor currently being used (regardless of where it is on the screen), while this.Cursor is the cursor it will be set to, when the mouse passes over your window. | Cursor.Current vs. this.Cursor | [
"",
"c#",
".net",
"winforms",
"mouse-cursor",
""
] |
What are the C++ coding and file organization guidelines you suggest for people who have to deal with lots of interdependent classes spread over several source and header files?
I have this situation in my project and solving class definition related errors crossing over several header files has become quite a headach... | Some general guidelines:
* Pair up your interfaces with implementations. If you have `foo.cxx`, everything defined in there had better be declared in `foo.h`.
* Ensure that every header file #includes all other necessary headers or forward-declarations necessary for independent compilation.
* Resist the temptation to ... | Check out the C and C++ coding standards at the [NASA Goddard Space Flight Center](http://software.gsfc.nasa.gov/assetsbytype.cfm?TypeAsset=Standard). The one rule that I specially noted in the C standard and have adopted in my own code is the one that enforces the 'standalone' nature of header files. In the implementa... | C++ class header files organization | [
"",
"c++",
"class",
"file",
"header",
"organization",
""
] |
In the Fibonacci sequence, I have seen conventional implementations which recursively call the same method twice:
```
public void fibonacci(int i)
{
fibonacci(1) + fibonacci(2);
}
```
Now this method is not the exact copy of what I have seen or the right way of solving the problem, but I've seen the two methods added... | This is one of those times when it's useful to think about the way the computer does it.
Let's start with the function. I'm going to write it in Python flavored pseudocode because I want you to get away from thinking about the LANGUAGE for a second.
```
def fib(n):
if n == 0: return 0
if n == 1: return 1
... | No, they are called one after another. No additional threads are made unless you explicitly ask for it (with System.Threading stuff). I'm not sure on the order they are called, but I would guess that from left to the right. C# specification definately has it in it. | Recursively calling the same method twice | [
"",
"c#",
".net",
"fibonacci",
""
] |
Explain why a nullable int can't be assigned the value of null e.g
```
int? accom = (accomStr == "noval" ? null : Convert.ToInt32(accomStr));
```
What's wrong with that code? | The problem isn't that null cannot be assigned to an int?. The problem is that both values returned by the ternary operator must be the same type, or one must be implicitly convertible to the other. In this case, null cannot be implicitly converted to int nor vice-versus, so an explict cast is necessary. Try this inste... | What Harry S says is exactly right, but
```
int? accom = (accomStr == "noval" ? null : (int?)Convert.ToInt32(accomStr));
```
would also do the trick. (We Resharper users can always spot each other in crowds...) | c# why can't a nullable int be assigned null as a value | [
"",
"c#",
"nullable",
""
] |
Given this:
```
Interface IBase {string X {get;set;}}
Interface ISuper {string Y {get;set;}}
class Base : IBase {etc...}
class Super : Base, ISuper {etc...}
void Questionable (Base b) {
Console.WriteLine ("The class supports the following interfaces... ")
// The Magic Happens Here
}
```
What can I replace "The ... | The Magic :
```
foreach (Type iface in b.GetType().GetInterfaces())
Console.WriteLine(iface.Name);
``` | b.GetType().[GetInterfaces](http://msdn.microsoft.com/en-us/library/system.type.getinterfaces.aspx)() | Given an Object, How can I programatically tell what Interfaces it supports? | [
"",
"c#",
".net",
"reflection",
"interface",
""
] |
I'd like to know when i should and shouldn't be wrapping things in a USING block.
From what I understand, the compiler translates it into a try/finally, where the finally calls Dispose() on the object.
I always use a USING around database connections and file access, but its more out of habit rather than a 100% under... | No, `IDisposable` items are not disposed when they go out of scope. It is for precisely this reason that we need `IDisposable` - for deterministic cleanup.
They will *eventually* get garbage collected, and if there is a finalizer it will (maybe) be called - but that could be a long time in the future (not good for con... | > "Are IDisposables not disposed of when
> they go out of scope?"
No. If the IDisposable object is *finalizable*, which is not the same thing, then it will be finalized when it's garbage collected.
Which might be soon or might be almost never.
Jeff Richter's C#/CLR book is very good on all this stuff, and the Framew... | C# USING keyword - when and when not to use it? | [
"",
"c#",
"dispose",
""
] |
Here's the purpose of my console program: Make a web request > Save results from web request > Use QueryString to get next page from web request > Save those results > Use QueryString to get next page from web request, etc.
So here's some pseudocode for how I set the code up.
```
for (int i = 0; i < 3; i++)
... | Have you tried creating a new WebRequest object for each time during the loop, it could be the Create() method isn't adequately flushing out all of its old data.
Another thing to check is that the ResponseStream is adequately flushed out before the next loop iteration. | This code works fine for me:
```
var urls = new [] { "http://www.google.com", "http://www.yahoo.com", "http://www.live.com" };
foreach (var url in urls)
{
WebRequest request = WebRequest.Create(url);
using (Stream responseStream = request.GetResponse().GetResponseStream())
using (Stream outputStream = new... | C# - WebRequest Doesn't Return Different Pages | [
"",
"c#",
"html",
""
] |
I'm trying to get my head around tuples (thanks @litb), and the common suggestion for their use is for functions returning > 1 value.
This is something that I'd normally use a struct for , and I can't understand the advantages to tuples in this case - it seems an error-prone approach for the terminally lazy.
[Borrowi... | ### tuples
I think i agree with you that the issue with what position corresponds to what variable can introduce confusion. But i think there are two sides. One is the *call-side* and the other is the *callee-side*:
```
int remainder;
int quotient;
tie(quotient, remainder) = div(10, 3);
```
I think it's crystal cle... | Another option is to use a Boost Fusion map (code untested):
```
struct quotient;
struct remainder;
using boost::fusion::map;
using boost::fusion::pair;
typedef map<
pair< quotient, int >,
pair< remainder, int >
> div_result;
```
You can access the results relatively intuitively:
```
using boost::fusion::a... | Boost::Tuples vs Structs for return values | [
"",
"c++",
"tuples",
"boost-tuples",
""
] |
Are there any good reasons not to use \u0000 as a delimiter within a Java String? I would be encoding and decoding the string myself.
This is for saving a list of user-inputted (I'm expecting input to be typed?) strings to an Eclipse preference and reading it back. The list may be variable size so I don't think I can ... | There used to be some libraries which erroneously handled Java strings as null terminated. I don't know if it's still true but it's worth keeping such things in mind. Especially if you interop with external libraries that will handle strings as null terminated. | If the data stays in Java, why don't you use an array or a List instead? | Null \u0000 in Java String? | [
"",
"java",
"string",
"null",
""
] |
If `UNION ALL` is an *addition* in T-SQL. What is the equivalent of subtraction?
For example, if I have a table `PEOPLE` and a table `EMPLOYEES`. And I know if I remove `EMPLOYEES` records from `PEOPLE` I will be left with my companies `CONTRACTORS`.
Is there a way of doing this that is similar to `UNION ALL`? One wh... | Instead of using UNION, use EXCEPT, ( or INTERSECT to get only records in both )
as described in
[msdn EXCEPT Link for Sql2k8](http://msdn.microsoft.com/en-us/library/ms188055.aspx)
[msdn EXCEPT Link for Sql2k5](http://msdn.microsoft.com/en-us/library/ms188055(SQL.90).aspx) | You can use the [EXCEPT operator](http://msdn.microsoft.com/en-us/library/ms188055.aspx) to subtract one set from another. Here's a sample of code using EMPLOYEES and PEOPLE temporary tables. You'll need to use the field names with the EXCEPT operator as far as I know.
```
CREATE TABLE #PEOPLE
(ID INTEGER,
Name NVARC... | T-SQL: Comparing Two Tables - Records that don't exist in second table | [
"",
"sql",
"sql-server-2005",
"t-sql",
""
] |
I am using the [SQLite](http://www.sqlite.org/) database and have the following persistent class (simplified):
```
public class Project
{
public virtual int Id { get; set; }
public virtual DateTime StartDate { get; set; }
}
```
which is mapped to this table in the database:
```
CREATE TABLE projects (
id... | If you're regularly querying against months, days, years, you shouldn't really be storing your date as a DateTime column - it makes the queries incredibly inefficient. You could easily create a "Month" column and query against that (and your DBA would love you again) | I would highly recommend you to write a custom function.
<http://ayende.com/Blog/archive/2006/10/01/UsingSQLFunctionsInNHibernate.aspx>
I don't mean the sql function, I mean the NHibernate function that is registered with RegisterFunction to enhance the NHibernate dialect.
Another probably better example:
<http://ay... | Using dates in the "where" clause of HQL query | [
"",
"c#",
"nhibernate",
""
] |
I am trying to run my Django sites with mod\_wsgi instead of mod\_python (RHEL 5). I tried this with all my sites, but get the same problem. I configured it the standard way everyone recommends, but requests to the site simply time out.
Apache conf:
```
<VirtualHost 74.54.144.34>
DocumentRoot /wwwclients/thymeand... | The problem is that mod\_python doesn't go well together with mod\_wsgi. I got into similar issue few weeks ago and everything started working for me shortly after I commented out mod\_python inclusion.
Try to search [modwsgi.org](http://modwsgi.org) wiki for "mod\_python", I believe there was someone talking about th... | The real problem is permissions on Apache log directory. It is necessary to tell Apache/mod\_wsgi to use an alternate location for the UNIX sockets used to communicate with the daemon processes. See:
<http://code.google.com/p/modwsgi/wiki/ConfigurationIssues#Location_Of_UNIX_Sockets> | Running a Django site under mod_wsgi | [
"",
"python",
"django",
"apache",
"mod-wsgi",
""
] |
How can I obtain the .NET Framework directory path inside my C# application?
The folder that I refer is "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727" | The path to the installation directory of the CLR active for the current .NET application can be obtained by using the following method:
```
System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()
```
I would **strongly** advice against reading the registry directly. For example, when a .NET applicati... | An easier way is to include the Microsoft.Build.Utilities assembly and use
```
using Microsoft.Build.Utilities;
ToolLocationHelper.GetPathToDotNetFramework(
TargetDotNetFrameworkVersion.VersionLatest);
``` | Getting the .NET Framework directory path | [
"",
"c#",
".net",
"frameworks",
"directory",
""
] |
I'd like to use regex with Java.
What I want to do is find the first integer in a string.
Example:
```
String = "the 14 dogs ate 12 bones"
```
Would return 14.
```
String = "djakld;asjl14ajdka;sdj"
```
Would also return 14.
This is what I have so far.
```
Pattern intsOnly = Pattern.compile("\\d*");
Matcher make... | You're asking for 0 or more digits. You need to ask for 1 or more:
```
"\\d+"
``` | It looks like the other solutions failed to handle `+/-` and cases like `2e3`, which `java.lang.Integer.parseInt(String)` supports, so I'll take my go at the problem. I'm somewhat inexperienced at regex, so I may have made a few mistakes, used something that Java's regex parser doesn't support, or made it overly compli... | Regex to find an integer within a string | [
"",
"java",
"regex",
"integer",
""
] |
I'm looking to have a simple custom dialog box, like a message box, that has a label and a TextBox. If there's a simple way to do this, sorry! I'm really not well versed in the dialog stuff.
Thanks for any help, guys! | Here is how to make a small custom dialog box in Windows Mobile that looks like this:
[alt text http://www.freeimagehosting.net/uploads/b8fb5421d6.jpg](http://www.freeimagehosting.net/uploads/b8fb5421d6.jpg)
Add a form to your project, and set its FormBorderStyle property to None. This allows the form to be resized a... | If you want a super-simple but[t] ugly solution, you can include a reference in your project to Microsoft.VisualBasic, which lets you use the VB function InputBox like this:
```
string s = Microsoft.VisualBasic.Interaction.InputBox("prompt text",
"title text", "default value", 0, 0);
```
The dialog takes up the e... | custom dialog with a text field in winmobile | [
"",
"c#",
"windows-mobile",
"smartphone",
""
] |
I have a huge number of mail archives that I want to de-duplicate and sort out. The archives are either in mbox format or contain a single mail message. To add a bit of complication, some of the files have windows EOL sequences, and some have the unix EOL.
Using C#. how do I read an archive and split it into its indi... | It is unlikely that you will find a library to read that file for C# - there aren't that many Unix users who also use C#.
What I would do would be either to:
1. Read the Python code, and then port it to C#
2. Find the description of the mbox format online. As it is a Unix system, chances are that the format is just a... | Most standard Unix mail files delimit entries with a line starting "From "
So if you read in the mail file as a text file and switch to a new mail entry every time you see the string "From " at the start of a line it should work
- Any strings elsewhere should already have been delimited by the email program | Reading email from a mail file | [
"",
"c#",
".net",
"email",
""
] |
What the difference between `LPCSTR`, `LPCTSTR` and `LPTSTR`?
Why do we need to do this to convert a string into a `LV` / `_ITEM` structure variable `pszText`:
```
LV_DISPINFO dispinfo;
dispinfo.item.pszText = LPTSTR((LPCTSTR)string);
``` | To answer the first part of your question:
`LPCSTR` is a pointer to a const string (LP means [Long Pointer](https://stackoverflow.com/questions/2315311/what-is-a-long-pointer))
`LPCTSTR` is a pointer to a `const TCHAR` string, (`TCHAR` being either a wide char or char depending on whether UNICODE is defined in your p... | Quick and dirty:
`LP` == **L**ong **P**ointer. Just think pointer or char\*
`C` = **C**onst, in this case, I think they mean the character string is a const, not the pointer being const.
`STR` is **string**
the `T` is for a wide character or char (TCHAR) depending on compiler options.
## Bonus Reading
From [What ... | LPCSTR, LPCTSTR and LPTSTR | [
"",
"c++",
"windows",
"visual-c++",
"mfc",
""
] |
Anyone know a good lib where i can run the strings before they are inserted, that can strip out sql/javascript code? To be run in jsp pages.
Idealy the lib would be:
* Free
* Lightweight
* Easy to use
Thanks in advance to the SO community who will happily reply :) | Apache Commons lang StringEscapeUtils will get you some of the way. It escapes, doesnt strip.
<http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html>
Edit: Escaping can save you from injection attacks because it makes sure that the data the user has entered is not executed as code, but alw... | You need to rely on the your database api's mechanism for using parameterized queries. If you're *first* building an sql string dynamically and *then* want to sanitize the completed query string, you're doing it wrong. That's just asking for trouble.
---
Edit: after re-reading your question, it seems I mis-understood... | Lib to protect SQL/javascript injection for java/jsp | [
"",
"java",
"security",
"jsp",
"sql-injection",
"javascript-injection",
""
] |
AFAIK, you never need to specify the protocol in an onclick:
`onclick="javascript:myFunction()"` **Bad**
`onclick="myFunction()"` **Good**
Today I noticed in [this article](http://web.archive.org/web/20080428095515/http://www.google.com/support/analytics/bin/answer.py?answer=55527) on Google Anallytics that *they* a... | Some of the responses here claim that the "javascript:" prefix is a "leftover from the old days", implying that it's intentionally, specially handled by the browsers for backwards compatibility. Is there solid evidence that this is the case (has anyone checked source code)?
```
<span onclick="javascript:alert(42)">Tes... | It's never needed on anchors and is never good practice. An anchor is for navigation only.
An article about this topic is *[The useless JavaScript: pseudo-protocol](http://crisp.tweakblogs.net/blog/the-useless-javascript-pseudo-protocol.html)*. | Do you ever need to specify 'javascript:' in an onclick? | [
"",
"javascript",
"google-api",
""
] |
Consider the code:
```
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.createStatement(myQueryString);
rs = ps.executeQuery();
// process the results...
} catch (java.sql.SQLException e) {
log.error("an error!", e);
throw new MyAppException("I'm sorry. Your query did not work.");
} finally ... | For file I/O, I generally add a try/catch to the finally block. However, you must be careful not to throw any exceptions from the finally block, since they will cause the original exception (if any) to be lost.
See [this article](http://accu.org/index.php/journals/236) for a more specific example of database connectio... | In Java 7, you should not close them explicitly, but use [automatic resource management](http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html) to ensure that [resources](http://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html) are closed and exceptions are handled appropriately. Ex... | Where to close java PreparedStatements and ResultSets? | [
"",
"java",
"jdbc",
"resource-management",
""
] |
What is the best was to evaluate an expression like the following:
(A And B) Or (A And C) Or (Not B And C)
or
(A && B) || (A && C) || (!B && C)
At runtime, I was planning on converting the above expressions to the following:
(True And False) Or (True And False) Or (Not False And True)
or
(True && False) |... | If you're using .NET3.5 then you can parse the text and create an abstract sytax tree using the Expression classes. Then create a suitable LambdaExpression instance and compile it into a delegate, which you can then execute.
Constructing a parser and syntax tree builder for this kind of fairly simple grammer is quite ... | Be warned: the two final conditions you're talking about are not necessarily equivalent. The && operators in C# will use short-circuit evalution, while the logical `And` operator in VB does not. If you want to be sure the statements are equivalent, translate a user `And` to `AndAlso` and a user `Or` to `OrElse`.
For s... | Dynamic logical expression parsing/evaluation in C# or VB? | [
"",
"c#",
"vb.net",
"expression",
""
] |
I have two processes one will query other for data.There will be huge amount of queries in a limited time (10000 per second) and data (>100 mb) will be transferred per second.Type of data will be an integral type(double,int)
My question is in which way to connect this process?
Shared memory , message queue , lpc(Local... | One Word: [Boost.InterProcess](https://www.boost.org/doc/libs/1_74_0/doc/html/interprocess.html). If it really needs to be fast, shared memory is the way to go. You nearly have zero overhead as the operation system does the usual mapping between virtual and physical addresses and no copy is required for the data. You j... | I would use shared memory to store the data, and message queues to send the queries. | Best way for interprocess communication in C++ | [
"",
"c++",
"memory",
"boost",
"ipc",
"shared",
""
] |
I have been doing a lot of research on this lately, but have yet to get a really good solid answer. I read somewhere that a new Function() object is created when the JavaScript engine comes across a function statement, which would lead me to believe it could be a child of an object (thus becoming one). So I emailed Dou... | Your understanding is wrong:
```
myFunction().myProperty; // myFunction has no properties
```
The reason it does not work is because ".myProperty" is applied to the returned value of "myFunction()", not to the object "myFunction". To wit:
```
$ js
js> function a() { this.b=1;return {b: 2};}
js> a().b
2
js>
```
Reme... | There is nothing magical about functions and constructors. All objects in JavaScript are … well, objects. But some objects are more special than the others: namely built-in objects. The difference lies mostly in following aspects:
1. General treatment of objects. Examples:
* Numbers and Strings are immutable (⇒ con... | Why in JavaScript is a function considered both a constructor and an object? | [
"",
"javascript",
"object",
"constructor",
""
] |
On some websites or forums I usually go to, entries that I havn't read yet are marked as "new". I would like to implement this feature on a website I have developed (with news being posted from time to time) -- php/mySQL. How is this usually done ? Does it require using a cookie remembering the last visit date/time ? O... | Cookies are just one possible way of identifying the user for the session, or between visits for those without authentication. Though a very common and useful way. (PHP can also use the sid or another parameter, though its not common anymore.)
You need to store either which threads/posts the user have read, or which h... | A side note: doing so would actually be duplicating browser functionality: (as long as you use fixed urls) the browser will give links a different style on visited links. Of course this will reset if you clear history, but then again a cookie only based solution will allso clear if the cookie is deleted (with many brow... | Marking latest news as ... "new" | [
"",
"php",
"mysql",
""
] |
For our site, Im using a lot of jQuery - right now Im looking at 340 lines of jQuery code on top of the base library. How much is too much? I will be adding more, when do I start trying to condense the code and eventually move to OOP? | Optimally, you should keep you script size as minimum as possible, but with today's 'Web 2.0' websites, you will most probably accumulate quite a lot of JavaScript code.
The important thing is that before you deploy your website, **make sure to [minify](http://www.crockford.com/javascript/jsmin.html) and [gzip](http:/... | The number of lines doesn't mean anything - what matters is what you're actually doing. You could have 10 lines of supremely inefficient code that would do much more damage than a meticulously crafted 1000 lines of code. | How many lines of code is in your custom jQuery script on your site? And how much is too much? | [
"",
"javascript",
"design-patterns",
"jquery-plugins",
"jquery",
""
] |
Is it alright to expect that the user using the back end will have Javascript enabled?
I guess the answer I'll get is 'it depends on your target users'. I am developing a system for fun that will hopefully be used by other people. I would like to hear from other people developing back end systems, and what did they de... | Personally I would expect the failover, but there are circumstances (particularly low profile sites, intranets, e-learning content) where you can assume JS.
Mostly you can even go with a simple "You require JS / This works better with JS" and I would consider that good enough, but there's a couple of instances where I... | if its for fun please go ahead and require javascript. | When writing a web backend for a system, is it important the code can still work without Javascript? | [
"",
"javascript",
"xhtml",
""
] |
I am looking for template/generator libraries for C++ that are similar to eg. Ruby's Erb, Haml, PHP's Smarty, etc.
It would be great if I it would sport some basic features like loops, if/else, int conversion to strings, etc.
Parameter passing to template rendering engine is also important if I could pass all of them... | A quick review of the mentioned project.
<http://rgrz.tumblr.com/post/13808947359/review-of-html-template-engines-in-c-language>
## ClearSilver
* Site: <http://www.clearsilver.net>
* Project: <https://code.google.com/p/clearsilver/>
* Group: <http://tech.groups.yahoo.com/group/ClearSilver>
* License: New BSD License... | [Grantlee](https://github.com/steveire/grantlee) is a string template engine based on the Django template system. It is ported to C++/Qt. | C++ HTML template framework, templatizing library, HTML generator library | [
"",
"c++",
"template-engine",
""
] |
I want place ads in my website, but I'm unsure about the common practices to place thes ads.
By example, some cool asp.net articles sites shows ads in the middle of the article! So you read 2-3 paragraphs, read some ad, then finish the article reading...
Another worry is about sabotage. One of mine customers get their... | Google (unsurprisingly) knows a fair amount about where people look on a page. They have [an article about where to place ads](https://www.google.com/adsense/support/bin/answer.py?hl=en&answer=17954).
Personally, I have the ads on my C# articles right at the bottom - by the time you get there, you've received all the ... | I find the ads in the middle of an article to be very annoying. Avoid this if possible. Place the ads on sides and top, but remember to leave plenty of space for contents too. Remember that >90% users will come for the contents anyway and will not care for the ads no matter where you put them. Those who want them, will... | What the best practices to place ads in a website? | [
"",
"asp.net",
"javascript",
"html",
"design-patterns",
"seo",
""
] |
I had a little bit of budget left at year end and I wanted to start a little skunk works project to display build status what everyone was working on (our team is aobut 10 folks all told). I am thinking to buy a 47" LCD HD TV and drive it from a small pc via a browser/.NET web application.
I was going to build the sof... | A friend of mine is teaching himself how to work with Arduino so that he can build a computer-controlled LED sculpture for Burning Man next year. His first project? Using Arduino to control a little array of red and green LEDs so that everyone on his team can look up at it and see if the build is broken and who broke i... | Would it really benefit your team in any way?
I'd rather brought something like a table hockey machine to make lunch time more fun. | Software to simplify displaying build status on a big visible monitor for team? | [
"",
"c#",
"asp.net",
"rss",
""
] |
How do I find areas of my code that run slowly in a C++ application running on Linux? | If your goal is to use a profiler, use one of the suggested ones.
However, if you're in a hurry and you can manually interrupt your program under the debugger while it's being subjectively slow, there's a simple way to find performance problems.
Execute your code in a debugger like gdb, halt it and each time look at ... | Use [Valgrind](http://en.wikipedia.org/wiki/Valgrind) with the following options:
```
valgrind --tool=callgrind ./(Your binary)
```
This generates a file called `callgrind.out.x`. Use the `kcachegrind` tool to read this file. It will give you a graphical analysis of things with results like which lines cost how much. | How do I profile C++ code running on Linux? | [
"",
"c++",
"linux",
"profiling",
""
] |
While researching the issue of [JSON vs XML](http://www.subbu.org/blog/2006/08/json-vs-xml), I came across [this question](https://stackoverflow.com/questions/325085/when-to-prefer-json-over-xml). Now one of the reasons to prefer JSON was listed as the ease of conversion in Javascript, namely with the `eval()`. Now thi... | The main security hole from the blog (CSRF), is not JSON specific. It's just as big a hole using XML instead. Indeed, it's just as bad with no asynchronous calls at all; regular links are just as vulnerable.
When people talk about unique URLs, they generally DON'T mean <http://yourbank.com/json-api/your-name/big-long-... | There are a number of security attacks against JSON, especially XSRF.
The vulnerability occurs when a web service uses cookies for authentication, and responds with a JSON array containing sensitive data in response to a GET request.
If an attacker can trick a user who is logged into a service, naive-webapp.com, into... | JSON security best practices? | [
"",
"javascript",
"ajax",
"security",
"json",
""
] |
I have a database which holds the residents of each house in a certain street. I have a 'house view' php web page which can display an individual house and residents when given the house number using 'post'. I also have a 'street view' web page which gives a list of houses. What I want to know is if you can have links ... | I assume that each house is stored in its own table and has an 'id' field, e.g house id. So when you loop through the houses and display them, you could do something like this:
```
<a href="house.php?id=<?php echo $house_id;?>">
<?php echo $house_name;?>
</a>
```
Then in house.php, you would get the house id using ... | If you want to pass the data using POST instead of GET, you can do it using a combination of PHP and JavaScript, like this:
```
function formSubmit(house_number)
{
document.forms[0].house_number.value = house_number;
document.forms[0].submit();
}
```
Then in PHP you loop through the house-numbers, and create link... | How do you post data with a link | [
"",
"php",
"html",
""
] |
What is the easiest way in Java to map strings (Java `String`) to (positive) integers (Java `int`), so that
* equal strings map to equal integers, and
* different strings map to different integers?
So, similar to `hashCode()` but different strings are required to produce different integers. So, in a sense, it would b... | This is impossible to achieve without any restrictions, simply because there are more possible Strings than there are integers, so eventually you will run out of numbers.
A solution is only possible when you limit the number of usable Strings. Then you can use a simple counter. Here is a simple implementation where al... | Have a look at [perfect hashing](http://en.wikipedia.org/wiki/Perfect_hash_function). | Mapping of strings to integers | [
"",
"java",
""
] |
```
<form action="/Villa/Add" method="post">
<table>
<tr>
<td>
Name:
</td>
<td>
<%= Html.TextBox("name") %>
<%= Html.ValidationMessage("Name") %>
</td>
</tr>
<tr>
<td>
... | This works for ASP.Net MVC Beta.
```
public ActionResult Add( string name ) {
....
}
or
public ActionResult Add( FormCollection form ) {
string name = form["Name"];
}
or
public ActionResult Add( [Bind(Prefix="")]Villa villa ) {
villa.Name ...
}
``` | Have you tried something like this? Pseudocode...
```
public class VillaController : Controller
{
public ActionResult Add(string name)
{
// Code...
}
}
``` | ASP.NET MVC Form Post | [
"",
"c#",
"asp.net-mvc",
""
] |
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file.
So I have this .py file that reads like:
```
starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
```
Then I execute the file and get the data. Since the program is all on my machine ... | ```
vinko@mithril$ more a.py
def foo(a):
print a
vinko@mithril$ more b.py
import a
import inspect
a.foo(89)
print inspect.getsource(a.foo)
vinko@mithril$ python b.py
89
def foo(a):
print a
``` | You might also consider some other means of data persistence. In my own (astronomy) research, I've been experimenting with two different means of storing scripts for reproducibility. The first is to have them exclusively inside a subversion repository, and then have the job submission script automatically commit them. ... | How do you get Python to write down the code of a function it has in memory? | [
"",
"python",
"artificial-intelligence",
""
] |
I am currently doing a code review and the following code made me jump. I see multiple issues with this code. Do you agree with me? If so, how do I explain to my colleague that this is wrong (stubborn type...)?
* Catch a generic exception (Exception ex)
* The use of "if (ex is something)" instead of having another cat... | The mantra is:
* You should only catch exceptions if
you can properly handle them
Thus:
* You should not catch general
exceptions.
---
In your case, yes, you should just catch those exceptions and do something helpful (probably not just eat them--you could `throw` after you log them).
Your coder is using `thr... | > I am currently doing a code review and the following code made me jump. I see multiple issues with this code. Do you agree with me?
Not totally, see below.
> * Catch a generic exception (Exception ex)
In general, catching a generic exception is actually ok as long as you rethrow it (with throw;) when you come to t... | Is this a bad practice to catch a non-specific exception such as System.Exception? Why? | [
"",
"c#",
".net",
"exception",
""
] |
Is it possible to embed a DOS console in a Windows Form or User Control in C# 2.0?
We have a legacy DOS product that my Windows app has to interact with, and it's been requested that an instance of the legacy product should run within the Windows application.
At the moment, I'm using the user32.dll to locate the wind... | It's possible to redirect the standard input/output of console/dos applications using the Process class. It might look something like this:
```
var processStartInfo = new ProcessStartInfo("someoldapp.exe", "-p someparameters");
processStartInfo.UseShellExecute = false;
processStartInfo.ErrorDialog = false;
processSt... | Concerning your question on how to display the DOS app inside the Windows app.
There are a few solutions.
* The first one is to simply not display the DOS app (with CreateNoWindow)
and "simulate" the UI of the DOS app in your Windows application by reading and writing to the streams.
* The other solution would be t... | Embedding a DOS console in a windows form | [
"",
"c#",
"winforms",
"c#-2.0",
"dos",
""
] |
What I'd like to do is provide a link on an intranet web page that will launch a telnet session and pass context information to a shell script that will take the user to a specific "green screen."
This "pseudolink" might help show what I'm looking for:
```
<a href="telnet://<user>:<password>@<host>?showdetail%20123">... | You cannot do this with a telnet: URL in most browsers (IE, FF, afaik). The telnet URL was originally described in RFC 1738, and it provided only information for a hostname, port, username and password.
When you click on it, the browser will usually ask the OS for the default "telnet" handler, which is an external app... | In my opinion, and I'd love to be proved wrong, you will have sandbox (security) problems. Check out [my question here which got little interest](https://stackoverflow.com/questions/376600), but I think it's basically the same thing: you cannot open external apps from the browser unless they are **already** associated ... | How do I launch a specific telnet-based app from a web browser? | [
"",
"javascript",
"html",
"browser",
"telnet",
""
] |
I quite like Rails' database migration management system. It is not 100% perfect, but it does the trick. Django does not ship with such a database migration system (yet?) but there are a number of open source projects to do just that, such as django-evolution and south for example.
So I am wondering, what database mig... | I've been using [South](http://south.aeracode.org/), but [Migratory](http://bitbucket.org/DeadWisdom/migratory/) looks promising as well. | [Migratory](http://bitbucket.org/DeadWisdom/migratory/) looks nice and simple. | What is your favorite solution for managing database migrations in django? | [
"",
"python",
"database",
"django",
"data-migration",
"schema-migration",
""
] |
So I purchased myself an iPhone ... everybody has one ... so I figured I'd **see** what the big deal was. To my surprise ... and overall skepticism ... I must say that I am **very** impressed with the iPhone. There's not any **real** magic going on here ... it just seems to be a **very clean and very easy** to use devi... | If you are talking about webpages, yes it can be done.
See Aaron Rocks post here:[Rock the iPhone with ASP.NET MVC](http://weblogs.asp.net/aaronlerch/archive/2008/06/08/rock-the-iphone-with-asp-net-mvc.aspx) (via [Scott Hanselman](http://www.hanselman.com/blog/TheWeeklySourceCode28IPhoneWithASPNETMVCEdition.aspx))
H... | The apple [developer site](http://developer.apple.com/webapps/) is the best starting point.
You don't need to use a mac for development if you're just doing a web app and you're happy with a browser based interface.
I don't use ASP.NET myself, however there should be nothing special about using it for this, you just ... | What can I do to optimize my web page for a mobile phone, specifically the iPhone? | [
"",
"c#",
"asp.net",
"iphone",
""
] |
I have a script that forces a download and I make a call to this via Javascript. However, the dialog box doesn't pop up, here is the download.php script:
```
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",... | It's not showing the dialog box for the very fact that its an Ajax call.
```
window.location.href = msg;
```
Thats what's redirecting you. I don't think you need an ajax call here, just call the page normally with an href link.
**edit**
If you want the form to submit and show the dialog box for the download, do thi... | If it full download.php script I can't find in it variable $file (only a $filename) - but in JS you send a $file variable. Second: something wrong in JS - why you use such variable name `msg` in `data:` and in `success:`? | Pushing Headers and AJAX | [
"",
"php",
"ajax",
"http-headers",
""
] |
I'm developing an application which currently have hundreds of objects created.
Is it possible to determine (or approximate) the memory allocated by an object (class instance)? | You could use a memory profiler like
.NET Memory Profiler (<http://memprofiler.com/>)
or
CLR Profiler (free) (<http://clrprofiler.codeplex.com/>) | A coarse way could be this in-case you wanna know whats happening with a particular object
```
// Measure starting point memory use
GC_MemoryStart = System.GC.GetTotalMemory(true);
// Allocate a new byte array of 20000 elements (about 20000 bytes)
MyByteArray = new byte[20000];
// Obtain measurements after creating ... | How much memory does a C#/.NET object use? | [
"",
"c#",
".net",
"object",
"memory",
"profiling",
""
] |
What is the best way to store instances of a class to file/database?
We have a base class called Command and loads of derived classes.
Users create instances of these classes by adding commands to a graphical designer
where they can configure them. (Set the properties).
We then need a way to store these "commands" to... | serialization does the trick! Serialization is nothing more than converting an object or a connected graph of objects into a stream of bytes (in order to persist the current state of the object). This can be a binary stream, XML or whatever. You don't have to do this conversion by your own since .Net has great support ... | Are you trying to save the data in tables? or as blob/clob data? Since you mention files, I assume the latter: any of the standard .NET serializers should be fine - they all support inheritance etc. I'd consider for `DataContractSerializer`, as this combines the field-level support (like `BinaryFormatter`), and the ass... | The best way to store class instances to a file/database | [
"",
"c#",
".net",
"serialization",
"persistence",
"object-oriented-database",
""
] |
For example, java.io.File is just a concrete class. My replacement for it supports resolving Windows shortcuts. I need to preprocess constructor parameters to resolve possible .lnk files because the FileSystem object that does normalizing/canonicalision/resolving on the abstract paths is not accessible. The need for pr... | In the specific case you suggest it looks to me like you're better off with a separate factory class that makes the decisions about normalizing/canonicalision/resolving.
Then you can just let File be File. Simpler. | If you really want the subclass route, you can cheat the requirement that a call to `super()` has to be the first line of a subclass constructor by placing your cleanup code outside of your class, or in a static block:
```
public class MyFile extends File {
public MyFile(String path) {
// static blocks a... | Using subclassing to replace a Java class that doesn't implement an interface | [
"",
"java",
"file",
"delegates",
"subclass",
""
] |
The built-in `Math.Pow()` function in .NET raises a `double` base to a `double` exponent and returns a `double` result.
What's the best way to do the same with integers?
Added: It seems that one can just cast `Math.Pow()` result to (int), but will this always produce the correct number and no rounding errors? | A pretty fast one might be something like this:
```
int IntPow(int x, uint pow)
{
int ret = 1;
while ( pow != 0 )
{
if ( (pow & 1) == 1 )
ret *= x;
x *= x;
pow >>= 1;
}
return ret;
}
```
Note that this does not allow negative powers. I'll leave that as an exerci... | LINQ anyone?
```
public static int Pow(this int bas, int exp)
{
return Enumerable
.Repeat(bas, exp)
.Aggregate(1, (a, b) => a * b);
}
```
usage as extension:
```
var threeToThePowerOfNine = 3.Pow(9);
``` | How do you do *integer* exponentiation in C#? | [
"",
"c#",
"math",
"integer",
"exponentiation",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.