Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
How does container object like vector in stl get destroyed even though they are created in heap?
**EDIT**
If the container holds pointers then how to destroy those pointer objects | An STL container of pointer will NOT clean up the data pointed at. It will only clean up the space holding the pointer. If you want the vector to clean up pointer data you need to use some kind of smart pointer implementation:
```
{
std::vector<SomeClass*> v1;
v1.push_back(new SomeClass());
std::vector<bo... | If you have a `vector<T*>`, your code needs to delete those pointers before delete'ing the vector: otherwise, that memory is leaked.
Know that C++ doesn't do garbage collection, here is an example of why (appologies for syntax errors, it has been a while since I've written C++):
```
typedef vector<T*> vt;
⋮
vt *vt1 =... | How do stl containers get deleted? | [
"",
"c++",
"memory-management",
"stl",
"vector",
"containers",
""
] |
I need some SQL to update a record in a database if it exists and insert it when it does not, looking around there looks to be several solutions for this, but I don't know what are the correct/ accepted ways to do this.
I would ideally like it to work on both Firebird 2 and MySQL 5 as the update will need to be ran ag... | You should either use something like this:
```
BEGIN TRANSACTION
IF EXISTS (SELECT * FROM the_table WHERE pk = 'whatever')
UPDATE the_table SET data = 'stuff' WHERE pk = 'whatever'
ELSE
INSERT INTO the_table (pk, data) VALUES ('whatever', 'stuff')
COMMIT
```
Or this, but send them separately and ignore any er... | In Firebird 2.1 you can use [UPDATE OR INSERT](http://www.firebirdsql.org/refdocs/langrefupd25-update-or-insert.html) for simple cases or [MERGE](http://www.firebirdsql.org/refdocs/langrefupd21-merge.html) for more complex scenarios. | What is the correct/ fastest way to update/insert a record in sql (Firebird/MySql) | [
"",
"sql",
"mysql",
"firebird",
"upsert",
""
] |
I have to following code:
<http://www.nomorepasting.com/getpaste.php?pasteid=22987>
If `PHPSESSID` is not already in the table the `REPLACE INTO` query works just fine, however if `PHPSESSID` exists the call to execute succeeds but sqlstate is set to 'HY000' which isn't very helpful and `$_mysqli_session_write->errno... | So as it turns out there are other issues with using REPLACE that I was not aware of:
[Bug #10795: REPLACE reallocates new AUTO\_INCREMENT](http://bugs.mysql.com/bug.php?id=10795) (Which according to the comments is not actually a bug but the 'expected' behaviour)
As a result my id field keeps getting incremented so ... | Why are you trying to doing your prepare in the session open function? I don't believe the write function is called more then once during a session, so preparing it in the open doesn't do much for you, you might as well do that in your session write.
Anyway I believe you need some whitespace after the table name, and ... | MySQLi prepared statements and REPLACE INTO | [
"",
"php",
"mysql",
"mysqli",
""
] |
When reviewing our codebase, I found an inheritance structure that resembles the following pattern:
```
interface IBase
{
void Method1();
void Method2();
}
interface IInterface2 : IBase
{
void Method3();
}
class Class1 : IInterface2
{
...
}
class Class2 : IInterface2
{
...
}
class Class3 : IInt... | Well, first of all, I'm generally against implementing an interface by throwing NotImplementedException exceptions. It is basically like saying "Well, this class can also function as a calculator, err, almost".
But in some cases it really is the only way to do something "the right way", so I'm not 100% against it.
Ju... | So, I'm assuming the question you're asking is:
> If a derived type throws a
> `NotImplementedException` for a method
> where a base type does not, does this
> violate the Liskov subsitution
> principle.
I'd say that depends on whether the interface documentation says that a method may throw this exception to fulfill... | Interface inheritance: what do you think of this: | [
"",
"c#",
"oop",
"inheritance",
"liskov-substitution-principle",
""
] |
How can you join between a table with a sparse number of dates and another table with an exhaustive number of dates such that the gaps between the sparse dates take the values of the previous sparse date?
Illustrative example:
```
PRICE table (sparse dates):
date itemid price
2008-12-04 1 $1
2008-12-11... | This isn't as simple as a single LEFT OUTER JOIN to the sparse table, because you want the NULLs left by the outer join to be filled with the most recent price.
```
EXPLAIN SELECT v.`date`, v.volume_amt, p1.item_id, p1.price
FROM Volume v JOIN Price p1
ON (v.`date` >= p1.`date` AND v.item_id = p1.item_id)
LEFT OUTER... | Assuming there is only 1 price per date/itemid:
```
select v.date, v.itemid, p.price
from volume v
join price p on p.itemid = v.item_id
where p.date = (select max(p2.date) from price p2
where p2.itemid = v.itemid
and p2.date <= v.date);
``` | Need help with a complex Join statement in SQL | [
"",
"sql",
"greatest-n-per-group",
""
] |
I am new to threads and in need of help. I have a data entry app that takes an exorbitant amount of time to insert a new record(i.e 50-75 seconds). So my solution was to send an insert statement out via a ThreadPool and allow the user to begin entering the data for the record while that insert which returns a new recor... | Everyone else, including you, addressed the core problems (insert time, why you're doing an insert, then update), so I'll stick with just the technical concerns with your proposed solution. So, if I get the flow right:
* Thread 1: Start data entry for
record
* Thread 2: Background calls to DB to retrieve new Id
* Th... | 1) Many :), for example you could disable the "save" button while the thread is inserting the object, or you can setup a Thread Worker which handle a queue of "save requests" (but I think the problem here is that the user wants to modify the newly created record, so disabling the button maybe it's better)
2) I think w... | ThreadPool and GUI wait question | [
"",
"c#",
"threadpool",
"deadlock",
""
] |
While looking at online code samples, I have sometimes come across an assignment of a String constant to a String object via the use of the new operator.
For example:
```
String s;
...
s = new String("Hello World");
```
This, of course, compared to
```
s = "Hello World";
```
I'm not familiar with this syntax and h... | The one place where you may *think* you want `new String(String)` is to force a distinct copy of the internal character array, as in
```
small=new String(huge.substring(10,20))
```
However, this behavior is unfortunately undocumented and implementation dependent.
I have been burned by this when reading large files (... | The only time I have found this useful is in declaring lock variables:
```
private final String lock = new String("Database lock");
....
synchronized(lock)
{
// do something
}
```
In this case, debugging tools like Eclipse will show the string when listing what locks a thread currently holds or is waiting for. ... | What is the purpose of the expression "new String(...)" in Java? | [
"",
"java",
"string",
""
] |
Okay, so basically I want to be able to retrieve keyboard text. Like entering text into a text field or something. I'm only writing my game for windows.
I've disregarded using Guide.BeginShowKeyboardInput because it breaks the feel of a self contained game, and the fact that the Guide always shows XBOX buttons doesn't ... | Maybe I'm not understanding the question, but why can't you use the XNA Keyboard and KeyboardState classes? | For adding a windows hook in XNA
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
/* Author: Sekhat
*
* License: Public Domain.
*
* Usage:
*
* Inherit from this class, and override... | XNA - Keyboard text input | [
"",
"c#",
".net",
"xna",
""
] |
I have just moved job and gone from VB 6 to VB.Net and found the learning jump fairly steep, have more a problem with the object / conceptual side of things .. but getting there now ... but as I was a assembler / C++ 10/15 years ago and was considering learning C++/C# .Net (XNA games library calls my name) but not sure... | To me the biggest obstacle for .NET is learn what is available in the framework. Therefore, if you find it easier to code in C# it will mean you only struggle with one thing instead of two. Once you know the framework it's just syntax really as 95% of the stuff you can do with C# can be done with VB.
Also, C# will for... | I was (back in the day) a VB6 dev, and I would expect it to help. There is a much-commented tendency for VB6 developers to keep writing VB6 in .NET; even just a brief look at C# might help you think about VB.NET as a .NET language, rather than a Visual Studio 6 ancestor.
Of course, you might find (as I did) that you d... | Learning C# help or hinder VB.NET learning | [
"",
"c#",
"vb.net",
""
] |
I can't tell if this is a result of the jQuery I'm using, but this is what I'm trying to do:
```
<div class="info" style="display: inline;"
onMouseOut="$(this).children('div').hide('normal');"
onMouseOver="$(this).children('div').show('normal');"
>
<img src="images/target.png">
<div class="tooltiptwo" id="to... | **edit**: actually this is a much better solution ([credit](https://stackoverflow.com/questions/308411/#308720)):
```
$('.info').bind('mouseenter', function() {
$('div', this).show('normal');
});
$('.info').bind('mouseleave', function() {
$('div', this).hide('normal');
});
// hide the tooltip to start off
$(... | Did you follow this **[tutorial](http://www.kriesi.at/archives/create-simple-tooltips-with-css-and-jquery)** ?
Especially the mousemove part, where he constantly sets the positioning values left and top to align the tooltip next to the cursor. the X and Y coordinates are called via .pageX and .pageY. And he also adds ... | Javascript "onMouseOver" triggering for children? | [
"",
"javascript",
"jquery",
"parent-child",
"jquery-events",
""
] |
I once came across a validation framework for java, where you wrote one method that protected the integrity of the data-type and any CRUD operations on that data-type automatically called this method.
Does anyone know what this framework is? I simply want to avoid repetitive validation on every CRUD method attached to... | Here's a huge list of Java Validation Libraries / Frameworks - <http://java-source.net/open-source/validation> | Apache Commons has a [validation](http://commons.apache.org/validator/) framework. | Java Validation Frameworks | [
"",
"java",
"validation",
"frameworks",
""
] |
Are there any sorts of useful idioms I can make use of when writing an API that is asynchronous? I would like to standardize on something as I seem to be using a few different styles throughout. It seems hard to make asynchronous code simple; I suppose this is because asynchronous operations are anything but.
At the m... | Also have a look at the Asynchronous Completion Token and ActiveObject patterns. | You may want to look at [Python Twisted](http://twistedmatrix.com/trac/). It is a nice [Reactor](http://en.wikipedia.org/wiki/Reactor_pattern) based API that supports [asynchronous](http://twistedmatrix.com/projects/core/documentation/howto/async.html) operations. [Proactor](http://www.cs.uu.nl/docs/vakken/no/proactor.... | Idiomatic asynchronous design | [
"",
"python",
"asynchronous",
""
] |
George Marsaglia has written an excellent random number generator that is extremely fast, simple, and has a much higher period than the Mersenne Twister. Here is the code with a description:
[good C random number generator](http://school.anhb.uwa.edu.au/personalpages/kwessen/shared/Marsaglia03.html)
I wanted to port ... | > Can anyone port this to Java? How does
> this work when you only have signed
> numbers available?
No Stress! `a=18782` so the largest `t` could ever be is not large enough to cause signed vs. unsigned problems. You would have to "upgrade" the result of using Q to a value equal to a 32-bit unsigned number before usin... | Most of the time there is no need to use larger numeric types for simulating unsigned types in Java.
For addition, subtraction, multiplication, shift left, the logical operations, equality
and casting to a smaller numeric type
it doesn't matter whether the operands are signed or unsigned,
the result will be the same r... | Port of Random generator from C to Java? | [
"",
"java",
"c",
"random",
"porting",
""
] |
I have a group of strings in Javascript and I need to write a function that detects if another specific string belongs to this group or not.
What is the fastest way to achieve this? Is it alright to put the group of values into an array, and then write a function that searches through the array?
I think if I keep the... | Use a hash table, and do this:
```
// Initialise the set
mySet = {};
// Add to the set
mySet["some string value"] = true;
...
// Test if a value is in the set:
if (testValue in mySet) {
alert(testValue + " is in the set");
} else {
alert(testValue + " is not in the set");
}
``` | You can use an object like so:
```
// prepare a mock-up object
setOfValues = {};
for (var i = 0; i < 100; i++)
setOfValues["example value " + i] = true;
// check for existence
if (setOfValues["example value 99"]); // true
if (setOfValues["example value 101"]); // undefined, essentially: false
```
This takes adv... | fastest way to detect if a value is in a group of values in Javascript | [
"",
"javascript",
"search",
""
] |
I want to know if its possible and how to do the following , i have a basic MVC application (ASP.Net) that i have modified to work for me. Now the application already handles authentication perfectly fine but i need to use this authentication in another app.
Without creating a webservice is it possible for me to make ... | You can't directly call a controller in another application because it is in a separate AppDomain. If you just want to reuse the existing code, you could refactor it into a separate assembly (library project), include that assembly in your new application, and just reference it from your logon controller. If you are tr... | Authentication is a cross-cutting concern that shouldn't be embedded into a single use case/controller. AOP afficionados would say it should be encapsulated in an aspect. | Make a call to a external mvc controller | [
"",
"c#",
"asp.net-mvc",
""
] |
I'm using this to check for the availability of a URL:
```
$fp = fsockopen($url, 443, $errno, $errstr);
```
and I get this error back...
**Warning: fsockopen() [function.fsockopen]: unable to connect to <https://example.com/soapserver.php:443> (Unable to find the socket transport "https" - did you forget to enable i... | also for ssl you need to prefix the host with ssl:// | Uncomment the line: `extension=php_openssl.dll` in `php.ini` | Unable to find the socket transport "https" | [
"",
"php",
"iis",
"fsockopen",
""
] |
How can I create a list in C++? I need it to create a linked list. How would I go about doing that? Are there good tutorials or examples I could follow? | I take it that you know that C++ already has a linked list class, and you want to implement your own because you want to learn how to do it.
First, read [Why do we use arrays instead of other data structures?](https://stackoverflow.com/questions/392397/arrays-whats-the-point) , which contains a good answer of basic da... | You should really use the [standard List class](http://en.cppreference.com/w/cpp/container/list). Unless, of course, this is a homework question, or you want to know how lists are implemented by STL.
You'll find plenty of simple tutorials via google, like [this one](http://www.mochima.com/tutorials/STL.html). If you w... | How could I create a list in c++? | [
"",
"c++",
"list",
"linked-list",
""
] |
I've got a structure as follows:
```
typedef struct
{
std::wstring DevAgentVersion;
std::wstring SerialNumber;
} DeviceInfo;
```
But when I try to use it I get all sorts of memory allocation errors.
If I try to pass it into a function like this:
```
GetDeviceInfo(DeviceInfo *info);
```
I will get a runtim... | You should use `new` instead of `malloc`, to assure the constructor gets called for the `DeviceInfo` and its contained `wstring`s.
```
DeviceInfo *info = new DeviceInfo;
```
In general, it's best to avoid using `malloc` in C++.
Also, make sure to `delete` the pointer when you're done using it.
Edit: Of course if yo... | std::wstring creates an object, and objects need to be constructed. By using malloc, you bypassed the constructor for your structure, which would include constructors for all the members.
The error you're getting is from std::wstring trying to use one of its own members that is still uninitialized.
You can use new in... | Init Structure with std::wstring | [
"",
"c++",
"string",
"structure",
""
] |
I'm having an issue with the following code:
```
private void DataPortal_Fetch(TaskCriteria criteria)
{
using (var ctx = ContextManager<Gimli.Data.GimliDataContext>
.GetManager(Database.ApplicationConnection, false))
{
this.RaiseListChangedEvents = false;
... | The following code works ... interestingly enough ... any idea of why?
```
query = query.Where(row => row.InvoiceId == new Guid("00000000-0000-0000-0000-000000000000"));
``` | Try changing the code to:
```
query.Where(row => object.Equals(row.InvoiceId, Guid.Empty))
```
Post back if that helped... | Hanging Linq query with Guid.Empty in the where expression | [
"",
"c#",
"linq",
"linq-to-sql",
"csla",
""
] |
Checkstyle reports this code as "The double-checked locking idiom is broken", but I don't think that my code actually is affected by the problems with double-checked locking.
The code is supposed to create a row in a database if a row with that id doesn't exist. It runs in a multi-threaded environment and I want to av... | Assuming you want that innermost line to read:
```
row = dao().create(id);
```
It's not a classic double-checked lock problem assuming `dao().fetch` is properly mutexed from the create method.
**Edit**: (code was updated)
The classic problem of a double-checked lock is having a value assigned before initialization ... | I think in this case, checkstyle is correct. In your code as presented, consider what would happen if two threads both had `row == null` at the entry to the synchronized block. Thread A would enter the block, and insert the new row. Then after thread A exits the block, thread B would enter the block (because it doesn't... | Is this broken double checked locking? | [
"",
"java",
"synchronization",
"locking",
"double-checked-locking",
""
] |
How do you open a file from a java application when you do not know which application the file is associated with. Also, because I'm using Java, I'd prefer a platform independent solution. | With JDK1.6, the [`java.awt.Desktop`](http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html) class can be useful.
```
public static void open(File document) throws IOException {
Desktop dt = Desktop.getDesktop();
dt.open(document);
}
``` | ```
File file
Desktop.getDesktop().open( file );
```
Since Java 1.6
Previous to that you could [check this question](https://stackoverflow.com/questions/325299)
*Summary*
It would look something like this:
```
Runtime.getRuntime().exec( getCommand( file ) );
public String getCommand( String file ){
// Depend... | Open a file with an external application on Java | [
"",
"java",
"external-application",
""
] |
I wrote a google map lookup page. Everthing worked fine until I referenced the page to use a master page. I removed the form tag from the master page as the search button on the map page is a submit button. Everything else on my page appears but the google map div appears with map navigation controls and logo but no ma... | Please view below Code and let me know its useful ...
**MasterPage Code ( GMap.master page)**
```
< body onload="initialize()" onunload="GUnload()" >
< form id="form1" runat="server" >
< div >
< asp:contentplaceholder id="ContentPlaceHolder1" runat="server" >
< /asp:contentplaceholder >
< ... | this is the code i used.it works fine here but whenever i add master page it does not perform any use functionality
```
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-stri... | Google map blank when used with master page | [
"",
"c#",
"asp.net",
"google-maps",
""
] |
For the following code:
```
<% foreach (Entities.Core.Location loc in locations){ %>
<div class="place_meta">
<img src="~/static/images/stars/star_25_sml.gif" runat="server" class="star_rating"/>
</div>
<% }; %>
```
I would like to display the star rating image for each location object displayed. However, only the fi... | You can't use server controls within an inline loop, because ASP.NET needs to be able to uniquely identify each control to process it. The for... loop prevents this. The easiest and cleanest way is to use a Repeater control and bind your collection to it (in code-behind). Set the URL property in the bind event handler,... | Unless you're using MVC, you might find a Repeater Control more useful in this situation.
If I remember correctly, you can use a source of data (your *locations* in this instance) and then loop through and set each image. | foreach in ASP.net with nested runat="server" | [
"",
"c#",
"asp.net",
""
] |
We have lots of logging calls in our app. Our logger takes a System.Type parameter so it can show which component created the call. Sometimes, when we can be bothered, we do something like:
```
class Foo
{
private static readonly Type myType = typeof(Foo);
void SomeMethod()
{
Logger.Log(myType, "SomeMethod... | I strongly suspect that GetType() will take significantly less time than any actual logging. Of course, there's the possibility that your call to Logger.Log won't do any actual IO... I still suspect the difference will be irrelevant though.
EDIT: Benchmark code is at the bottom. Results:
```
typeof(Test): 2756ms
Test... | The `GetType()` function is marked with the special attribute `[MethodImpl(MethodImplOptions.InternalCall)]`. This means its method body doesn't contain IL but instead is a hook into the internals of the .NET CLR. In this case, it looks at the binary structure of the object's metadata and constructs a `System.Type` obj... | Performance of Object.GetType() | [
"",
"c#",
".net",
"performance",
""
] |
Hey, i am currently working on a django app for my studies, and came to the point of l18n. Localizing the site itself was very easy, but now i have to allow users, to translate the dynamic content of the application.
Users can save "products" in the database and give them names and descriptions, but since the whole sit... | I would suggest checking out [django-multilingual](http://code.google.com/p/django-multilingual/). It is a third party app that lets you define translation fields on your models.
Of course, you still have to type in the actual translations, but they are stored transparently in the database (as opposed to in static PO ... | I use [django-multilingual](http://code.google.com/p/django-multilingual/) for localize content and [django-localeurl](http://code.google.com/p/django-localeurl/) for choosing language based on url (for example mypage/en/).
You can see how multilingua and localeurl work on [JewishKrakow.net](http://www.jewishkrakow.nw... | How to localize Content of a Django application | [
"",
"python",
"django",
"localization",
"internationalization",
""
] |
I have an xml in which i have stored some html under comments like this
```
<root>
<node>
<!--
<a href="mailto:some@one.com"> Mail me </a>
-->
</node>
</root>
```
now in my Transform Xslt code of mine i am giving XPathNavigator which is pointing to node and in xslt i am passing the commen... | When part of the comment the node looses its special meaning - thus "href" is not a node so you cannot use it to select stuff.
You can select comments like this:
```
<xsl:template match="/">
<xsl:value-of select="/root/node/comment()" disable-output-escaping="yes"/>
</xsl:template>
```
This will produce based on you... | As diciu mentioned, once commented the text inside is no longer XML-parsed.
One solution to this problem is to use a two-pass approach. One pass to take out the commented `<a href=""></a>` node and place it into normal XML, and a second pass to enrich the data with your desired output: `<a href="">Your Text Here</a>`.... | XSLT Transformation Problem with disable output escaping | [
"",
"c#",
"xslt",
"escaping",
""
] |
I am trying to use onkeypress on an input type="text" control to fire off some javascript if the enter button is pressed. It works on most pages, but I also have some pages with custom .NET controls.
The problem is that the .NET submit fires before the onkeypress. Does anybody have an insight on how to make onkeypress... | How are you assigning the javascript?
It should look like:
```
<input id="TextID" type="text" onkeypress="return SearchSiteSubmit('TextID', event)" />
``` | Javascript `OnKeyPress` will always fire first, it's more a case of wether or not it has completed its operation before the page is posted back..
I would say rethink what is going on and where.. What is taking place at the server side? | .NET Submit Fires Before Javascript onKeypress | [
"",
".net",
"javascript",
"onkeypress",
""
] |
You guys were very helpful yesterday. I am still a bit confused here though.
I want to make it so that the numbers on the rightmost column are rounded off to the nearest dollar:
<http://www.nextadvisor.com/voip_services/voip_calculator.php?monthlybill=50&Submit=Submit>
the code for the table looks like this:
I want... | Do you want rounded up/down/truncated to the nearest dollar?
Here are some suggested functions you can use:
**Rounding**
[round](http://us.php.net/manual/en/function.round.php)
[floor](http://us.php.net/manual/en/function.floor.php)
[ceil](http://us.php.net/manual/en/function.ceil.php)
**Formatting/Truncating**
... | Grepsedawk's answer is good; the only thing I would add is that rather than displaying $336.6, for example, you could could use [number\_format](http://php.net/number_format) to output $336.60.
(I know this wasn't your question, but looking at the link, I thought that might be useful for you.)
Edit - Thanks to Andy f... | basic php form help (currency display) | [
"",
"php",
"forms",
"currency",
"rounding",
""
] |
I find this comes up a lot, and I'm not sure the best way to approach it.
**The question I have is how to make the decision between using foreign keys to lookup tables, or using lookup table values directly in the tables requesting it, avoiding the lookup table relationship completely.**
Points to keep in mind:
* Wi... | You can use a lookup table with a VARCHAR primary key, and your main data table uses a FOREIGN KEY on its column, with cascading updates.
```
CREATE TABLE ColorLookup (
color VARCHAR(20) PRIMARY KEY
);
CREATE TABLE ItemsWithColors (
...other columns...,
color VARCHAR(20),
FOREIGN KEY (color) REFERENCES ColorL... | In cases of simple atomic values, I tend to disagree with the common wisdom on this one, mainly on the complexity front. Consider a table containing hats. You can do the "denormalized" way:
```
CREATE TABLE Hat (
hat_id INT NOT NULL PRIMARY KEY,
brand VARCHAR(255) NOT NULL,
size INT NOT NULL,
color VARCHAR(30)... | Decision between storing lookup table id's or pure data | [
"",
"sql",
"database",
"lookup",
"database-normalization",
""
] |
I am sorry, my question is stupid, but I am not able to answer it, as a java illiterate. I run a tomcat (5) on CentOS5 (for a CAS server), and when I try to open this URL <http://192.168.1.17:8080/cas-server-webapp-3.3.1/login> I get this error :
first error:
java.lang.NoClassDefFoundError: Could not initialize class ... | It is important to keep two or three different exceptions strait in our head in this case:
1. **`java.lang.ClassNotFoundException`** This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.
2. ... | Nowadays, the environment variable $CLASSPATH should not be used; instead, the java application should have the classpath set on the command line.
However, in the case of tomcat and libraries used in the webapps, you simply put the JARs (for Spring) into the shared/lib/ folder of the tomcat installation. | Error java.lang.NoClassDefFoundError on org.springframework.webflow.util.RandomGuid | [
"",
"java",
"linux",
"tomcat",
"classpath",
"centos5",
""
] |
i've got a site with a lot of referenced .js-Files; those are rather small files, but I want to keep my methods separated by topic/functionality.
Is it better to keep all the methods in one .js-File or is it no problem to have many (~ 20 - 30) small files all including only some lines? | By all means keep them separate for development, but you should consider bundling them together into one file for production.
There is a nice discussion at [sitepoint.com](http://www.sitepoint.com/blogs/2007/04/10/faster-page-loads-bundle-your-css-and-javascript/)
> For each of these files, an HTTP
> request is sent ... | Actually it's a bad idea to have so many referenced files. The basic idea for performance issues is to try to minimize HTTP Requests as much as possible (at least on your production server). Take a look at this <http://developer.yahoo.com/performance/rules.html#num_http> | jQuery/JavaScript - performance-issue when having a lot of small .js-Files? | [
"",
"javascript",
"jquery",
"performance",
"include",
"jscompress",
""
] |
I am building a calculator in C#.
I am not sure what the best way is to have it increment a number in an array every time the button is pressed. Here is one of my current button event handler methods:
```
//Assign button '2' to 2 with array address of 1
private void num2_Click(object sender, EventArgs e)
{... | ```
numbers[1] += 2;
``` | numbers[1] += 2;
That should do the trick. | incrementing array value with each button press? | [
"",
"c#",
"arrays",
"events",
"increment",
"calculator",
""
] |
Or is it okay to do something like this:
```
new Thread( new ThreadStart( delegate { DoSomething(); } ) ).Start();
```
?
I seem to recall that under such a scenario, the Thread object would be garbage collected, but the underlying OS thread would continue to run until the end of the delegate passed into it. I'm basi... | I have generally found that if I need to directly start a new thread the way you are in your example, rather than grabbing one from the thread pool, then it is a long running thread and I will need a reference to it later to kill it, monitor it, etc. For short run threads like invoking IO on a background thread, etc, I... | It depends. In the situation where the user can cancel the operation of your thread, you should keep the reference so the thread can be canceled when the user want. In other situations, there may be no need to store the reference. | Should one always keep a reference to a running Thread object in C#? | [
"",
"c#",
"multithreading",
"reference",
""
] |
How do I get whole and fractional parts from double in JSP/Java ? If the value is 3.25 then I want to get `fractional =.25`, `whole = 3`
How can we do this in Java? | <http://www.java2s.com/Code/Java/Data-Type/Obtainingtheintegerandfractionalparts.htm>
```
double num;
long iPart;
double fPart;
// Get user input
num = 2.3d;
iPart = (long) num;
fPart = num - iPart;
System.out.println("Integer part = " + iPart);
System.out.println("Fractional part = " + fPart);
```
Outputs:
```
Int... | ```
double value = 3.25;
double fractionalPart = value % 1;
double integralPart = value - fractionalPart;
``` | How do I get whole and fractional parts from double in JSP/Java? | [
"",
"java",
"math",
"jsp",
""
] |
I have a cookie which is generated from a servlet and that I would like to be persistent - that is, set the cookie, close down IE, start it back up, and still be able to read the cookie. The code that I'm using is the following:
```
HttpServletResponse response =
(HttpServletResponse) FacesContext.getCurrentInsta... | I know nothing of Java or servlets, but IE will only persist a cookie if it has an Expires date, setting max-age is not sufficient, IE will continue to treat it as a session cookie. | Few suggestions.
1. Are you using fqdn to access the site?
2. use [fiddler](http://www.fiddlertool.com/fiddler/) to check how does the cookie looks in the http response.
3. Check if other sites on the internet are storing cookies successfully. | Persistent cookies from a servlet in IE | [
"",
"java",
"internet-explorer",
"servlets",
"cookies",
""
] |
I am running an Ubuntu 8.10, using Python 2.5 out of the box. This is fine from the system point of view, but I need Python2.4 since I dev on Zope / Plone.
Well, installing python2.4 is no challenge, but I can't find a (clean) way to make iPython use it : no option in the man nor in the config file.
Before, there was... | Ok, I answer my own question : I'm dumb :-)
```
ls /usr/bin/ipython*
/usr/bin/ipython /usr/bin/ipython2.4 /usr/bin/ipython2.5
```
Now it's built-in... | I'm using Ubuntu 10.10 and there's only on ipython installed. (There's also only one python available, but I got an older version with [the deadsnakes ppa](https://launchpad.net/~fkrull/+archive/deadsnakes).)
To get ipython2.5, I installed ipython from your virtualenv:
```
virtualenv --python=/usr/bin/python2.5 proje... | How to force iPython to use an older version of Python? | [
"",
"python",
"ipython",
""
] |
As a [C#](http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29) developer I'm used to running through constructors:
```
class Test {
public Test() {
DoSomething();
}
public Test(int count) : this() {
DoSomethingWithCount(count);
}
public Test(int count, string name) : t... | **C++11: Yes!**
C++11 and onwards has this same feature (called [delegating constructors](https://secure.wikimedia.org/wikipedia/en/wiki/C++11#Object_construction_improvement)).
The syntax is slightly different from C#:
```
class Foo {
public:
Foo(char x, int y) {}
Foo(int y) : Foo('a', y) {}
};
```
**C++03: N... | Yes and No, depending on which version of C++.
In C++03, you can't call one constructor from another (called a delegating constructor).
This changed in C++11 (aka C++0x), which added support for the following syntax:
(example taken from [Wikipedia](http://en.wikipedia.org/wiki/C%2B%2B11#Object_construction_improvem... | Can I call a constructor from another constructor (do constructor chaining) in C++? | [
"",
"c++",
"constructor",
"delegates",
""
] |
I am working on a C++ project and I noticed that we have a number of warnings about unused parameters.
What effect could it have if these warnings are ignored? | The function with an unused parameter may have a real bug in the following cases:
1. There is an **output** parameter, which is not being assigned or written into, resulting in undefined value for the caller.
2. One of parameters is a callback function pointer, which you must invoke and forget to do so. May happen if ... | If you have a whole lot of unimportant warnings that are not important to you, you may overlook the important warning about the line of code that you just wrote that is hiding in the middle of them. | What are the consequences of ignoring: warning: unused parameter | [
"",
"c++",
"warnings",
""
] |
Been thinking, what's the difference between declaring a variable with [] or \* ? The way I see it:
```
char *str = new char[100];
char str2[] = "Hi world!";
```
.. should be the main difference, though Im unsure if you can do something like
```
char *str = "Hi all";
```
.. since the pointer should the reference to... | Let's look into it (for the following, note `char const` and `const char` are the same in C++):
## String literals and char \*
`"hello"` is an array of 6 const characters: `char const[6]`. As every array, it can convert implicitly to a pointer to its first element: `char const * s = "hello";` For compatibility with C... | The three different declarations let the pointer point to different memory segments:
```
char* str = new char[100];
```
lets str point to the heap.
```
char str2[] = "Hi world!";
```
puts the string on the stack.
```
char* str3 = "Hi world!";
```
points to the data segment.
The two declarations
```
void upperCa... | C++ strings: [] vs. * | [
"",
"c++",
"syntax",
"reference",
"pointers",
""
] |
When we can catch an exception like: `Violation of UNIQUE KEY constraint 'IX_Product'. Cannot insert duplicate key in object 'Product'. (2627)`.
The challenge is how to dechiper the Index Name IX\_Product as a Member (i.e. I don't want to substring out the message). There could be more than one unique constraint on a... | You'll have to either:
1. code your client component to
recognize the constraint names that
each insert/update statement might
throw exceptions for,
2. rename all your constraints so that they are "decipherable" in the way you want to use them in client code, or...
3. check all the contraints in a stored proc... | uh...maybe i'm missing something obvious...but wouldn't it be a better use of your time to *fix the bug* instead of parsing the exception? | Handling database exceptions in .net | [
"",
"c#",
"sql-server",
"exception",
""
] |
I am working on a c++ win32 program that involves a keyboard hook. The application is a win32 project with no user interface whatsoever. I need to keep the application from closing without using causing the hook to not work or use up a bunch of system resources. I used to use a message box but I need the application to... | I think what you need is [message only window](http://msdn.microsoft.com/en-us/library/ms632599(VS.85).aspx#message_only)
> (***MSDN says***) A message-only window enables you to send and receive messages. It is not visible, has no z-order, cannot be enumerated, and does not receive broadcast messages. The window simp... | Do you really need windows?
The [MSDN LowLevelKeyboardProc page](http://msdn.microsoft.com/en-us/library/ms644985%28v=vs.85%29.aspx) recommends using a simple message loop.
Just insert this snippet after the hook call.
```
// message loop to keep the keyboard hook running
MSG msg;
while(GetMessage(&msg, NULL, 0, 0) > ... | keep a formless application from closing for a keyboard hook | [
"",
"c++",
"winapi",
"keyboard",
"hook",
""
] |
I'm writing a little arcade-like game in C++ (a multidirectional 2d space shooter) and I'm finishing up the collision detection part.
Here's how I organized it (I just made it up so it might be a shitty system):
Every ship is composed of circular components - the amount of components in each ship is sort of arbitrary... | You should absolutely try to avoid doing memory allocations for your component-vector on each call to the getter-function. Do the allocation as seldom as possible, instead. For instance, you could do it when the component composition of the ship changes, or even more seldom (by over-allocating).
You could of course al... | If your 2D vector is just:
```
class Vector2D { double x, y; };
```
Then by all means return it! E.g:
```
Vector2D function( ... );
```
Or pass by reference:
```
void function( Vector2D * theReturnedVector2D, ... );
```
**Avoid at all costs:**
```
vector<double> function(...);
```
The constant heap alloca... | Simple efficiency question C++ (memory allocation)..and maybe some collision detection help? | [
"",
"c++",
"memory",
"performance",
"allocation",
""
] |
Tried something like this:
```
HttpApplication app = s as HttpApplication; //s is sender of the OnBeginRequest event
System.Web.UI.Page p = (System.Web.UI.Page)app.Context.Handler;
System.Web.UI.WebControls.Label lbl = new System.Web.UI.WebControls.Label();
lbl.Text = "TEST TEST TEST";
p.Controls.Add(lbl);
```
when r... | I'm not sure, but I don't think you can use an HttpModule to alter the Page's control tree (please correct me if I'm wrong). You CAN modify the HTML markup however, you'll have to write a "response filter" for this. For an example, see <http://aspnetresources.com/articles/HttpFilters.aspx>, or google for "httpmodule re... | Its simplier than you think:
```
public void Init(HttpApplication app)
{
app.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
}
private void OnPreRequestHandlerExecute(object sender, EventArgs args)
{
HttpApplication app = sender as HttpApplication;
if (app != null)
... | HttpModule - get HTML content or controls for modifications | [
"",
"c#",
"httpmodule",
".net-1.1",
""
] |
As a win32 developer moving into web deveopment the last few years, I found the
web desktops based on extjs very interesting.
[Coolite Desktop](http://examples.coolite.com/Examples/Desktop/Introduction/Overview/Desktop.aspx) (broken)
[Extjs Desktop](http://extjs.com/deploy/dev/examples/desktop/desktop.html)
[Pu... | I find it an interesting experiment, but I don't really find much added value in it.
The desktop concept works for an operating system. Most people use one operating system. They are familiar with how it works and what to expect in terms of navigation. That being said, having a desktop at an application (or site) leve... | NO.
Also, [Uncanny valley](https://blog.codinghorror.com/avoiding-the-uncanny-valley-of-user-interface/) of UI. | Web desktops - do you find it interesting? | [
"",
"javascript",
"windows",
""
] |
```
class String
{
private:
char* rep;
public:
String (const char*);
void toUpper() const;
};
String :: String (const char* s)
{
rep = new char [strlen(s)+1];
strcpy (rep, s);
}
void String :: toUpper () const
{
for (int i = 0; rep [i]; i++)
rep[i] = toupper(rep[i])... | **A const member function, is a member function that does not mutate its member variables.**
**const on a member function does not imply const char \*. Which would mean that you can't change the data in the address the pointer holds.**
Your example does not mutate the member variables themselves.
A const on a member... | The reason is that you don't change `rep`. If you would, you would find `rep = ...;` somewhere in your code. This is the difference between
```
char*const rep;
```
and
```
const char* rep;
```
In your case, the first one is done if you execute a const member-function: The pointer is const. So, you won't be able to ... | Why does this const member function allow a member variable to be modified? | [
"",
"c++",
"constants",
""
] |
My code is built to multiple .dll files, and I have a template class that has a static member variable.
I want the same instance of this static member variable to be available in all dlls, but it doesn't work: I see different instance (different value) in each of them.
When I don't use templates, there is no problem:... | Create template specialization and then export the static members of the specialization. | There exists the following solution, as well:
* in the **library**: explicitly instantiate some template specialization and share them with dllexport
* in the **main program**:
+ if the specialization is available it will be used from the library
+ if the specialization is not available it is compiled in the main ... | Static member variable in template, with multiple dlls | [
"",
"c++",
"dll",
"visual-studio-2005",
"static",
"templates",
""
] |
I have a business case whereby I need to be able to specify my own calling convention when using P/Invoke. Specifically, I have a legacy dll which uses a non-standard ABI, and I need to able to specify the calling convention for each function.
For example, one function in this dll accepts its first two arguments via E... | I don't understand what you mean with custom P/Invoke, but I can't see how you could get away without non-managed C++ with inline assembly. However, since almost everything is passed as 32-bit values, you might get away with writing only one proxy for each function signature, as apposed to one per function. Or you coul... | I'm fairly certain there is no builtin way of accomplishing what you want without a separate dll. I've not seen a way to specify a calling convention other than what the runtime system supports. | Custom calling convention for P/Invoke and C# | [
"",
"c#",
"pinvoke",
"calling-convention",
""
] |
I'm planning to develop a web-services (SOAP to C++ client) in Java with Metro/Hibernate and front it up with a web-site written in JRuby on Rails, connecting Java modules through JRuby and generally through a database. I already wrote some code and set up everything.
Now, I've heard that .NET 3.5 is really powerful a... | I'm sorry, but what you are doing sounds like a big ball o' mud. Doesn't matter to me what path you take, but I'd simplify the architecture by reducing the number of technologies/frameworks that you are using. If you can find a way to do it in Ruby/Rails without reference to Java (although you may need to keep the C++ ... | .NET 3.5 is loads of fun (among mainstream platforms), but in my personal opinion Ruby is as much fun as if not more fun than .NET 3.5.
About the capabilities, they are also roughly equivalent, you certainly can make a SOAP web services application in both without problems.
About the "monstrous hybrid", there's no su... | Java/JRuby on Rails vs .NET 3.5... feel like I'm doing it wrong | [
"",
"java",
".net",
"ruby-on-rails",
"jruby",
""
] |
Is there a Php function to determine if a string consist of only ASCII alphanumerical characters?
Note: I'm sorry if the question sounds dumb to some, but I couldn't easily find such a function in the Php manual. | Try [ctype\_alnum](https://www.php.net/manual/en/function.ctype-alnum.php) | ```
preg_match('/^[a-z0-9]+$/i', $str);
```
Edit: John T's answer is better. Just providing another method. | Php function to determine if a string consist of only alphanumerical characters? | [
"",
"php",
"string",
""
] |
The following event can possibly get called hundreds of times a frame.
```
public bool OnCollision(Body body1, Body body2)
{
if(body2.Tag is Dog)
((Dog)body2.Tag).Bark();
}
```
I understand that using "is" causes a cast to be made and then when i want to do something with it, cast it a second time. Is there a ... | ```
if(body2.Tag is Dog)
```
is actually compiled as
```
Dog Temp = body2.Tag as Dog;
if (temp != null)
```
In your code, you're then doing the cast again. Better would be:
```
Dog dog = body2.Tag as Dog;
if (dog != null)
{
dog.Bark();
}
``` | I would just make an abstract method on the Body object called Collided:
```
abstract class Body
{
abstract void Collision(Body other);
}
class Dog : Body
{
public override void Collision(Body other) {
this.Bark();
}
public void Bark() { ... }
}
```
Then in your collision function just call Collis... | Fastest Type Comparison? | [
"",
"c#",
"types",
"xna",
""
] |
I have a problem with the [`jquery-ui dialog box`](https://jqueryui.com/dialog/).
**The problem is that when I close the dialog box and then I click on the link that triggers it, it does not pop-up again unless I refresh the page.**
How can I call the dialog box back without refreshing the actual page.
Below is my c... | I solved it.
I used destroy instead close function (it doesn't make any sense), but it worked.
```
$(document).ready(function() {
$('#showTerms').click(function()
{
$('#terms').css('display','inline');
$('#terms').dialog({resizable: false,
modal: true,
width: 400,
height: 450,
... | You're actually supposed to use `$("#terms").dialog({ autoOpen: false });` to initialize it.
Then you can use `$('#terms').dialog('open');` to open the dialog, and `$('#terms').dialog('close');` to close it. | jQuery UI Dialog Box - does not open after being closed | [
"",
"javascript",
"jquery",
"jquery-ui",
"modal-dialog",
"jquery-ui-dialog",
""
] |
I'm about to put my head thru this sliding glass door. I can't figure out how to execute the following code in VB.NET to save my life.
```
private static void InitStructureMap()
{
ObjectFactory.Initialize(x =>
{
x.AddRegistry(new... | At the moment, it's simply not possible. The current version of VB does not support multiline (or statement) lambdas. Each lambda can only comprise one single expression. The next version of VB will fix that (there simply wasn't enough time in the last release).
In the meantime, you'll have to make do with a delegate:... | You can see another approach at:
<http://blogs.lessthandot.com/index.php/DesktopDev/MSTech/structuremap-is-way-cool-even-in-vb-net> | How to convert C# StructureMap initialization to VB.NET? | [
"",
"c#",
"vb.net",
"structuremap",
""
] |
It's quite possible a question like this has been asked before, but I can't think of the terms to search for.
I'm working on a photo gallery application, and want to display 9 thumbnails showing the context of the current photo being shown (in a 3x3 grid with the current photo in the centre, unless the current photo i... | Probably could just use a UNION, and then trim off the extra results in the procedural code that displays the results (as this will return 20 rows in the non-edge cases):
```
(SELECT
*
FROM photos
WHERE ID < #current_id#
ORDER BY ID DESC LIMIT 10)
UNION
(SELECT *
FROM photos
WHERE ID >= #current_i... | If you are using SQL Server, you can use the row\_number() function to give you the row order index and do something like this:
```
declare @selected_photo integer;
set @selected_photo = 5;
declare @buffer_size integer;
set @buffer_size = 2;
select
ph.rownum,
ph.id
from
(select row_number() over (order by I... | SQL Selecting "Window" Around Particular Row | [
"",
"sql",
"mysql",
""
] |
Earlier I asked a question about [why I see so many examples use the `var`keyword](https://stackoverflow.com/questions/335682/mvc-examples-use-of-var) and got the answer that while it is only necessary for anonymous types, that it is used nonetheless to make writing code 'quicker'/easier and 'just because'.
Following ... | There's no extra Intermediate language (IL) code for the `var` keyword: the resulting IL should be identical for non-anonymous types. If the compiler can't create that IL because it can't figure out what type you intended to use, you'll get a compiler error.
The only trick is that `var` will infer an exact type where ... | As Joel says, the compiler works out at *compile-time* what type var should be, effectively it's just a trick the compiler performs to save keystrokes, so for example
```
var s = "hi";
```
gets replaced by
```
string s = "hi";
```
*by the compiler* before any IL is generated. The Generated IL will be *exactly* the ... | Will using 'var' affect performance? | [
"",
"c#",
"performance",
"variables",
"var",
""
] |
I have been given a DLL ("InfoLookup.dll") that internally allocates structures and returns pointers to them from a lookup function. The structures contain string pointers:
```
extern "C"
{
struct Info
{
int id;
char* szName;
};
Info* LookupInfo( int id );
}
```
In C#, how can I declare the s... | Try the following layout. Code automatically generated using the [PInvoke Interop Assistant](http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120). Hand coded LookpInfoWrapper()
```
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
p... | For an example, see this [netapi32.NetShareAdd](http://www.pinvoke.net/default.aspx/netapi32.NetShareAdd) interop declaration. It includes a `SHARE_INFO_502` structure, with a `public string shi502_netname` member. Many more examples are available at [Pinvoke.net](http://www.pinvoke.net/). | In C#, how do I invoke a DLL function that returns an unmanaged structure containing a string pointer? | [
"",
"c#",
"interop",
""
] |
What's a surefire way of detecting whether a user has Firebug enabled? | # Original answer:
Check for the `console` object (created only with Firebug), like such:
```
if (window.console && window.console.firebug) {
//Firebug is enabled
}
```
---
# Update (January 2012):
The Firebug developers have [decided to remove `window.console.firebug`](http://code.google.com/p/fbug/issues/detai... | If firebug is enabled, window.console will not be undefined. console.firebug will return the version number. | Javascript that detects Firebug? | [
"",
"javascript",
"firebug",
""
] |
Can anyone point me in the right direction how to configure Visual Studio 2005 with our C++ console project how we can include a 'File Version' in the details section of the file properties.
I've tried resource files without any luck. This is with a C++ project just for clarification, and big thank you for the guys yo... | If you are talking about unmanaged c++, you need to add a version resource to the project.
right-click on the project, choose add - Resource.... Choose Version and press new.
There you can enter all info you need. | You have to have one `VS_VERSION_INFO` section in your resource (\*.rc) file(s) that compile into your project.
In the Visual Studio 2005 Solution Explorer, open the context menu on your C++ project and choose Add, Resource.
Mark Version and click "New".
Fill in the fields as desired and save the file.
Build.
Now ... | Setting file version number in Visual Studio 2005 C++ | [
"",
"c++",
"visual-studio",
"visual-c++-2005",
""
] |
What's the most efficient way to calculate the last day of the prior quarter?
Example: given the date 11/19/2008, I want to return 9/30/2008.
Platform is SQL Server | If @Date has the date in question
```
Select DateAdd(day, -1, dateadd(qq, DateDiff(qq, 0, @Date), 0))
```
EDIT: Thanks to @strEagle below, simpler still is:
```
Select dateadd(qq, DateDiff(qq, 0, @Date), -1)
``` | Actually simpler is:
```
SELECT DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), -1)
``` | Calculate the last day of the prior quarter | [
"",
"sql",
"sql-server",
"date",
""
] |
Is it possible to create a parameterized SQL statement that will taken an arbitrary number of parameters? I'm trying to allow users to filter a list based on multiple keywords, each separated by a semicolon. So the input would be something like "Oakland;City;Planning" and the WHERE clause would come out something equiv... | A basic proof-of-concept... Actual code would be less, but since I don't know your table/field names, this is the full code, so anyone can verify it works, tweak it, etc.
```
--Search Parameters
DECLARE @SearchString VARCHAR(MAX)
SET @SearchString='Oakland;City;Planning' --Using your example search
DECLARE @Delim CHA... | You might also want to consider Full Text Search and using `CONTAINS` or `CONTAINSTABLE` for a more "natural" search capability.
May be overkill for 1K rows, but it is written and is not easily subverted by injection. | Using an arbitrary number of parameters in T-SQL | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.
How can you determine if another point c is on the line segment defined by a and b?
I use python most, but examples in any language would be helpful. | Check if the **cross product** of (b-a) and (c-a) is 0, as tells Darius Bacon, tells you if the points a, b and c are aligned.
But, as you want to know if c is between a and b, you also have to check that the **dot product** of (b-a) and (c-a) is *positive* and is *less* than the square of the distance between a and b... | Here's how I'd do it:
```
def distance(a,b):
return sqrt((a.x - b.x)**2 + (a.y - b.y)**2)
def is_between(a,c,b):
return distance(a,c) + distance(c,b) == distance(a,b)
``` | How can you determine a point is between two other points on a line segment? | [
"",
"python",
"math",
"geometry",
""
] |
Let's say I have my pizza application with Topping and Pizza classes and they show in Django Admin like this:
```
PizzaApp
-
Toppings >>>>>>>>>> Add / Change
Pizzas >>>>>>>>>> Add / Change
```
But I want them like this:
```
PizzaApp
-
Pizzas >>>>>>>>>> Add / Change
Toppings >... | This is actually covered at the very bottom of [Writing your first Django app, part 7](https://docs.djangoproject.com/en/3.0/intro/tutorial07/).
Here's the relevant section:
> **Customize the admin index page**
>
> On a similar note, you might want to
> customize the look and feel of the
> Django admin index page.
>
... | A workaround that you can try is tweaking your models.py as follows:
```
class Topping(models.Model):
.
.
.
class Meta:
verbose_name_plural = "2. Toppings"
class Pizza(models.Model):
.
.
.
class Meta:
verbose_name_plural = "1. Pizzas"
```
Not sure if it is against the ... | Ordering admin.ModelAdmin objects in Django Admin | [
"",
"python",
"django",
"django-admin",
"django-apps",
"django-modeladmin",
""
] |
I have a table with the following columns:
```
A B C
---------
1 10 X
1 11 X
2 15 X
3 20 Y
4 15 Y
4 20 Y
```
I want to group the data based on the B and C columns and count the distinct values of the A column. But if there are two ore more rows where the value on the A column is the same I want ... | I like to work in steps: first get rid of duplicate A records, then group. Not the most efficient, but it works on your example.
```
with t1 as (
select A, max(B) as B, C
from YourTable
group by A, C
)
select count(A) as CountA, B, C
from t1
group by B, C
``` | I have actually tested this:
```
SELECT
MAX( B ) AS B,
C,
Count
FROM
(
SELECT
B, C, COUNT(DISTINCT A) AS Count
FROM
t
GROUP BY
B, C
) X
GROUP BY C, Count
```
and it gives me:
```
B C Count
---- ---- --------
15 X 1
15 y 1
... | SQL grouping | [
"",
"sql",
"sql-server",
"sql-server-2005",
"grouping",
""
] |
I wanted to see what folks thought were the best way to help junior members gain confidence in their ability to refactor code. I find that often junior developers simply follow the existing patterns and sense an aversion to break anything due to the perceived risk. I am trying to get them to look at the requirements (n... | The only reliable answer will be unit tests IMHO. Not necessarily TDD -- just get them to write tests for the existing methods/classes they want to refactor, make sure they're doing what they're doing, then allow them to refactor like crazy while relying on the tests to make sure the methods are still valid.
The confi... | It seems that **pair programming with a senior developer in combination with writing tests** would be the optimal situation. If the more experienced developer in the pair is leading, the testing will just be part of it.
Writing tests alone leaves room for improvement. Writing tests in a pair environment is the best of... | How can I help junior members gain confidence in their ability to refactor code? | [
"",
"c#",
"refactoring",
""
] |
I've just done a test with bitfields, and the results are surprising me.
```
class test1 {
public:
bool test_a:1;
bool test_b:1;
bool test_c:1;
bool test_d:1;
bool test_e:1;
bool test_f:1;
bool test_g:1;
bool test_h:1;
};
class test2 {
public:
int test_a:1;
int test_b:1;
in... | your compiler has arranged all of the members of test3 on integer size boundaries. Once a block has been used for a given type (integer bit-field, or boolean bit-field), the compiler does not allocate any further bit fields of a different type until the next boundary.
I doubt it is a bug. It probably has something to ... | Be careful with bitfields as much of its behavior is implementation (compiler) defined:
From C++03, 9.6 Bitfields (pg. 163):
> Allocation of bit-fields within a
> class object is
> implementation-defined. Alignment of
> bit-fields is implementation-defined.
> Bit-fields are packed into some
> addressable allocation u... | C++ bitfield packing with bools | [
"",
"c++",
"bit-fields",
""
] |
I am looking in the Collections framework of Java for a LIFO Structure (Stack) without any success. Basically I want a really simple stack; my perfect option would be a Deque, but I am in Java 1.5.
I would like not to have to add another class to my structure but I am wondering if that is possible:
1. Is there any cl... | There's actually a Stack class: <http://java.sun.com/j2se/1.5.0/docs/api/java/util/Stack.html>
If you don't want to use that, the LinkedList class (<http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedList.html>) has `addFirst` and `addLast` and `removeFirst` and `removeLast` methods, making it perfect for use as ... | I realize I'm late to the party here, but java.util.Collections (Java 7) has a static 'asLifoQueue' that takes a Deque argument and returns (obviously) a LIFO queue view of the deque. I'm not sure what version this was added.
<http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#asLifoQueue(java.util.De... | Java Collections (LIFO Structure) | [
"",
"java",
"collections",
"stack",
"queue",
""
] |
For example, files, in Python, are iterable - they iterate over the lines in the file. I want to count the number of lines.
One quick way is to do this:
```
lines = len(list(open(fname)))
```
However, this loads the whole file into memory (at once). This rather defeats the purpose of an iterator (which only needs to... | Short of iterating through the iterable and counting the number of iterations, no. That's what makes it an iterable and not a list. This isn't really even a python-specific problem. Look at the classic linked-list data structure. Finding the length is an O(n) operation that involves iterating the whole list to find the... | If you need a count of lines you can do this, I don't know of any better way to do it:
```
line_count = sum(1 for line in open("yourfile.txt"))
``` | Is there any built-in way to get the length of an iterable in python? | [
"",
"python",
"iterator",
""
] |
I am using SQL Advantage and need to know what the SQL is to identify the triggers associated with a table. I don't have the option to use another tool so the good old fashioned SQL solution is the ideal answer. | I also found out that
```
sp_depends <object_name>
```
will show you a lot of information about a table, including all triggers associated with it. Using that, along with Ray's query can make it much easier to find the triggers. Combined with this query from Ray's linked article:
```
sp_helptext <trigger_name>
```
... | ```
select *
from sysobjects
where type = 'TR'
```
Taken from [here](https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-1061431.html). | How do you identify the triggers associated with a table in a sybase database? | [
"",
"sql",
"triggers",
"sybase",
"advantage-database-server",
""
] |
I'm starting out with wxPython and have been working my way through every tutorial and example I can get my hands on. I've run into a slight problem, however, and it has to do with the wx.App versus the wx.Frame and which should contain specific methods. Just about every example I've seen don't go much beyond layouts/s... | Your classes that inherit from wxWidgets/wxPython data types should not implement any business logic. wxWidgets is a GUI library, so any subclasses of wxApp or wxFrame should remain focused on GUI, that is on displaying the interface and being responsive to user actions.
The code that does something useful should be s... | As Mark stated you should make a new class that handles things like this.
The ideal layout of code when using something like wxWidgets is the model view controller where the wxFrame class only has the code needed to display items and all the logic and business rules are handled by other class that interact with the wx... | Calling Application Methods from a wx Frame Class | [
"",
"python",
"wxpython",
"wxwidgets",
"model-view-controller",
"project-organization",
""
] |
C#, .NET 3.5
I am trying to get all of the properties of an object that have BOTH a getter and a setter for the instance. The code I *thought* should work is
```
PropertyInfo[] infos = source.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.GetProperty);
``... | Call [`GetGetMethod`](http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getgetmethod.aspx) and [`GetSetMethod`](http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getsetmethod.aspx) on the property - if both results are non-null, you're there :)
(The parameterless versions only... | You can check the `PropertyInfo.CanRead` and `PropertyInfo.CanWrite` properties. | How do you find only properties that have both a getter and setter? | [
"",
"c#",
".net",
"reflection",
""
] |
According to the documentation of the `==` operator in [MSDN](http://msdn.microsoft.com/en-us/library/53k8ybth.aspx),
> For predefined value types, the
> equality operator (==) returns true if
> the values of its operands are equal,
> false otherwise. For reference types
> other than string, == returns true if
> its t... | "...by default == behaves as described above for both predefined and user-defined reference types."
Type T is not necessarily a reference type, so the compiler can't make that assumption.
However, this will compile because it is more explicit:
```
bool Compare<T>(T x, T y) where T : class
{
return x ... | As others have said, it will only work when T is constrained to be a reference type. Without any constraints, you can compare with null, but only null - and that comparison will always be false for non-nullable value types.
Instead of calling Equals, it's better to use an `IComparer<T>` - and if you have no more infor... | Can't operator == be applied to generic types in C#? | [
"",
"c#",
"generics",
"operators",
"equals-operator",
""
] |
If I'm using an ArrayList in C#.NET, is the order guaranteed to stay the same as the order I add items to it? | Yes, elements are always added to the end (unless you specify otherwise, e.g. with a call to [Insert](http://msdn.microsoft.com/en-us/library/system.collections.arraylist.insert.aspx)). In other words, if you do:
```
int size = list.Count;
int index = list.Add(element);
Assert.AreEqual(size, index); // Element is alwa... | Yes, it is, unless some piece of your code changes the order by e.g. swapping. | Is the order of an arraylist guaranteed in C#.NET? | [
"",
"c#",
".net",
"arraylist",
""
] |
I just installed the FindBugs plugin for Eclipse, with the hope that it will help me find SQL injection vulnerabilities in my code. However, it doesn't seem to be finding anything, even when I deliberately put some in.
In the following examples, assume `staticFinalBaseQuery` is declared as follows:
public static fina... | It is hard to distinguish between safe code and unsafe code here. Sure, userInputfilterString *may* be unsafe, but it is impossible to determine this at compile time. However, the single-quote character in a string concatenation is a tell-tale sign of using inject-able code. That's why FindBugs is triggering on the lin... | I don't think [PMD](http://pmd.sourceforge.net/) or [Checkstyle](http://checkstyle.sourceforge.net/) will catch it either, but you might give them a try (I use all 3 on a regular basis, good tools to use).
EDIT: PMD was the correct link, but I called it findbugs... findbugs on the brain I guess... | Findbugs not finding potential SQL injection vulnerability | [
"",
"java",
"sql-injection",
"findbugs",
""
] |
I am looking for a small wiki engine that is easy to embed into an existing PHP application. Or perhaps a set of libraries to handle all the typical wiki functions.
Currently I am using [ErfurtWiki](http://erfurtwiki.sourceforge.net/), but it is starting to show its age. It hasn't been updated since 2005, and several ... | [Pear::Text\_Wiki](http://pear.php.net/package/Text_Wiki) is another option, albeit it only handles the case of text formatting. It has not been updated since June of 2007, but includes several Wiki formats (all of which have other latest release dates).
The formats that Text\_Wiki supports are:
* BBCode: latest rele... | I highly recommend [MediaWiki](http://www.mediawiki.org/wiki/MediaWiki), the wiki engine that runs wikipedia.
EDIT: As per your comment, MediaWiki is highly embeddable. I've integrated it in numerous projects over the years. | Suggest a good PHP wiki engine | [
"",
"php",
"wiki",
"wiki-engine",
""
] |
[I was trying to get my Netbeans to autocomplete with PHP](https://stackoverflow.com/questions/390192), and I learned that this code is valid in PHP:
```
function blah(Bur $bur) {}
```
A couple of questions:
1. **Does this actually impose any limits** on what type of variable I can pass to the blah method?
2. If thi... | This type-hinting only works for validating function arguments; you can't declare that a PHP variable must always be of a certain type. This means that in your example, $bur must be of type Bur when "blah" is called, but $bur could be reassigned to a non-Bur value inside the function.
Type-hinting only works for class... | 1. Specifying a data type for a function parameter will cause PHP to throw a catchable fatal error if you pass a value which is not of that type. Please note though, you can only specify types for classes, and not primitives such as strings or integers.
2. Most IDE's can infer a data type from a PHPDoc style comment if... | Declaring Variable Types in PHP? | [
"",
"php",
"variable-types",
""
] |
I'm using .Net 2.0 and this is driving me crazy but there's probably some easy thing I'm not doing that I am now too confused to see.
I have an application that has a bespoke collection of objects in it, only the main form should be able to change the contents of that collection and all other forms should be able to r... | If the main form needs read/write access but other forms don't, then I would make the collection a property of your main form that is read/write from within your form, but read only from outside your form. You can do this using something like:
C#
```
private myCollection _MyCollection;
public myCollection MyCollecti... | Check out the method `List<T>.AsReadOnly()`
This allows you to return a read-only wrapper for the list.
e.g.
```
private LIst<Foo> fooList;
public ReadOnlyCollection<Foo> Foo {
get { return fooList.AsReadOnly(); }
``` | C# Forms App Collections | [
"",
"c#",
"winforms",
"collections",
""
] |
Pretty straightforward stuff, here -- I'm just not good enough with mysql to understand what it wants from me.
I've got a short java test-case that opens a connection on mysql on my dev system but, when I try to put it to my server, it fails.
Any help in tracking this down would be most appreciated.
Thanks!
**Test ... | Bah! My apologies -- I just had "local connections only" set up. I was confused by the fact that the java app was running locally (so seemed a "local connection" but, because it is connecting via TCP, it's a "remote" connection, even though it originates on localhost.
I will eventually learn how to administer these th... | Just a helpful note on this subject. I spent at least 30 minutes trying to debug the same error and this was my mistake.
In my MySQL conf file I happened to set the *BIND ADDR* to the IP of the machine. I did not set it to `127.0.0.1`, or `0.0.0.0`. So MySQL would accept JDBC connections from outside, but not internal... | Java Driver.getConnection() yields "Connection Refused" from mysql on live system, not dev | [
"",
"java",
"mysql",
"jdbc",
""
] |
I have an HTML (not XHTML) document that renders fine in Firefox 3 and IE 7. It uses fairly basic CSS to style it and renders fine in HTML.
I'm now after a way of converting it to PDF. I have tried:
* [DOMPDF](https://github.com/dompdf/dompdf): it had huge problems with tables. I factored out my large nested tables a... | **Important:**
Please note that this answer was written in 2009 and it might not be the most cost-effective solution today in 2019. Online alternatives are better today at this than they were back then.
Here are some online services that you can use:
* [PDFShift](https://pdfshift.io)
* [Restpack](https://restpack.io/... | Have a look at [`wkhtmltopdf`](http://wkhtmltopdf.org/) . It is open source, based on webkit and free.
We wrote a small tutorial [here](http://beebole.com/blog/general/convert-html-to-pdf-with-full-css-support-an-opensource-alternative-based-on-webkit/).
**EDIT( 2017 ):**
If it was to build something today, I wouldn... | How Can I add HTML And CSS Into PDF | [
"",
"php",
"html",
"css",
"pdf",
"pdf-generation",
""
] |
Is it possible to display the text in a TextBlock vertically so that all letters are stacked upon each other (not rotated with LayoutTransform)? | Nobody has yet mentioned the obvious and trivial way to stack the letters of an arbitrary string vertically (without rotating them) using pure XAML:
```
<ItemsControl
ItemsSource="Text goes here, or you could use a binding to a string" />
```
This simply lays out the text vertically by recognizing the fact that the... | Just in case anybody still comes across this post... here is a simple 100% xaml solution.
```
<TabControl TabStripPlacement="Left">
<TabItem Header="Tab 1">
<TabItem.LayoutTransform>
<RotateTransform Angle="-90"></RotateTransform>
</TabItem.LayoutTransform>
... | Vertical Text in Wpf TextBlock | [
"",
"c#",
"wpf",
""
] |
I'm asking for a suitable architecture for the following Java web application:
The goal is to build several web applications which all operate on the same data. Suppose a banking system in which account data can be accessed by different web applications; it can be accessed by customers (online banking), by service per... | B, C, and D are all just different ways to accomplish the same thing.
My first thought would be to simply have all consumer code connecting to a common database. This is certainly doable, and would eliminate the code you don't want to place in the middle. The drawback, of course, is that if the schema changes, all con... | I think that you have to go in the oppposite direction - from the bottom up. Of course, you have to go forth and back to verify that everything is playing, but here is the general direction:
Think about your data - DB scheme, how transactions are important (for example in banking systems everything is about transactio... | Architecture - Multiple web apps operating on the same data | [
"",
"java",
"architecture",
""
] |
I need to randomly 'sort' a list of integers (0-1999) in the most efficient way possible. Any ideas?
Currently, I am doing something like this:
```
bool[] bIndexSet = new bool[iItemCount];
for (int iCurIndex = 0; iCurIndex < iItemCount; iCurIndex++)
{
int iSwapIndex = random.Next(iItemCount);
if (!bIndexSet[... | A good linear-time shuffling algorithm is the [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
One problem you'll find with your proposed algorithm is that as you near the end of the shuffle, your loop will spend a lot of time looking for randomly chosen elements that have not yet been swappe... | ```
static Random random = new Random();
public static IEnumerable<T> RandomPermutation<T>(IEnumerable<T> sequence)
{
T[] retArray = sequence.ToArray();
for (int i = 0; i < retArray.Length - 1; i += 1)
{
int swapIndex = random.Next(i, retArray.Length);
if (swapIndex != i) {
T ... | Most efficient way to randomly "sort" (Shuffle) a list of integers in C# | [
"",
"c#",
"random",
"shuffle",
""
] |
I work on a database driven website. Most pages' titles are the names of partners we have, and served from a database using php.
For example one page might be called "Experian". The problem is that some of the values for partner names don't work because the values are things like
```
$partnername22 = Discover<sup>t... | For:
```
<title><?php echo $offer22name ?>is a magazine</title>
```
change to:
```
<title><?php echo preg_replace('|<sup>(.*?)</sup>|', '($1)', $offer22name) ?> is a magazine</title>
```
But like Bryan mentioned, you should use PHP's strip\_tags() in this scenario. So:
```
<title><?php echo strip_tags($offer22name... | It would be very simple (and probably advisable) to use PHP's strip\_tags() command to remove all of the html from your string before posting it as a title. | Ignoring superscript in title tags | [
"",
"php",
"html",
"css",
"superscript",
""
] |
I'm making a php web application which stores user specific information that is not shared with other users.
Would it be a good idea to store some of this information in the $\_SESSION variable for caching? For example: cache a list of categories the user has created for their account. | This would be an appropriate use of the session mechanism as long as you keep this in mind:
* Session does not persist for an indefinite amount of time.
* When pulling from session, ensure you actually got a result (ASP.NET will return NULL if the Session has expired/cleared)
* Server restarts may wipe the session cac... | That could work well for relatively small amounts of data but you'll have to take some things into consideration:
1. $\_SESSION is stored somewhere between requests, file on disk or database or something else depending on what you choose to use (default to file)
2. $\_SESSION is local to a single user on a single mach... | Caching variables in the $_SESSION variable? | [
"",
"php",
"session",
"caching",
""
] |
In a web application I am working on, the user can click on a link to a CSV file. There is no header set for the mime-type, so the browser just renders it as text. I would like for this file to be sent as a .csv file, so the user can directly open it with calc, excel, gnumeric, etc.
```
header('Content-Type: text/csv'... | You could try to force the browser to open a "Save As..." dialog by doing something like:
```
header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyVerySpecial.csv');
echo "cell 1, cell 2";
```
Which should work across most major browsers. | You are not specifying a language or framework, but the following header is used for file downloads:
```
"Content-Disposition: attachment; filename=abc.csv"
``` | How to use the CSV MIME-type? | [
"",
"php",
"csv",
"http-headers",
"mime",
""
] |
Is there a way to avoid row deletion on an specific table using constrains?
I'd like to (for example) deny row deletion if the id is 0,1 or 2
This is in order to avoid users deleting master accounts for an application, and I'd like to avoid it even if someone tries it (by mistake) using sql directly.
Thanks!
**EDIT... | As far as enforcing this in a *constraint*, my solution would be to create a dependent table, so referenced rows cannot be deleted.
```
CREATE TABLE NoKillI (
id INT NOT NULL, FOREIGN KEY (id) REFERENCES Accounts(id) ON DELETE RESTRICT
);
INSERT INTO NoKillI (id) VALUES (0);
INSERT INTO NoKillI (id) VALUES (1);
INSE... | You do this by writing a database trigger that fires on DELETE for the table in question. All it needs to do is throw an exception if the ID is invalid. | Is there a way to avoid row deletion on an specific table using constrains or triggers? | [
"",
"sql",
"sql-server",
"database",
"constraints",
""
] |
On Stackers' recommendation, I have been reading Crockford's excellent *Javascript: The Good Parts*.
It's a great book, but since so much of it is devoted to describing the best way to use Javascript's basic functionality, I'm not sure how I can put his advice into practice without duplicating the efforts of many othe... | [Prototype](http://prototypejs.org/) has many great features, including a [Class helper](http://prototypejs.org/api/class) that handles the details of JS "inheritance" via the object prototype.
Edit: damn, I keep forgetting that jQuery (my own library of choice) has [jQuery.extend](http://docs.jquery.com/Utilities/jQu... | Doesn't he work for Yahoo? You could always use the [Yahoo User Interface libraries](http://developer.yahoo.com/yui/).
Personally, I'm partial to [JQuery](http://jquery.com/), as it strikes me as more concise, but you know: horses for courses. | Best way to use Javascript's "good parts" | [
"",
"javascript",
"abstraction",
""
] |
If I type the command:
```
mvn dependency:list
```
The [docs](http://maven.apache.org/plugins/maven-dependency-plugin/) suggest that I'll get a list of my project's dependencies. Instead though, I get this:
```
[INFO] Searching repository for plugin with prefix: 'dependency'.
[INFO] ---------------------------------... | To answer my own question, thanks to some comments that were made on it, the settings.xml file had been customized and did not list the central maven repository.
Oops. | Have you tried `mvn -cpu dependency:list` (or: `mvn --check-plugin-updates dependency:list`)? Probably, you have older version of dependency plugin which does not have goal `list`
If this does not help, try upgrading Maven. Since 2.0.9 default versions are provided by the Super POM for most important plugins (dependen... | Why can't maven find a plugin? | [
"",
"java",
"maven-2",
"dependencies",
"maven-plugin",
""
] |
I have this html...
```
<select id="View" name="View">
<option value="1">With issue covers</option>
<option value="0">No issue covers</option>
</select>
```
It won't let me insert code like this...
```
<select id="View" name="View">
<option value="1" <% ..logic code..%> >With issue covers</option>
<opti... | I would agree with Marc on using helpers but if you must avoid them then you could try something like the following:
```
<select id="View" name="View">
<option value="1" <% if (something) { %> selected <% } %> >With issue covers</option>
<option value="0" <% if (!something) { %> selected <% } %> >No issue covers... | The "best" approach is probably to *use* the helpers:
```
var selectList = new SelectList(data, "ValueProp", "TextProp", data[1].ValueProp);
... Html.DropDownList("foo", selectList)
```
Where "data" could be an array of anonymous types, such as:
```
var data = new[] {
new {Key=1, Text="With issue covers"},
new {... | Whats the best way to set a dropdown to selected in ASP.NET MVC markup? | [
"",
"c#",
"html",
"asp.net-mvc",
""
] |
How to (programmatically, without xml config) configure multiple loggers with Log4Net?
I need them to write to different files. | [This thread at the log4net Dashboard details an approach](http://mail-archives.apache.org/mod_mbox/logging-log4net-user/200602.mbox/%3CDDEB64C8619AC64DBC074208B046611C769745@kronos.neoworks.co.uk%3E).
To summarize a little, hopefully without ripping off too much code:
```
using log4net;
using log4net.Appender;
using... | ```
using System;
using Com.Foo;
using System.Collections.Generic;
using System.Text;
using log4net.Config;
using log4net;
using log4net.Appender;
using log4net.Layout;
using log4net.Repository.Hierarchy;
public class MyApp
{
public static void SetLevel(string loggerName, string levelName)
{
ILog lo... | Log4Net: Programmatically specify multiple loggers (with multiple file appenders) | [
"",
"c#",
"log4net",
""
] |
I am using tinyMCE and, rather annoyingly, it replaces all of my apostrophes with their HTML numeric equivalent. Now most of the time this isn't a problem but for some reason I am having a problem storing the apostrophe replacement. So i have to search through the string and replace them all. Any help would be much app... | did you try:
```
$string = str_replace("'", "<replacement>", $string);
``` | Is it just apostrophes that you want decoded from HTML entities, or everything?
```
print html_entity_decode("Hello, that's an apostophe.", ENT_QUOTE);
```
will print
```
Hello, that's an apostrophe.
``` | Searching through a string trying to find ' in PHP | [
"",
"php",
""
] |
I'm currently working on a pet project and need to do C++ development on Windows, Mac, Linux, and Solaris, and I've narrowed it down to Netbeans and Eclipse, so I was wonderig which is more solid as a C++ editor. I just need solid editing, good autocompletion for templated code ad external libraries, and project file m... | I haven't used NetBeans, but Eclipse CDT (C Developer Tools, which includes C++), especially with the latest version, is really quite excellent:
* Syntax checking and spell checking
* Syntax highlighting that distinguishes between library calls and your function calls and between local and member variables and is even... | I'm using Netbeans from time to time on Solaris and the latest (6.5) version is pretty neat. It has all the features that you need, perhaps autocompletion could work better, but I have a really bad code base so it might be the result of it. Keep in mind that you need strong machine for that, if it's your PC it's ok but... | Netbeans or Eclipse for C++? | [
"",
"c++",
"eclipse",
"netbeans",
""
] |
I have a table containing the runtimes for generators on different sites, and I want to select the most recent entry for each site. Each generator is run once or twice a week.
I have a query that will do this, but I wonder if it's the best option. I can't help thinking that using WHERE x IN (SELECT ...) is lazy and no... | I would use joins as they perform much better then "IN" clause:
```
select gl.id, gl.site_id, gl.start, gl."end", gl.duration
from
generator_logs gl
inner join (
select max(start) as start, site_id
from generator_logs
group by site_id
) gl2
on gl.site_id = gl2.site_id
... | Should your query not be correlated? i.e.:
```
SELECT id, site_id, start, "end", duration
FROM generator_logs g1
WHERE start = (SELECT MAX(g2.start) AS start
FROM generator_logs g2
WHERE g2.site_id = g1.site_id)
ORDER BY start DESC
```
Otherwise you will potentially pick up non-lates... | Are inline queries a bad idea? | [
"",
"sql",
"postgresql",
""
] |
I have to delete some rows from a data table. I've heard that it is not ok to change a collection while iterating through it. So instead of a for loop in which I check if a row meets the demands for deletion and then mark it as deleted, I should first iterate through the data table and add all of the rows in a list, th... | You can remove elements from a collection if you use a simple `for` loop.
Take a look at this example:
```
var l = new List<int>();
l.Add(0);
l.Add(1);
l.Add(2);
l.Add(3);
l.Add(4);
l.Add(5);
l.Add(6);
for (int i = 0; i < l.Count; i++)
... | Iterating Backwards through the List sounds like a better approach, because if you remove an element and other elements "fall into the gap", that does not matter because you have already looked at those. Also, you do not have to worry about your counter variable becoming larger than the .Count.
```
List<int> t... | How to modify or delete items from an enumerable collection while iterating through it in C# | [
"",
"c#",
"collections",
"iteration",
""
] |
What is the fastest way to find out whether two `ICollection<T>` collections contain precisely the same entries? Brute force is clear, I was wondering if there is a more elegant method.
We are using C# 2.0, so no extension methods if possible, please!
Edit: the answer would be interesting both for ordered and unorder... | use C5
<http://www.itu.dk/research/c5/>
[ContainsAll](http://www.itu.dk/research/c5/Release1.1/c5doc/types/C5.ICollection_1.htm#T:C5.ICollection%601|M:C5.ICollection%601.ContainsAll%60%601(System.Collections.Generic.IEnumerable%7B%60%600%7D))
> " Check if all items in a
> supplied collection is in this bag
> (coun... | First compare the .**Count** of the collections if they have the same count the do a brute force compare on all elements. Worst case scenarios is O(n). This is in the case the order of elements needs to be the same.
The second case where the order is not the same, you need to use a dictionary to store the count of ele... | Fastest way to find out whether two ICollection<T> collections contain the same objects | [
"",
"c#",
"performance",
"collections",
"c#-2.0",
"equality",
""
] |
How much do using smart pointers, particularly boost::shared\_ptr cost more compared to bare pointers in terms of time and memory? Is using bare pointers better for performance intensive parts of gaming/embedded systems? Would you recommend using bare pointers or smart pointers for performance intensive components? | Dereferencing smart pointers is typically trivial, certainly for boost in release mode. All boost checks are at compile-time. (Smart pointers could in theory do smart stuff across threads). This still leaves a lot of other operations. Nicola mentioned construction, copying and destruction. This is not the complete set,... | Boost provide different smart pointers. Generally both the memory occupation, which varies in accordance to the kind of smart pointer, and the performance should not be an issue. For a performance comparison you can check this <http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/smarttests.htm>.
As you can see only co... | C++ Smart Pointer performance | [
"",
"c++",
"boost",
"smart-pointers",
""
] |
I often use this recursive 'visitor' in F#
```
let rec visitor dir filter=
seq { yield! Directory.GetFiles(dir, filter)
for subdir in Directory.GetDirectories(dir) do yield! visitor subdir filter}
```
Recently I've started working on implementing some F# functionality in C#, and I'm trying to reproduce... | `yield!` does a 'flatten' operation, so it integrates the sequence you passed it into the outer sequence, implicitly performing a `foreach` over each element of the sequence and `yield` on each one. | There is no simple way to do this.
You could workaround this by defining a C# type that can store either one value or a sequence of values - using the F# notation it would be:
```
type EnumerationResult<'a> =
| One of 'a
| Seq of seq<'a>
```
(translate this to C# in any way you like :-))
Now, you could write so... | Writing the F# recursive folder visitor in C# - seq vs IEnumerable | [
"",
"c#",
"f#",
""
] |
I want to check that two passwords are the same using Dojo.
Here is the HTML I have:
> `<form id="form" action="." dojoType="dijit.form.Form" /`>
>
> `<p`>Password: `<input type="password"
> name="password1"
> id="password1"
> dojoType="dijit.form.ValidationTextBox"
> required="true"
> invalidMessage="Pleas... | This will get you a lot closer
* setting intermediateChanges=false keeps the validator running at every keystroke.
* the validation dijit's constraint object is passed to its validator. Use this to pass in the other password entry
* dijit.form.Form automatically calls isValid() on all its child dijits when it's submit... | Even easier, use the pre-written Dojox widget, **dojox.form.PasswordValidator**.
<http://docs.dojocampus.org/dojox/form/PasswordValidator>
It does everything you want straight out of the box! | Password checking in dojo | [
"",
"javascript",
"security",
"dojo",
""
] |
In Firefox when you add an `onclick` event handler to a method an event object is automatically passed to that method. This allows, among other things, the ability to detect which specific element was clicked. For example
```
document.body.onclick = handleClick;
function handleClick(e)
{
// this works if FireFox
... | Here is how would I do it in case I cannot use jQuery
```
document.body.onclick = handleClick;
function handleClick(e)
{
//If "e" is undefined use the global "event" variable
e = e || event;
var target = e.srcElement || e.target;
alert(target.className);
}
```
And here is a jQuery solution
```
$(do... | That is not the approved notation to add events to dom nodes.
```
if (el.addEventListener){
el.addEventListener('click', modifyText, false);
} else if (el.attachEvent){
el.attachEvent('onclick', modifyText);
}
```
Is the recommended Notation for binding click events cross-browser friendly.
See:
* <http://www.q... | Firefox style onclick arguments in IE | [
"",
"javascript",
"dom-events",
""
] |
Given the below XML snippet I need to get a list of name/value pairs for each child under DataElements. XPath or an XML parser cannot be used for reasons beyond my control so I am using regex.
```
<?xml version="1.0"?>
<StandardDataObject xmlns="myns">
<DataElements>
<EmpStatus>2.0</EmpStatus>
<Expenditure>9... | This should work in Java, if you can assume that between the DataElements tags, everything has the form value. I.e. no attributes, and no nested elements.
```
Pattern regex = Pattern.compile("<DataElements>(.*?)</DataElements>", Pattern.DOTALL);
Matcher matcher = regex.matcher(subjectString);
Pattern regex2 = Pattern.... | XML is not a regular language. You **cannot** parse it using a regular expression. An expression you think will work will break when you get nested tags, then when you fix that it will break on XML comments, then CDATA sections, then processor directives, then namespaces, ... It cannot work, use an XML parser. | Parsing XML with REGEX in Java | [
"",
"java",
"xml",
"regex",
""
] |
My Java application is saving stuff in 'user.home' but on windows this does not seem to be the correct path to save application information (as a friend told me). An other option is using the preferences api but it's not possible to set up the hsqldb location using the preferences api. Also, I want all files to be avai... | On my WinXP Pro SP3 system, user.home points to `C:\Documents and settings\<username>`
Lot of applications just store their data there (instead of this path + Application data, but some others go down to there), creating a directory in Unix style, ie. dot + application name (examples: .antexplorer, .sqlworkbench, .squi... | It's unusual for a window app to save data in user.home but not "wrong". Windows applications love to spread their data all over the place (a bit in the registry, a bit in the application's install directory, a bit in the Windows directory, a bit in System32, a bit here and a bit there). In the end, this makes it impos... | Saving user settings/database/cache... in Java (On every OS) | [
"",
"java",
"operating-system",
"settings",
"configuration-files",
""
] |
I am using a custom validator to compare value in two text box. This is comparing the values fine. But it says "025" and "25" are different.. can this do a float comparision.
the custom validator i am using is
```
<asp:CompareValidator id="compval" runat="server" ControlToValidate="txtBox1"
ErrorM... | Use System.Double.Parse(value) to convert both to a floating point number, and compare those numbers.
You can also use TryParse if you don't want to handle exceptions if the value is not a valid floating point number.
See also:
* <http://msdn.microsoft.com/en-us/library/system.double.parse.aspx>
* <http://msdn.micro... | The only thing I can think of without seeing your validation code is that 025 is being interpreted as an octal number (in C, putting a zero before an integer means it's in base 8). Then 025 would be 21 in base-10 and your two numbers wouldn't be the same.
I'm not sure how you'd come up with that, though. I tested out ... | custom validation to compare the float value of two text box | [
"",
"c#",
".net",
"asp.net",
"vb.net",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.