Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm trying to run a freshly created ASP.NET Website using C#, however when I do so it launches FireFox and attempts to connect to <http://localhost:1295/WebSite1/Default.aspx> (for example), but after about 10-15 seconds it displays a "Connection Interrupted - The connection to the server was reset while the page was l... | When you launch the application, a little info mark appears at the right bottom of your screen telling you that the local web server was started and on wich port. You should compare that port to the one that appears in your browser. If they are different, an anti-virus could be responsible for that problem.
Another pla... | I had the same problem, and when I was about to quit and run away and join a monastry I had an idea to check ELMAH - maybe it had caught it...
Sure enough, ELMAH told me it had caught this:
```
System.Web.HttpException (0x80004005): Maximum request length exceeded.
```
and this fixed it:
```
<system.web>
<httpRun... | What could cause "Connection Interrupted" on LocalHost when debugging in ASP.NET | [
"",
"c#",
"asp.net",
"localhost",
""
] |
I have a list of articles, and each article belongs to a section.
```
class Section(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
class Article(models.Model):
section = models.ForeignKey(Section)
headline = models.CharField(max_length=200)
# ...
```
I w... | Following Jeb's suggeston in a comment, I created a [custom template tag](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags).
I replaced `{{ forloop.counter }}` with `{% counter %}`, a tag that simply prints how many times it's been called.
Here's the code for my counter ta... | This isn't exactly neat, but may be appropriate for someone:
```
{% for article in articles %}
{% ifchanged article.section %}
{% if not forloop.first %}</ul>{% endif %}
<h4>{{article.section}}</h4>
<ul>
{% endifchanged %}
<li>{{forloop.counter}}. {{ article.headline }}</li>
... | Django Template System: How do I solve this looping / grouping / counting? | [
"",
"python",
"django",
"django-templates",
""
] |
I'd like to send mail without bothering with the SMTP-Server which is used for delivery.
So [JavaMail API](http://java.sun.com/products/javamail/) doesn't work for me because I have to specify a SMTP server to connect to.
I'd like the library to find out on its own which SMTP server is responsible for which email add... | This is completely the wrong way to handle this.
Anyone connected to the internet will have some kind of "legit" SMTP server available to them to take the submission of email -- your ISP, your office, etc.
You WANT to leverage because they do several things for you.
1) they take your message and the responsibility t... | One possible solution: get the MX record on your own and use [JavaMail API](http://java.sun.com/products/javamail/).
You can get the MX record using the [dnsjava](http://www.dnsjava.org/) project:
Maven2 dependency:
```
<dependency>
<groupId>dnsjava</groupId>
<artifactId>dnsjava</artifactId>
<version>2.0... | Someone knows a mail (SMTP) delivery library for Java? | [
"",
"java",
"smtp",
"email",
"james",
""
] |
The first batch file launches a command prompt, i need the second command to be in the ccontext of the first. how can I do this in python?
As is, it launches the batch, and blocks until the batch (with its command prompt context) terminates, and then executes `devenv` without the necessary context.
```
os.system(r'%c... | I these situations I use script that does it all. That way you can chain as much as you want. Sometimes I will generate the script on the fly.
```
compileit.cmd
call C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat
devenv $1.sln /rebuild Debug /Out last-build.txt
``` | I think that the proper way for achieving this would be running this command:
```
%comspec% /C "%VCINSTALLDIR%\vcvarsall.bat" x86 && vcbuild "project.sln"
```
Below you'll see the Python version of the same command:
```
os.system('%comspec% /C "%VCINSTALLDIR%\\vcvarsall.bat" x86 && vcbuild "project.sln"')
```
This ... | launching vs2008 build from python | [
"",
"python",
"windows",
"visual-studio-2008",
"build-automation",
""
] |
I would like to know if it is possible, to select certain columns from one table, and another column from a second table, which would relate to a non imported column in the first table. I have to obtain this data from access, and do not know if this is possible with Access, or SQL in general. | Assuming the following table structure:
```
CREATE TABLE tbl_1 (
pk_1 int,
field_1 varchar(25),
field_2 varchar(25)
);
CREATE TABLE tbl_2 (
pk_2 int,
fk_1 int,
field_3 varchar(25),
field_4 varchar(25)
);
```
You could use the following:
```
SELECT t1.field_1, t2.field_3
FROM tbl_1 t1
INN... | What you are looking for are JOINs:
<http://en.wikipedia.org/wiki/Join_(SQL)>
You need primary keys for the referenced data sets and foreign keys in the first table. | SQL statement from two tables | [
"",
"sql",
"ms-access",
""
] |
.NET 3.5, C#
I have a web app with a "search" feature. Some of the fields that are searchable are first-class columns in the table, but some of them are in fact nested fields inside an XML data type.
Previously, I built a system for dynamically constructing the SQL for my search. I had a nice class hierarchy that bui... | Now that is an interesting question.
Right now, you cannot instruct SQL Server to perform XML functions directly from Linq.
However, you can get Linq to use user defined functions...
so, you could setup a udf to process the xml, get the right data, etc, and then use that in your Linq expresion. This will execute on th... | To clarify Daniel's answer - you cannot use a function to do this unless the XPath part of the query is fixed. See my blog entry on this: <http://conficient.wordpress.com/2008/08/11/linq-to-sql-faq-xml-columns-in-sql/>
Basically you cannot query an xml column via LINQ to SQL. Although it returns an XElement type you c... | Can LINQ to SQL query an XML field DB-serverside? | [
"",
"sql",
"xml",
"linq-to-sql",
".net-3.5",
""
] |
```
class C {
T a;
public:
C(T a): a(a) {;}
};
```
Is it legal? | Yes it is legal and works on all platforms.
It will correctly initialize your member variable a, to the passed in value a.
It is considered by some more clean to name them differently though, but not all. I personally actually use it a lot :)
Initialization lists with the same variable name works because the syntax o... | One of the things that may lead to confusion regarding this topic is how variables are prioritized by the compiler. For example, if one of the constructor arguments has the same name as a class member you could write the following in the initialization list:
```
MyClass(int a) : a(a)
{
}
```
But does the above code h... | Can I use identical names for fields and constructor parameters? | [
"",
"c++",
"parameters",
"constructor",
""
] |
I'm trying to get a specific asp:button onclick event to fire when I press the enter key in a specific asp:textbox control.
The other factor to be taken into account is that the button is within a asp:Login control template.
I've no idea how to do this, suggestions on a postcard please. | You could look at the [`DefaultButton`](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.panel.defaultbutton.aspx) property of the panel control. | You could set the DefaultButton property on the form. Either as an attribute of the form tag in your markup DefaultButton = "btnSubmit" or using something like this in your code-behind:
```
Page.Form.DefaultButton = "btnSubmit"
``` | Call a specific button onClick event when the enter key is pressed C# | [
"",
"c#",
"onclick",
"keypress",
"enter",
""
] |
Let's say I wanted to make a python script interface with a site like Twitter.
What would I use to do that? I'm used to using curl/wget from bash, but Python seems to be much nicer to use. What's the equivalent?
(This isn't Python run from a webserver, but run locally via the command line) | For something like Twitter, you'll save yourself a ton of time by not reinventing the wheel. Try a library like [python-twitter](http://code.google.com/p/python-twitter/). This way, you can write your script, or even a full fledged application, that interfaces with Twitter, and you don't have to care about the implemen... | Python has urllib2, which is extensible library for opening URLs
Full-featured easy to use library.
<https://docs.python.org/library/urllib2.html> | What Python tools can I use to interface with a website's API? | [
"",
"python",
"web-services",
"twitter",
""
] |
We've used both JWebUnit and HttpUnit in the past to do functional tests of web applications. Both of them seem to have issues in handling javascript. We are not particularly interested in testing the javascript at this point, but JWebUnit and HttpUnit tests have broken since we added some small Ajax components (Dojo D... | [Canoo's WebTest](http://webtest.canoo.com/webtest/manual/Downloads.html) is pretty good and can handle what you're looking for. | You want [HtmlUnit](http://htmlunit.sourceforge.net/).
It isn't perfect browser emulation (for that you need a browser driver) but it has significant javascript support. Check out the [introduction to testing your JavaScript](http://htmlunit.sourceforge.net/javascript-howto.html). | Replacement for JWebUnit / HttpUnit | [
"",
"java",
"testing",
"continuous-integration",
"web-testing",
""
] |
If you have a Java object and an XML schema (XSD), what is the best way to take that object and convert it into an xml file in line with the schema. The object and the schema do not know about each other (in that the java classes weren't created from the schema).
For example, in the class, there may be an integer fiel... | I believe this can be achieved via JAXB using it's annotations. I've usually found it much easier to generate Objects from JAXB ( as defined in your schema) using XJC than to map an existing Java object to match my schema. YMMV. | I'm doing Object do XML serialization with XStream. What don't you find "obvious" with this serializer? Once you get the hang of it its very simple.
In the example you provided you could have something like this:
```
...
XStream xstream = new XStream(new DomDriver());
xstream.alias("myclass", MyClass.class);
xstream... | Java object to XML schema | [
"",
"java",
"xml",
"object",
""
] |
I would like to include a different file depending on the version of GCC. More precisely I want to write:
```
#if GCC_VERSION >= 4.2
# include <unordered_map>
# define EXT std
#elif GCC_VERSION >= 4
# include <tr1/unordered_map>
# define EXT std
#else
# include <ext/hash_map>
# define unordered_map __gnu_cxx::ha... | Ok, after more searches, it one possible way of doing it is using `__GNUC_PREREQ` defined in `features.h`.
```
#ifdef __GNUC__
# include <features.h>
# if __GNUC_PREREQ(4,0)
// If gcc_version >= 4.0
# elif __GNUC_PREREQ(3,2)
// If gcc_version >= 3.2
# else
// Else
# endif
#else
// If not gcc
... | There are a number of macros that should be defined for your needs:
```
__GNUC__ // major
__GNUC_MINOR__ // minor
__GNUC_PATCHLEVEL__ // patch
```
The version format is major.minor.patch, e.g. 4.0.2
The documentation for these can be found [here](http://gcc.gnu.org/onlinedocs/cpp/Common-Predefi... | How to test the current version of GCC at compile time? | [
"",
"c++",
"c",
"gcc",
"versions",
""
] |
I'm stuck in having to write a simple spam filter
I'm not really sure about how I'm going to do it.
So far I've come up with wordlist and domain filtering, which will give or remove points up to a certain threshold.
For example, if you're writing about "v1agr4" from a blacklisted domain, you'll get like 2 points for ... | Some really good algorithm info here:
<http://www.paulgraham.com/spam.html>
<http://www.paulgraham.com/better.html>
But, seriously, why reinvent the wheel?
Just download K9: <http://keir.net/k9.html> | Some open source Java projects related to Bayesian Spam Filtering (that was mentioned by LFSR Consulting):
* [Classifier4j](http://classifier4j.sourceforge.net/)
* [jBNC](http://sourceforge.net/project/showfiles.php?group_id=49871)
* [Naiban](http://www.tempeststrings.com/naiban/)
And one extra for C++:
* [SpamProbe... | How to write spam filter | [
"",
"java",
"email-spam",
""
] |
**In C#, is there a way to instantiate an instance of a class without invoking its constructor?**
Assume the class is public and is defined in a 3rd party library and the constructor is internal. The reasons I want to do this are complicated but it would be helpful to know if it's possible using some kind of C# hacker... | I have not tried this, but there is a method called [FormatterServices.GetUninitializedObject](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatterservices.getuninitializedobject.aspx) that is used during deserialization.
Remarks from MSDN says:
> Because the new instance of the object
> is ... | Actually it sounds like they made the constructor internal just so you can't instantiate it. It may have a builder or factory method.
Check out these articles:
[Preventing Third Party Derivation: Part 1](http://blogs.msdn.com/ericlippert/archive/2008/09/26/preventing-third-party-derivation-part-one.aspx)
[Preventing... | Create object instance without invoking constructor? | [
"",
"c#",
""
] |
What is the most concise and efficient way to find out if a JavaScript array contains a value?
This is the only way I know to do it:
```
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
```
Is there a better ... | Modern browsers have [`Array#includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#browser_compatibility), which does *exactly* that and [is widely supported](https://kangax.github.io/compat-table/es2016plus/#test-Array.prototype.includes) by everyone except IE:
```... | **Update from 2019: This answer is from 2008 (11 years old!) and is not relevant for modern JS usage. The promised performance improvement was based on a benchmark done in browsers of that time. It might not be relevant to modern JS execution contexts. If you need an easy solution, look for other answers. If you need t... | How do I check if an array includes a value in JavaScript? | [
"",
"javascript",
"arrays",
"algorithm",
"time-complexity",
"javascript-objects",
""
] |
I am writing a small program. The interface I am writing to control each repository that is made defines a method of Save(IPublicObject). I am using LINQ for the SQL Version of the repository CRUD. My question is this. I would like to have only the one method which accepts the interface type. I want to think how I can ... | For LINQ-to-SQL, the data-context already does a lot of the mapping for you. As such, I think generics might be the best way to achieve a save while still having some consideration of your interface (although I'm not quite sure what the interface is giving you in this scenario...).
You can access the generic aspect of... | What you wish to do is to have a:
```
Repository.Save(publicObject)
```
and the repository to call a method from publicObject?
If this is the requirement then you can define the Save method in repository as:
```
public class Repository {
public void Save(IPublicObject publicObject) {
publicObject.Save()... | LINQ, Polymorphism, MetaDataMapping, Inheritance Mapper | [
"",
"c#",
"linq",
"poeaa",
""
] |
Is there a max length for an array in C++?
Is it a C++ limit or does it depend on my machine? Is it tweakable? Does it depend on the type the array is made of?
Can I break that limit somehow or do I have to search for a better way of storing information? And what should be the simplest way?
What I have to do is stor... | There are two limits, both not enforced by C++ but rather by the hardware.
The first limit (should never be reached) is set by the restrictions of the size type used to describe an index in the array (and the size thereof). It is given by the maximum value the system's `std::size_t` can take. This data type is large e... | Nobody mentioned the limit on the size of the **stack frame**.
There are two places memory can be allocated:
* On the heap (dynamically allocated memory).
The size limit here is a combination of available hardware and the OS's ability to simulate space by using other devices to temporarily store unused data (**i.... | Is there a max array length limit in C++? | [
"",
"c++",
"arrays",
""
] |
We have a system where customers, mainly European enter texts (in UTF-8) that has to be distributed to different systems, most of them accepting UTF-8, but now we must also distribute the texts to a US system which only accepts US-Ascii 7-bit
So now we'll need to translate all European characters to the nearest US-Asc... | The [uni2ascii](http://billposer.org/Software/uni2ascii.html) program is written in C, but you could probably convert it to Java with little effort. It contains a large table of approximations (implicitly, in the switch-case statements).
Be aware that there are no universally accepted approximations: Germans want you ... | You can do this with the following (from the NFD example in [this Core Java Technology Tech Tip](http://web.archive.org/web/20070917051642/http://java.sun.com/mailers/techtips/corejava/2007/tt0207.html#1)):
```
public static String decompose(String s) {
return java.text.Normalizer.normalize(s, java.text.Normalizer... | How to convert UTF-8 to US-Ascii in Java | [
"",
"java",
"utf-8",
"ascii",
""
] |
I have a single user java program that I would like to have store data in a light weight database such as Derby or Sqlite. I would like to use a data abstraction layer in my program. Hibernate appears to require a lot of configuration and is overkill for what I need. What are light weight alternatives to Hibernate? | Hibernate requires next to zero configuration if you use annotations. It even can auto-discover mapped beans in the classpath! I don't see any alternative to it from both simplicity **and** power point of view.
It can also expose itself as JPA, which is (IMHO) even simpler. | My [ORMLite](http://ormlite.com/) library is one such alternative. It supports MySQL, Postgres, Microsoft SQL Server, H2, Derby, HSQLDB, and Sqlite, and can be easily extended to others. It uses annotations to configure classes, good Spring support, flexible query builder, etc.. | Light weight alternative to Hibernate? | [
"",
"java",
"database",
"hibernate",
"sqlite",
""
] |
So the [transparent background problem](https://stackoverflow.com/questions/214215/user-drawn-controls-are-using-the-previous-forms-background) is solved. Now, every time I show the form (or have to have it repainted), I get a lot of flickering. Is there any way I can not update the screen until the paint event is comp... | Did you try setting the [DoubleBuffered](https://stackoverflow.com/questions/220100/how-do-i-enable-double-buffering-of-a-control-using-c-window-forms) property for the form? | Double Buffering might help, another thing you might want to try is:
SuspendLayout();
dostuffhere...
ResumeLayout(); | How to avoid screen flickering when showing form with user drawn controls? | [
"",
"c#",
".net",
"winforms",
"user-controls",
"onpaint",
""
] |
I have a loop that reads each line in a file using `getline()`:
```
istream is;
string line;
while (!getline(is, line).eof())
{
// ...
}
```
I noticed that calling `getline()` like this also seems to work:
```
while (getline(is, line))
```
What's going on here? `getline()` returns a stream reference. Is it bein... | The `istream` returned by `getline()` is having its operator `void*()` method implicitly called, which returns whether the stream has run into an error. As such it's making more checks than a call to `eof()`. | **Updated:**
I had mistakenly pointed to the [basic\_istream documentation](http://www.unc.edu/depts/case/pgi/pgC++_lib/stdlibcr/bas_3074.htm#Sentry%20Classbool()) for the operator bool() method on the basic\_istream::sentry class, but as has been pointed out this is not actually what's happening. I've voted up Charle... | std::getline() returns | [
"",
"c++",
"getline",
""
] |
I've written a VB.NET application that uses SQL CE 3.5. I'm curious if anyone has any best practice or code to help check if A) SQL CE is installed and B) If so, what version.
I searched msdn and google for anything but I didn't find anything helpful. I was poking around the registry and found this key:
HKEY\_LOCAL\_M... | The widely accepted method for doing this is checking the product identifier (GUID) which is saved in the registry by the MSI installer. If you dont have the product in question installed you can crack open the MSI with a tool called Orca (part of Windows SDK) and grab the GUID that way. Most if not all install builder... | Not sure if you are talking about SQL CE on a Windows machine or a portable device. On a PC, your best bet is to distribute the version of SQL CE with your application. You can register for the rights to do so at <http://www.microsoft.com/Sqlserver/2005/en/us/compact-redistribute.aspx>. | The best way to check if SQL CE is installed, and if so what version? | [
"",
".net",
"sql",
"vb.net",
"sql-server-ce",
""
] |
I've been hearing/reading a lot about the new language enhancements for C# 4. I'm a little curious if these same enhancements are also going to be applied to VB as well, or what. Does anyone know where I can get some insight here? With all the new changes happening to C#, it seems like there will very little reason lef... | I'd actually overlook the dismissal of VB.Net by Lou Franco. Checkout Panopticon Central:
* <http://www.panopticoncentral.net/archive/2008/10/31/24803.aspx>
* <http://www.panopticoncentral.net/archive/2008/10/29/24764.aspx>
For example:
> Then Lucian did a really wonderful
> demo of VB 10.0, which is shipping in
> V... | Some of the changes to C# (e.g Named Optional Parameters) were already in VB. The main strength of VB.NET over C# was Office/COM integration, and the new C# is addressing that.
If you need to target an older .NET version, VB.NET will still be the one to use if you need these features. | New vb.net enhancements? | [
"",
"c#",
"vb.net",
""
] |
This code:
```
#include <iostream>
int main( int, char **argv )
{
std::cout << 1.23e45 << std::endl;
}
```
prints
> 1.23e+045
when compiled with MS Visual Studio 2003, and
> 1.23e+45
on my Linux machine.
How can I specify the width of the exponent field (and why is there a difference in the first place)? | I don't think this is possible with standard manipulators. (if it is, I'd love to be corrected and learn how)
Your only remaining option is creating a streambuf yourself, and intercepting all exponent numbers that go to the stream, reformat them by hand, and pass them on to the underlying stream.
Seems a lot of work,... | As a follow-up of @Pieter's answer, I've been looking inside the operator<< (ostream&, double). Indeed, there is no field to specify the significance or width of the exponent. On windows, the operator<< forwards to sprintf, which has no exponent-size either.
In it's turn, the sprintf function (on Windows) calls into \... | How to set the width of the exponent field for an ostream? | [
"",
"c++",
""
] |
These two methods exhibit repetition:
```
public static Expression<Func<Foo, FooEditDto>> EditDtoSelector()
{
return f => new FooEditDto
{
PropertyA = f.PropertyA,
PropertyB = f.PropertyB,
PropertyC = f.PropertyC,
PropertyD = f.PropertyD,
PropertyE = f.PropertyE
};
}... | If `FooEditDto` is a sublass of `FooDto` and you don't need the MemberInitExpressions, use a constructor:
```
class FooDto
{ public FooDto(Bar a, Bar b, Bar c)
{ PropertyA = a;
PropertyB = b;
PropertyC = c;
}
public Bar PropertyA {get;set;}
public Bar PropertyB {get;set;}
public Bar Prop... | Well, I have a *really horrible* way you could do it.
You could write a method which used reflection (bear with me!) to work out all the properties for a particular type, and built a delegate (using Reflection.Emit) to copy properties from that type to another. Then use an anonymous type to make sure you only need to ... | Refactor To Eliminate Repetition In Lambda Expression | [
"",
"c#",
"refactoring",
"lambda",
""
] |
I was watching [Anders' talk about C# 4.0 and sneak preview of C# 5.0](http://channel9.msdn.com/pdc2008/TL16/), and it got me thinking about when optional parameters are available in C# what is going to be the recommended way to declare methods that do not need all parameters specified?
For example something like the ... | I'd consider the following:
* Do you need your code to be used from languages which don't support optional parameters? If so, consider including the overloads.
* Do you have any members on your team who violently oppose optional parameters? (Sometimes it's easier to live with a decision you don't like than to argue th... | When a method overload normally performs the same thing with a different number of arguments then defaults will be used.
When a method overload performs a function differently based on its parameters then overloading will continue to be used.
I used optional back in my VB6 days and have since missed it, it will reduc... | Should you declare methods using overloads or optional parameters in C# 4.0? | [
"",
"c#",
"c#-4.0",
"overloading",
"optional-parameters",
""
] |
I have just started migrating my homegrown persistence framework to JPA.
Given that the persistence frameworks hide a lot of the plumbing, I'm interested in knowing if NOT closing EntityManagers will create a resource leak, or if the frameworks will collect and close them for me.
I intend in all places to close them,... | It depends how you obtained it.
If you created it using EntityManagerFactory you will have to close it no matter what framework you use.
If you obtained it using dependency injection (eg using EJB and [@PersistenceContext](https://docs.oracle.com/javaee/7/api/javax/persistence/PersistenceContext.html) annotation) you... | You should.
Frameworks have no idea how you intend to use the EM, so they cannot close it (except, may be, on finalization, which is not guaranteed). Yes, not closing them would create a resource leak.
The idea is the same as "always close java.sql.Connection" (despite some data sources have settings to close them au... | Do I have to close() every EntityManager? | [
"",
"java",
"jpa",
"persistence",
"toplink",
""
] |
This is probably a simple answer but I can't find it. I have a table with a column of integers and I want to ensure that when a row is inserted that the value in this column is greater than zero. I could do this on the code side but thought it would be best to enforce it on the table.
Thanks!
I was in error with my l... | You can use a check constraint on the column. IIRC the syntax for this looks like:
```
create table foo (
[...]
,Foobar int not null check (Foobar > 0)
[...]
)
```
As the poster below says (thanks Constantin), you should create the check constraint outside the table definition and give it a meaningful name... | Create a database constraint:
```
ALTER TABLE Table1 ADD CONSTRAINT Constraint1 CHECK (YourCol > 0)
```
You can have pretty sophisticated constraints, too, involving multiple columns. For example:
```
ALTER TABLE Table1 ADD CONSTRAINT Constraint2 CHECK (StartDate<EndDate OR EndDate IS NULL)
``` | In SQL Server 2005, how do I set a column of integers to ensure values are greater than 0? | [
"",
"sql",
"sql-server-2005",
"constraints",
"check-constraints",
""
] |
FreeMarker templates support an if-statement with the following syntax
```
<#if hot>
It's hot.
</#if>
```
I've looked in the documentation and can't find any support for an if-else statement. Of course, I could achieve the same result with:
```
<#if hot>
It's hot.
</#if>
<#if !hot>
It's not hot.
</#if>
``... | Yes, you can write:
```
<#if hot>
it's hot
<#else>
it's not
</#if>
```
And if you're doing lots of freemarker, I really can recommend IntelliJ IDEA 8, its freemarker support really helps... | Yes, the sintaxis is:
```
<#if condition>
...
<#elseif condition2>
...
<#elseif condition3>
...
<#else>
...
<#/if>
```
You can find [Freemarker complete reference](http://freemarker.sourceforge.net/docs/)
If you are using Netbeans, there is [this plugin](http://plugins.netbeans.org/PluginPortal/faces/PluginListPage.... | if-else in FreeMarker template | [
"",
"java",
"template-engine",
"freemarker",
""
] |
Let's say I'm running a simple server and have `accept()`ed a connection from a client.
What is the best way to tell when the client has disconnected? Normally, a client is supposed to send a close command, but what if it disconnects manually or loses network connection altogether? How can the server detect or handle ... | select (with the read mask set) will return with the handle signalled, but when you use ioctl\* to check the number of bytes pending to be read, it will be zero. This is a sign that the socket has been disconnected.
This is a great discussion on the various methods of checking that the client has disconnected: [Stephe... | In TCP there is only one way to detect an orderly disconnect, and that is by getting zero as a return value from `read()/recv()/recvXXX()` when reading.
There is also only one reliable way to detect a broken connection: by writing to it. After enough writes to a broken connection, TCP will have done enough retries and... | Detecting TCP Client Disconnect | [
"",
"c++",
"sockets",
"tcp",
""
] |
Presently I have a some legacy code, which generates the op code. If the code has more number of macros then the code generation takes so much of time (In terms of hours!!).
I have gone through the logic, they are handling the macro by searching for it and doing a replace of each variable in it some thing like inlining... | You **must** tokenize your input before starting this kind of process. (I can't recommend the famous [Dragon Book](http://en.wikipedia.org/wiki/21st_Century_Compilers) highly enough - even the ancient edition stood the test of time, the updated 2006 version looks great). Compiling is the sort of job that's best split u... | I have an application which has its own grammer. It supports all types of datatypes that a typical compiler supports (Even macros). More precisely it is a type of compiler which generates the opcodes by taking a program (which is written using that grammer) as input.
For handling the macros, it uses the text replacemen... | Macro Replacement during Code Generation | [
"",
"c++",
"compiler-construction",
"macros",
""
] |
At the moment my code looks like this:
```
# Assign values for saving to the db
$data = array(
'table_of_contents' => $_POST['table_of_contents'],
'length' => $_POST['length']
);
# Check for fields that may not be set
if ( isset($_POST['lossless_copy']) )
{
$data = array(
'lossless_copy' => $_POST['... | How about this:
```
// this is an array of default values for the fields that could be in the POST
$defaultValues = array(
'table_of_contents' => '',
'length' => 25,
'lossless_copy' => false,
);
$data = array_merge($defaultValues, $_POST);
// $data is now the post with all the keys set
```
`array_merge()`... | ```
foreach ($_POST as $key => $value) {
$data[$key] = $value;
}
```
remember to sanitize your $\_POST values!
**edit**: if you're looking to match up optional $\_POST values with fields that may or may not exist in your table, you could do something like this (i'm assuming you're using mysql):
```
$fields = array... | How to check for optional fields in $_POST | [
"",
"php",
"forms",
"post",
""
] |
This is a follow-up to [two](https://stackoverflow.com/questions/269417/which-language-should-i-use) [questions](https://stackoverflow.com/questions/271488/linking-languages) I asked a week or so back. The upshot of those was that I was building a prototype of an AI-based application for the web, and I wondered what la... | "how easy is CGI programming in python?" Easier than C, that's for sure. Python is easier because -- simply -- it's an easier language to work with than C. First and foremost: no memory allocation-deallocation. Beyond that, the OO programming model is excellent.
Beyond the essential language simplicity, the Python [WS... | Python is a good choice.
I would avoid the CGI model though - you'll pay a large penalty for the interpreter launch on each request. Most Python web frameworks support [the WSGI standard](http://www.wsgi.org/wsgi/) and can be hooked up to servers in a myriad of ways, but most live in some sort of long-running process ... | Using python to build web applications | [
"",
"python",
"cgi",
""
] |
What is the difference between `atan` and `atan2` in C++? | [`std::atan2`](http://en.cppreference.com/w/cpp/numeric/math/atan2) allows calculating the arctangent of all four quadrants. [`std::atan`](http://en.cppreference.com/w/cpp/numeric/math/atan) only allows calculating from quadrants 1 and 4. | From school mathematics we know that the tangent has the definition
```
tan(α) = sin(α) / cos(α)
```
and we differentiate between four quadrants based on the angle that we supply to the functions. The sign of the `sin`, `cos` and `tan` have the following relationship (where we neglect the exact multiples of `π/2`):
... | What is the difference between atan and atan2 in C++? | [
"",
"c++",
"math.h",
""
] |
I am reworking some ui in an application written by freelance .Net developers from another country.
I am not going to go into how bad the code is and entangled the code with structure content and presentation are...
But one of the things I notice is that menu for accessing the parts of the app is made with Button con... | You could re-style the buttons to look like links, then you can maintain any server-side code, and not have to rely on javascript like the LinkButton does.
```
.linkButton
{
background-color: transparent;
border-style: none;
color: /* Something nice */
cursor: pointer;
text-align: left;
text-decorati... | A LinkButton is just that--an anchor tag with javascript that submits the page's form. If you don't want that behavior, don't use a link button. Just use a standard anchor tag.
I've used LinkButtons in the past because its a very easy way to merge the behavior of a button with the style of a regular html link. Noobs m... | Why would someone use Button instead of LinkButton control in navigation | [
"",
"c#",
".net",
"web-applications",
""
] |
I have a toolstrip containing, among other things, a ToolStripComboBox and a ToolStripButton. I want to add a ContextMenuStrip to both of them, but I don't have direct access to the toolstrip or its other contents, so I can't set the context menu of the toolstrip.
Setting the ContextMenuStrip for the ToolStripComboBox... | What Jeff Yates has suggested should work.
However, another alternative is to create your own derived classes (MyToolSTripButton, MyToolStripTextBox ...etc) give these items a ContextMenuStrip property that you can set at design time, and have your derived classes detect the right mouse down, or whatever other events ... | You will need to set the context menu to the ToolStrip and then handle the Popup of the context menu or a related event and hit test which button the mouse is over to determine if you should show the ToolStrip's context menu and what it should contain. | How do I add a ContextMenuStrip to a ToolStripButton? | [
"",
"c#",
"winforms",
"contextmenustrip",
"toolstripbutton",
""
] |
What exactly does *immutable* mean - that is, what are the consequences of an object being mutable or immutable? In particular, why are Java's `String`s immutable?
My understanding is that the `StringBuilder` type is something like a mutable equivalent to `String`. When would I use `StringBuilder` rather than `String`... | Immutable means that once the constructor for an object has completed execution that instance can't be altered.
This is useful as it means you can pass references to the object around, without worrying that someone else is going to change its contents. *Especially when dealing with concurrency, there are no locking is... | An immutable object is an object where the internal fields (or at least, all the internal fields that affect its external behavior) cannot be changed.
There are a lot of advantages to immutable strings:
**Performance:** Take the following operation:
```
String substring = fullstring.substring(x,y);
```
The underlyi... | What is meant by immutable? | [
"",
"java",
"string",
"immutability",
""
] |
I usually type my map declarations but was doing some maint and found one without typing. This got me thinking (Oh No!). What is the default typing of a Map declaration. Consider the following:
```
Map map = new HashMap();
map.put("one", "1st");
map.put("two", new Integer(2));
map.put("three", "3rd");
for (Map.Entry e... | The type is *java.lang.Object*.
The *for* construct takes a type of *Iterable* and calls its *iterator* method. Since the *Set* isn't typed with generics, the iterator returns objects of type *Object*. These need to be explicitly cast to type *Map.Entry*.
```
Map map = new HashMap();
map.put("one", "1st");
map.put("t... | There is no default type.
The types in Java generics are only for compile-time checking. They are erased at runtime and essentially gone.
Think of generics as a static helper to a) better document your code, and b) enable some limited compile-time checking for type safety. | HashMap default types for K and V | [
"",
"java",
"generics",
"collections",
""
] |
I am evaluating several Javascript UI toolkits for building web applications that have a desktop-like feel, mainly because of dialogs and window management.
I looked at several options - here are my evaluations so far:
* [ExtJS](http://extjs.com/) - Great widget library, great docs! Not so great license.
* [jQuery UI... | In terms of a desktop look/feel the best of that bunch has to be ExtJS. In terms of the UI it really is leaps ahead of the rest. Of course there are licensing issues but they have their FLOSS exceptions and if you intend to make money from the project then a commercial license isn't exactly going to break the bank.
Ot... | Have you thought about GWT (Google Web Toolkit <http://code.google.com/webtoolkit/> )? | Javascript library for building desktop-like web application: ExtJS, jQuery, YahooUI, Mocha, SproutCore, Cappuccino, others? | [
"",
"javascript",
"jquery",
"extjs",
"yui",
"mootools",
""
] |
I am running my `HTTPServer` in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.
The Python documentation states that `BaseHTTPServer.HTTPServer` is a subclass of `SocketServer.TCPServer`, which supports a `shutdo... | I should start by saying that "I probably wouldn't do this myself, but I have in the past". The serve\_forever (from SocketServer.py) method looks like this:
```
def serve_forever(self):
"""Handle one request at a time until doomsday."""
while 1:
self.handle_request()
```
You could replace (in subclas... | Another way to do it, based on <http://docs.python.org/2/library/basehttpserver.html#more-examples>, is: instead of serve\_forever(), keep serving as long as a condition is met, with the server checking the condition before and after each request. For example:
```
import CGIHTTPServer
import BaseHTTPServer
KEEP_RUNNI... | How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass? | [
"",
"python",
"http",
"basehttpserver",
""
] |
This isn't my code; I am trying to figure out what exactly this does. This is a part of a big, ancient system written in C (actually it was written 4 years ago, but most likely written by a late 80s programmer mentality). Part of the code:
```
char DestFile[256];
char DestFile2[256];
//This part is just to show an ex... | You are correct.
In C a string is an array of chars terminated by a character with ASCII code 0.
So, first, DestFile is copied to DestFile2
Then a scan from the right is performed, to find the right-most occurrence of '.'
This returns a pointer to the char that matches, or null if no occurrence is found.
So now you... | Yeah, that's what it looks like to me too. It's renaming any .gz or .Z (gzipped or Unix Compressed files) to remove the extension.
Why it would want to do that beats me. The only use I've seen for doing such things is to get around fascist email servers that don't allow compressed attachments through. | Does this code remove a file extension? | [
"",
"c++",
"c",
""
] |
How do you do your Hibernate session management in a Java Desktop Swing application? Do you use a single session? Multiple sessions?
Here are a few references on the subject:
* <http://www.hibernate.org/333.html>
* <http://blog.schauderhaft.de/2008/09/28/hibernate-sessions-in-two-tier-rich-client-applications/>
* <ht... | Single session. Start transaction when you need to do a set of operations (like update data after dialog box OK button), commit the tx at the end. The connection though is constantly open (since it's the same session), and thus all opportunities for caching can be used by both Hib and RDBMS.
It may also be a good idea... | Don't use a single session. For everything but the smallest applications, it will grow, collecting outdated data and become slower and slower, since the dirty check needs to check every entity in the session.
If you don't need/want lazy loading and tracking of changes by Hibernate, you can use short-lived sessions.
B... | Session management using Hibernate in a Swing application | [
"",
"java",
"database",
"hibernate",
"swing",
"session",
""
] |
Say I have a string of 16 numeric characters (i.e. 0123456789012345) what is the most efficient way to delimit it into sets like : 0123-4567-8901-2345, in PHP?
Note: I am rewriting an existing system that is painfully slow. | Use [str\_split()](http://php.net/str_split):
```
$string = '0123456789012345';
$sets = str_split($string, 4);
print_r($sets);
```
The output:
```
Array
(
[0] => 0123
[1] => 4567
[2] => 8901
[3] => 2345
)
```
Then of course to insert hyphens between the sets you just [implode()](http://php.net/implo... | This is a bit more general:
```
<?php
// arr[string] = strChunk(string, length [, length [...]] );
function strChunk() {
$n = func_num_args();
$str = func_get_arg(0);
$ret = array();
if ($n >= 2) {
for($i=1, $offs=0; $i<$n; ++$i) {
$chars = abs( func_get_arg($i) );
$re... | Most efficient way to delimit key | [
"",
"php",
"string",
""
] |
One of the [appropriate uses](http://www.sqlite.org/whentouse.html) for [sqlite3](http://www.sqlite.org) is "in-memory databases". This sounds like a really useful tool for my C++ applications. Does anyone have an example of how this is done in C or C++? I'm specifically looking for a canonical way to slurp several fla... | It's actually quite easy. Just specify ':memory:' as the database filename when opening a database using the C/C++ API. It's a special constant that the engine will recognize. The same actually works for other languages such as Python or Ruby, since they typically just wrap the C/C++ API. See <http://sqlite.org/c3ref/o... | Just open the file :memory: and that should do it (at least it does in PHP).
You mention that you want to read in several flat files and do joins on them. If it's possible to store the flat files as SQLite databases, you can work directly with both by attaching one to the other:
```
ATTACH foo.db AS foo
```
Then ref... | How do I create a sqllite3 in-memory database? | [
"",
"c++",
"c",
"database",
"sqlite",
"in-memory-database",
""
] |
Using jQuery, what's the best way to find the next form element on the page, starting from an arbitrary element? When I say form element I mean `<input>`, `<select>`, `<button>` or `<textarea>`.
In the following examples, the element with the id "this" is the arbitrary starting point, and the element with the id "next... | kudos,
What about using .index?
e.g `$(':input:eq(' + ($(':input').index(this) + 1) + ')');` | redsquare is absolutely right, and a great solution also, which I also used in one of my project.
I just wanted to point out that he is missing some parentheses, since the current solution concatenates the index with 1, instead of adding them together.
So the corrected solution would look like:
```
$(":input:eq(" + ... | Best way to find "next" form input element in jQuery? | [
"",
"javascript",
"jquery",
""
] |
I am working on a large project that uses the STL and have a question about your preferred way to organise your STL `#includes`.
* Do you prefer to #include each header in the source file it is used. For example, if both `foo.cpp` and `bar.cpp` require `std::string`, then both will `#include <string>`.
* Do you prefer... | I only include the header files that are really needed in every source, and not 'catch all' headers, to keep dependencies (and hence compile times) as low as possible.
Precompiled headers can work irrespective of this (i.e. I rely on precompiled headers to speed up the compiling process, not to get declarations). So e... | What I do is include all STL headers I'm going to need in the entire project in my single [precompiled header](http://msdn.microsoft.com/en-us/library/szfdksca.aspx), usually the default StdAfx.h. A precompiled header is the de-facto first thing to set up in a project, including all STL-/boost-/platform headers and thi... | How do you organise your STL headers? | [
"",
"c++",
"stl",
"include",
""
] |
I want to parse an Apache **access.log** file with a python program in a certain way, and though I am completely new to object-oriented programming, I want to start doing it now.
I am going to create a class **ApacheAccessLog**, and the only thing I can imagine now, it will be doing is '**readline**' method. Is it con... | In this case I would use *delegation* rather than *inheritance*. It means that your class should contain the file object as an attribute and invoke a `readline` method on it. You could pass a file object in the constructor of the logger class.
There are at least two reasons for this:
1. Delegation reduces coupling, f... | I am coming from a Java background but I am fairly confident that the same principles will apply in Python. As a rule of thumb you should **never** inherit from a class whose implementation you don't understand and control unless that class has been designed specifically for inheritance. If it has been designed in this... | Is it correct to inherit from built-in classes? | [
"",
"python",
"inheritance",
"oop",
""
] |
In C# you can use verbatim strings like this:
```
@"\\server\share\file.txt"
```
Is there something similar in JavaScript? | No, there isn't support for that in JavaScript. And that workaround seems very problematic as you now lose the ability to have forward slashes.
I've run into this issue myself when I needed to build an alert message or something from an ASP.NET back end, and stick it in a JavaScript alert on the front end. The issue w... | **Template strings** do support line breaks.
```
`so you can
do this if you want`
```
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals>
It does not of course prevent expansion from occurring the in the text, and by extension, code execution but maybe that's a good thing?
> **Note... | Does JavaScript support verbatim strings? | [
"",
"javascript",
"string",
""
] |
I know you can do it file by file.
Is there any way to do this in one step for all files in a project? | Do you mean using statements? First, note that they generally do no harm other that take space.
Tools like [ReSharper](http://www.jetbrains.com/resharper/) offer automated tricks to do this, however: there was a [link in the VS feed](http://blogs.msdn.com/djpark/archive/2008/08/16/organize-usings-across-your-entire-sol... | There is no need for any plugins in VS 2017, 2019, or 2022. Click the bulb icon near any using statement and click `Solution` next to `Fix all occurrences in` part.
[](https://i.stack.imgur.com/bqi3C.png) | Remove unused namespaces across a whole project or solution at once | [
"",
"c#",
"namespaces",
""
] |
I am wondering what is the "best practice" to break long strings in C# source code. Is this string
```
"string1"+
"string2"+
"string3"
```
concatenated during compiling or in run time? | It's done at compile time. That's exactly equivalent to "string1string2string3".
Suppose you have:
```
string x = "string1string2string3"
string y = "string1" + "string2" + "string3"
```
The compiler will perform appropriate interning such that x and y refer to the same objects.
EDIT: There's a lot of talk about `S... | If the whitespace isn't important then you can use the @ escape character to write multi-line strings in your code.
This is useful if you have a query in your code for example:
```
string query = @"SELECT whatever
FROM tableName
WHERE column = 1";
```
This will give you a string with line breaks and tabs, but for a q... | Best way to break long strings in C# source code | [
"",
"c#",
"string",
""
] |
Suppose I have the following directory layout in a Maven project:
```
src/
|-- main
| |-- bin
| | |-- run.cmd
| | `-- run.sh
| |-- etc
| | |-- common-spring.xml
| | |-- log4j.xml
| | `-- xml-spring.xml
| `-- java
| `-- com
...
```
I would like to build a zip file that, when unzipped, p... | I use the [AppAssembler plugin](http://mojo.codehaus.org/appassembler/appassembler-maven-plugin/) to get something similar. Example:
```
...
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>appassembler-maven-plugin</artifactId>
<configuration>
<programs>
<program... | I've used the maven-assembly-plugin to acheive something similar in a project. I wanted a zip file to be built during the package phase, instead of manually calling assembly:assembly. Here's what I came up with:
/src/assemble/distribution.xml:
```
<assembly>
<id>distribution</id>
<!-- specify the output formats ... | How do I assemble a console application with Maven without unpacking all dependencies? | [
"",
"java",
"maven-2",
""
] |
I'm tring to build a library for simplifing late binding calls in C#, and I'm getting trouble tring with reference parameteres. I have the following method to add a parameter used in a method call
```
public IInvoker AddParameter(ref object value)
{
//List<object> _parameters = new List<object>();
... | If the value is changing *inside the method*, you will need to declare a temp (`object`) variable to pass (`ref`) to the method, and unbox it yourself afterwards:
```
int i = 3;
//...
object obj = i;
Foo(ref obj);
i = (int)obj;
```
Note that this will not allow you to update the value after the ev... | Your method isn't changing `value` anyway - why are you passing it by reference? It may make sense, but it's not really clear to me. Note that the sample code you've provided wouldn't compile anyway, as `ref` arguments have to be *exactly* the same type as the parameter.
(Also, are you aware that C# 4.0 and .NET 4.0 w... | How to modify a boxed value type inside a method | [
"",
"c#",
"value-type",
"late-binding",
""
] |
Given a method signature:
```
public bool AreTheSame<T>(Expression<Func<T, object>> exp1, Expression<Func<T, object>> exp2)
```
What would be the most efficient way to say if the two expressions are the same? This only needs to work for simple expressions, by this I mean all that would be "supported" would be simple ... | Hmmm... I guess you'd have to parse the tree, checking the node-type and member of each. I'll knock up an example...
```
using System;
using System.Linq.Expressions;
class Test {
public string Foo { get; set; }
public string Bar { get; set; }
static void Main()
{
bool test1 = FuncTest<Test>.Fun... | **UPDATE:** Due to interest to my solution, I have updated the code so it supports arrays, new operators and other stuff and compares the ASTs in more elegant way.
Here is an improved version of Marc's code and now **it's available as a [nuget package](https://www.nuget.org/packages/Neleus.LambdaCompare/)**:
```
publ... | Most efficient way to test equality of lambda expressions | [
"",
"c#",
"lambda",
""
] |
I have just moved from phase 1 to phase 2 of a project. In this transition we got rid of all of the XML configuration for spring and struts2, switching to a fully annotated regime.
All of the participants are amazed at the actual effect this has on development speed. There are a number of reasons for this:
* Structur... | Basically, this could be viewed as a question about config files vs. annotation.
If you experienced an amelioration in productivity boost when putting some data as annotations, that means they were not "configuration" material in the first place.
The difference between the two:
* annotation: everything is in one pla... | (I really didn't mean to respond with a bag of cliches, but XML seems to bring out the proverb collection... ;-)
I have found XML configuration (and config files in general, but that's another question) to introduce multiple levels of your question, because, "To a small boy with a hammer, everything looks like a nail.... | What are your efficiency gains by removing XML in java projects? | [
"",
"java",
"xml",
""
] |
I am struggling with a creating a query. It is related to a large and complicated database but for the sake of this post I have boiled the problem down to something simpler.
I have three tables X, Y, Z defined as
```
CREATE TABLE [dbo].[X](
[ID] [bigint] NOT NULL
)
CREATE TABLE [dbo].[Y](
[ID] [nchar](10) NOT NU... | ```
SELECT
(SELECT COUNT(*) FROM Z WHERE IDX = X.ID AND IDY = Y.ID),
X.ID,
Y.ID
FROM
X,Y
```
That's your answer... why do you possibly want that query, no clue :) | This seems to work:
```
SELECT COUNT(*) AS CNT, IDX, IDY
FROM Z
GROUP BY IDX, IDY
UNION
SELECT 0, X.ID, Y.ID
FROM X, Y
WHERE NOT EXISTS (
SELECT * FROM Z WHERE Z.IDX = X.ID AND Z.IDY = Y.ID
)
ORDER BY CNT DESC
``` | Trouble with SQL query with cartesian product | [
"",
"sql",
"t-sql",
""
] |
**Original Question**
I am writting a logging class where the goal is to be able to do this:
```
// thread one
Logger() << "Some string" << std::ios::hex << 45;
// thread two
Logger() << L"Some wide string" << std::endl;
```
Currently my Logger header looks something like this:
```
#pragma once;
#include <ostream> ... | You can use friend definition, which will define the operator in the surrounding namespace of the class, and make it only visible to operator overloading resolution (not callable manually using the ::operator<<... syntax):
```
class Logger
{
public:
Logger();
~Logger();
std::ostream* out_stream;
temp... | Using a template is the right way to do it, but you just have to make sure the template is in the **header** file (`logger.h`, or whatever you called), *not* in the implementation file (`logger.cpp`). This will automatically work for any type which has `operator <<` defined with an `std::ostream`. It will also automati... | How to overload operator<< that doesn't take or return ostream | [
"",
"c++",
"templates",
"operator-overloading",
""
] |
I would like to programatically convert a Microsoft Word document into XHTML. The language of choice is PHP, so I would appreciate any suggestions with PHP.
The initial idea is trying to convert the doc file into odt, and then use the [Odt2Xhtml](http://odt2xhtml.eu.org/index_en.html) PHP class to get it into XHTML fo... | If you're running Linux one way to go would be to install OpenOffice on the server.
Example instructions for a 'headless' (i.e. no UI) install can be found [here](http://www.oooforum.org/forum/viewtopic.phtml?t=6691).
You could then use a nice CLI app like [unoconv](http://dag.wieers.com/home-made/unoconv/) executed ... | The most robust way is to [use COM to let Word save the document as HTML](http://www.joelonsoftware.com/items/2008/02/19.html).
I don't know whether Word can generate XHTML directly; if not, Google shows [plenty of options](http://www.google.com/search?q=convert+HTML+to+XHTML) for doing that conversion. | What is the best way of converting a Microsoft Word document into XHTML? | [
"",
"php",
"xhtml",
"ms-word",
""
] |
Can someone show me how to get the `top` & `left` position of a `div` or `span` element when one is not specified?
ie:
```
<span id='11a' style='top:55px;' onmouseover="GetPos(this);">stuff</span>
<span id='12a' onmouseover="GetPos(this);">stuff</span>
```
In the above, if I do:
```
document.getElementById('11a').s... | This function will tell you the x,y position of the element relative to the page. Basically you have to loop up through all the element's parents and add their offsets together.
```
function getPos(el) {
// yay readability
for (var lx=0, ly=0;
el != null;
lx += el.offsetLeft, ly += el.offsetT... | You can call the method `getBoundingClientRect()` on a reference to the element. Then you can examine the `top`, `left`, `right` and/or `bottom` properties...
```
var offsets = document.getElementById('11a').getBoundingClientRect();
var top = offsets.top;
var left = offsets.left;
```
If using jQuery, you can use the ... | Get the position of a div/span tag | [
"",
"javascript",
"html",
""
] |
This article [here](http://www.petefreitag.com/articles/gctuning/) suggests to use `-XX:+UseParNewGC` "To enable a parallel young generation GC with the concurrent GC".
My confusion is that in order to enable both parallel and concurrent GC, should I
* use `-XX:+UseParNewGC` or
* use both `-XX:+UseParNewGC` *and* `-X... | Since the document you linked was for a 1.4.2 VM that's what I'll assume you're using (JVMs 5 and 6 behave differently).
From [http://java.sun.com/docs/hotspot/gc1.4.2/](https://web.archive.org/web/20120624153924/http://java.sun.com/docs/hotspot/gc1.4.2/)
> if -XX:+UseConcMarkSweepGC is used on
> the command line the... | This blog entry has a nice breakdown of the different collectors, and which options are valid: <http://blogs.oracle.com/jonthecollector/entry/our_collectors> | Java Concurrent and Parallel GC | [
"",
"java",
"garbage-collection",
"concurrency",
""
] |
This is the exception that I'm getting when I'm trying to bind to a System.Type.Name.
Here is what I'm doing:
```
this.propertyTypeBindingSource.DataSource = typeof(System.Type);
/* snip */
this.nameTextBox1.DataBindings.Add(
new System.Windows.Forms.Binding(
"Text",
this.propertyTypeBindingSou... | Found a workaround. Made a class
```
public class StubPropertyType
{
public StubPropertyType(Type type)
{
this.StubPropertyTypeName = type.Name;
}
public string StubPropertyTypeName = string.Empty;
}
```
created a binding source
```
this.propertyStubBindingSource.DataSource = typeof(StubProp... | Indeed, there is special treatment of Type... this approach is used in the IDE etc to configure meta-data ahead of time. If you look at IDE-generated bindings, they do things like:
```
bindingSource1.DataSource = typeof(MyObject);
```
saying "when we get real data, we expect MyObject isntance(s)"; i.e. when you ask f... | Cannot bind to the property or column Name on the DataSource. Parameter name: dataMember | [
"",
"c#",
"asp.net",
"data-binding",
""
] |
I'm working on a Facebook FBML controls library and would like to create my FBML controls somewhat patterned like the ASP.NET WebControls library. I have a base class that handles rendering by default; here's my render method:
```
protected override void Render(HtmlTextWriter writer)
{
AddA... | This should get you going - it will render as `<fb:name uid="00101010101"/>`. You could also override the RenderBeginTag, RenderContents, RenderEndTag. Depending on what you are doing there may be some other things going on in RenderControl that you need. You could also look into using a ControlAdapter, this may give y... | Since this is the top SO question that comes up when searching for "HtmlTextWriter self closing tag", this is for anyone coming here that wants to know how to do it:
```
writer.WriteBeginTag("tag");
writer.WriteAttribute("attribute", "attribute value");
// ... add other attributes here ...
writer.Write(HtmlTextWriter.... | Render Self-Closing Tag in ASP.NET custom control derived from Control | [
"",
"c#",
"asp.net",
"facebook",
"custom-server-controls",
""
] |
Currently, my Objective C classes use C++ objects by doing a `new` when the owner is created, and calling `delete` when it is destroyed. But is there another way? I'd like to be able to declare, say, an `auto_ptr` whose scope lasts the duration of the Objective C class' lifetime. | Ok, let me assume you are using C++ and Objective-C on a Mac, if I'm right you are likely using X-code. So if you go to the properties (info) of your project. You can check the compile options (GCC's). In there, there is an option to enable C++ constructors/destructors (which is turned off by default in Cocoa projects)... | If you have even the slightest hope of retaining what little sanity that we as developers have left you won't do that. It is best to `delete` your C++ objects. In general, while it is safe to mix Objective-C and C++ on a line-by-line basis, do not expect the runtime to support doing something fancy like mixing lifetime... | Using C++ from Objective C : how to allocate/deallocate? | [
"",
"c++",
"objective-c",
"object",
"scope",
"auto-ptr",
""
] |
From time to time, I run into communications issue with other programmers, when we talk about NULL. Now NULL could be
a NULL pointer
the NUL character
an empty data element in some sort of database.
NUL seems to be the most confusing. It is the ASCII character 0x00.
I tend to use '\0' in my code to ... | I use `'\0'` for the nul-character and `NULL` for pointers because it is clearest in both cases.
BTW, both `0` and `'\0'` are `int`s in C and either one will be converted to `char` when stored in a `char` variable. | I like the pre-defined *NULL* macro, as it preserves the semantic meaning, rather than some other use of the number 0. | How do you deal with NUL? | [
"",
"c++",
"c",
""
] |
I recently saw an announcement and [article](http://www.linux.com/feature/150399) outlining the release of the first [Python 3.0](http://www.python.org/download/releases/3.0/) release candidate. I was wondering whether there were any commercial, free, open source etc. IDE's that support its syntax. | Python 3 is just **not that different** from Python 2.x. In terms of syntax *per se*, things that will actually need to be handled differently by the parser, the only major change is in the replacement of the `print` statement with the `print` function.
Most of the features of Python can be easily probed via introspec... | Komodo 5 beta 1 was released in October 2008 and has initial support for Python 3 but I don't think I'd be using it for production code yet.
Given that Python 3 is still a very early release candidate, you may have some trouble finding mature support in IDEs. | Are there any IDE's that support Python 3 syntax? | [
"",
"python",
"syntax",
"ide",
"python-3.x",
""
] |
I know how to fill an std::vector with non-trivial initial values, e.g. sequence numbers:
```
void IndexArray( unsigned int length, std::vector<unsigned int>& v )
{
v.resize(length);
for ( unsigned int i = 0; i < length; ++i )
{
v[i] = i;
}
}
```
But this is a for-loop. Is there an elegant way... | You can use the generate algorithm, for a more general way of filling up containers:
```
#include <iostream>
#include <algorithm>
#include <vector>
struct c_unique {
int current;
c_unique() {current=0;}
int operator()() {return ++current;}
} UniqueNumber;
int main () {
vector<int> myvector (8);
generat... | I usually go with `std::generate` plus a simple generator:
```
template <typename T>
struct gen {
T x;
gen(T seed) : x(seed) { }
T operator ()() { return x++; }
};
generate(a.begin(), a.end(), gen<int>(0));
``` | How to fill a vector with non-trivial initial values? | [
"",
"c++",
"stl",
""
] |
Say I have an array of strings in a php array called $foo with a few hundred entries, and I have a MySQL table 'people' that has a field named 'name' with a few thousand entries. What is an efficient way to find out which strings in $foo aren't a 'name' in an entry in 'people' without submitting a query for every strin... | ```
CREATE TEMPORARY TABLE PhpArray (name varchar(50));
-- you can probably do this more efficiently
INSERT INTO PhpArray VALUES ($foo[0]), ($foo[1]), ...;
SELECT People.*
FROM People
LEFT OUTER JOIN PhpArray USING (name)
WHERE PhpArray.name IS NULL;
``` | I'd put your $foo data in another table and do a LEFT OUTER JOIN with your names table. Otherwise, there aren't a lot of great ways to do this that don't involve iteration at some point. | How do I filter a php array with a MySQL table? | [
"",
"php",
"mysql",
""
] |
According to the [PHP manual](https://www.php.net/manual/en/function.get-magic-quotes-gpc.php), in order to make code more portable, they recommend using something like the following for escaping data:
```
if (!get_magic_quotes_gpc()) {
$lastname = addslashes($_POST['lastname']);
} else {
$lastname = $_POST['l... | Magic quotes are inherently broken. They were meant to sanitize input to the PHP script, but without knowing how that input will be used it's impossible to sanitize correctly. If anything, you're better off checking if magic quotes are enabled, then calling stripslashes() on $\_GET/$\_POST/$\_COOKIES/$\_REQUEST, and th... | Magic quotes were a design error. Their use is incompatible with retainnig your sanity.
I prefer:
```
if (get_magic_quotes_gpc()) {
throw new Exception("Turn magic quotes off now!");
}
```
Don't write code for compatibility with inherently broken setups. Instead defend aginst their use by having your code [FAIL F... | Magic quotes in PHP | [
"",
"php",
"security",
"magic-quotes",
""
] |
When would you call Java's `thread.run()` instead of `thread.start()`? | You might want to call run() in a particular unit test that is concerned strictly with functionality and not with concurrency. | Never. Calling run() directly just executes the code synchronously (in the same thread), just like a normal method call. | When would you call java's thread.run() instead of thread.start()? | [
"",
"java",
"multithreading",
"concurrency",
""
] |
Working on a project where a sequential set of methods must be run every `x` seconds. Right now I have the methods contained within another "parent method", and just sequentially call them right after another.
```
class DoTheseThings()
{
DoThis();
NowDoThat();
NowDoThis();
MoreWork();
AndImSpent();... | ```
Action[] work=new Action[]{new Action(DoThis), new Action(NowDoThat),
new Action(NowDoThis), new Action(MoreWork), new Action(AndImSpent)};
int current =0;
while(current!=work.Length)
{
try
{
work[current]();
current++;
}
catch(Exception ex)
{
// log the error or wha... | > Isn't some kind of Delegate collection the proper way to implement this?
Delegate is a possible way to solve this problem.
Just create a delegate something like:
> public delegate void WorkDelegate();
and put them in arraylist which you can iterate over. | What is the best way to execute sequential methods? | [
"",
"c#",
"exception",
"delegates",
""
] |
How would I be able to programmatically search and replace some text in a large number of PDF files? I would like to remove a URL that has been added to a set of files. I have been able to remove the link using javascript under Batch Processing in Adobe Pro, but the link text remains. I have seen recommendations to use... | Finding text in a PDF can be inherently hard because of the graphical nature of the document format -- the letters you are searching for may not be contiguous in the file. That said, [CAM::PDF](http://search.cpan.org/dist/CAM-PDF) has some search-replace capabilities and heuristics. Give [changepagestring.pl](http://se... | I have also become desperate. After 10 PDF Editor installations which all cost money, and no success:
pdftk + editor suffice:
**Replace Text in PDF Files**
* Use pdftk to uncompress PDF page streams
```
pdftk original.pdf output original.uncompressed.pdf uncompress
```
* Replace the text (sometimes this
wor... | How to program a text search and replace in PDF files | [
"",
"javascript",
"pdf",
"replace",
""
] |
I followed the commonly-linked tip for reducing an application to the system tray : <http://www.developer.com/net/csharp/article.php/3336751> Now it works, but there is still a problem : my application is shown when it starts ; I want it to start directly in the systray. I tried to minimize and hide it in the Load even... | In your main program you probably have a line of the form:
```
Application.Run(new Form1());
```
This will force the form to be shown. You will need to create the form but *not* pass it to `Application.Run`:
```
Form1 form = new Form1();
Application.Run();
```
Note that the program will now not terminate until you ... | this is how you do it
```
static class Program
{
[STAThread]
static void Main()
{
NotifyIcon icon = new NotifyIcon();
icon.Icon = System.Drawing.SystemIcons.Application;
icon.Click += delegate { MessageBox.Show("Bye!"); icon.Visible = false; Application.Exit(); };
icon.Visib... | Put a program in the system tray at startup | [
"",
"c#",
".net",
"vb.net",
""
] |
Can I utilise the new functionality provided by the new JavaFX APIs directly from Java to the same extent as I would be able to using JavaFX Script?
Are all the underlying JavaFX APIs purely Java or JavaFX Script or a mix? | The JavaFX APIs are a mix of JavaFX and Java. The SDK comes with an archive src.zip which contains a part of the APIs (only the most basic classes are included, but things like javafx.scene are missing).
Calling JavaFX code from Java is not officially supported in JavaFX 1.x AFAIK. There's a [blog entry in the JavaFX ... | The scenegraph used in JavaFX is opensource. You can check it here (<https://scenegraph.dev.java.net>). While the site hasn't been updated to reflect the final version shipped with JavaFX 1.x, you can still use the jar that comes with the JavaFX SDK and mix scenegraph and swing nodes inside your swing application. Howe... | JavaFX and Java Interoperability | [
"",
"java",
"api",
"interop",
"javafx",
""
] |
In some existing code there is a test to see if the user is running IE, by checking if the object Browser.Engine.trident is defined and returns true.
But how can I determine if the user is running IE6 (or earlier) or IE7 (or later)?
The test is needed inside a JavaScript function so a conditional comment doesn't seem... | From [detecting Internet Explorer More Effectively](http://msdn.microsoft.com/en-us/library/ms537509.aspx) at msdn:
```
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
var rv = -1; // Return value assumes failure.
if (navigator... | If you really want to be sure you are using IE and a specific version then you could obviously use IE's conditional tags to only run certain code within IE. It's not really that pretty but at least you can be sure that it is really IE and not some spoofed version.
```
<script>
var isIE = false;
var version = -... | How can I determine which version of IE a user is running in JavaScript? | [
"",
"javascript",
"internet-explorer",
"browser",
""
] |
If I am evaluating two variables and not two method calls does it matter weather I use "&&" or "&"
```
//some logic that sets bool values
boolean X = true;
boolean Y = true;
if (X & Y){
// perform some operation
}
if (X && Y){
// perform some operation
}
```
Further a book I am using for C# 3.0 / .NET 3.5 on... | As has been observed, `&` is the bitwise AND operator. Raw binary math is seeming to be less and less common over time, with an increasing number of developers not really understanding bitwise arithmetic. Which can be a pain at times.
However there are a lot of tasks that are best solved with such, in particular anyth... | Always use && if you are performing a true/false logic test. A single & performs a bit-wise 'and'. It make work like a logic test in some cases but it is not guaranteed to work for all logic cases. The most common use of a single & is when applying a bit-mask.
Examples (&&):
```
true && true == true
```
Example (&):... | Is there a time when && (AndAlso) does not matter over & (And) | [
"",
"c#",
"boolean-logic",
""
] |
I have in my Form constructor, after the InitializeComponent the following code:
```
using (WebClient client = new WebClient())
{
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
client.DownloadDataAsync("http://example.com/version.txt");
}
```
When I start ... | Now that we've got full code, I can say I'm definitely not seeing the problem - not quite as described, anyway.
I've got a bit of logging to indicate just before and after the DownloadDataAsync calls, and when the completed handler is fired. If I download a large file over 3G, there *is* a pause between "before" and "... | Encountered the same problem, and found a solution.
Quite complex discussion here:
<http://social.msdn.microsoft.com/Forums/en-US/a00dba00-5432-450b-9904-9d343c11888d/webclient-downloadstringasync-freeze-my-ui?forum=ncl>
In short, the problem is web client is searching for proxy servers and hanging the app.
The follow... | WebClient.DownloadDataAsync is freezing my UI | [
"",
"c#",
".net",
"webclient",
""
] |
I need to generate buttons initially based on quite a processor and disk intensive search. Each button will represent a selection and trigger a postback. My issue is that the postback does not trigger the command b\_Command. I guess because the original buttons have not been re-created. I cannot affort to execute the o... | The b\_Command Event Handler method is not being executed because on post back buttons are not being recreated (since they are dynamically generated). You need to re-create them every time your page gets recreated but in order to do this you need to explicitly cache information somewhere in state.
If this a page-scope... | The buttons need to be created *before* the load event, or state won't be wired up correctly. Re-create your buttons in Init() instead.
As for how to do this without re-running the search, I suggest you cache the results somewhere. The existence of a result set in the cache is how your button code in the Init() event ... | How can I create buttons and hook up events from postback | [
"",
"c#",
".net",
"asp.net",
"events",
"postback",
""
] |
I am trying to set the background color of a DataGridView row to red. I tried with the following line:
dgvActiveCalls.Rows[1].DefaultCellStyle.BackColor = Color.Red;
but it doesn't work. Then just to see if something is wrong with update I tried to paint the column instead of row:
dgvActiveCalls.Columns[1].DefaultCe... | Make sure that the default style isn't being overriden by another of the styles. Interesting quirk of DGV in 2.0: Seems like the inheritence chain is almost upside down from what you'd expect. If you are dynamically adding columns, your DefaultCellStyle can be ignored and be overridden by the RowsDefaultCellStyle. Sort... | I tested that on my machine and it worked fine. Are you sure that line isn't highlighted? If it's highlighted you'll see the highlighted color, not the red. | painting DataGridView Row | [
"",
"c#",
"datagridview",
""
] |
I'e been programming Java forever, but have been away from it for a while. Can anyone recommend a really good Java reference, where "really good" is defined by "Good coverage of the language, detailed coverage of recent extensions, and written for the technical reader (not a "for Dummies" sort of book)"? | As well as references saying what has changed in the languages (which other answers already cover better than I could) I can't recommend highly enough the [Second edition of Effective Java by Joshua Bloch](https://rads.stackoverflow.com/amzn/click/com/0321356683) - which explains the most effective ways of using the la... | For anything to do with concurrency, get [Java Concurrency In Practice](http://www.javaconcurrencyinpractice.com/).
As well as helping you avoid most of the many nasty pitfalls awaiting you, it gives a very good treatment of the new [java.util.concurrent](http://java.sun.com/javase/6/docs/api/java/util/concurrent/pack... | RECENT Java References? | [
"",
"java",
"reference",
""
] |
I'm not looking for the usual answer like Web-services. I'm looking for a light solution to be run in the same machine.
Edit: I'm looking for way in Java to call .NET methods | I believe Java can talk to COM and .NET can expose COM interfaces. So that may be a very light weight solution that doesn't require any 3rd party. There is also the option of using sockets to communicate between the programs which wouldn't require a heavy instance of IIS to be installed on the machine. | I am author of [jni4net](http://jni4net.sf.net/), open source interprocess bridge between JVM and CLR. It's build on top of JNI and PInvoke. No C/C++ code needed. I hope it will help you. | How can I call .NET code from Java? | [
"",
"java",
".net",
"cross-platform",
""
] |
Are there limits or performance penalties on the amount of code inside of my `home.cs` form?
I am writing a database application front-end in C# in Visual Studio 2008. The way things are lining up, I am using a tab-page way of changing the info shown to the end users, instead of using new forms.
Coming from VBA/MS Ac... | It's not the lines of code in your .cs files that you need to be worried about with regards to performance - it's the number of controls on your form at runtime that might cause problems. If it's just a few controls on a few tabs, you will have no problems. If it's hundreds of controls on lots of tabs, you may have per... | The only problem i would foresee is that in the future its going to be very hard to maintain.
Try break the logic of that main form up as much as possible into classes so that when you need add something you can actually do it without having a fit. | C# penalty for number of lines of code? | [
"",
"c#",
"performance",
"lines-of-code",
""
] |
Is there a way to find the size of a file object that is currently open?
Specifically, I am working with the tarfile module to create tarfiles, but I don't want my tarfile to exceed a certain size. As far as I know, tarfile objects are file-like objects, so I imagine a generic solution would work. | ```
$ ls -la chardet-1.0.1.tgz
-rwxr-xr-x 1 vinko vinko 179218 2008-10-20 17:49 chardet-1.0.1.tgz
$ python
Python 2.5.1 (r251:54863, Jul 31 2008, 22:53:39)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('chardet-1.0.1.tgz','rb')
>>> f.se... | Well, if the file object support the tell method, you can do:
```
current_size = f.tell()
```
That will tell you were it is currently writing. If you write in a sequential way this will be the size of the file.
Otherwise, you can use the file system capabilities, i.e. `os.fstat` as suggested by others. | Size of an open file object | [
"",
"python",
"file",
"file-io",
"filesize",
"tarfile",
""
] |
What memory leak detection tools are available for use with open source C/C++ on Windows? | The [mem (revised)](http://teaching.idallen.com/c_programming/mem/) package is an effective and straightforward tool to detect memory buffer overflows, underflows, leaks, double-deletion, and dangling references.
[Original link to c.snippets.org, now invalid.](http://c.snippets.org/browser.php?sect=37#37) | I've been using VLD ([Visual Leak Detector](http://www.codeproject.com/KB/applications/visualleakdetector.aspx)) for some times, it works nicely for good code, for more complex code; it's not perfect. | Memory leak detection under Windows for GNU C/C++ | [
"",
"c++",
"windows",
"open-source",
"memory-leaks",
""
] |
I've spent hours trying to get my code to work, its a rats nest of if/elses. Basically I want to check a country name against these two arrays:
```
//if its in this array add a 'THE'
$keywords = array("bahamas","island","kingdom","republic","maldives","netherlands",
"isle of man","ivory","philipp... | This builds on @sgehrig's answer, but note the change in your exceptions:
```
//if its in this array add a 'THE'
$keywords = array("bahamas","island","kingdom","republic","maldives","netherlands",
"isle of man","ivory","philippines","seychelles","usa");
//if its in this array, take THE off!
$exce... | ```
$countryKey = strtolower($country);
if (in_array($countryKey, $keywords)) {
$country = 'The' . $country;
} else if (in_array($countryKey, $exceptions) && stripos($country, 'the ') === 0) {
$country = substr($country, 4);
}
``` | Add / Remove the word 'The' to specific countries | [
"",
"php",
""
] |
I have the problem, that PHP replaces all spaces with underscores in POST and GET variables.
For example if I have the URL: `http://localhost/proxy.php?user name=Max`
the browser will convert it to `http://localhost/proxy.php?user%20name=Max`.
But if I give the $\_GET parameters out, the key is not `user name` but `u... | From the [PHP manual](http://www.php.net/manual/en/language.variables.external.php):
> Dots in incoming variable names
>
> Typically, PHP does not alter the
> names of variables when they are
> passed into a script. However, it
> should be noted that the dot (period,
> full stop) is not a valid character in
> a PHP va... | I think the only possibility to get the wanted parameters, is to parse them on your own using `$_SERVER['QUERY_STRING']`:
```
$a_pairs = explode('&', $_SERVER['QUERY_STRING']);
foreach($a_pairs AS $s_pair){
$a_pair = explode('=', $s_pair);
if(count($a_pair) == 1) $a_pair[1] = '';
$a_pair[0] = urldecode($a_pair[... | PHP replaces spaces with underscores | [
"",
"php",
""
] |
In a SQL Server database, I record people's date of birth. Is there an straight-forward method of working out the person's age on a given date using SQL only?
Using **DATEDIFF(YEAR, DateOfBirth, GETDATE())** does not work as this only looks at the year part of the date. For example **DATEDIFF(YEAR, '31 December 2007',... | Check out this article: [How to calculate age of a person using SQL codes](http://www.kodyaz.com/articles/calculate-age-sql-code.aspx)
Here is the code from the article:
```
DECLARE @BirthDate DATETIME
DECLARE @CurrentDate DATETIME
SELECT @CurrentDate = '20070210', @BirthDate = '19790519'
SELECT DATEDIFF(YY, @Birth... | There is another way that is a bit simpler:
```
Select CAST(DATEDIFF(hh, [birthdate], GETDATE()) / 8766 AS int) AS Age
```
Because the rounding here is very granular, this is *almost* perfectly accurate. The exceptions are so convoluted that they are almost humorous: every fourth year the age returned will be one yea... | Finding someone's age in SQL | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have an application that imports data from a pickled file. It works just fine in Windows but Mac and Linux behaviour is odd.
In OS X, the pickled file (file extension ".char") is unavailable as a selection unless I set the file type to \*.\*. Then, if I select a file that has the .char extension, it won't load, givi... | Probably you didn't open the file in binary mode when writing and/or reading the pickled data. In this case newline format conversion will occur, which can break the binary data.
To open a file in binary mode you have to provide "b" as part of the mode string:
```
char_file = open('pickle.char', 'rb')
``` | As mentioned by [Adam](https://stackoverflow.com/questions/283766/pickled-file-wont-load-on-maclinux#283802), the problem is likely to be the newline format of the pickle file.
Unfortunately, the real problem is actually caused on *save* rather than load. This may be recoverable if you're using text mode pickles, rath... | Pickled file won't load on Mac/Linux | [
"",
"python",
"linux",
"macos",
"cross-platform",
""
] |
I know that python has a `len()` function that is used to determine the size of a string, but I was wondering why it's not a method of the string object? | Strings do have a length method: `__len__()`
The protocol in Python is to implement this method on objects which have a length and use the built-in [`len()`](http://www.python.org/doc/2.5.2/lib/built-in-funcs.html#l2h-45) function, which calls it for you, similar to the way you would implement `__iter__()` and use the... | Jim's answer to [this question](https://stackoverflow.com/questions/83983/why-isnt-the-len-function-inherited-by-dictionaries-and-lists-in-python) may help; I copy it here. Quoting Guido van Rossum:
> First of all, I chose len(x) over x.len() for HCI reasons (def \_\_len\_\_() came much later). There are two intertwin... | Why does Python code use len() function instead of a length method? | [
"",
"python",
""
] |
I'm working now together with others in a grails project. I have to write some Java-classes. But I need access to an searchable object created with groovy. It seems, that this object has to be placed in the default-package.
My question is: **Is there a way to access this object in the default-package from a Java-class... | [You can’t use](http://mindprod.com/jgloss/import.html) classes in the default package from a named package.
(*Technically* you can, as shown in Sharique Abdullah's [answer](https://stackoverflow.com/a/561183/6309) through reflection API, *but* classes from the unnamed namespace are **not in scope** in an **import de... | In fact, you can.
Using reflections API you can access any class so far. At least I was able to :)
```
Class fooClass = Class.forName("FooBar");
Method fooMethod = fooClass.getMethod("fooMethod", String.class);
String fooReturned = (String)fooMethod.invoke(fooClass.newInstance(), "I did it");
``` | How to access java-classes in the default-package? | [
"",
"java",
"groovy",
"default-package",
""
] |
How can I get rid of:
```
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="..."/>
```
Completely ! | You need to add the EnableViewState="false" to the @Page directive in the Default.aspx file.
```
<%@ Page Language="C#" AutoEventWireup="true"
Codebehind="Default.aspx.cs" Inherits="Sample._Default"
EnableViewState="false" %>
```
Then, add the following code to the Default.aspx.cs file. This removes the hidden field ... | At the control level, EnableViewState="false".
At the page level, EnableViewState=false in the Page directive.
At the applicaiton level add this to .config, < pages enableViewState="false" > | How to get rid of View State completely in .NET | [
"",
"c#",
".net",
"asp.net",
""
] |
I can't figure out why the following wont work, any ideas??
```
public interface IFieldSimpleItem
{ }
public interface IFieldNormalItem : IFieldSimpleItem
{ }
public class Person
{
public virtual T Create<T>()
where T : IFieldSimpleItem
{
return default(T);
}
}
public class Bose : Person... | I'm pretty sure you're out of luck as far as using the compiler and generics to save you some runtime checks. You can't override something that doesn't already exist, and you can't have different return types to the same methods.
I can't say I completely understand your motivation, but it has technical merit.
My firs... | That's not allowed because it violates Liskov Substitution Principle.
Let's say you have another interface:
```
public interface IFieldSuperItem : IFieldSimpleItem
```
You then might do this
```
Person p = new Boss();
p.Create<IFieldSuperItem>();
```
The call in second line, while compatible with the definition of... | "Constraints for explicit interface implementation..." | [
"",
"c#",
".net",
"generics",
""
] |
I'm trying to add a new node to an jQuery [SimpleTree](http://news.kg/wp-content/uploads/tree/), but all I seem to be able to get is "sTC.addNode is not a function"...
```
var simpleTreeCollection = $('.simpleTree').simpleTree({
animate:true,
drag:false,
autoclose: false,
afterClick:function(node){},
... | Maybe take a look at [jsTree](http://www.jstree.com/jsTree/examples/) | hmm tricky one this and I have to say I dont like the plugin as it uses numerics as id's and w3c states "The attribute's value must begin with a letter in the range A-Z or a-z and may be followed by letters......."
However to get you working u need to select one of the nodes first in order to add to it like this
```
... | jQuery SimpleTree: Add a node programatically | [
"",
"javascript",
"jquery",
""
] |
I've decided to reimplement the datetime picker, as a standard datetime picker isn't nullable. The user wants to start with a blank field and type (not select) the date.
I've created a user control to do just that, but if the user control is near the edge of the form, it will be cut off on the form boundry. The standa... | The ToolStripDropDown control has this functionallity so by inheriting from it we can make a simple PopupWindow.
```
/// <summary>
/// A simple popup window that can host any System.Windows.Forms.Control
/// </summary>
public class PopupWindow : System.Windows.Forms.ToolStripDropDown
{
private System.Windows.Forms... | The screenshots looks like a Windows Forms applications, so my answer is for winforms.
I guess the best solution would be to create a customcontrol that itself uses the datetime picker that already has the behavior.
Show a empty textbox until it gets clicked, then display the datetimepicker.
That would save you a bu... | Make user control display outside of form boundry | [
"",
"c#",
"winforms",
""
] |
How do you split a string?
Lets say i have a string "dog, cat, mouse,bird"
My actual goal is to insert each of those animals into a listBox, so they would become items in a list box.
but i think i get the idea on how to insert those items if i know how to split the string. or does anyone know a better way to do this... | ```
string[] tokens = text.Split(',');
for (int i = 0; i < tokens.Length; i++)
{
yourListBox.Add(new ListItem(token[i], token[i]));
}
``` | Have you tried [String.Split](http://msdn.microsoft.com/en-us/library/system.string.split.aspx)? You may need some post-processing to remove whitespace if you want "a, b, c" to end up as {"a", "b", "c"} but "a b, c" to end up as {"a b", "c"}.
For instance:
```
private readonly char[] Delimiters = new char[]{','};
pr... | How do i split a String into multiple values? | [
"",
"c#",
"asp.net",
"visual-studio",
"string",
"listbox",
""
] |
We have a collection of photo images sizing a few hundred gigs. A large number of the photos are visually duplicates, but with differing filesizes, resolution, compression etc.
Is it possible to use any specific image processing methods to search out and remove these duplicate images? | I recently wanted to accomplish this task for a PHP image gallery. I wanted to be able to generate a "fuzzy" fingerprint for an uploaded image, and check a database for any images that had the same fingerprint, indicating they were similar, and then compare them more closely to determine how similar.
I accomplished it... | Try [PerceptualDiff](http://pdiff.sourceforge.net/) for comparing 2 images with the same dimensions. Allows threshholds such as considering images with only X number of pixels different to be visually indistinguishable.
If visual duplicates may have different dimensions due to scaling, or different filetypes,
you may ... | Removing Duplicate Images | [
"",
"c#",
"algorithm",
"image-processing",
""
] |
Recently, when porting some STL code to VS2008 I wanted to disable warnings generated by `std::copy` by defining the new `_SCL_SECURE_NO_WARNINGS` flag. You can do this in two ways:
* Using the **/D** compiler switch, which can be specified in the project properties. You need to ensure it is defined for both Release a... | The /D option is generally used when you want to define it differently on different builds (so it can be changed in the makefile)
If you will "always" want it set the same way, use #define. | By putting them in your project file you maintain a close association between the platform specific warnings and the platform, which seems correct to me.
If they're in the code, they're always in the code whether or not it's appropriate for the platform. You don't need it for GCC or possibly future versions of Visual ... | Defining macros in Visual Studio - /D or #define? | [
"",
"c++",
"visual-studio",
""
] |
I have a function, `a()`, that I want to override, but also have the original `a()` be performed in an order depending on the context. For example, sometimes when I'm generating a page I'll want to override like this:
```
function a() {
new_code();
original_a();
}
```
and sometimes like this:
```
function a(... | You could do something like this:
```
var a = (function() {
var original_a = a;
if (condition) {
return function() {
new_code();
original_a();
}
} else {
return function() {
original_a();
other_new_code();
}
}
})();
```
D... | The [Proxy pattern](http://docs.jquery.com/Types#Proxy_Pattern) might help you:
```
(function() {
// log all calls to setArray
var proxied = jQuery.fn.setArray;
jQuery.fn.setArray = function() {
console.log( this, arguments );
return proxied.apply( this, arguments );
};
})();
```
> The... | Overriding a JavaScript function while referencing the original | [
"",
"javascript",
"overriding",
"user-defined-functions",
""
] |
I have an array of values that is passed to my function from a different part of the program that I need to store for later processing. Since I don't know how many times my function will be called before it is time to process the data, I need a dynamic storage structure, so I chose a `std::vector`. I don't want to have... | If you can construct the vector after you've gotten the array and array size, you can just say:
```
std::vector<ValueType> vec(a, a + n);
```
...assuming `a` is your array and `n` is the number of elements it contains. Otherwise, `std::copy()` w/`resize()` will do the trick.
I'd stay away from `memcpy()` unless you ... | There have been many answers here and just about all of them will get the job done.
However there is some misleading advice!
Here are the options:
```
vector<int> dataVec;
int dataArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
unsigned dataArraySize = sizeof(dataArray) / sizeof(int);
// Method 1: Copy the array to t... | How do you copy the contents of an array to a std::vector in C++ without looping? | [
"",
"c++",
"stl",
"vector",
"copy",
""
] |
I've got the bare minimum to handle the Linux/MySQL parts of the stack, but I want to have a basic grasp of PHP before I dive in. I'll be working on WordPress plugins, in case there's anything specifically interesting for that.
PS - any recommendations regarding recommended source control/IDEs would also be great, but... | When you're developing C# you should definitely take a look at [VS.Php](http://www.jcxsoftware.com "VS.Php") | I would recomment the [PHP manual](http://www.php.net/manual/en/) too! | As a C# developer who wants to do some PHP work, what [book/online articles] should I [buy/read] to introduce myself to PHP? | [
"",
"php",
"wordpress",
""
] |
I'm trying to save the output of an vector image drawin in Java2D to an SWF file. There are great libraries for saving java2D output as things like SVG (BATIK) and PDF(itext) but I can't find one for SWF. Any ideas? | I just got an example to work using the [SpriteGraphics2D](http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/modules/swfutils/src/java/flash/graphics/g2d/SpriteGraphics2D.java) object from [Adobe's Flex 3](http://opensource.adobe.com/wiki/display/flexsdk/Downloads). FYI... Flex 3 is now open source.
> *(from S... | Mm, I know some libraries outputting Flash content, like or [Ming](http://www.libming.org/ "Ming"), or even [Haxe](http://haxe.org/), a language which can be "translated" into JavaScript, Flash or PHP code... But I know no Java library.
Searching a bit (I am curious), I found a commercial [Java Graph Library](http://... | Save Java2D to SWF (flash) | [
"",
"java",
"flash",
""
] |
what's the best/proper way of interacting between several windows in C# app?
Recently, I've run into a problem where one of program windows has to call method modifying main window. My solution was to create factory-like class, that would arrange all underlying model-data and organize the communication between various ... | You need to split the Model from the view by a Controller. Put an object that will be able to have both form reference and that will be able to manage the shared information.
An other solution is to send the reference of the formX to the formY this way they can communicate. | We use a custom built forms manager that uses the subject/observer pattern.
Every form that is opended is reported to the FormsManager, the FromsManager makes itself an observer of the form.
It also makes the form an observer of the FormsManager.
So you end up with every form observing the FormsManager and the Forms... | Interactions between windows | [
"",
"c#",
"delegates",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.