qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
26,098 | <p>I'm writing a C/C++ DLL and want to export certain functions which I've done before using a .def file like this</p>
<pre><code>LIBRARY "MyLib"
EXPORTS
Foo
Bar
</code></pre>
<p>with the code defined as this, for example:</p>
<pre><code>int Foo(int a);
void Bar(int foo);
</code></pre>
<p>However, what if I want to declare an overloaded method of Foo() like:</p>
<pre><code>int Foo(int a, int b);
</code></pre>
<p>As the def file only has the function name and not the full prototype I can't see how it would handle the overloaded functions. Do you just use the one entry and then specify which overloaded version you want when passing in the properly prototyped function pointer to LoadLibrary() ?</p>
<p>Edit: To be clear, this is on Windows using Visual Studio 2005</p>
<p>Edit: Marked the non-def (__declspec) method as the answer...I know this doesn't actually solve the problem using def files as I wanted, but it seems that there is likely no (official) solution using def files. Will leave the question open, however, in case someone knows something we don't have overloaded functions and def files.</p>
| [
{
"answer_id": 26121,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 4,
"selected": true,
"text": "<p>In the code itself, mark the functions you want to export using __declspec(dllexport). For example:</p>\n\n<pre><code... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] | I'm writing a C/C++ DLL and want to export certain functions which I've done before using a .def file like this
```
LIBRARY "MyLib"
EXPORTS
Foo
Bar
```
with the code defined as this, for example:
```
int Foo(int a);
void Bar(int foo);
```
However, what if I want to declare an overloaded method of Foo() like:
```
int Foo(int a, int b);
```
As the def file only has the function name and not the full prototype I can't see how it would handle the overloaded functions. Do you just use the one entry and then specify which overloaded version you want when passing in the properly prototyped function pointer to LoadLibrary() ?
Edit: To be clear, this is on Windows using Visual Studio 2005
Edit: Marked the non-def (\_\_declspec) method as the answer...I know this doesn't actually solve the problem using def files as I wanted, but it seems that there is likely no (official) solution using def files. Will leave the question open, however, in case someone knows something we don't have overloaded functions and def files. | In the code itself, mark the functions you want to export using \_\_declspec(dllexport). For example:
```
#define DllExport __declspec(dllexport)
int DllExport Foo( int a ) {
// implementation
}
int DllExport Foo( int a, int b ) {
// implementation
}
```
If you do this, you do not need to list the functions in the .def file.
Alternatively, you may be able to use a default parameter value, like:
```
int Foo( int a, int b = -1 )
```
This assumes that there exists a value for b that you can use to indicate that it is unused. If -1 is a legal value for b, or if there isn't or shouldn't be a default, this won't work.
Edit (Adam Haile): Corrected to use \_\_declspec as \_\_dllspec was not correct so I could mark this as the official answer...it was close enough.
Edit (Graeme): Oops - thanks for correcting my typo! |
26,123 | <p>I want to use Powershell to write some utilities, leveraging our own .NET components to handle the actual work. This is in place of writing a small console app to tie the calls together. My question is where I would find a good source of documentation or tutorial material to help me fast track this?</p>
| [
{
"answer_id": 26135,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 5,
"selected": true,
"text": "<p>If you want to load an assembly into your PowerShell session, you can use reflection and load the assembly.</p>\n\n... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1535/"
] | I want to use Powershell to write some utilities, leveraging our own .NET components to handle the actual work. This is in place of writing a small console app to tie the calls together. My question is where I would find a good source of documentation or tutorial material to help me fast track this? | If you want to load an assembly into your PowerShell session, you can use reflection and load the assembly.
```
[void][System.Reflection.Assembly]::LoadFrom(PathToYourAssembly)
```
After you load your assembly, you can call static methods and create new instances of a class.
A good tutorial can be found [here](http://stevenmurawski.com/powershell/2009/03/exploring-the-net-framework-with-powershell-constructors-part-3/).
Both books mentioned by EBGreen are excellent. The PowerShell Cookbook is very task oriented and PowerShell in Action is a great description of the language, its focus and useability. PowerShell in Action is one of my favorite books. :) |
26,137 | <p>I have a couple of questions regarding VBScript and ASP Classic:</p>
<ol>
<li><p>What is the preferred way to access an MS SQL Server database in VBScript/ASP?</p></li>
<li><p>What are best practices in regards to separating model from view from controller?</p></li>
<li><p>Any other things I should know about either VBScript or ASP?</p></li>
</ol>
<p>If you haven't noticed, I'm new at VBScript coding. I realize numbers 2 & 3 are kind of giant "black hole" questions that are overly general, so don't think that I'm expecting to learn everything there is to know about those two questions from here.</p>
| [
{
"answer_id": 26181,
"author": "Michael Pryor",
"author_id": 245,
"author_profile": "https://Stackoverflow.com/users/245",
"pm_score": 5,
"selected": true,
"text": "<p>ADO is an excellent way to access a database in VBScript/Classic ASP.</p>\n\n<pre><code>Dim db: Set db = Server.CreateO... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] | I have a couple of questions regarding VBScript and ASP Classic:
1. What is the preferred way to access an MS SQL Server database in VBScript/ASP?
2. What are best practices in regards to separating model from view from controller?
3. Any other things I should know about either VBScript or ASP?
If you haven't noticed, I'm new at VBScript coding. I realize numbers 2 & 3 are kind of giant "black hole" questions that are overly general, so don't think that I'm expecting to learn everything there is to know about those two questions from here. | ADO is an excellent way to access a database in VBScript/Classic ASP.
```
Dim db: Set db = Server.CreateObject("ADODB.Connection")
db.Open "yourconnectionstring -> see connectionstrings.com"
Dim rs: Set rs = db.Execute("SELECT firstName from Employees")
While Not rs.EOF
Response.Write rs("firstName")
rs.MoveNext
Wend
rs.Close
```
More info here: <http://www.technowledgebase.com/2007/06/12/vbscript-how-to-create-an-ado-connection-and-run-a-query/>
One caveat is that if you are returning a MEMO field in a recordset, be sure you only select ONE MEMO field at a time, and make sure it is the LAST column in your query. Otherwise you will run into problems.
(Reference: <http://lists.evolt.org/archive/Week-of-Mon-20040329/157305.html> ) |
26,145 | <p>I'm making a simple extra java app launcher for Eclipse 3.2 (JBuilder 2007-8) for internal use.</p>
<p>So I looked up all the documentations related, including this one <a href="http://www.eclipse.org/articles/Article-Launch-Framework/launch.html" rel="nofollow noreferrer" title="The Launching Framework">The Launching Framework from eclipse.org</a> and have managed to make everything else working with the exception of the launch shortcut. </p>
<p><img src="https://i.stack.imgur.com/8I8zw.jpg" alt="alt text"></p>
<p>This is the part of my plugin.xml. </p>
<pre><code> <extension
point="org.eclipse.debug.ui.launchShortcuts">
<shortcut
category="mycompany.javalaunchext.launchConfig"
class="mycompany.javalaunchext.LaunchShortcut"
description="launchshortcutsdescription"
icon="icons/k2mountain.png"
id="mycompany.javalaunchext.launchShortcut"
label="Java Application Ext."
modes="run, debug">
<perspective
id="org.eclipse.jdt.ui.JavaPerspective">
</perspective>
<perspective
id="org.eclipse.jdt.ui.JavaHierarchyPerspective">
</perspective>
<perspective
id="org.eclipse.jdt.ui.JavaBrowsingPerspective">
</perspective>
<perspective
id="org.eclipse.debug.ui.DebugPerspective">
</perspective>
</shortcut>
</code></pre>
<p></p>
<p>The configuration name in the category section is correct and the class in the class section, i believe, is correctly implemented. (basically copied from org.eclipse.jdt.debug.ui.launchConfigurations.JavaApplicationLaunchShortcut)</p>
<hr>
<p>I'm really not sure if I'm supposed to write a follow-up here but let me clarify my question more.
I've extended org.eclipse.jdt.debug.ui.launchConfigurations.JavaLaunchShortcut.
Plus, I've added my own logger to constructors and methods, but the class seems like it's never even instantiating.</p>
| [
{
"answer_id": 26341,
"author": "zvikico",
"author_id": 2823,
"author_profile": "https://Stackoverflow.com/users/2823",
"pm_score": 0,
"selected": false,
"text": "<p>You class should implement ILaunchShortcut.\nCheck out the <a href=\"http://help.eclipse.org/help32/nftopic/org.eclipse.pl... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2710/"
] | I'm making a simple extra java app launcher for Eclipse 3.2 (JBuilder 2007-8) for internal use.
So I looked up all the documentations related, including this one [The Launching Framework from eclipse.org](http://www.eclipse.org/articles/Article-Launch-Framework/launch.html "The Launching Framework") and have managed to make everything else working with the exception of the launch shortcut.

This is the part of my plugin.xml.
```
<extension
point="org.eclipse.debug.ui.launchShortcuts">
<shortcut
category="mycompany.javalaunchext.launchConfig"
class="mycompany.javalaunchext.LaunchShortcut"
description="launchshortcutsdescription"
icon="icons/k2mountain.png"
id="mycompany.javalaunchext.launchShortcut"
label="Java Application Ext."
modes="run, debug">
<perspective
id="org.eclipse.jdt.ui.JavaPerspective">
</perspective>
<perspective
id="org.eclipse.jdt.ui.JavaHierarchyPerspective">
</perspective>
<perspective
id="org.eclipse.jdt.ui.JavaBrowsingPerspective">
</perspective>
<perspective
id="org.eclipse.debug.ui.DebugPerspective">
</perspective>
</shortcut>
```
The configuration name in the category section is correct and the class in the class section, i believe, is correctly implemented. (basically copied from org.eclipse.jdt.debug.ui.launchConfigurations.JavaApplicationLaunchShortcut)
---
I'm really not sure if I'm supposed to write a follow-up here but let me clarify my question more.
I've extended org.eclipse.jdt.debug.ui.launchConfigurations.JavaLaunchShortcut.
Plus, I've added my own logger to constructors and methods, but the class seems like it's never even instantiating. | I had to add `contextualLaunch` under `org.eclipse.debug.ui.launchShortcuts`.
The old way seems like it's deprecated a long ago.
For other people who are working on the same subject,
you might want to extend `org.eclipse.ui.commands` and bindings, too.
I cannot choose this answer but this is the answer that I (the questioner) was looking for. |
26,151 | <p>C++ 0x has template aliases (sometimes referred to as template typedefs). See <a href="http://en.wikipedia.org/wiki/C%2B%2B0x#Alias_templates" rel="noreferrer">here</a>. Current spec of C++ does not. </p>
<p>What do you like to use as work around ? Container objects or Macros ?
Do you feel its worth it ?</p>
| [
{
"answer_id": 26162,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 8,
"selected": true,
"text": "<blockquote>\n <p>What do you like to use as work around ? Container objects or Macros ? Do you feel its worth it ?</p... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2759/"
] | C++ 0x has template aliases (sometimes referred to as template typedefs). See [here](http://en.wikipedia.org/wiki/C%2B%2B0x#Alias_templates). Current spec of C++ does not.
What do you like to use as work around ? Container objects or Macros ?
Do you feel its worth it ? | >
> What do you like to use as work around ? Container objects or Macros ? Do you feel its worth it ?
>
>
>
The canonical way is to use a metafunction like thus:
```
template <typename T>
struct my_string_map {
typedef std::map<std::string, T> type;
};
// Invoke:
my_string_map<int>::type my_str_int_map;
```
This is also used in the STL (`allocator::rebind<U>`) and in many libraries including Boost. We use it extensively in a [bioinformatical library](http://www.seqan.de/dddoc/html/index.html).
It's bloated, but it's the best alternative 99% of the time. Using macros here is not worth the many downsides.
(EDIT: I've amended the code to reflect Boost/STL conventions as pointed out by Daniel in his comment.) |
26,196 | <p>I am looking for a very fast way to filter down a collection in C#. I am currently using generic <code>List<object></code> collections, but am open to using other structures if they perform better.</p>
<p>Currently, I am just creating a new <code>List<object></code> and looping thru the original list. If the filtering criteria matches, I put a copy into the new list.</p>
<p>Is there a better way to do this? Is there a way to filter in place so there is no temporary list required?</p>
| [
{
"answer_id": 26203,
"author": "Jorge Córdoba",
"author_id": 2695,
"author_profile": "https://Stackoverflow.com/users/2695",
"pm_score": 9,
"selected": true,
"text": "<p>If you're using C# 3.0 you can use linq, which is way better and way more elegant:</p>\n<pre class=\"lang-c# prettypr... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2470/"
] | I am looking for a very fast way to filter down a collection in C#. I am currently using generic `List<object>` collections, but am open to using other structures if they perform better.
Currently, I am just creating a new `List<object>` and looping thru the original list. If the filtering criteria matches, I put a copy into the new list.
Is there a better way to do this? Is there a way to filter in place so there is no temporary list required? | If you're using C# 3.0 you can use linq, which is way better and way more elegant:
```c#
List<int> myList = GetListOfIntsFromSomewhere();
// This will filter ints that are not > 7 out of the list; Where returns an
// IEnumerable<T>, so call ToList to convert back to a List<T>.
List<int> filteredList = myList.Where(x => x > 7).ToList();
```
If you can't find the `.Where`, that means you need to import `using System.Linq;` at the top of your file. |
26,233 | <p>Given a URL, what would be the most efficient code to download the contents of that web page? I am only considering the HTML, not associated images, JS and CSS.</p>
| [
{
"answer_id": 26237,
"author": "Chris",
"author_id": 2134,
"author_profile": "https://Stackoverflow.com/users/2134",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.net.webclient%28VS.80%29.aspx\" rel=\"noreferrer\">System.Net.WebCl... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141/"
] | Given a URL, what would be the most efficient code to download the contents of that web page? I am only considering the HTML, not associated images, JS and CSS. | ```
public static void DownloadFile(string remoteFilename, string localFilename)
{
WebClient client = new WebClient();
client.DownloadFile(remoteFilename, localFilename);
}
``` |
26,305 | <p>I want to be able to play sound files in my program. Where should I look?</p>
| [
{
"answer_id": 26311,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 4,
"selected": false,
"text": "<p>A bad example:</p>\n\n<pre><code>import sun.audio.*; //import the sun.audio package\nimport java.io.*;\n\n//** add t... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
] | I want to be able to play sound files in my program. Where should I look? | I wrote the following code that works fine. But I think it only works with `.wav` format.
```
public static synchronized void playSound(final String url) {
new Thread(new Runnable() {
// The wrapper thread is unnecessary, unless it blocks on the
// Clip finishing; see comments.
public void run() {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(
Main.class.getResourceAsStream("/path/to/sounds/" + url));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}).start();
}
``` |
26,323 | <p>C#: What is a good Regex to parse hyperlinks and their description?</p>
<p>Please consider case insensitivity, white-space and use of single quotes (instead of double quotes) around the HREF tag.</p>
<p>Please also consider obtaining hyperlinks which have other tags within the <code><a></code> tags such as <code><b></code> and <code><i></code>.
</p>
| [
{
"answer_id": 26328,
"author": "Teifion",
"author_id": 1384652,
"author_profile": "https://Stackoverflow.com/users/1384652",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://regexlib.com/RETester.aspx?regexp_id=968\" rel=\"nofollow noreferrer\">I found this</a> but apparen... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141/"
] | C#: What is a good Regex to parse hyperlinks and their description?
Please consider case insensitivity, white-space and use of single quotes (instead of double quotes) around the HREF tag.
Please also consider obtaining hyperlinks which have other tags within the `<a>` tags such as `<b>` and `<i>`.
| As long as there are no nested tags (and no line breaks), the following variant works well:
```
<a\s+href=(?:"([^"]+)"|'([^']+)').*?>(.*?)</a>
```
As soon as nested tags come into play, regular expressions are unfit for parsing. However, you can still use them by applying more advanced features of modern interpreters (depending on your regex machine). E.g. .NET regular expressions use a stack; I found this:
```
(?:<a.*?href=[""'](?<url>.*?)[""'].*?>)(?<name>(?><a[^<]*>(?<DEPTH>)|</a>(?<-DEPTH>)|.)+)(?(DEPTH)(?!))(?:</a>)
```
Source: <http://weblogs.asp.net/scottcate/archive/2004/12/13/281955.aspx> |
26,354 | <p>Does anyone know how to print a barcode to the Intermec PB20 bluetooth printer from a Windows Compact Framework application? We are currently using the Intermec LinePrinter API but have been unable to find a way to print a barcode.
</p>
| [
{
"answer_id": 26356,
"author": "Martin Marconcini",
"author_id": 2684,
"author_profile": "https://Stackoverflow.com/users/2684",
"pm_score": 0,
"selected": false,
"text": "<p>Last time I had to print Barcode (despite the printer or framework) I resorted to use a True Type font with the ... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/620435/"
] | Does anyone know how to print a barcode to the Intermec PB20 bluetooth printer from a Windows Compact Framework application? We are currently using the Intermec LinePrinter API but have been unable to find a way to print a barcode.
| Thank you all for your thoughts. Printing directly to the serial port is likely the most flexible method. In this case we didn't want to replicate all of the work that was already built into the Intermec dll for handling the port, printer errors, etc. We were able to get this working by sending the printer the appropriate codes to switch it into a different mode and then pass direct printer commands that way.
Here was our solution in case anyone else happens to encounter a similar issue working with Intermec Printers. The following code is a test case that doesn't catch printer errors and retry, etc. (See Intermec code examples.)
```
Intermec.Print.LinePrinter lp;
int escapeCharacter = int.Parse("1b", NumberStyles.HexNumber);
char[] toEzPrintMode = new char[] { Convert.ToChar(num2), 'E', 'Z' };
lp = new Intermec.Print.LinePrinter("Printer_Config.XML", "PrinterPB20_40COL");
lp.Open();
lp.Write(charArray2); //switch to ez print mode
string testBarcode = "{PRINT:@75,10:PD417,YDIM 6,XDIM 2,COLUMNS 2, SECURITY 3|ABCDEFGHIJKL|}";
lp.Write(testBarcode);
lp.Write("{LP}"); //switch from ez print mode back to line printer mode
lp.NewLine();
lp.Write("Test"); //verify line printer mode is working
```
There is a technical document on Intermec's support site called the "Technical Manual" that describes the code for directly controlling the printer. The section about Easy Print describes how to print a variety of barcodes. |
26,362 | <p>Has anyone managed to use <code>ItemizedOverlays</code> in Android Beta 0.9? I can't get it to work, but I'm not sure if I've done something wrong or if this functionality isn't yet available. </p>
<p>I've been trying to use the <code>ItemizedOverlay</code> and <code>OverlayItem</code> classes. Their intended purpose is to simulate map markers (as seen in Google Maps Mashups) but I've had problems getting them to appear on the map.</p>
<p>I can add my own custom overlays using a similar technique, it's just the <code>ItemizedOverlays</code> that don't work.</p>
<p>Once I've implemented my own <code>ItemizedOverlay</code> (and overridden <code>createItem</code>), creating a new instance of my class seems to work (I can extract <code>OverlayItems</code> from it) but adding it to a map's <code>Overlay</code> list doesn't make it appear as it should.</p>
<p>This is the code I use to add the <code>ItemizedOverlay</code> class as an <code>Overlay</code> on to my <code>MapView</code>.</p>
<pre><code>// Add the ItemizedOverlay to the Map
private void addItemizedOverlay() {
Resources r = getResources();
MapView mapView = (MapView)findViewById(R.id.mymapview);
List<Overlay> overlays = mapView.getOverlays();
MyItemizedOverlay markers = new MyItemizedOverlay(r.getDrawable(R.drawable.icon));
overlays.add(markers);
OverlayItem oi = markers.getItem(0);
markers.setFocus(oi);
mapView.postInvalidate();
}
</code></pre>
<p>Where <code>MyItemizedOverlay</code> is defined as:</p>
<pre><code>public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
public MyItemizedOverlay(Drawable defaultMarker) {
super(defaultMarker);
populate();
}
@Override
protected OverlayItem createItem(int index) {
Double lat = (index+37.422006)*1E6;
Double lng = -122.084095*1E6;
GeoPoint point = new GeoPoint(lat.intValue(), lng.intValue());
OverlayItem oi = new OverlayItem(point, "Marker", "Marker Text");
return oi;
}
@Override
public int size() {
return 5;
}
}
</code></pre>
| [
{
"answer_id": 46766,
"author": "eon",
"author_id": 2000,
"author_profile": "https://Stackoverflow.com/users/2000",
"pm_score": 7,
"selected": true,
"text": "<p>For the sake of completeness I'll repeat the discussion on Reto's post over at the <a href=\"http://groups.google.com/group/and... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/822/"
] | Has anyone managed to use `ItemizedOverlays` in Android Beta 0.9? I can't get it to work, but I'm not sure if I've done something wrong or if this functionality isn't yet available.
I've been trying to use the `ItemizedOverlay` and `OverlayItem` classes. Their intended purpose is to simulate map markers (as seen in Google Maps Mashups) but I've had problems getting them to appear on the map.
I can add my own custom overlays using a similar technique, it's just the `ItemizedOverlays` that don't work.
Once I've implemented my own `ItemizedOverlay` (and overridden `createItem`), creating a new instance of my class seems to work (I can extract `OverlayItems` from it) but adding it to a map's `Overlay` list doesn't make it appear as it should.
This is the code I use to add the `ItemizedOverlay` class as an `Overlay` on to my `MapView`.
```
// Add the ItemizedOverlay to the Map
private void addItemizedOverlay() {
Resources r = getResources();
MapView mapView = (MapView)findViewById(R.id.mymapview);
List<Overlay> overlays = mapView.getOverlays();
MyItemizedOverlay markers = new MyItemizedOverlay(r.getDrawable(R.drawable.icon));
overlays.add(markers);
OverlayItem oi = markers.getItem(0);
markers.setFocus(oi);
mapView.postInvalidate();
}
```
Where `MyItemizedOverlay` is defined as:
```
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
public MyItemizedOverlay(Drawable defaultMarker) {
super(defaultMarker);
populate();
}
@Override
protected OverlayItem createItem(int index) {
Double lat = (index+37.422006)*1E6;
Double lng = -122.084095*1E6;
GeoPoint point = new GeoPoint(lat.intValue(), lng.intValue());
OverlayItem oi = new OverlayItem(point, "Marker", "Marker Text");
return oi;
}
@Override
public int size() {
return 5;
}
}
``` | For the sake of completeness I'll repeat the discussion on Reto's post over at the [Android Groups here](http://groups.google.com/group/android-developers/browse_thread/thread/36fe0648dabfe745#).
It seems that if you set the bounds on your drawable it does the trick:
```
Drawable defaultMarker = r.getDrawable(R.drawable.icon);
// You HAVE to specify the bounds! It seems like the markers are drawn
// through Drawable.draw(Canvas) and therefore must have its bounds set
// before drawing.
defaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(),
defaultMarker.getIntrinsicHeight());
MyItemizedOverlay markers = new MyItemizedOverlay(defaultMarker);
overlays.add(markers);
```
By the way, the above is shamelessly ripped from [the demo at MarcelP.info](http://www.marcelp.info/2008/09/01/android-itemizedoverlay-demo/). Also, here is a [good howto](http://androidguys.com/?p=1413). |
26,366 | <p>For the past 10 years or so there have been a smattering of articles and papers referencing Christopher Alexander's newer work "The Nature of Order" and how it can be applied to software.</p>
<p>Unfortunately, the only works I can find are from James Coplien and Richard Gabriel; there is nothing beyond that, at least from my attempts to find such things through google.</p>
<p>Is this kind of discussion happening anywhere?</p>
<p>MSN</p>
<hr>
<p>@Georgia</p>
<p>My question isn't about design patterns or pattern languages; it's about trying to see if more of Christopher Alexander's work can be applied to software (which it probably can, since it has even less physical constraints than architecture and building).</p>
<p>Design patterns and pattern languages seem to have embraced the structure of Alexander's design patterns, but not many capture the essence. The essence being something beyond solving a problem in a particular context.</p>
<p>It's difficult to explain without using some of Alexander's later works as a reference point.</p>
<p>Edit: No, I take that back.</p>
<p>For example, there's an architectural design pattern that is called Alcoves. The pattern has a context that isn't just rooted in the circumstances of the situation but also rooted in fundamentals about the purpose of buildings: that they are structures to be lived in and must promote living in them. In the case of the Alcove pattern, the context is that you want an area that allows for multiple people to be in the same area doing different things, because it is important for family members to be physically together as well as to be able to do things that tend to distract other family members.</p>
<p>Most software design patterns describe a problem in a context, but they make no deeper statement about why the problem is important, or why the problem is something that is fundamental to software. It makes it very easy to apply design patterns inappropriately or blithely, which is the exact opposite of the intent of design patterns to began with.</p>
<p>MSN
</p>
| [
{
"answer_id": 46766,
"author": "eon",
"author_id": 2000,
"author_profile": "https://Stackoverflow.com/users/2000",
"pm_score": 7,
"selected": true,
"text": "<p>For the sake of completeness I'll repeat the discussion on Reto's post over at the <a href=\"http://groups.google.com/group/and... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1799/"
] | For the past 10 years or so there have been a smattering of articles and papers referencing Christopher Alexander's newer work "The Nature of Order" and how it can be applied to software.
Unfortunately, the only works I can find are from James Coplien and Richard Gabriel; there is nothing beyond that, at least from my attempts to find such things through google.
Is this kind of discussion happening anywhere?
MSN
---
@Georgia
My question isn't about design patterns or pattern languages; it's about trying to see if more of Christopher Alexander's work can be applied to software (which it probably can, since it has even less physical constraints than architecture and building).
Design patterns and pattern languages seem to have embraced the structure of Alexander's design patterns, but not many capture the essence. The essence being something beyond solving a problem in a particular context.
It's difficult to explain without using some of Alexander's later works as a reference point.
Edit: No, I take that back.
For example, there's an architectural design pattern that is called Alcoves. The pattern has a context that isn't just rooted in the circumstances of the situation but also rooted in fundamentals about the purpose of buildings: that they are structures to be lived in and must promote living in them. In the case of the Alcove pattern, the context is that you want an area that allows for multiple people to be in the same area doing different things, because it is important for family members to be physically together as well as to be able to do things that tend to distract other family members.
Most software design patterns describe a problem in a context, but they make no deeper statement about why the problem is important, or why the problem is something that is fundamental to software. It makes it very easy to apply design patterns inappropriately or blithely, which is the exact opposite of the intent of design patterns to began with.
MSN
| For the sake of completeness I'll repeat the discussion on Reto's post over at the [Android Groups here](http://groups.google.com/group/android-developers/browse_thread/thread/36fe0648dabfe745#).
It seems that if you set the bounds on your drawable it does the trick:
```
Drawable defaultMarker = r.getDrawable(R.drawable.icon);
// You HAVE to specify the bounds! It seems like the markers are drawn
// through Drawable.draw(Canvas) and therefore must have its bounds set
// before drawing.
defaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(),
defaultMarker.getIntrinsicHeight());
MyItemizedOverlay markers = new MyItemizedOverlay(defaultMarker);
overlays.add(markers);
```
By the way, the above is shamelessly ripped from [the demo at MarcelP.info](http://www.marcelp.info/2008/09/01/android-itemizedoverlay-demo/). Also, here is a [good howto](http://androidguys.com/?p=1413). |
26,369 | <p>I have a .NET 2.0 Windows Forms application. Where is the best place the store user settings (considering Windows guidelines)?</p>
<p>Some people pointed to <code>Application.LocalUserAppDataPath</code>. However, that creates a folder structure like:</p>
<blockquote>
<p>C:\Documents and Settings\user_name\Local Settings\Application
Data\company_name\product_name\product_version\</p>
</blockquote>
<p>If I release version 1 of my application and store an XML file there, then release version 2, that would change to a different folder, right? I'd prefer to have a single folder, per user, to store settings, regardless of the application version.
</p>
| [
{
"answer_id": 26377,
"author": "LeoD",
"author_id": 2868,
"author_profile": "https://Stackoverflow.com/users/2868",
"pm_score": 0,
"selected": false,
"text": "<p>Settings are standard key-value pairs (string-string). I could wrap them in an XML file, if that helps.</p>\n\n<p>I'd rather ... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2868/"
] | I have a .NET 2.0 Windows Forms application. Where is the best place the store user settings (considering Windows guidelines)?
Some people pointed to `Application.LocalUserAppDataPath`. However, that creates a folder structure like:
>
> C:\Documents and Settings\user\_name\Local Settings\Application
> Data\company\_name\product\_name\product\_version\
>
>
>
If I release version 1 of my application and store an XML file there, then release version 2, that would change to a different folder, right? I'd prefer to have a single folder, per user, to store settings, regardless of the application version.
| I love using the built-in [Application Settings](http://msdn.microsoft.com/en-us/library/a65txexh.aspx). Then you have built in support for using the settings designer if you want at design-time, or at runtime to use:
```
// read setting
string setting1 = (string)Settings.Default["MySetting1"];
// save setting
Settings.Default["MySetting2"] = "My Setting Value";
// you can force a save with
Properties.Settings.Default.Save();
```
It does store the settings in a similar folder structure as you describe (with the version in the path). However, with a simple call to:
```
Properties.Settings.Default.Upgrade();
```
The app will pull all previous versions settings in to save in. |
26,383 | <p>I know two approaches to Exception handling, lets have a look at them.</p>
<ol>
<li><p>Contract approach.</p>
<p>When a method does not do what it says it will do in the method header, it will throw an exception. Thus the method "promises" that it will do the operation, and if it fails for some reason, it will throw an exception.</p>
</li>
<li><p>Exceptional approach.</p>
<p>Only throw exceptions when something truly weird happens. You should not use exceptions when you can resolve the situation with normal control flow (If statements). You don't use Exceptions for control flow, as you might in the contract approach.</p>
</li>
</ol>
<p>Lets use both approaches in different cases:</p>
<p>We have a Customer class that has a method called OrderProduct.</p>
<p>contract approach:</p>
<pre><code>class Customer
{
public void OrderProduct(Product product)
{
if((m_credit - product.Price) < 0)
throw new NoCreditException("Not enough credit!");
// do stuff
}
}
</code></pre>
<p>exceptional approach:</p>
<pre><code>class Customer
{
public bool OrderProduct(Product product)
{
if((m_credit - product.Price) < 0)
return false;
// do stuff
return true;
}
}
if !(customer.OrderProduct(product))
Console.WriteLine("Not enough credit!");
else
// go on with your life
</code></pre>
<p>Here I prefer the exceptional approach, as it is not truly Exceptional that a customer has no money assuming he did not win the lottery.</p>
<p>But here is a situation I err on the contract style.</p>
<p>Exceptional:</p>
<pre><code>class CarController
{
// returns null if car creation failed.
public Car CreateCar(string model)
{
// something went wrong, wrong model
return null;
}
}
</code></pre>
<p>When I call a method called CreateCar, I damn wel expect a Car instance instead of some lousy null pointer, which can ravage my running code a dozen lines later. Thus I prefer contract to this one:</p>
<pre><code>class CarController
{
public Car CreateCar(string model)
{
// something went wrong, wrong model
throw new CarModelNotKnownException("Model unkown");
return new Car();
}
}
</code></pre>
<p>Which do style do you use? What do you think is best general approach to Exceptions?</p>
| [
{
"answer_id": 26395,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 0,
"selected": false,
"text": "<p>I believe that if you are building a class which will be used by an external program (or will be reused by other programs) t... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I know two approaches to Exception handling, lets have a look at them.
1. Contract approach.
When a method does not do what it says it will do in the method header, it will throw an exception. Thus the method "promises" that it will do the operation, and if it fails for some reason, it will throw an exception.
2. Exceptional approach.
Only throw exceptions when something truly weird happens. You should not use exceptions when you can resolve the situation with normal control flow (If statements). You don't use Exceptions for control flow, as you might in the contract approach.
Lets use both approaches in different cases:
We have a Customer class that has a method called OrderProduct.
contract approach:
```
class Customer
{
public void OrderProduct(Product product)
{
if((m_credit - product.Price) < 0)
throw new NoCreditException("Not enough credit!");
// do stuff
}
}
```
exceptional approach:
```
class Customer
{
public bool OrderProduct(Product product)
{
if((m_credit - product.Price) < 0)
return false;
// do stuff
return true;
}
}
if !(customer.OrderProduct(product))
Console.WriteLine("Not enough credit!");
else
// go on with your life
```
Here I prefer the exceptional approach, as it is not truly Exceptional that a customer has no money assuming he did not win the lottery.
But here is a situation I err on the contract style.
Exceptional:
```
class CarController
{
// returns null if car creation failed.
public Car CreateCar(string model)
{
// something went wrong, wrong model
return null;
}
}
```
When I call a method called CreateCar, I damn wel expect a Car instance instead of some lousy null pointer, which can ravage my running code a dozen lines later. Thus I prefer contract to this one:
```
class CarController
{
public Car CreateCar(string model)
{
// something went wrong, wrong model
throw new CarModelNotKnownException("Model unkown");
return new Car();
}
}
```
Which do style do you use? What do you think is best general approach to Exceptions? | I favor what you call the "contract" approach. Returning nulls or other special values to indicate errors isn't necessary in a language that supports exceptions. I find it much easier to understand code when it doesn't have a bunch of "if (result == NULL)" or "if (result == -1)" clauses mixed in with what could be very simple, straightforward logic. |
26,393 | <p>I've seen news of <a href="http://github.com/jeresig/sizzle/tree/master" rel="noreferrer">John Resig's fast new selector engine named Sizzle</a> pop up in quite a few places, but I don't know what a selector engine is, nor have any of the articles given an explanation of what it is. I know Resig is the creator of jQuery, and that Sizzle is something in Javascript, but beyond that I don't know what it is. So, what is a selector engine?</p>
<p>Thanks!</p>
| [
{
"answer_id": 26411,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 7,
"selected": true,
"text": "<p>A selector engine is used to query a page's DOM for particular elements, based on some sort of query (usually CSS syntax or s... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1266/"
] | I've seen news of [John Resig's fast new selector engine named Sizzle](http://github.com/jeresig/sizzle/tree/master) pop up in quite a few places, but I don't know what a selector engine is, nor have any of the articles given an explanation of what it is. I know Resig is the creator of jQuery, and that Sizzle is something in Javascript, but beyond that I don't know what it is. So, what is a selector engine?
Thanks! | A selector engine is used to query a page's DOM for particular elements, based on some sort of query (usually CSS syntax or similar).
For example, this jQuery:
```
$('div')
```
Would search for and return all of the <div> elements on the page. It uses jQuery's selector engine to do that.
Optimizing the selector engine is a big deal because almost every operation you perform with these frameworks is based on some sort of DOM query. |
26,433 | <p>Say I have three files (template_*.txt):</p>
<ul>
<li>template_x.txt</li>
<li>template_y.txt</li>
<li>template_z.txt</li>
</ul>
<p>I want to copy them to three new files (foo_*.txt). </p>
<ul>
<li>foo_x.txt </li>
<li>foo_y.txt </li>
<li>foo_z.txt</li>
</ul>
<p>Is there some simple way to do that with one command, e.g. </p>
<p><code>cp --enableAwesomeness template_*.txt foo_*.txt</code></p>
| [
{
"answer_id": 26439,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know of anything in bash or on cp, but there are simple ways to do this sort of thing using (for example) a p... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/437/"
] | Say I have three files (template\_\*.txt):
* template\_x.txt
* template\_y.txt
* template\_z.txt
I want to copy them to three new files (foo\_\*.txt).
* foo\_x.txt
* foo\_y.txt
* foo\_z.txt
Is there some simple way to do that with one command, e.g.
`cp --enableAwesomeness template_*.txt foo_*.txt` | ```
for f in template_*.txt; do cp $f foo_${f#template_}; done
``` |
26,450 | <p>Is there any way to save an object using Hibernate if there is already an object using that identifier loaded into the session?</p>
<ul>
<li>Doing <code>session.contains(obj)</code> seems to only return true if the session contains that exact object, not another object with the same ID.</li>
<li>Using <code>merge(obj)</code> throws an exception if the object is new</li>
</ul>
| [
{
"answer_id": 26468,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried calling .SaveOrUpdateCopy()? \nIt should work in all instances, if there is an entity by the same id in... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2875/"
] | Is there any way to save an object using Hibernate if there is already an object using that identifier loaded into the session?
* Doing `session.contains(obj)` seems to only return true if the session contains that exact object, not another object with the same ID.
* Using `merge(obj)` throws an exception if the object is new | Have you tried calling .SaveOrUpdateCopy()?
It should work in all instances, if there is an entity by the same id in the session or if there is no entity at all. This is basically the catch-all method, as it converts a transient object into a persistent one (Save), updates the object if it is existing (Update) or even handles if the entity is a copy of an already existing object (Copy).
Failing that, you may have to identify and .Evict() the existing object before Attaching (.Update()) your "new" object.
This should be easy enough to do:
```
IPersistable entity = Whatever(); // This is the object we're trying to update
// (IPersistable has an id field)
session.Evict(session.Get(entity.GetType(), entity.Id));
session.SaveOrUpdate(entity);
```
Although the above code could probably do with some null checking for the .Get() call. |
26,455 | <p>Do you use Design by Contract professionally? Is it something you have to do from the beginning of a project, or can you change gears and start to incorporate it into your software development lifecycle? What have you found to be the pros/cons of the design approach?</p>
<p>I came across the <a href="http://en.wikipedia.org/wiki/Design_by_contract" rel="noreferrer">Design by Contract</a> approach in a grad school course. In the academic setting, it seemed to be a pretty useful technique. But I don't currently use Design by Contract professionally, and I don't know any other developers that are using it. It would be good to hear about its actual usage from the SO crowd.</p>
| [
{
"answer_id": 26484,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 5,
"selected": true,
"text": "<p>I can't recommend it highly enough. It's particularly nice if you have a suite that takes inline documentation cont... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Do you use Design by Contract professionally? Is it something you have to do from the beginning of a project, or can you change gears and start to incorporate it into your software development lifecycle? What have you found to be the pros/cons of the design approach?
I came across the [Design by Contract](http://en.wikipedia.org/wiki/Design_by_contract) approach in a grad school course. In the academic setting, it seemed to be a pretty useful technique. But I don't currently use Design by Contract professionally, and I don't know any other developers that are using it. It would be good to hear about its actual usage from the SO crowd. | I can't recommend it highly enough. It's particularly nice if you have a suite that takes inline documentation contract specifications, like so:
```
// @returns null iff x = 0
public foo(int x) {
...
}
```
and turns them into generated unit tests, like so:
```
public test_foo_returns_null_iff_x_equals_0() {
assertNull foo(0);
}
```
That way, you can actually see the tests you're running, but they're auto-generated. Generated tests shouldn't be checked into source control, by the way. |
26,478 | <p>I'm having trouble getting the following to work in SQL Server 2k, but it works in 2k5:</p>
<pre><code>--works in 2k5, not in 2k
create view foo as
SELECT usertable.legacyCSVVarcharCol as testvar
FROM usertable
WHERE rsrcID in
( select val
from
dbo.fnSplitStringToInt(usertable.legacyCSVVarcharCol, default)
)
--error message:
Msg 170, Level 15, State 1, Procedure foo, Line 4
Line 25: Incorrect syntax near '.'.
</code></pre>
<p>So, legacyCSVVarcharCol is a column containing comma-separated lists of INTs. I realize that this is a huge WTF, but this is legacy code, and there's nothing that can be done about the schema right now. Passing "testvar" as the argument to the function doesn't work in 2k either. In fact, it results in a slightly different (and even weirder error):</p>
<pre><code>Msg 155, Level 15, State 1, Line 8
'testvar' is not a recognized OPTIMIZER LOCK HINTS option.
</code></pre>
<p>Passing a hard-coded string as the argument to fnSplitStringToInt works in both 2k and 2k5.</p>
<p>Does anyone know why this doesn't work in 2k? Is this perhaps a known bug in the query planner? Any suggestions for how to make it work? Again, I realize that the real answer is "don't store CSV lists in your DB!", but alas, that's beyond my control.</p>
<p>Some sample data, if it helps:</p>
<pre><code>INSERT INTO usertable (legacyCSVVarcharCol) values ('1,2,3');
INSERT INTO usertable (legacyCSVVarcharCol) values ('11,13,42');
</code></pre>
<p>Note that the data in the table does not seem to matter since this is a syntax error, and it occurs even if usertable is completely empty.</p>
<p>EDIT: Realizing that perhaps the initial example was unclear, here are two examples, one of which works and one of which does not, which should highlight the problem that's occurring:</p>
<pre><code>--fails in sql2000, works in 2005
SELECT t1.*
FROM usertable t1
WHERE 1 in
(Select val
from
fnSplitStringToInt(t1.legacyCSVVarcharCol, ',')
)
--works everywhere:
SELECT t1.*
FROM usertable t1
WHERE 1 in
( Select val
from
fnSplitStringToInt('1,4,543,56578', ',')
)
</code></pre>
<p>Note that the only difference is the first argument to fnSplitStringToInt is a column in the case that fails in 2k and a literal string in the case that succeeds in both.</p>
| [
{
"answer_id": 26577,
"author": "wcm",
"author_id": 2173,
"author_profile": "https://Stackoverflow.com/users/2173",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think functions can have default values in functions in SS2K.</p>\n\n<p>What happens when you run this SQL in SS2K?</p... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2327/"
] | I'm having trouble getting the following to work in SQL Server 2k, but it works in 2k5:
```
--works in 2k5, not in 2k
create view foo as
SELECT usertable.legacyCSVVarcharCol as testvar
FROM usertable
WHERE rsrcID in
( select val
from
dbo.fnSplitStringToInt(usertable.legacyCSVVarcharCol, default)
)
--error message:
Msg 170, Level 15, State 1, Procedure foo, Line 4
Line 25: Incorrect syntax near '.'.
```
So, legacyCSVVarcharCol is a column containing comma-separated lists of INTs. I realize that this is a huge WTF, but this is legacy code, and there's nothing that can be done about the schema right now. Passing "testvar" as the argument to the function doesn't work in 2k either. In fact, it results in a slightly different (and even weirder error):
```
Msg 155, Level 15, State 1, Line 8
'testvar' is not a recognized OPTIMIZER LOCK HINTS option.
```
Passing a hard-coded string as the argument to fnSplitStringToInt works in both 2k and 2k5.
Does anyone know why this doesn't work in 2k? Is this perhaps a known bug in the query planner? Any suggestions for how to make it work? Again, I realize that the real answer is "don't store CSV lists in your DB!", but alas, that's beyond my control.
Some sample data, if it helps:
```
INSERT INTO usertable (legacyCSVVarcharCol) values ('1,2,3');
INSERT INTO usertable (legacyCSVVarcharCol) values ('11,13,42');
```
Note that the data in the table does not seem to matter since this is a syntax error, and it occurs even if usertable is completely empty.
EDIT: Realizing that perhaps the initial example was unclear, here are two examples, one of which works and one of which does not, which should highlight the problem that's occurring:
```
--fails in sql2000, works in 2005
SELECT t1.*
FROM usertable t1
WHERE 1 in
(Select val
from
fnSplitStringToInt(t1.legacyCSVVarcharCol, ',')
)
--works everywhere:
SELECT t1.*
FROM usertable t1
WHERE 1 in
( Select val
from
fnSplitStringToInt('1,4,543,56578', ',')
)
```
Note that the only difference is the first argument to fnSplitStringToInt is a column in the case that fails in 2k and a literal string in the case that succeeds in both. | Passing column-values to a table-valued user-defined function is not supported in SQL Server 2000, you can only use constants, so the following (simpler version) would also fail:
```
SELECT *, (SELECT TOP 1 val FROM dbo.fnSplitStringToInt(usertable.legacyCSVVarcharCol, ','))
FROM usertable
```
It will work on SQL Server 2005, though, as you have found out. |
26,512 | <p>I have a ComboBox that I bind to a standard HTTPService, I would like to add an event listener so that I can run some code after the ComboBox is populated from the data provider.</p>
<p>How can I do this?</p>
| [
{
"answer_id": 26553,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>BindingUtils</code> to get notified when the <code>dataProvider</code> property of the combo box changes:</... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | I have a ComboBox that I bind to a standard HTTPService, I would like to add an event listener so that I can run some code after the ComboBox is populated from the data provider.
How can I do this? | Flex doesn't have a specific data-binding events in the way that say ASP .Net does. You have to watch for the dataProvider property like John says in the first answer, but not simply to the combobox or its dataProvider property. Let's say you have a setup like this:
```
<!-- Assume you have extracted an XMLList out of the result
and attached it to the collection -->
<mx:HttpService id="svc" result="col.source = event.result.Project"/>
<mx:XMLListCollection id="col"/>
<mx:ComboBox id="cbProject" dataProvider="{col}"/>
```
Now if you set a changewatcher like this:
```
// Strategy 1
ChangeWatcher.watch(cbProject, "dataProvider", handler) ;
```
your handler will *not* get triggered when the data comes back. Why? Because the *dataProvider* itself didn't change - its underlying collection did. To trigger that, you have to do this:
```
// Strategy 2
ChangeWatcher.watch(cbProject, ["dataProvider", "source"], handler) ;
```
Now, when your collection has updated, your handler will get triggered. If you want to make it work using Strategy 1, *don't* set your dataProvider in MXML. Rather, handle the *collectionChange* event of your XMLListCollection and in AS, over-write the dataProvider of the ComboBox.
Are these exactly the same as a databound event? No, but I've used them and never had an issue. If you want to be *absolutely* sure your data *has* bound, just put a changeWatcher on the selectedItem property of your combobox and do your processing there. Just be prepared to have that event trigger multiple times and handle that appropriately. |
26,515 | <p>I have a habit of keeping my variable usage to a bare minimum. So I'm wondering if there is any advantage to be gained by the following:</p>
<pre><code>$query = $mysqli->query('SELECT * FROM `people` ORDER BY `name` ASC LIMIT 0,30');
// Example 1
$query = $query->fetch_assoc();
// Example 2
$query_r = $query->fetch_assoc();
$query->free();
</code></pre>
<p>Now if I'm right Example 1 should be more efficient as <code>$query</code> is <code>unset</code> when I reassign it which should free any memory associated with it. However there is a method (<code>MySQLi_Result::free()</code>) which frees associated memory - is this the same thing?</p>
<p>If I don't call <code>::free()</code> to free any memory associated with the result but <code>unset</code> it by reassigning the variable am I doing the same thing? I don't know how to log this sort of thing - does anyone have some ideas?</p>
| [
{
"answer_id": 26537,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 4,
"selected": true,
"text": "<p>The <a href=\"http://us2.php.net/manual/en/mysqli-result.free.php\" rel=\"noreferrer\">manual</a> seems to suggest th... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2025/"
] | I have a habit of keeping my variable usage to a bare minimum. So I'm wondering if there is any advantage to be gained by the following:
```
$query = $mysqli->query('SELECT * FROM `people` ORDER BY `name` ASC LIMIT 0,30');
// Example 1
$query = $query->fetch_assoc();
// Example 2
$query_r = $query->fetch_assoc();
$query->free();
```
Now if I'm right Example 1 should be more efficient as `$query` is `unset` when I reassign it which should free any memory associated with it. However there is a method (`MySQLi_Result::free()`) which frees associated memory - is this the same thing?
If I don't call `::free()` to free any memory associated with the result but `unset` it by reassigning the variable am I doing the same thing? I don't know how to log this sort of thing - does anyone have some ideas? | The [manual](http://us2.php.net/manual/en/mysqli-result.free.php) seems to suggest that you should still be using `free()` to release the memory. I believe the reasoning is that `free()` is freeing the memory in *MySQL*, not in PHP. Since PHP can't garbage-collect for MySQL, you need to call `free()`. |
26,522 | <p>Let's say I have a .NET Array of n number of dimensions. I would like to foreach through the elements and print out something like:</p>
<pre><code>[0, 0, 0] = 2
[0, 0, 1] = 32
</code></pre>
<p>And so on. I could write a loop using some the Rank and dimension functions to come up with the indices. Is there a built in function instead?</p>
| [
{
"answer_id": 26546,
"author": "Gabriël",
"author_id": 2104,
"author_profile": "https://Stackoverflow.com/users/2104",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://forums.msdn.microsoft.com/en-US/csharplanguage/thread/2ca85aa4-0672-40ad-b780-e181b28fcd80/\" rel=\"nofol... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632/"
] | Let's say I have a .NET Array of n number of dimensions. I would like to foreach through the elements and print out something like:
```
[0, 0, 0] = 2
[0, 0, 1] = 32
```
And so on. I could write a loop using some the Rank and dimension functions to come up with the indices. Is there a built in function instead? | Thanks for the answer, here is what I wrote while I waited:
```
public static string Format(Array array)
{
var builder = new StringBuilder();
builder.AppendLine("Count: " + array.Length);
var counter = 0;
var dimensions = new List<int>();
for (int i = 0; i < array.Rank; i++)
{
dimensions.Add(array.GetUpperBound(i) + 1);
}
foreach (var current in array)
{
var index = "";
var remainder = counter;
foreach (var bound in dimensions)
{
index = remainder % bound + ", " + index;
remainder = remainder / bound;
}
index = index.Substring(0, index.Length - 2);
builder.AppendLine(" [" + index + "] " + current);
counter++;
}
return builder.ToString();
}
``` |
26,547 | <p>Let's say that you want to create a dead simple BlogEditor and, one of your ideas, is to do what Live Writer does and ask only the URL of the persons Blog. How can you detect what type of blog is it?</p>
<p>Basic detection can be done with the URL itself, such as “<a href="http://myblog.blogger.com" rel="nofollow noreferrer">http://myblog.blogger.com</a>” etc. But what if it's self hosted?</p>
<p>I'm mostly interested on how to do this in Java, but this question could be also used as a reference for any other language.</p>
| [
{
"answer_id": 26579,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 1,
"selected": false,
"text": "<p>Some blogs provide a Generator meta tag - e.g. Wordpress - you could find out if there's any exceptions to this.</p>\n\n<p>Yo... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
] | Let's say that you want to create a dead simple BlogEditor and, one of your ideas, is to do what Live Writer does and ask only the URL of the persons Blog. How can you detect what type of blog is it?
Basic detection can be done with the URL itself, such as “<http://myblog.blogger.com>” etc. But what if it's self hosted?
I'm mostly interested on how to do this in Java, but this question could be also used as a reference for any other language. | Many (most?) blogs will have a meta tag for "generator" which will list the blog engine. For example a blogger blog will contain the following meta tag:
```
<meta name="generator" content="Blogger" />
```
My Subtext blog shows the following generator meta tag:
```
<meta name="Generator" content="Subtext Version 1.9.5.177" />
```
This meta tag would be the first place to look. For blogs that don't set this meta tag in the source, you'd have to resort to looking for patterns to determine the blog type. |
26,551 | <p>I need to pass an ID and a password to a batch file at the time of running rather than hardcoding them into the file.</p>
<p>Here's what the command line looks like:</p>
<pre><code>test.cmd admin P@55w0rd > test-log.txt
</code></pre>
| [
{
"answer_id": 26556,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 6,
"selected": false,
"text": "<p>Yep, and just don't forget to use variables like <code>%%1</code> when using <code>if</code> and <code>for</code> and ... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
] | I need to pass an ID and a password to a batch file at the time of running rather than hardcoding them into the file.
Here's what the command line looks like:
```
test.cmd admin P@55w0rd > test-log.txt
``` | Here's how I did it:
```
@fake-command /u %1 /p %2
```
Here's what the command looks like:
```
test.cmd admin P@55w0rd > test-log.txt
```
The `%1` applies to the first parameter the `%2` (and here's the tricky part) applies to the second. You can have up to 9 parameters passed in this way. |
26,567 | <p>I have a report with many fields that I'm trying to get down to 1 page horizontally (I don't care whether it's 2 or 200 pages vertically... just don't want to have to deal with 2 pages wide by x pages long train-wreck). That said, it deals with contact information.</p>
<p>My idea was to do:</p>
<pre><code>Name: Address: City: State: ...
Jon Doe Addr1 ThisTown XX ...
Addr2
Addr3
-----------------------------------------------
Jane Doe Addr1 ThisTown XX ...
Addr2
Addr3
-----------------------------------------------
</code></pre>
<p>Is there some way to set a <code>textbox</code> to be multi-line (or the SQL result)? Have I missed something bloody obvious?</p>
<hr>
<p>The CanGrow Property is on by default, and I've double checked that this is true. My problem is that I don't know how to force a line-break. I get the 3 address fields that just fills a line, then wraps to another. I've tried <code>/n</code>, <code>\n</code> (since I can never remember which is the correct slash to put), <code><br></code>, <code><br /></code> (since the report will be viewed in a ReportViewer control in an ASP.NET website). I can't think of any other ways to wrap the text. </p>
<p>Is there some way to get the results from the database as 3 lines of text/characters?
</p>
| [
{
"answer_id": 26953,
"author": "Sean Carpenter",
"author_id": 729,
"author_profile": "https://Stackoverflow.com/users/729",
"pm_score": 2,
"selected": false,
"text": "<p>I believe you need to set the CanGrow property to <strong>true</strong> on the Textbox. See <a href=\"http://msdn.mi... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2156/"
] | I have a report with many fields that I'm trying to get down to 1 page horizontally (I don't care whether it's 2 or 200 pages vertically... just don't want to have to deal with 2 pages wide by x pages long train-wreck). That said, it deals with contact information.
My idea was to do:
```
Name: Address: City: State: ...
Jon Doe Addr1 ThisTown XX ...
Addr2
Addr3
-----------------------------------------------
Jane Doe Addr1 ThisTown XX ...
Addr2
Addr3
-----------------------------------------------
```
Is there some way to set a `textbox` to be multi-line (or the SQL result)? Have I missed something bloody obvious?
---
The CanGrow Property is on by default, and I've double checked that this is true. My problem is that I don't know how to force a line-break. I get the 3 address fields that just fills a line, then wraps to another. I've tried `/n`, `\n` (since I can never remember which is the correct slash to put), `<br>`, `<br />` (since the report will be viewed in a ReportViewer control in an ASP.NET website). I can't think of any other ways to wrap the text.
Is there some way to get the results from the database as 3 lines of text/characters?
| Alter the report's text box to:
```
= Fields!Addr1.Value + VbCrLf +
Fields!Addr2.Value + VbCrLf +
Fields!Addr3.Value
``` |
26,595 | <p>Is there any difference between:</p>
<pre><code>if foo is None: pass
</code></pre>
<p>and</p>
<pre><code>if foo == None: pass
</code></pre>
<p>The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?</p>
| [
{
"answer_id": 26611,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 9,
"selected": true,
"text": "<p><code>is</code> always returns <code>True</code> if it compares the same object instance</p>\n\n<p>Whereas <code>==</code> is... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156/"
] | Is there any difference between:
```
if foo is None: pass
```
and
```
if foo == None: pass
```
The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might? | `is` always returns `True` if it compares the same object instance
Whereas `==` is ultimately determined by the `__eq__()` method
i.e.
```
>>> class Foo(object):
def __eq__(self, other):
return True
>>> f = Foo()
>>> f == None
True
>>> f is None
False
``` |
26,620 | <p>In my web app, I submit some form fields with jQuery's <code>$.getJSON()</code> method. I am having some problems with the encoding. The character-set of my app is <code>charset=ISO-8859-1</code>, but I think these fields are submitted with <code>UTF-8</code>. </p>
<p>How I can set encoding used in <code>$.getJSON</code> calls? </p>
| [
{
"answer_id": 26681,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 6,
"selected": true,
"text": "<p>I think that you'll probably have to use <a href=\"http://docs.jquery.com/Ajax/jQuery.ajax#options\" rel=\"noreferrer\"><cod... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] | In my web app, I submit some form fields with jQuery's `$.getJSON()` method. I am having some problems with the encoding. The character-set of my app is `charset=ISO-8859-1`, but I think these fields are submitted with `UTF-8`.
How I can set encoding used in `$.getJSON` calls? | I think that you'll probably have to use [`$.ajax()`](http://docs.jquery.com/Ajax/jQuery.ajax#options) if you want to change the encoding, see the `contentType` param below (the `success` and `error` callbacks assume you have `<div id="success"></div>` and `<div id="error"></div>` in the html):
```
$.ajax({
type: "POST",
url: "SomePage.aspx/GetSomeObjects",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{id: '" + someId + "'}",
success: function(json) {
$("#success").html("json.length=" + json.length);
itemAddCallback(json);
},
error: function (xhr, textStatus, errorThrown) {
$("#error").html(xhr.responseText);
}
});
```
I actually just had to do this about an hour ago, what a coincidence! |
26,652 | <p>Is there a way to make a TSQL variable constant?</p>
| [
{
"answer_id": 26655,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 0,
"selected": false,
"text": "<p>There are no such thing as \"creating a constant\" in database literature. Constants exist as they are and often called v... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1874/"
] | Is there a way to make a TSQL variable constant? | No, but you can create a function and hardcode it in there and use that.
Here is an example:
```
CREATE FUNCTION fnConstant()
RETURNS INT
AS
BEGIN
RETURN 2
END
GO
SELECT dbo.fnConstant()
``` |
26,670 | <p>I'm creating PDFs on-demand with ColdFusion's <a href="http://cfquickdocs.com/cf8/?getDoc=cfdocument" rel="nofollow noreferrer">CFDocument</a> tag, like so:</p>
<pre><code><cfdocument format="PDF" filename="#attributes.fileName#" overwrite="true">
<cfdocumentitem type="footer">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left"><font face="Tahoma" color="black"><strong>My Client's Corporation</strong><br/>Street address<br/>City, ST 55555</font></td>
<td align="right"><font face="Tahoma" color="black">Phone: 555.555.5555<br/>Fax: 555.555.5555<br/>Email: info@domain.com</font></td>
</tr>
</table>
</cfdocumentitem>
<html>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<!--- some content here ... --->
</table>
</body>
</html>
</cfdocument>
</code></pre>
<p>The problem I'm having is that sometimes (actually, most of the time, but not always) <strong><em>some</em></strong> of the footer text is there, but invisible. I can highlight it and copy/paste it into notepad, where I can see it all -- but in the generated PDF only the first line of the left column of the footer is visible, the rest is invisible. Hence why I added the font color of black in the code.</p>
<p><img src="https://i.stack.imgur.com/LHZ96.png" alt="screenshot of problem"></p>
<p>Any ideas on how to correct this?</p>
| [
{
"answer_id": 30688,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 3,
"selected": true,
"text": "<p>A PDF is what I'm after, so I'm not sure how outputting another format would help.</p>\n\n<p>As it turns out, the footer ... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751/"
] | I'm creating PDFs on-demand with ColdFusion's [CFDocument](http://cfquickdocs.com/cf8/?getDoc=cfdocument) tag, like so:
```
<cfdocument format="PDF" filename="#attributes.fileName#" overwrite="true">
<cfdocumentitem type="footer">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left"><font face="Tahoma" color="black"><strong>My Client's Corporation</strong><br/>Street address<br/>City, ST 55555</font></td>
<td align="right"><font face="Tahoma" color="black">Phone: 555.555.5555<br/>Fax: 555.555.5555<br/>Email: info@domain.com</font></td>
</tr>
</table>
</cfdocumentitem>
<html>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<!--- some content here ... --->
</table>
</body>
</html>
</cfdocument>
```
The problem I'm having is that sometimes (actually, most of the time, but not always) ***some*** of the footer text is there, but invisible. I can highlight it and copy/paste it into notepad, where I can see it all -- but in the generated PDF only the first line of the left column of the footer is visible, the rest is invisible. Hence why I added the font color of black in the code.

Any ideas on how to correct this? | A PDF is what I'm after, so I'm not sure how outputting another format would help.
As it turns out, the footer space just wasn't enough to fit all of this text; verified by the fact that changing the font size to 4pt would fit it all in without a problem.
I spent some time attempting to rewrite the footer code using DDX [as outlined here](http://www.coldfusionjedi.com/index.cfm/2008/6/2/Changing-the-size-of-a-footer-in-CFDOCUMENT) and the [CFPDF](http://cfquickdocs.com/cf8/?getDoc=cfpdf) tag to implement it; but even after several hours of hacking away and finally getting a valid DDX as reported by the new [isDDX function](http://cfquickdocs.com/cf8/?getDoc=IsDDX), the CFPDF tag reported that it was invalid DDX for some reason.
At this point I decided I had wasted enough of the client's time/money and just reformatted the footer to be 2 lines of centered text, which was good enough. |
26,715 | <p>How does the new Microsoft asp.net mvc implementation handle partitioning your application - for example:</p>
<pre><code>--index.aspx
--about.aspx
--contact.aspx
--/feature1
--/feature1/subfeature/action
--/feature2/subfeature/action
</code></pre>
<p>I guess what I am trying to say is that it seems everything has to go into the root of the views/controllers folders which could get unwieldy when working on a project that if built with web forms might have lots and lots of folders and sub-folders to partition the application.</p>
<p>I think I get the MVC model and I like the look of it compared to web forms but still getting my head round how you would build a large project in practice.</p>
| [
{
"answer_id": 26741,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 5,
"selected": true,
"text": "<p>There isn't any issues with organizing your controllers. You just need to setup the routes to take the organization int... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2041/"
] | How does the new Microsoft asp.net mvc implementation handle partitioning your application - for example:
```
--index.aspx
--about.aspx
--contact.aspx
--/feature1
--/feature1/subfeature/action
--/feature2/subfeature/action
```
I guess what I am trying to say is that it seems everything has to go into the root of the views/controllers folders which could get unwieldy when working on a project that if built with web forms might have lots and lots of folders and sub-folders to partition the application.
I think I get the MVC model and I like the look of it compared to web forms but still getting my head round how you would build a large project in practice. | There isn't any issues with organizing your controllers. You just need to setup the routes to take the organization into consideration. The problem you will run into is finding the view for the controller, since you changed the convention. There isn't any built in functionality for it yet, but it is easy to create a work around yourself with a ActionFilterAttribute and a custom view locator that inherits off ViewLocator. Then when creating your controller, you just specify what ViewLocator to use, so the controller knows how to find the view. I can post some code if needed.
This method kind of goes along with some advice I gave another person for separating their views out for a portal using ASP.NET MVC. Here is the [link to the question](https://stackoverflow.com/questions/19746/views-in-seperate-assemblies-in-aspnet-mvc) as a reference. |
26,721 | <p>When creating scrollable user controls with .NET and WinForms I have repeatedly encountered situations where, for example, a vertical scrollbar pops up, overlapping the control's content, causing a horizontal scrollbar to also be needed. Ideally the content would shrink just a bit to make room for the vertical scrollbar.</p>
<p>My current solution has been to just keep my controls out of the far right 40 pixels or so that the vertical scroll-bar will be taking up. Since this is still effectively client space for the control, the horizontal scroll-bar still comes up when it gets covered by the vertical scroll-bar, even though no controls are being hidden at all. But then at least the user doesn't actually need to <strong>use</strong> the horizontal scrollbar that comes up.</p>
<p>Is there a better way to make this all work? Some way to keep the unneeded and unwanted scrollbars from showing up at all?</p>
| [
{
"answer_id": 26782,
"author": "Bryan Roth",
"author_id": 299,
"author_profile": "https://Stackoverflow.com/users/299",
"pm_score": 0,
"selected": false,
"text": "<p>If your controls are inside a panel, try setting the AutoScroll property of the Panel to False. This will hide the scrol... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2729/"
] | When creating scrollable user controls with .NET and WinForms I have repeatedly encountered situations where, for example, a vertical scrollbar pops up, overlapping the control's content, causing a horizontal scrollbar to also be needed. Ideally the content would shrink just a bit to make room for the vertical scrollbar.
My current solution has been to just keep my controls out of the far right 40 pixels or so that the vertical scroll-bar will be taking up. Since this is still effectively client space for the control, the horizontal scroll-bar still comes up when it gets covered by the vertical scroll-bar, even though no controls are being hidden at all. But then at least the user doesn't actually need to **use** the horizontal scrollbar that comes up.
Is there a better way to make this all work? Some way to keep the unneeded and unwanted scrollbars from showing up at all? | You will need your controls to resize slightly to accommodate the width of the vertical scroll bar. One way to achieve this achieved through docking. Rather than just dropping controls on the form, you'll have to play a bit with panels, padding, min/max sizing and docking.
Here is example code you can place behind a blank new Form1. Resize the form, in designer or runtime and you'll see that the horizontal scrollbar is not shown and the fields are not overlapped. I've also given the fields a max width for good measure :
```
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.textBox1 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.panel1 = new System.Windows.Forms.Panel();
this.panel2 = new System.Windows.Forms.Panel();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Dock = System.Windows.Forms.DockStyle.Top;
this.textBox1.Location = new System.Drawing.Point(32, 0);
this.textBox1.MaximumSize = new System.Drawing.Size(250, 0);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(250, 20);
this.textBox1.TabIndex = 0;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Dock = System.Windows.Forms.DockStyle.Left;
this.label1.Location = new System.Drawing.Point(0, 0);
this.label1.Name = "label1";
this.label1.Padding = new System.Windows.Forms.Padding(0, 3, 0, 0);
this.label1.Size = new System.Drawing.Size(32, 16);
this.label1.TabIndex = 0;
this.label1.Text = "Field:";
//
// panel1
//
this.panel1.Controls.Add(this.textBox1);
this.panel1.Controls.Add(this.label1);
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(392, 37);
this.panel1.TabIndex = 2;
//
// panel2
//
this.panel2.Controls.Add(this.textBox2);
this.panel2.Controls.Add(this.label2);
this.panel2.Dock = System.Windows.Forms.DockStyle.Top;
this.panel2.Location = new System.Drawing.Point(0, 37);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(392, 37);
this.panel2.TabIndex = 3;
//
// textBox2
//
this.textBox2.Dock = System.Windows.Forms.DockStyle.Top;
this.textBox2.Location = new System.Drawing.Point(32, 0);
this.textBox2.MaximumSize = new System.Drawing.Size(250, 0);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(250, 20);
this.textBox2.TabIndex = 0;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Dock = System.Windows.Forms.DockStyle.Left;
this.label2.Location = new System.Drawing.Point(0, 0);
this.label2.Name = "label2";
this.label2.Padding = new System.Windows.Forms.Padding(0, 3, 0, 0);
this.label2.Size = new System.Drawing.Size(32, 16);
this.label2.TabIndex = 0;
this.label2.Text = "Field:";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoScroll = true;
this.ClientSize = new System.Drawing.Size(392, 116);
this.Controls.Add(this.panel2);
this.Controls.Add(this.panel1);
this.Name = "Form1";
this.Text = "Form1";
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label2;
``` |
26,732 | <pre><code><servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>workflow.WDispatcher</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>*NEXTEVENT*</url-pattern>
</servlet-mapping>
</code></pre>
<p>Above is the snippet from Tomcat's <code>web.xml</code>. The URL pattern <code>*NEXTEVENT*</code> on start up throws</p>
<blockquote>
<p>java.lang.IllegalArgumentException: Invalid <url-pattern> in servlet mapping</p>
</blockquote>
<p>It will be greatly appreciated if someone can hint at the error.
</p>
| [
{
"answer_id": 26744,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 8,
"selected": true,
"text": "<pre><code><url-pattern>*NEXTEVENT*</url-pattern>\n</code></pre>\n\n<p>The URL pattern is not valid. It can either ... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>workflow.WDispatcher</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>*NEXTEVENT*</url-pattern>
</servlet-mapping>
```
Above is the snippet from Tomcat's `web.xml`. The URL pattern `*NEXTEVENT*` on start up throws
>
> java.lang.IllegalArgumentException: Invalid <url-pattern> in servlet mapping
>
>
>
It will be greatly appreciated if someone can hint at the error.
| ```
<url-pattern>*NEXTEVENT*</url-pattern>
```
The URL pattern is not valid. It can either end in an asterisk or start with one (to denote a file extension mapping).
The url-pattern specification:
>
> * A string beginning with a ‘/’ character and ending with a ‘/\*’
> suffix is used for path mapping.
> * A string beginning with a ‘\*.’ prefix is used as an extension
> mapping.
> * A string containing only the ’/’ character indicates the "default"
> servlet of the application. In this
> case the servlet path is the request
> URI minus the context path and the
> path info is null.
> * All other strings are used for exact matches only.
>
>
>
See section 12.2 of the [Java Servlet Specification](https://jcp.org/aboutJava/communityprocess/final/jsr340/index.html) Version 3.1 for more details. |
26,733 | <p>Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?</p>
<p>This is what I want to re-write:</p>
<pre><code>foreach (Type t in this.GetType().Assembly.GetTypes())
if (t is IMyInterface)
; //do stuff
</code></pre>
| [
{
"answer_id": 26745,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 4,
"selected": false,
"text": "<p>loop through all loaded assemblies, loop through all their types, and check if they implement the interface.</p>\n\... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] | Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?
This is what I want to re-write:
```
foreach (Type t in this.GetType().Assembly.GetTypes())
if (t is IMyInterface)
; //do stuff
``` | Mine would be this in c# 3.0 :)
```
var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
```
Basically, the least amount of iterations will always be:
```
loop assemblies
loop types
see if implemented.
``` |
26,743 | <p>I use .NET XML technologies quite extensively on my work. One of the things the I like very much is the XSLT engine, more precisely the extensibility of it. However there one little piece which keeps being a source of annoyance. Nothing major or something we can't live with but it is preventing us from producing the beautiful XML we would like to produce. </p>
<p>One of the things we do is transform nodes inline and importing nodes from one XML document to another. </p>
<p>Sadly , when you save nodes to an <code>XmlTextWriter</code> (actually whatever <code>XmlWriter.Create(Stream)</code> returns), the namespace definitions get all thrown in there, regardless of it is necessary (previously defined) or not. You get kind of the following xml:</p>
<pre><code><root xmlns:abx="http://bladibla">
<abx:child id="A">
<grandchild id="B">
<abx:grandgrandchild xmlns:abx="http://bladibla" />
</grandchild>
</abx:child>
</root>
</code></pre>
<p>Does anyone have a suggestion as to how to convince .NET to be efficient about its namespace definitions?</p>
<p>PS. As an added bonus I would like to override the default namespace, changing it as I write a node.</p>
| [
{
"answer_id": 6421794,
"author": "Simon Mourier",
"author_id": 403671,
"author_profile": "https://Stackoverflow.com/users/403671",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure this is what you're looking for, but you can use this kind of code when you start writing to the ... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2892/"
] | I use .NET XML technologies quite extensively on my work. One of the things the I like very much is the XSLT engine, more precisely the extensibility of it. However there one little piece which keeps being a source of annoyance. Nothing major or something we can't live with but it is preventing us from producing the beautiful XML we would like to produce.
One of the things we do is transform nodes inline and importing nodes from one XML document to another.
Sadly , when you save nodes to an `XmlTextWriter` (actually whatever `XmlWriter.Create(Stream)` returns), the namespace definitions get all thrown in there, regardless of it is necessary (previously defined) or not. You get kind of the following xml:
```
<root xmlns:abx="http://bladibla">
<abx:child id="A">
<grandchild id="B">
<abx:grandgrandchild xmlns:abx="http://bladibla" />
</grandchild>
</abx:child>
</root>
```
Does anyone have a suggestion as to how to convince .NET to be efficient about its namespace definitions?
PS. As an added bonus I would like to override the default namespace, changing it as I write a node. | Use this code:
```cs
using (var writer = XmlWriter.Create("file.xml"))
{
const string Ns = "http://bladibla";
const string Prefix = "abx";
writer.WriteStartDocument();
writer.WriteStartElement("root");
// set root namespace
writer.WriteAttributeString("xmlns", Prefix, null, Ns);
writer.WriteStartElement(Prefix, "child", Ns);
writer.WriteAttributeString("id", "A");
writer.WriteStartElement("grandchild");
writer.WriteAttributeString("id", "B");
writer.WriteElementString(Prefix, "grandgrandchild", Ns, null);
// grandchild
writer.WriteEndElement();
// child
writer.WriteEndElement();
// root
writer.WriteEndElement();
writer.WriteEndDocument();
}
```
This code produced desired output:
```
<?xml version="1.0" encoding="utf-8"?>
<root xmlns:abx="http://bladibla">
<abx:child id="A">
<grandchild id="B">
<abx:grandgrandchild />
</grandchild>
</abx:child>
</root>
``` |
26,760 | <p>I have some strings of xxh:yym format where xx is hours and yy is minutes like "05h:30m". What is an elegant way to convert a string of this type to TimeSpan?</p>
| [
{
"answer_id": 26769,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 6,
"selected": true,
"text": "<p>This seems to work, though it is a bit hackish:</p>\n\n<pre><code>TimeSpan span;\n\n\nif (TimeSpan.TryParse(\"05h:30m\".R... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] | I have some strings of xxh:yym format where xx is hours and yy is minutes like "05h:30m". What is an elegant way to convert a string of this type to TimeSpan? | This seems to work, though it is a bit hackish:
```
TimeSpan span;
if (TimeSpan.TryParse("05h:30m".Replace("m","").Replace("h",""), out span))
MessageBox.Show(span.ToString());
``` |
26,795 | <p>I have an extender (IExtenderProvider) which extends certain types of
controls with additional properties. For one of these properties, I have
written a UITypeEditor. So far, all works just fine.</p>
<p>The extender also has a couple of properties itself, which I am trying to
use as a sort of default for the UITypeEditor. What I want to do is to be
able to set a property on the extender itself (not the extended controls),
and when I open up the UITypeEditor for one of the additional properties on
an extended control, I want to set a value in the UITypeEditor to the value
of the property on the extender.</p>
<p>A simple example: The ExtenderProvider has a property DefaultExtendedValue. On the form I set the value of this property to "My Value". Extended controls have, through the provider, a property ExtendedValue with a UITypeEditor. When I open the editor for the property ExtendedValue the default (initial) value should be set to "My Value".</p>
<p>It seems to me that the best place to do this would be
UITypeEditor.EditValue, just before calling
IWindowsFormsEditorService.DropDownControl or .ShowDialog.</p>
<p>The only problem is that I can't (or I haven't discovered how to) get hold
of the extender provider itself in EditValue, to read the value of the property in question and set it in the UITypeEditor. Context gives me the extended
control, but that is of no use to me in this case.</p>
<p>Is there any way to achieve what I'm trying? Any help appreciated!</p>
<p>Thanks
Tom</p>
<hr>
<p>@samjudson: That's not a bad idea, but unfortunately it doesn't quite get me there. I'd really like to be able to set this default value individually for each instance of the extender provider. (I might have more than one on a single form with different values for different groups of extended controls.)</p>
| [
{
"answer_id": 30275,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 0,
"selected": false,
"text": "<p>Have you considered adding the DefaultValue as a static property of the ExtenderProvider, then you can access it without... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2899/"
] | I have an extender (IExtenderProvider) which extends certain types of
controls with additional properties. For one of these properties, I have
written a UITypeEditor. So far, all works just fine.
The extender also has a couple of properties itself, which I am trying to
use as a sort of default for the UITypeEditor. What I want to do is to be
able to set a property on the extender itself (not the extended controls),
and when I open up the UITypeEditor for one of the additional properties on
an extended control, I want to set a value in the UITypeEditor to the value
of the property on the extender.
A simple example: The ExtenderProvider has a property DefaultExtendedValue. On the form I set the value of this property to "My Value". Extended controls have, through the provider, a property ExtendedValue with a UITypeEditor. When I open the editor for the property ExtendedValue the default (initial) value should be set to "My Value".
It seems to me that the best place to do this would be
UITypeEditor.EditValue, just before calling
IWindowsFormsEditorService.DropDownControl or .ShowDialog.
The only problem is that I can't (or I haven't discovered how to) get hold
of the extender provider itself in EditValue, to read the value of the property in question and set it in the UITypeEditor. Context gives me the extended
control, but that is of no use to me in this case.
Is there any way to achieve what I'm trying? Any help appreciated!
Thanks
Tom
---
@samjudson: That's not a bad idea, but unfortunately it doesn't quite get me there. I'd really like to be able to set this default value individually for each instance of the extender provider. (I might have more than one on a single form with different values for different groups of extended controls.) | Could you read the attribute yourself?
```
DefaultValueAttribute att = context.
PropertyDescriptor.Attributes.
OfType<DefaultValueAttribute>().
FirstOrDefault();
object myDefault = null;
if ( att != null )
myDefault = att.Value;
```
I've used Linq to simplify the code, but you could do something similar back in .Net 1 |
26,796 | <p>What is the best way to use ResolveUrl() in a Shared/static function in Asp.Net? My current solution for VB.Net is:</p>
<pre><code>Dim x As New System.Web.UI.Control
x.ResolveUrl("~/someUrl")
</code></pre>
<p>Or C#:</p>
<pre><code>System.Web.UI.Control x = new System.Web.UI.Control();
x.ResolveUrl("~/someUrl");
</code></pre>
<p>But I realize that isn't the best way of calling it.</p>
| [
{
"answer_id": 26807,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 7,
"selected": true,
"text": "<p>I use <a href=\"http://msdn.microsoft.com/en-us/library/system.web.virtualpathutility.aspx\" rel=\"noreferrer\">System.Web.Vi... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
] | What is the best way to use ResolveUrl() in a Shared/static function in Asp.Net? My current solution for VB.Net is:
```
Dim x As New System.Web.UI.Control
x.ResolveUrl("~/someUrl")
```
Or C#:
```
System.Web.UI.Control x = new System.Web.UI.Control();
x.ResolveUrl("~/someUrl");
```
But I realize that isn't the best way of calling it. | I use [System.Web.VirtualPathUtility.ToAbsolute](http://msdn.microsoft.com/en-us/library/system.web.virtualpathutility.aspx). |
26,800 | <p>I'm using XPath in .NET to parse an XML document, along the lines of:</p>
<pre class="lang-cs prettyprint-override"><code>XmlNodeList lotsOStuff = doc.SelectNodes("//stuff");
foreach (XmlNode stuff in lotsOStuff) {
XmlNode stuffChild = stuff.SelectSingleNode("//stuffChild");
// ... etc
}
</code></pre>
<p>The issue is that the XPath Query for <code>stuffChild</code> is always returning the child of the first <code>stuff</code> element, never the rest. Can XPath not be used to query against an individual <code>XMLElement</code>?</p>
| [
{
"answer_id": 26805,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 4,
"selected": true,
"text": "<p><code>//</code> at the beginning of an XPath expression starts from the document root. Try \".//stuffChild\". . i... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | I'm using XPath in .NET to parse an XML document, along the lines of:
```cs
XmlNodeList lotsOStuff = doc.SelectNodes("//stuff");
foreach (XmlNode stuff in lotsOStuff) {
XmlNode stuffChild = stuff.SelectSingleNode("//stuffChild");
// ... etc
}
```
The issue is that the XPath Query for `stuffChild` is always returning the child of the first `stuff` element, never the rest. Can XPath not be used to query against an individual `XMLElement`? | `//` at the beginning of an XPath expression starts from the document root. Try ".//stuffChild". . is shorthand for self::node(), which will set the context for the search, and // is shorthand for the descendant axis.
So you have:
```
XmlNode stuffChild = stuff.SelectSingleNode(".//stuffChild");
```
which translates to:
xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild");
```
xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant-or-self::stuffChild");
```
In the case where the child node could have the same name as the parent, you would want to use the slightly more verbose syntax that follows, to ensure that you don't re-select the parent:
```
xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild");
```
Also note that if "stuffChild" is a direct descendant of "stuff", you can completely omit the prefixes, and just select "stuffChild".
```
XmlNode stuffChild = stuff.SelectSingleNode("stuffChild");
```
The [W3Schools](http://www.w3schools.com/xsl/xpath_syntax.asp) tutorial has helpful info in an easy to digest format. |
26,809 | <p>I frequently have problems dealing with <code>DataRows</code> returned from <code>SqlDataAdapters</code>. When I try to fill in an object using code like this:</p>
<pre><code>DataRow row = ds.Tables[0].Rows[0];
string value = (string)row;
</code></pre>
<p>What is the best way to deal with <code>DBNull's</code> in this type of situation.</p>
| [
{
"answer_id": 26832,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 6,
"selected": true,
"text": "<p>Nullable types are good, but only for types that are not nullable to begin with.</p>\n\n<p>To make a type \"nullable\" ap... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2191/"
] | I frequently have problems dealing with `DataRows` returned from `SqlDataAdapters`. When I try to fill in an object using code like this:
```
DataRow row = ds.Tables[0].Rows[0];
string value = (string)row;
```
What is the best way to deal with `DBNull's` in this type of situation. | Nullable types are good, but only for types that are not nullable to begin with.
To make a type "nullable" append a question mark to the type, for example:
```
int? value = 5;
```
I would also recommend using the "`as`" keyword instead of casting. You can only use the "as" keyword on nullable types, so make sure you're casting things that are already nullable (like strings) or you use nullable types as mentioned above. The reasoning for this is
1. If a type is nullable, the "`as`" keyword returns `null` if a value is `DBNull`.
2. It's [ever-so-slightly faster than casting](http://www.codeproject.com/Articles/8052/Type-casting-impact-over-execution-performance-in) though [only in certain cases](https://stackoverflow.com/a/496167/392). This on its own is never a good enough reason to use `as`, but coupled with the reason above it's useful.
I'd recommend doing something like this
```
DataRow row = ds.Tables[0].Rows[0];
string value = row as string;
```
In the case above, if `row` comes back as `DBNull`, then `value` will become `null` instead of throwing an exception. Be aware that if your DB query changes the columns/types being returned, **using `as` will cause your code to silently fail** and make values simple `null` instead of throwing the appropriate exception when incorrect data is returned so it is recommended that you have tests in place to validate your queries in other ways to ensure data integrity as your codebase evolves. |
26,825 | <p>I have a CollapsiblePanelExtender that will not collapse. I have "collapsed" set to true and all the ControlID set correctly. I try to collapse and it goes through the animation but then expands almost instantly. This is in an User Control with the following structure.</p>
<pre><code><asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="odsPartners" Width="450px" BorderWidth="0"
ShowHeader="false" ShowFooter="false" AllowSorting="true"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Contract Partners" SortExpression="Name">
<ItemTemplate>
<asp:Panel id="pnlRow" runat="server">
<table>
...Stuff...
</table>
</asp:Panel>
<ajaxToolkit:CollapsiblePanelExtender runat="server" ID="DDE"
Collapsed="true" ImageControlID="btnExpander" ExpandedImage="../Images/collapse.jpg" CollapsedImage="../Images/expand.jpg"
TargetControlID="DropPanel" CollapseControlID="btnExpander" ExpandControlID="btnExpander" />
<asp:Panel ID="DropPanel" runat="server" CssClass="CollapsedPanel">
<asp:Table ID="tblContracts" runat="server">
<asp:TableRow ID="row" runat="server">
<asp:TableCell ID="spacer" runat="server" Width="30">&nbsp;</asp:TableCell>
<asp:TableCell ID="cellData" runat="server" Width="400">
<uc1:ContractList ID="ContractList1" runat="server" PartnerID='<%# Bind("ID") %>' />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tbFilter" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
</code></pre>
| [
{
"answer_id": 26912,
"author": "Ian Patrick Hughes",
"author_id": 2213,
"author_profile": "https://Stackoverflow.com/users/2213",
"pm_score": 3,
"selected": true,
"text": "<p>I am sorry I do not have time to trouble-shoot your code, so this is from the hip.</p>\n\n<p>There is a good cha... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2894/"
] | I have a CollapsiblePanelExtender that will not collapse. I have "collapsed" set to true and all the ControlID set correctly. I try to collapse and it goes through the animation but then expands almost instantly. This is in an User Control with the following structure.
```
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="odsPartners" Width="450px" BorderWidth="0"
ShowHeader="false" ShowFooter="false" AllowSorting="true"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Contract Partners" SortExpression="Name">
<ItemTemplate>
<asp:Panel id="pnlRow" runat="server">
<table>
...Stuff...
</table>
</asp:Panel>
<ajaxToolkit:CollapsiblePanelExtender runat="server" ID="DDE"
Collapsed="true" ImageControlID="btnExpander" ExpandedImage="../Images/collapse.jpg" CollapsedImage="../Images/expand.jpg"
TargetControlID="DropPanel" CollapseControlID="btnExpander" ExpandControlID="btnExpander" />
<asp:Panel ID="DropPanel" runat="server" CssClass="CollapsedPanel">
<asp:Table ID="tblContracts" runat="server">
<asp:TableRow ID="row" runat="server">
<asp:TableCell ID="spacer" runat="server" Width="30"> </asp:TableCell>
<asp:TableCell ID="cellData" runat="server" Width="400">
<uc1:ContractList ID="ContractList1" runat="server" PartnerID='<%# Bind("ID") %>' />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tbFilter" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
``` | I am sorry I do not have time to trouble-shoot your code, so this is from the hip.
There is a good chance that this a client-side action that is failing. Make certain that your page has the correct doctype tag if you took it out of your page or masterPage. Furthermore, attempt to set the ClientState as well:
DDE.ClientState = true;
The issue is you have that thing wrapped inside of your TemplateField. I have ran into issues using the AjaxControlToolkit on repeated fields and usually side with using a lighter weight client-side option, up to and including rolling your own show/hide method that can be reused just by passing in an DOM understood id. |
26,842 | <p>I'm attempting to use an existing CAS server to authenticate login for a Perl CGI web script and am using the <a href="http://search.cpan.org/dist/AuthCAS" rel="nofollow noreferrer">AuthCAS</a> Perl module (v 1.3.1). I can connect to the CAS server to get the service ticket but when I try to connect to validate the ticket my script returns with the following error from the <a href="http://search.cpan.org/dist/IO-Socket-SSL" rel="nofollow noreferrer">IO::Socket::SSL</a> module:</p>
<pre><code> 500 Can't connect to [CAS Server]:443 (Bad hostname '[CAS Server]')
([CAS Server] substituted for real server name)
</code></pre>
<p>Symptoms/Tests:</p>
<ol>
<li>If I type the generated URL for the authentication into the web browser's location bar it returns just fine with the expected XML snippet. So it is not a bad host name.</li>
<li>If I generate a script without using the AuthCAS module but using the IO::Socket::SSL module directly to query the CAS server for validation on the generated service ticket the Perl script will run fine from the command line but not in the browser.</li>
<li>If I add the AuthCAS module into the script in item 2, the script no longer works on the command line and still doesn't work in the browser.</li>
</ol>
<p>Here is the bare-bones script that produces the error:</p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use CGI;
use AuthCAS;
use CGI::Carp qw( fatalsToBrowser );
my $id = $ENV{QUERY_STRING};
my $q = new CGI;
my $target = "http://localhost/cgi-bin/testCAS.cgi";
my $cas = new AuthCAS(casUrl => 'https://cas_server/cas');
if ($id eq ""){
my $login_url = $cas->getServerLoginURL($target);
printf "Location: $login_url\n\n";
exit 0;
} else {
print $q->header();
print "CAS TEST<br>\n";
## When coming back from the CAS server a ticket is provided in the QUERY_STRING
print "QUERY_STRING = " . $id . "</br>\n";
## $ST should contain the received Service Ticket
my $ST = $q->param('ticket');
my $user = $cas->validateST($target, $ST); #### This is what fails
printf "Error: %s\n", &AuthCAS::get_errors() unless (defined $user);
}
</code></pre>
<p>Any ideas on where the conflict might be?</p>
<hr>
<p>The error is coming from the line directly above the snippet Cebjyre quoted namely</p>
<pre><code>$ssl_socket = new IO::Socket::SSL(%ssl_options);
</code></pre>
<p>namely the socket creation. All of the input parameters are correct. I had edited the module to put in debug statements and print out all the parameters just before that call and they are all fine. Looks like I'm going to have to dive deeper into the IO::Socket::SSL module.</p>
| [
{
"answer_id": 27602,
"author": "Cebjyre",
"author_id": 1612,
"author_profile": "https://Stackoverflow.com/users/1612",
"pm_score": -1,
"selected": false,
"text": "<p>Well, from the <a href=\"http://search.cpan.org/src/OSALAUN/AuthCAS-1.3.1/lib/AuthCAS.pm\" rel=\"nofollow noreferrer\">mo... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/171/"
] | I'm attempting to use an existing CAS server to authenticate login for a Perl CGI web script and am using the [AuthCAS](http://search.cpan.org/dist/AuthCAS) Perl module (v 1.3.1). I can connect to the CAS server to get the service ticket but when I try to connect to validate the ticket my script returns with the following error from the [IO::Socket::SSL](http://search.cpan.org/dist/IO-Socket-SSL) module:
```
500 Can't connect to [CAS Server]:443 (Bad hostname '[CAS Server]')
([CAS Server] substituted for real server name)
```
Symptoms/Tests:
1. If I type the generated URL for the authentication into the web browser's location bar it returns just fine with the expected XML snippet. So it is not a bad host name.
2. If I generate a script without using the AuthCAS module but using the IO::Socket::SSL module directly to query the CAS server for validation on the generated service ticket the Perl script will run fine from the command line but not in the browser.
3. If I add the AuthCAS module into the script in item 2, the script no longer works on the command line and still doesn't work in the browser.
Here is the bare-bones script that produces the error:
```
#!/usr/bin/perl
use strict;
use warnings;
use CGI;
use AuthCAS;
use CGI::Carp qw( fatalsToBrowser );
my $id = $ENV{QUERY_STRING};
my $q = new CGI;
my $target = "http://localhost/cgi-bin/testCAS.cgi";
my $cas = new AuthCAS(casUrl => 'https://cas_server/cas');
if ($id eq ""){
my $login_url = $cas->getServerLoginURL($target);
printf "Location: $login_url\n\n";
exit 0;
} else {
print $q->header();
print "CAS TEST<br>\n";
## When coming back from the CAS server a ticket is provided in the QUERY_STRING
print "QUERY_STRING = " . $id . "</br>\n";
## $ST should contain the received Service Ticket
my $ST = $q->param('ticket');
my $user = $cas->validateST($target, $ST); #### This is what fails
printf "Error: %s\n", &AuthCAS::get_errors() unless (defined $user);
}
```
Any ideas on where the conflict might be?
---
The error is coming from the line directly above the snippet Cebjyre quoted namely
```
$ssl_socket = new IO::Socket::SSL(%ssl_options);
```
namely the socket creation. All of the input parameters are correct. I had edited the module to put in debug statements and print out all the parameters just before that call and they are all fine. Looks like I'm going to have to dive deeper into the IO::Socket::SSL module. | As usually happens when I post questions like this, I found the problem. It turns out the [Crypt::SSLeay](http://search.cpan.org/dist/Crypt-SSLeay) module was not installed or at least not up to date. Of course the error messages didn't give me any clues. Updating it and all the problems go away and things are working fine now. |
26,855 | <p>I'm currently using the module <code>URI::URL</code> to generate a full URL from a relative URL; however, it isn't running as fast as I'd like it to be. Does anyone know another way to do this that may be faster?</p>
| [
{
"answer_id": 26894,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps I got the wrong end of the stick but wouldn't,</p>\n\n<pre><code>$full_url = $base_url . $relative_url</code></pre>\... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2901/"
] | I'm currently using the module `URI::URL` to generate a full URL from a relative URL; however, it isn't running as fast as I'd like it to be. Does anyone know another way to do this that may be faster? | The following code should work.
```
$uri = URI->new_abs( $str, $base_uri )
```
You should also take a look at [the URI page on search.cpan.org](http://search.cpan.org/dist/URI/URI.pm). |
26,857 | <p>Using C# and ASP.NET I want to programmatically fill in some values (4 text boxes) on a web page (form) and then 'POST' those values. How do I do this?</p>
<p>Edit: Clarification: There is a service (www.stopforumspam.com) where you can submit ip, username and email address on their 'add' page. I want to be able to create a link/button on my site's page that will fill in those values and submit the info without having to copy/paste them across and click the submit button.</p>
<p>Further clarification: How do automated spam bots fill out forms and click the submit button if they were written in C#?</p>
| [
{
"answer_id": 26881,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 7,
"selected": true,
"text": "<p>The code will look something like this: </p>\n\n<pre><code>WebRequest req = WebRequest.Create(\"http://mysite/myform.a... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] | Using C# and ASP.NET I want to programmatically fill in some values (4 text boxes) on a web page (form) and then 'POST' those values. How do I do this?
Edit: Clarification: There is a service (www.stopforumspam.com) where you can submit ip, username and email address on their 'add' page. I want to be able to create a link/button on my site's page that will fill in those values and submit the info without having to copy/paste them across and click the submit button.
Further clarification: How do automated spam bots fill out forms and click the submit button if they were written in C#? | The code will look something like this:
```
WebRequest req = WebRequest.Create("http://mysite/myform.aspx");
string postData = "item1=11111&item2=22222&Item3=33333";
byte[] send = Encoding.Default.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = send.Length;
Stream sout = req.GetRequestStream();
sout.Write(send, 0, send.Length);
sout.Flush();
sout.Close();
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
``` |
26,877 | <p>In C#, what is the difference (if any) between these two lines of code?</p>
<pre><code>tmrMain.Elapsed += new ElapsedEventHandler(tmrMain_Tick);
</code></pre>
<p>and</p>
<pre><code>tmrMain.Elapsed += tmrMain_Tick;
</code></pre>
<p>Both appear to work exactly the same. Does C# just assume you mean the former when you type the latter?</p>
| [
{
"answer_id": 26884,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 6,
"selected": true,
"text": "<p>I did this</p>\n\n<pre><code>static void Hook1()\n{\n someEvent += new EventHandler( Program_someEvent );\n}\n\nstat... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369/"
] | In C#, what is the difference (if any) between these two lines of code?
```
tmrMain.Elapsed += new ElapsedEventHandler(tmrMain_Tick);
```
and
```
tmrMain.Elapsed += tmrMain_Tick;
```
Both appear to work exactly the same. Does C# just assume you mean the former when you type the latter? | I did this
```
static void Hook1()
{
someEvent += new EventHandler( Program_someEvent );
}
static void Hook2()
{
someEvent += Program_someEvent;
}
```
And then ran ildasm over the code.
The generated MSIL was exactly the same.
So to answer your question, yes they are the same thing.
The compiler is just inferring that you want `someEvent += new EventHandler( Program_someEvent );`
-- You can see it creating the new `EventHandler` object in both cases in the MSIL |
26,879 | <p>I have a website that is perfectely centered aligned. The CSS code works fine. The problem doesn't really have to do with CSS. I have headers for each page that perfectely match eachother.</p>
<p>However, when the content gets larger, Opera and FireFox show a scrollbar at the left so you can scroll to the content not on the screen. This makes my site jump a few pixels to the left. Thus the headers are not perfectely aligned anymore.</p>
<p>IE always has a scrollbar, so the site never jumps around in IE. </p>
<p>Does anyone know a JavaScript/CSS/HTML solution for this problem?</p>
| [
{
"answer_id": 26891,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 0,
"selected": false,
"text": "<p>Are you aligning with percentage widths or fixed widths? I'm also guessing you're applying a background to the body - I've ha... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a website that is perfectely centered aligned. The CSS code works fine. The problem doesn't really have to do with CSS. I have headers for each page that perfectely match eachother.
However, when the content gets larger, Opera and FireFox show a scrollbar at the left so you can scroll to the content not on the screen. This makes my site jump a few pixels to the left. Thus the headers are not perfectely aligned anymore.
IE always has a scrollbar, so the site never jumps around in IE.
Does anyone know a JavaScript/CSS/HTML solution for this problem? | I use
```
html { overflow-y: scroll; }
```
To standardize the scrollbar behavior in IE and FF |
26,882 | <p>My asp.net page will render different controls based on which report a user has selected e.g. some reports require 5 drop downs, some two checkboxes and 6 dropdowns).</p>
<p>They can select a report using two methods. With <code>SelectedReport=MyReport</code> in the query string, or by selecting it from a dropdown. And it's a common case for them to come to the page with SelectedReport in the query string, and then change the report selected in the drop down.</p>
<p>My question is, is there anyway of making the dropdown modify the query string when it's selected. So I'd want <code>SelectedReport=MyNewReport</code> in the query string and the page to post back.</p>
<p>At the moment it's just doing a normal postback, which leaves the <code>SelectedReport=MyReport</code> in the query string, even if it's not the currently selected report.</p>
<p><strong>Edit:</strong> And I also need to preserve ViewState.</p>
<p>I've tried doing <code>Server.Transfer(Request.Path + "?SelectedReport=" + SelectedReport, true)</code> in the event handler for the Dropdown, and this works function wise, unfortunately because it's a Server.Transfer (to preserve ViewState) instead of a Response.Redirect the URL lags behind what's shown.</p>
<p>Maybe I'm asking the impossible or going about it completely the wrong way. </p>
<p><strong>@Craig</strong> The QueryString collection is read-only and cannot be modified.<br>
<strong>@Jason</strong> That would be great, except I'd lose the ViewState wouldn't I? (Sorry I added that after seeing your response).</p>
| [
{
"answer_id": 26902,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If it's an automatic post when the data changes then you should be able to redirect to the new query string with a server si... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233/"
] | My asp.net page will render different controls based on which report a user has selected e.g. some reports require 5 drop downs, some two checkboxes and 6 dropdowns).
They can select a report using two methods. With `SelectedReport=MyReport` in the query string, or by selecting it from a dropdown. And it's a common case for them to come to the page with SelectedReport in the query string, and then change the report selected in the drop down.
My question is, is there anyway of making the dropdown modify the query string when it's selected. So I'd want `SelectedReport=MyNewReport` in the query string and the page to post back.
At the moment it's just doing a normal postback, which leaves the `SelectedReport=MyReport` in the query string, even if it's not the currently selected report.
**Edit:** And I also need to preserve ViewState.
I've tried doing `Server.Transfer(Request.Path + "?SelectedReport=" + SelectedReport, true)` in the event handler for the Dropdown, and this works function wise, unfortunately because it's a Server.Transfer (to preserve ViewState) instead of a Response.Redirect the URL lags behind what's shown.
Maybe I'm asking the impossible or going about it completely the wrong way.
**@Craig** The QueryString collection is read-only and cannot be modified.
**@Jason** That would be great, except I'd lose the ViewState wouldn't I? (Sorry I added that after seeing your response). | You need to turn off autopostback on the dropdown - then, you need to hook up some javascript code that will take over that role - in the event handler code for the onchange event for the dropdown, you would create a URL based on the currently-selected value from the dropdown and use javascript to then request that page.
EDIT: Here is some quick and dirty code that is indicative of what would do the trick:
```
<script>
function changeReport(dropDownList) {
var selectedReport = dropDownList.options[dropDownList.selectedIndex];
window.location = ("scratch.htm?SelectedReport=" + selectedReport.value);
}
</script>
<select id="SelectedReport" onchange="changeReport(this)">
<option value="foo">foo</option>
<option value="bar">bar</option>
<option value="baz">baz</option>
</select>
```
Obviously you would need to do a bit more, but this does work and would give you what it seems you are after. I would recommend using a JavaScript toolkit (I use MochiKit, but it isn't for everyone) to get some of the harder work done - use unobtrusive JavaScript techniques if at all possible (unlike what I use in this example).
**@Ray:** You use ViewState?! I'm so sorry. :P Why, in this instance, do you need to preserve it. pray tell? |
26,903 | <p>Is there a way?</p>
<p>I need all types that implement a specific interface to have a parameterless constructor, can it be done?</p>
<p>I am developing the base code for other developers in my company to use in a specific project.</p>
<p>There's a proccess which will create instances of types (in different threads) that perform certain tasks, and I need those types to follow a specific contract (ergo, the interface).</p>
<p>The interface will be internal to the assembly</p>
<p>If you have a suggestion for this scenario without interfaces, I'll gladly take it into consideration...</p>
| [
{
"answer_id": 26909,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think so. </p>\n\n<p>You also can't use an abstract class for this.</p>\n"
},
{
"answer_id": 26928,
"aut... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] | Is there a way?
I need all types that implement a specific interface to have a parameterless constructor, can it be done?
I am developing the base code for other developers in my company to use in a specific project.
There's a proccess which will create instances of types (in different threads) that perform certain tasks, and I need those types to follow a specific contract (ergo, the interface).
The interface will be internal to the assembly
If you have a suggestion for this scenario without interfaces, I'll gladly take it into consideration... | [Juan Manuel said:](https://stackoverflow.com/questions/26903/how-can-you-require-a-constructor-with-no-parameters-for-types-implementing-an#27386)
>
> that's one of the reasons I don't understand why it cannot be a part of the contract in the interface
>
>
>
It's an indirect mechanism. The generic allows you to "cheat" and send type information along with the interface. The critical thing to remember here is that the constraint isn't on the interface that you are working with directly. It's not a constraint on the interface itself, but on some other type that will "ride along" on the interface. This is the best explanation I can offer, I'm afraid.
By way of illustration of this fact, I'll point out a hole that I have noticed in aku's code. It's possible to write a class that would compile fine but fail at runtime when you try to instantiate it:
```
public class Something : ITest<String>
{
private Something() { }
}
```
Something derives from ITest<T>, but implements no parameterless constructor. It will compile fine, because String does implement a parameterless constructor. Again, the constraint is on T, and therefore String, rather than ITest or Something. Since the constraint on T is satisfied, this will compile. But it will fail at runtime.
To prevent **some** instances of this problem, you need to add another constraint to T, as below:
```
public interface ITest<T>
where T : ITest<T>, new()
{
}
```
Note the new constraint: T : ITest<T>. This constraint specifies that what you pass into the argument parameter of ITest<T> **must** also **derive** from ITest<T>.
Even so this will not prevent **all** cases of the hole. The code below will compile fine, because A has a parameterless constructor. But since B's parameterless constructor is private, instantiating B with your process will fail at runtime.
```
public class A : ITest<A>
{
}
public class B : ITest<A>
{
private B() { }
}
``` |
26,947 | <p>What built-in PHP functions are useful for web scraping? What are some good resources (web or print) for getting up to speed on web scraping with PHP?</p>
| [
{
"answer_id": 26951,
"author": "Peter Stuifzand",
"author_id": 1633,
"author_profile": "https://Stackoverflow.com/users/1633",
"pm_score": -1,
"selected": false,
"text": "<p>The curl library allows you to download web pages. You should look into regular expressions for doing the scrapin... | 2008/08/25 | [
"https://Stackoverflow.com/questions/26947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2052/"
] | What built-in PHP functions are useful for web scraping? What are some good resources (web or print) for getting up to speed on web scraping with PHP? | Scraping generally encompasses 3 steps:
* first you GET or POST your request
to a specified URL
* next you receive
the html that is returned as the
response
* finally you parse out of
that html the text you'd like to
scrape.
To accomplish steps 1 and 2, below is a simple php class which uses Curl to fetch webpages using either GET or POST. After you get the HTML back, you just use Regular Expressions to accomplish step 3 by parsing out the text you'd like to scrape.
For regular expressions, my favorite tutorial site is the following:
[Regular Expressions Tutorial](http://www.regular-expressions.info/)
My Favorite program for working with RegExs is [Regex Buddy](http://www.regexbuddy.com/). I would advise you to try the demo of that product even if you have no intention of buying it. It is an invaluable tool and will even generate code for your regexs you make in your language of choice (including php).
Usage:
$curl = new Curl();
$html = $curl->get("<http://www.google.com>");
// now, do your regex work against $html
PHP Class:
```
<?php
class Curl
{
public $cookieJar = "";
public function __construct($cookieJarFile = 'cookies.txt') {
$this->cookieJar = $cookieJarFile;
}
function setup()
{
$header = array();
$header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
$header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
$header[] = "Cache-Control: max-age=0";
$header[] = "Connection: keep-alive";
$header[] = "Keep-Alive: 300";
$header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
$header[] = "Accept-Language: en-us,en;q=0.5";
$header[] = "Pragma: "; // browsers keep this blank.
curl_setopt($this->curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7');
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($this->curl,CURLOPT_COOKIEJAR, $this->cookieJar);
curl_setopt($this->curl,CURLOPT_COOKIEFILE, $this->cookieJar);
curl_setopt($this->curl,CURLOPT_AUTOREFERER, true);
curl_setopt($this->curl,CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->curl,CURLOPT_RETURNTRANSFER, true);
}
function get($url)
{
$this->curl = curl_init($url);
$this->setup();
return $this->request();
}
function getAll($reg,$str)
{
preg_match_all($reg,$str,$matches);
return $matches[1];
}
function postForm($url, $fields, $referer='')
{
$this->curl = curl_init($url);
$this->setup();
curl_setopt($this->curl, CURLOPT_URL, $url);
curl_setopt($this->curl, CURLOPT_POST, 1);
curl_setopt($this->curl, CURLOPT_REFERER, $referer);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $fields);
return $this->request();
}
function getInfo($info)
{
$info = ($info == 'lasturl') ? curl_getinfo($this->curl, CURLINFO_EFFECTIVE_URL) : curl_getinfo($this->curl, $info);
return $info;
}
function request()
{
return curl_exec($this->curl);
}
}
?>
``` |
27,020 | <p>I have an Excel Spreadsheet like this</p>
<pre>
id | data for id
| more data for id
id | data for id
id | data for id
| more data for id
| even more data for id
id | data for id
| more data for id
id | data for id
id | data for id
| more data for id
</pre>
<p>Now I want to group the data of one id by alternating the background color of the rows</p>
<pre>
var color = white
for each row
if the first cell is not empty and color is white
set color to green
if the first cell is not empty and color is green
set color to white
set background of row to color
</pre>
<p>Can anyone help me with a macro or some VBA code</p>
<p>Thanks</p>
| [
{
"answer_id": 27043,
"author": "Daniel Pollard",
"author_id": 2758,
"author_profile": "https://Stackoverflow.com/users/2758",
"pm_score": 0,
"selected": false,
"text": "<p>If you select the Conditional Formatting menu option under the Format menu item, you will be given a dialog that le... | 2008/08/25 | [
"https://Stackoverflow.com/questions/27020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2798/"
] | I have an Excel Spreadsheet like this
```
id | data for id
| more data for id
id | data for id
id | data for id
| more data for id
| even more data for id
id | data for id
| more data for id
id | data for id
id | data for id
| more data for id
```
Now I want to group the data of one id by alternating the background color of the rows
```
var color = white
for each row
if the first cell is not empty and color is white
set color to green
if the first cell is not empty and color is green
set color to white
set background of row to color
```
Can anyone help me with a macro or some VBA code
Thanks | I think this does what you are looking for. Flips color when the cell in column A changes value. Runs until there is no value in column B.
```
Public Sub HighLightRows()
Dim i As Integer
i = 1
Dim c As Integer
c = 3 'red
Do While (Cells(i, 2) <> "")
If (Cells(i, 1) <> "") Then 'check for new ID
If c = 3 Then
c = 4 'green
Else
c = 3 'red
End If
End If
Rows(Trim(Str(i)) + ":" + Trim(Str(i))).Interior.ColorIndex = c
i = i + 1
Loop
End Sub
``` |
27,030 | <p>I want to compare 2 arrays of objects in JavaScript code. The objects have 8 total properties, but each object will not have a value for each, and the arrays are never going to be any larger than 8 items each, so maybe the brute force method of traversing each and then looking at the values of the 8 properties is the easiest way to do what I want to do, but before implementing, I wanted to see if anyone had a more elegant solution. Any thoughts?</p>
| [
{
"answer_id": 27212,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 7,
"selected": true,
"text": "<p>EDIT: You cannot overload operators in current, common browser-based implementations of JavaScript interpreters.</p>\... | 2008/08/25 | [
"https://Stackoverflow.com/questions/27030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2176/"
] | I want to compare 2 arrays of objects in JavaScript code. The objects have 8 total properties, but each object will not have a value for each, and the arrays are never going to be any larger than 8 items each, so maybe the brute force method of traversing each and then looking at the values of the 8 properties is the easiest way to do what I want to do, but before implementing, I wanted to see if anyone had a more elegant solution. Any thoughts? | EDIT: You cannot overload operators in current, common browser-based implementations of JavaScript interpreters.
To answer the original question, one way you could do this, and mind you, this is a bit of a hack, simply [serialize the two arrays to JSON](https://github.com/douglascrockford/JSON-js/blob/master/json2.js) and then compare the two JSON strings. That would simply tell you if the arrays are different, obviously you could do this to *each* of the objects within the arrays as well to see which ones were different.
Another option is to use a library which has some nice facilities for comparing objects - I use and recommend [**MochiKit**](http://www.mochikit.com/).
---
**EDIT:** [The answer kamens gave](https://stackoverflow.com/questions/27030/comparing-arrays-of-objects-in-javascript#27932) deserves consideration as well, since a single function to compare two given objects would be much smaller than any library to do what I suggest (although my suggestion would certainly work well enough).
Here is a naïve implemenation that may do just enough for you - be aware that there are potential problems with this implementation:
```
function objectsAreSame(x, y) {
var objectsAreSame = true;
for(var propertyName in x) {
if(x[propertyName] !== y[propertyName]) {
objectsAreSame = false;
break;
}
}
return objectsAreSame;
}
```
The assumption is that both objects have the same exact list of properties.
Oh, and it is probably obvious that, for better or worse, I belong to the only-one-return-point camp. :) |
27,034 | <p>My JavaScript is pretty nominal, so when I saw this construction, I was kind of baffled:</p>
<pre><code>var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings");
shareProxiesPref.disabled = proxyTypePref.value != 1;
</code></pre>
<p>Isn't it better to do an if on <code>proxyTypePref.value</code>, and then declare the var inside the result, only if you need it?</p>
<p>(Incidentally, I also found this form very hard to read in comparison to the normal usage. There were a set of two or three of these conditionals, instead of doing a single if with a block of statements in the result.)</p>
<hr>
<p><strong>UPDATE:</strong></p>
<p>The responses were very helpful and asked for more context. The code fragment is from Firefox 3, so you can see the code here:</p>
<p><a href="http://mxr.mozilla.org/firefox/source/browser/components/preferences/connection.js" rel="nofollow noreferrer">http://mxr.mozilla.org/firefox/source/browser/components/preferences/connection.js</a></p>
<p>Basically, when you look at the <strong>Connect</strong> preferences window in Firefox, clicking the proxy <strong>modes</strong> (radio buttons), causes various form elements to enable|disable.</p>
| [
{
"answer_id": 27039,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>(Incidentally, I also found this form very hard to read in comparison to the normal usage.</p>\n</b... | 2008/08/25 | [
"https://Stackoverflow.com/questions/27034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | My JavaScript is pretty nominal, so when I saw this construction, I was kind of baffled:
```
var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings");
shareProxiesPref.disabled = proxyTypePref.value != 1;
```
Isn't it better to do an if on `proxyTypePref.value`, and then declare the var inside the result, only if you need it?
(Incidentally, I also found this form very hard to read in comparison to the normal usage. There were a set of two or three of these conditionals, instead of doing a single if with a block of statements in the result.)
---
**UPDATE:**
The responses were very helpful and asked for more context. The code fragment is from Firefox 3, so you can see the code here:
<http://mxr.mozilla.org/firefox/source/browser/components/preferences/connection.js>
Basically, when you look at the **Connect** preferences window in Firefox, clicking the proxy **modes** (radio buttons), causes various form elements to enable|disable. | It depends on the context of this code. If it's running on page load, then it would be better to put this code in an if block.
But, if this is part of a validation function, and the field switches between enabled and disabled throughout the life of the page, then this code sort of makes sense.
It's important to remember that setting disabled to false also alters page state. |
27,044 | <p>I'm accessing an Ubuntu machine using PuTTY, and using gcc.</p>
<p>The default <code>LANG</code> environment variable on this machine is set to <code>en_NZ.UTF-8</code>, which causes GCC to think PuTTY is capable of displaying UTF-8 text, which it doesn't seem to be.
Maybe it's my font, I don't know - it does this:</p>
<pre><code>foo.c:1: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â at end of input
</code></pre>
<p>If I set it with <code>export LANG=en_NZ</code>, then this causes GCC to behave correctly, I get:</p>
<pre><code>foo.c:1: error: expected '=', ',', ';', 'asm' or '__attribute__' at end of input
</code></pre>
<p>but this then causes everything else to go wrong. For example</p>
<pre><code>man foo
man: can't set the locale; make sure $LC_* and $LANG are correct
</code></pre>
<p>I've trawled Google and I can't for the life of me find out what I have to put in there for it to just use ASCII. <code>en_NZ.ASCII</code> doesn't work, nor do any of the other things I can find.</p>
<p>Thanks</p>
| [
{
"answer_id": 27051,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": true,
"text": "<p><code>LANG=en_NZ</code> is correct. However, you must make locale files for <code>en_NZ</code>.</p>\n\n<p>For Ubuntu, edit ... | 2008/08/25 | [
"https://Stackoverflow.com/questions/27044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
] | I'm accessing an Ubuntu machine using PuTTY, and using gcc.
The default `LANG` environment variable on this machine is set to `en_NZ.UTF-8`, which causes GCC to think PuTTY is capable of displaying UTF-8 text, which it doesn't seem to be.
Maybe it's my font, I don't know - it does this:
```
foo.c:1: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â at end of input
```
If I set it with `export LANG=en_NZ`, then this causes GCC to behave correctly, I get:
```
foo.c:1: error: expected '=', ',', ';', 'asm' or '__attribute__' at end of input
```
but this then causes everything else to go wrong. For example
```
man foo
man: can't set the locale; make sure $LC_* and $LANG are correct
```
I've trawled Google and I can't for the life of me find out what I have to put in there for it to just use ASCII. `en_NZ.ASCII` doesn't work, nor do any of the other things I can find.
Thanks | `LANG=en_NZ` is correct. However, you must make locale files for `en_NZ`.
For Ubuntu, edit `/var/lib/locales/supported.d/local` and add `en_NZ ISO-8859-1` to the file. If your system is another distribution (including Debian), the location will be different. Look at `/usr/sbin/locale-gen` and see where it stores this info.
Afterwards, run `locale-gen` to create the `en_NZ` locale file. Hope this helps! |
27,065 | <p>Do any of you know of a tool that will search for .class files and then display their compiled versions?</p>
<p>I know you can look at them individually in a hex editor but I have a lot of class files to look over (something in my giant application is compiling to Java6 for some reason).</p>
| [
{
"answer_id": 27123,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 6,
"selected": false,
"text": "<p>It is easy enough to read the <a href=\"http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.1\" rel=\"nore... | 2008/08/25 | [
"https://Stackoverflow.com/questions/27065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] | Do any of you know of a tool that will search for .class files and then display their compiled versions?
I know you can look at them individually in a hex editor but I have a lot of class files to look over (something in my giant application is compiling to Java6 for some reason). | Use the [javap](http://java.sun.com/javase/6/docs/technotes/tools/solaris/javap.html) tool that comes with the JDK. The `-verbose` option will print the version number of the class file.
```
> javap -verbose MyClass
Compiled from "MyClass.java"
public class MyClass
SourceFile: "MyClass.java"
minor version: 0
major version: 46
...
```
To only show the version:
```
WINDOWS> javap -verbose MyClass | find "version"
LINUX > javap -verbose MyClass | grep version
``` |
27,071 | <p>I have an old C library with a function that takes a void**:</p>
<pre><code>oldFunction(void** pStuff);
</code></pre>
<p>I'm trying to call this function from managed C++ (m_pStuff is a member of the parent ref class of type void*):</p>
<pre><code>oldFunction( static_cast<sqlite3**>( &m_pStuff ) );
</code></pre>
<p>This gives me the following error from Visual Studio:</p>
<blockquote>
<p>error C2440: 'static_cast' : cannot convert from 'cli::interior_ptr' to 'void **'</p>
</blockquote>
<p>I'm guessing the compiler is converting the void* member pointer to a cli::interior_ptr behind my back.</p>
<p>Any advice on how to do this?</p>
| [
{
"answer_id": 27326,
"author": "Ben Childs",
"author_id": 2925,
"author_profile": "https://Stackoverflow.com/users/2925",
"pm_score": 2,
"selected": true,
"text": "<p>EDIT: Fixed answer, see below.</p>\n\n<p>Really you need to know what oldFunction is going to be doing with pStuff. If p... | 2008/08/25 | [
"https://Stackoverflow.com/questions/27071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39040/"
] | I have an old C library with a function that takes a void\*\*:
```
oldFunction(void** pStuff);
```
I'm trying to call this function from managed C++ (m\_pStuff is a member of the parent ref class of type void\*):
```
oldFunction( static_cast<sqlite3**>( &m_pStuff ) );
```
This gives me the following error from Visual Studio:
>
> error C2440: 'static\_cast' : cannot convert from 'cli::interior\_ptr' to 'void \*\*'
>
>
>
I'm guessing the compiler is converting the void\* member pointer to a cli::interior\_ptr behind my back.
Any advice on how to do this? | EDIT: Fixed answer, see below.
Really you need to know what oldFunction is going to be doing with pStuff. If pStuff is a pointer to some unmanaged data you can try wrapping the definition of m\_pStuff with:
```
#pragma unmanaged
void* m_pStuff
#pragma managed
```
This will make the pointer unmanaged which can then be passed into unmanaged functions. Of course you will not be able to assign any managed objects to this pointer directly.
Fundamentally unmanaged and managed pointers are not the same and can't be converted without some sort of glue code that copies the underlying data. Basically managed pointers point to the managed heap and since this is garbage collected the actual memory address they point to can change over time. Unmanaged pointers do not change the memory address without you explicitly doing so.
Scratch that, you can't define unmanaged / managed inside a class definition. But this test code seems to work just fine:
```
// TestSol.cpp : main project file.
#include "stdafx.h"
using namespace System;
#pragma unmanaged
void oldFunction(void** pStuff)
{
return;
}
#pragma managed
ref class Test
{
public:
void* m_test;
};
int main(array<System::String ^> ^args)
{
Console::WriteLine(L"Hello World");
Test^ test = gcnew Test();
void* pStuff = test->m_test;
oldFunction(&pStuff);
test->m_test = pStuff;
return 0;
}
```
Here I copy the pointer out of the managed object first and then pass that in by to the oldFunction. Then I copy the result (probably updated by oldFunction) back into the managed object. Since the managed object is on the managed heap, the compiler won't let you pass a reference to the pointer contained in that object as it may move when the garbage collector runs. |
27,077 | <p>When I do:</p>
<pre><code>$ find /
</code></pre>
<p>It searches the entire system.<br>
How do I prevent that?</p>
<p>(This question comes from an "<a href="https://stackoverflow.com/questions/18836/why-doesnt-find-find-anything#26182">answer</a>" to another question.)</p>
| [
{
"answer_id": 27080,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 0,
"selected": false,
"text": "<p>Use the <strong>-prune</strong> option.</p>\n"
},
{
"answer_id": 27084,
"author": "Jon Ericson",
"auth... | 2008/08/25 | [
"https://Stackoverflow.com/questions/27077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1438/"
] | When I do:
```
$ find /
```
It searches the entire system.
How do I prevent that?
(This question comes from an "[answer](https://stackoverflow.com/questions/18836/why-doesnt-find-find-anything#26182)" to another question.) | G'day,
Just wanted to expand on the suggestion from Jon to use -prune. It isn't the easiest of find options to use, for example to just search in the current directory the find command looks like:
```
find . \( -type d ! -name . -prune \) -o \( <the bit you want to look for> \)
```
this will stop find from descending into sub-directories within this directory.
Basically, it says, "prune anything that is a directory, whose name isn't ".", i.e. current dir."
The find command evals left to right for each item found in the current directory so after completion of the first element, i.e. the prune segment, it will then continue on with the matched item in your second -o (OR'd) expression.
HTH.
cheers,
Rob |
27,078 | <p>I am debugging my ASP.NET application on my Windows XP box with a virtual directory set up in IIS (5.1).</p>
<p>I am also running <strong>VirtualPC</strong> with XP and IE6 for testing purposes. When I connect to my real machine from the virtual machine, I enter the URL: <a href="http://machinename/projectname" rel="nofollow noreferrer">http://machinename/projectname</a>.</p>
<p>I get a security popup to connect to my machine (which I expect), but the User name field is disabled. I cannot change it from machinename\Guest to machinename\username in order to connect.</p>
<p>How do I get this to enable so I can enter the correct credentials.</p>
| [
{
"answer_id": 27080,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 0,
"selected": false,
"text": "<p>Use the <strong>-prune</strong> option.</p>\n"
},
{
"answer_id": 27084,
"author": "Jon Ericson",
"auth... | 2008/08/25 | [
"https://Stackoverflow.com/questions/27078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417/"
] | I am debugging my ASP.NET application on my Windows XP box with a virtual directory set up in IIS (5.1).
I am also running **VirtualPC** with XP and IE6 for testing purposes. When I connect to my real machine from the virtual machine, I enter the URL: <http://machinename/projectname>.
I get a security popup to connect to my machine (which I expect), but the User name field is disabled. I cannot change it from machinename\Guest to machinename\username in order to connect.
How do I get this to enable so I can enter the correct credentials. | G'day,
Just wanted to expand on the suggestion from Jon to use -prune. It isn't the easiest of find options to use, for example to just search in the current directory the find command looks like:
```
find . \( -type d ! -name . -prune \) -o \( <the bit you want to look for> \)
```
this will stop find from descending into sub-directories within this directory.
Basically, it says, "prune anything that is a directory, whose name isn't ".", i.e. current dir."
The find command evals left to right for each item found in the current directory so after completion of the first element, i.e. the prune segment, it will then continue on with the matched item in your second -o (OR'd) expression.
HTH.
cheers,
Rob |
27,095 | <p>I did this Just for kicks (so, not exactly a question, i can see the downmodding happening already) but, in lieu of Google's newfound <a href="http://www.google.com/search?hl=en&q=1999999999999999-1999999999999995&btnG=Search" rel="nofollow noreferrer">inability</a> to do <a href="http://www.google.com/search?hl=en&q=400000000000002-400000000000001&btnG=Search" rel="nofollow noreferrer">math</a> <a href="http://www.google.com/search?hl=en&q=10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001-10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000&btnG=Search" rel="nofollow noreferrer">correctly</a> (check it! according to google 500,000,000,000,002 - 500,000,000,000,001 = 0), i figured i'd try the following in C to run a little theory.</p>
<pre><code>int main()
{
char* a = "399999999999999";
char* b = "399999999999998";
float da = atof(a);
float db = atof(b);
printf("%s - %s = %f\n", a, b, da-db);
a = "500000000000002";
b = "500000000000001";
da = atof(a);
db = atof(b);
printf("%s - %s = %f\n", a, b, da-db);
}
</code></pre>
<p>When you run this program, you get the following</p>
<pre><code> 399999999999999 - 399999999999998 = 0.000000
500000000000002 - 500000000000001 = 0.000000
</code></pre>
<p>It would seem like Google is using simple 32 bit floating precision (the error here), if you switch float for double in the above code, you fix the issue! Could this be it?</p>
<p>/mp</p>
| [
{
"answer_id": 27105,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": false,
"text": "<p>For more of this kind of silliness see this nice article pertaining to Windows calculator.</p>\n\n<p><a href=\"http://... | 2008/08/25 | [
"https://Stackoverflow.com/questions/27095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547/"
] | I did this Just for kicks (so, not exactly a question, i can see the downmodding happening already) but, in lieu of Google's newfound [inability](http://www.google.com/search?hl=en&q=1999999999999999-1999999999999995&btnG=Search) to do [math](http://www.google.com/search?hl=en&q=400000000000002-400000000000001&btnG=Search) [correctly](http://www.google.com/search?hl=en&q=10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001-10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000&btnG=Search) (check it! according to google 500,000,000,000,002 - 500,000,000,000,001 = 0), i figured i'd try the following in C to run a little theory.
```
int main()
{
char* a = "399999999999999";
char* b = "399999999999998";
float da = atof(a);
float db = atof(b);
printf("%s - %s = %f\n", a, b, da-db);
a = "500000000000002";
b = "500000000000001";
da = atof(a);
db = atof(b);
printf("%s - %s = %f\n", a, b, da-db);
}
```
When you run this program, you get the following
```
399999999999999 - 399999999999998 = 0.000000
500000000000002 - 500000000000001 = 0.000000
```
It would seem like Google is using simple 32 bit floating precision (the error here), if you switch float for double in the above code, you fix the issue! Could this be it?
/mp | in C#, try (double.maxvalue == (double.maxvalue - 100)) , you'll get true ...
but thats what it is supposed to be:
<http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems>
thinking about it, you have 64 bit representing a number greater than 2^64 (double.maxvalue), so inaccuracy is expected. |
27,219 | <p>Given a select with multiple option's in jQuery. </p>
<pre><code>$select = $("<select></select>");
$select.append("<option>Jason</option>") //Key = 1
.append("<option>John</option>") //Key = 32
.append("<option>Paul</option>") //Key = 423
</code></pre>
<p>How should the key be stored and retrieved?</p>
<p>The ID may be an OK place but would not be guaranteed unique if I had multiple select's sharing values (and other scenarios).</p>
<p>Thanks</p>
<p>and in the spirit of TMTOWTDI.</p>
<pre><code>$option = $("<option></option>");
$select = $("<select></select>");
$select.addOption = function(value,text){
$(this).append($("<option/>").val(value).text(text));
};
$select.append($option.val(1).text("Jason").clone())
.append("<option value=32>John</option>")
.append($("<option/>").val(423).text("Paul"))
.addOption("321","Lenny");
</code></pre>
| [
{
"answer_id": 27231,
"author": "Lucas Wilson-Richter",
"author_id": 1157,
"author_profile": "https://Stackoverflow.com/users/1157",
"pm_score": 3,
"selected": false,
"text": "<p>The HTML <code><option></code> tag has an attribute called \"value\", where you can store your key.</p>... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1293/"
] | Given a select with multiple option's in jQuery.
```
$select = $("<select></select>");
$select.append("<option>Jason</option>") //Key = 1
.append("<option>John</option>") //Key = 32
.append("<option>Paul</option>") //Key = 423
```
How should the key be stored and retrieved?
The ID may be an OK place but would not be guaranteed unique if I had multiple select's sharing values (and other scenarios).
Thanks
and in the spirit of TMTOWTDI.
```
$option = $("<option></option>");
$select = $("<select></select>");
$select.addOption = function(value,text){
$(this).append($("<option/>").val(value).text(text));
};
$select.append($option.val(1).text("Jason").clone())
.append("<option value=32>John</option>")
.append($("<option/>").val(423).text("Paul"))
.addOption("321","Lenny");
``` | Like lucas said the value attribute is what you need. Using your code it would look something like this ( I added an id attribute to the select to make it fit ):
```
$select = $('<select id="mySelect"></select>');
$select.append('<option value="1">Jason</option>') //Key = 1
.append('<option value="32">John</option>') //Key = 32
.append('<option value="423">Paul</option>') //Key = 423
```
jQuery lets you get the value using the val() method. Using it on the select tag you get the current selected option's value.
```
$( '#mySelect' ).val(); //Gets the value for the current selected option
$( '#mySelect > option' ).each( function( index, option ) {
option.val(); //The value for each individual option
} );
```
Just in case, the .each method loops throught every element the query matched. |
27,220 | <p>I'm looking for a method, or a code snippet for converting std::string to LPCWSTR</p>
| [
{
"answer_id": 27291,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 4,
"selected": false,
"text": "<p>If you are in an ATL/MFC environment, You can use the ATL conversion macro:</p>\n\n<pre><code>#include <atlbase.h>\... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2701/"
] | I'm looking for a method, or a code snippet for converting std::string to LPCWSTR | The solution is actually a lot easier than any of the other suggestions:
```
std::wstring stemp = std::wstring(s.begin(), s.end());
LPCWSTR sw = stemp.c_str();
```
Best of all, it's platform independent. |
27,222 | <p>I am looking for good methods of manipulating HTML in PHP. For example, the problem I currently have is dealing with malformed HTML.</p>
<p>I am getting input that looks something like this:</p>
<pre><code><div>This is some <b>text
</code></pre>
<p>As you noticed, the HTML is missing closing tags. I could use regex or an XML Parser to solve this problem. However, it is likely that I will have to do other DOM manipulation in the future. I wonder if there are any good PHP libraries that handle DOM manipulation similar to how Javascript deals with DOM manipulation.</p>
| [
{
"answer_id": 27236,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 5,
"selected": true,
"text": "<p>PHP has <a href=\"http://php.net/tidy\" rel=\"noreferrer\">a PECL extension that gives you access to the features of... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] | I am looking for good methods of manipulating HTML in PHP. For example, the problem I currently have is dealing with malformed HTML.
I am getting input that looks something like this:
```
<div>This is some <b>text
```
As you noticed, the HTML is missing closing tags. I could use regex or an XML Parser to solve this problem. However, it is likely that I will have to do other DOM manipulation in the future. I wonder if there are any good PHP libraries that handle DOM manipulation similar to how Javascript deals with DOM manipulation. | PHP has [a PECL extension that gives you access to the features of HTML Tidy](http://php.net/tidy). Tidy is a pretty powerful library that should be able to take code like that and close tags in an intelligent manner.
I use it to clean up malformed XML and HTML sent to me by a classified ad system prior to import. |
27,240 | <p>In Java 5 and above you have the foreach loop, which works magically on anything that implements <code>Iterable</code>:</p>
<pre><code>for (Object o : list) {
doStuff(o);
}
</code></pre>
<p>However, <code>Enumerable</code> still does not implement <code>Iterable</code>, meaning that to iterate over an <code>Enumeration</code> you must do the following:</p>
<pre><code>for(; e.hasMoreElements() ;) {
doStuff(e.nextElement());
}
</code></pre>
<p>Does anyone know if there is a reason why <code>Enumeration</code> still does not implement <code>Iterable</code>?</p>
<p><strong>Edit:</strong> As a clarification, I'm not talking about the language concept of an <a href="http://en.wikipedia.org/wiki/Enumerated_type" rel="noreferrer">enum</a>, I'm talking a Java-specific class in the Java API called '<a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Enumeration.html" rel="noreferrer">Enumeration</a>'. </p>
| [
{
"answer_id": 27389,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 6,
"selected": true,
"text": "<p>Enumeration hasn't been modified to support Iterable because it's an interface not a concrete class (like Vector, which wa... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] | In Java 5 and above you have the foreach loop, which works magically on anything that implements `Iterable`:
```
for (Object o : list) {
doStuff(o);
}
```
However, `Enumerable` still does not implement `Iterable`, meaning that to iterate over an `Enumeration` you must do the following:
```
for(; e.hasMoreElements() ;) {
doStuff(e.nextElement());
}
```
Does anyone know if there is a reason why `Enumeration` still does not implement `Iterable`?
**Edit:** As a clarification, I'm not talking about the language concept of an [enum](http://en.wikipedia.org/wiki/Enumerated_type), I'm talking a Java-specific class in the Java API called '[Enumeration](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Enumeration.html)'. | Enumeration hasn't been modified to support Iterable because it's an interface not a concrete class (like Vector, which was modifed to support the Collections interface).
If Enumeration was changed to support Iterable it would break a bunch of people's code. |
27,258 | <p>I'm about to start a fairly Ajax heavy feature in my company's application. What I need to do is make an Ajax callback every few minutes a user has been on the page. </p>
<ul>
<li>I don't need to do any DOM updates before, after, or during the callbacks. </li>
<li>I don't need any information from the page, just from a site cookie which should always be sent with requests anyway, and an ID value.</li>
</ul>
<p>What I'm curious to find out, is if there is any clean and simple way to make a JavaScript Ajax callback to an ASP.NET page without posting back the rest of the information on the page. I'd like to not have to do this if it is possible.</p>
<p>I really just want to be able to call a single method on the page, nothing else.</p>
<p>Also, I'm restricted to ASP.NET 2.0 so I can't use any of the new 3.5 framework ASP AJAX features, although I can use the ASP AJAX extensions for the 2.0 framework.</p>
<p><strong>UPDATE</strong><br>
I've decided to accept <a href="https://stackoverflow.com/questions/27258/aspnet-javascript-callbacks-without-full-postbacks#27270">DanP</a>'s answer as it seems to be exactly what I'm looking for. Our site already uses jQuery for some things so I'll probably use jQuery for making requests since in my experience it seems to perform much better than ASP's AJAX framework does. </p>
<p>What do you think would be the best method of transferring data to the IHttpHandler? Should I add variables to the query string or POST the data I need to send?</p>
<p>The only thing I think I have to send is a single ID, but I can't decide what the best method is to send the ID and have the IHttpHandler handle it. I'd like to come up with a solution that would prevent a person with basic computer skills from accidentally or intentionally accessing the page directly or repeating requests. Is this possible?</p>
| [
{
"answer_id": 27264,
"author": "abigblackman",
"author_id": 2279,
"author_profile": "https://Stackoverflow.com/users/2279",
"pm_score": 2,
"selected": false,
"text": "<p>You are not just restricted to ASP.NET AJAX but can use any 3rd party library like jQuery, YUI etc to do the same thi... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] | I'm about to start a fairly Ajax heavy feature in my company's application. What I need to do is make an Ajax callback every few minutes a user has been on the page.
* I don't need to do any DOM updates before, after, or during the callbacks.
* I don't need any information from the page, just from a site cookie which should always be sent with requests anyway, and an ID value.
What I'm curious to find out, is if there is any clean and simple way to make a JavaScript Ajax callback to an ASP.NET page without posting back the rest of the information on the page. I'd like to not have to do this if it is possible.
I really just want to be able to call a single method on the page, nothing else.
Also, I'm restricted to ASP.NET 2.0 so I can't use any of the new 3.5 framework ASP AJAX features, although I can use the ASP AJAX extensions for the 2.0 framework.
**UPDATE**
I've decided to accept [DanP](https://stackoverflow.com/questions/27258/aspnet-javascript-callbacks-without-full-postbacks#27270)'s answer as it seems to be exactly what I'm looking for. Our site already uses jQuery for some things so I'll probably use jQuery for making requests since in my experience it seems to perform much better than ASP's AJAX framework does.
What do you think would be the best method of transferring data to the IHttpHandler? Should I add variables to the query string or POST the data I need to send?
The only thing I think I have to send is a single ID, but I can't decide what the best method is to send the ID and have the IHttpHandler handle it. I'd like to come up with a solution that would prevent a person with basic computer skills from accidentally or intentionally accessing the page directly or repeating requests. Is this possible? | If you don't want to create a blank page, you could call a IHttpHandler (ashx) file:
```
public class RSSHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/xml";
string sXml = BuildXMLString(); //not showing this function,
//but it creates the XML string
context.Response.Write( sXml );
}
public bool IsReusable
{
get { return true; }
}
}
``` |
27,294 | <p>I'm working on an internal project for my company, and part of the project is to be able to parse various "Tasks" from an XML file into a collection of tasks to be ran later.</p>
<p>Because each type of Task has a multitude of different associated fields, I decided it would be best to represent each type of Task with a seperate class.</p>
<p>To do this, I constructed an abstract base class:</p>
<pre><code>public abstract class Task
{
public enum TaskType
{
// Types of Tasks
}
public abstract TaskType Type
{
get;
}
public abstract LoadFromXml(XmlElement task);
public abstract XmlElement CreateXml(XmlDocument currentDoc);
}
</code></pre>
<p>Each task inherited from this base class, and included the code necessary to create itself from the passed in XmlElement, as well as serialize itself back out to an XmlElement.</p>
<p>A basic example:</p>
<pre><code>public class MergeTask : Task
{
public override TaskType Type
{
get { return TaskType.Merge; }
}
// Lots of Properties / Methods for this Task
public MergeTask (XmlElement elem)
{
this.LoadFromXml(elem);
}
public override LoadFromXml(XmlElement task)
{
// Populates this Task from the Xml.
}
public override XmlElement CreateXml(XmlDocument currentDoc)
{
// Serializes this class back to xml.
}
}
</code></pre>
<p>The parser would then use code similar to this to create a task collection:</p>
<pre><code>XmlNode taskNode = parent.SelectNode("tasks");
TaskFactory tf = new TaskFactory();
foreach (XmlNode task in taskNode.ChildNodes)
{
// Since XmlComments etc will show up
if (task is XmlElement)
{
tasks.Add(tf.CreateTask(task as XmlElement));
}
}
</code></pre>
<p>All of this works wonderfully, and allows me to pass tasks around using the base class, while retaining the structure of having individual classes for each task.</p>
<p>However, I am not happy with my code for TaskFactory.CreateTask. This method accepts an XmlElement, and then returns an instance of the appropriate Task class:</p>
<pre><code>public Task CreateTask(XmlElement elem)
{
if (elem != null)
{
switch(elem.Name)
{
case "merge":
return new MergeTask(elem);
default:
throw new ArgumentException("Invalid Task");
}
}
}
</code></pre>
<p>Because I have to parse the XMLElement, I'm using a huge (10-15 cases in the real code) switch to pick which child class to instantiate. I'm hoping there is some sort of polymorphic trick I can do here to clean up this method.</p>
<p>Any advice?</p>
| [
{
"answer_id": 27310,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 5,
"selected": true,
"text": "<p>I use reflection to do this.\nYou can make a factory that basically expands without you having to add any extra cod... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | I'm working on an internal project for my company, and part of the project is to be able to parse various "Tasks" from an XML file into a collection of tasks to be ran later.
Because each type of Task has a multitude of different associated fields, I decided it would be best to represent each type of Task with a seperate class.
To do this, I constructed an abstract base class:
```
public abstract class Task
{
public enum TaskType
{
// Types of Tasks
}
public abstract TaskType Type
{
get;
}
public abstract LoadFromXml(XmlElement task);
public abstract XmlElement CreateXml(XmlDocument currentDoc);
}
```
Each task inherited from this base class, and included the code necessary to create itself from the passed in XmlElement, as well as serialize itself back out to an XmlElement.
A basic example:
```
public class MergeTask : Task
{
public override TaskType Type
{
get { return TaskType.Merge; }
}
// Lots of Properties / Methods for this Task
public MergeTask (XmlElement elem)
{
this.LoadFromXml(elem);
}
public override LoadFromXml(XmlElement task)
{
// Populates this Task from the Xml.
}
public override XmlElement CreateXml(XmlDocument currentDoc)
{
// Serializes this class back to xml.
}
}
```
The parser would then use code similar to this to create a task collection:
```
XmlNode taskNode = parent.SelectNode("tasks");
TaskFactory tf = new TaskFactory();
foreach (XmlNode task in taskNode.ChildNodes)
{
// Since XmlComments etc will show up
if (task is XmlElement)
{
tasks.Add(tf.CreateTask(task as XmlElement));
}
}
```
All of this works wonderfully, and allows me to pass tasks around using the base class, while retaining the structure of having individual classes for each task.
However, I am not happy with my code for TaskFactory.CreateTask. This method accepts an XmlElement, and then returns an instance of the appropriate Task class:
```
public Task CreateTask(XmlElement elem)
{
if (elem != null)
{
switch(elem.Name)
{
case "merge":
return new MergeTask(elem);
default:
throw new ArgumentException("Invalid Task");
}
}
}
```
Because I have to parse the XMLElement, I'm using a huge (10-15 cases in the real code) switch to pick which child class to instantiate. I'm hoping there is some sort of polymorphic trick I can do here to clean up this method.
Any advice? | I use reflection to do this.
You can make a factory that basically expands without you having to add any extra code.
make sure you have "using System.Reflection", place the following code in your instantiation method.
```
public Task CreateTask(XmlElement elem)
{
if (elem != null)
{
try
{
Assembly a = typeof(Task).Assembly
string type = string.Format("{0}.{1}Task",typeof(Task).Namespace,elem.Name);
//this is only here, so that if that type doesn't exist, this method
//throws an exception
Type t = a.GetType(type, true, true);
return a.CreateInstance(type, true) as Task;
}
catch(System.Exception)
{
throw new ArgumentException("Invalid Task");
}
}
}
```
Another observation, is that you can make this method, a static and hang it off of the Task class, so that you don't have to new up the TaskFactory, and also you get to save yourself a moving piece to maintain. |
27,303 | <p>Anyone know if it's possible to databind the ScaleX and ScaleY of a render transform in Silverlight 2 Beta 2? Binding transforms is possible in WPF - But I'm getting an error when setting up my binding in Silverlight through XAML. Perhaps it's possible to do it through code?</p>
<pre><code><Image Height="60" HorizontalAlignment="Right"
Margin="0,122,11,0" VerticalAlignment="Top" Width="60"
Source="Images/Fish128x128.png" Stretch="Fill"
RenderTransformOrigin="0.5,0.5" x:Name="fishImage">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="1" ScaleY="1"/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform>
</Image>
</code></pre>
<p>I want to bind the ScaleX and ScaleY of the ScaleTransform element.</p>
<p>I'm getting a runtime error when I try to bind against a double property on my data context: </p>
<pre><code>Message="AG_E_PARSER_BAD_PROPERTY_VALUE [Line: 1570 Position: 108]"
</code></pre>
<p>My binding looks like this:</p>
<pre><code><ScaleTransform ScaleX="{Binding Path=SelectedDive.Visibility}"
ScaleY="{Binding Path=SelectedDive.Visibility}"/>
</code></pre>
<p>I have triple verified that the binding path is correct - I'm binding a slidebar against the same value and that works just fine...</p>
<p>Visibility is of type double and is a number between 0.0 and 30.0. I have a value converter that scales that number down to 0.5 and 1 - I want to scale the size of the fish depending on the clarity of the water. So I don't think it's a problem with the type I'm binding against...</p>
| [
{
"answer_id": 27309,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 1,
"selected": false,
"text": "<p>Is it a runtime error or compile-time, Jonas? Looking at the <a href=\"http://msdn.microsoft.com/en-us/library/system.... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199387/"
] | Anyone know if it's possible to databind the ScaleX and ScaleY of a render transform in Silverlight 2 Beta 2? Binding transforms is possible in WPF - But I'm getting an error when setting up my binding in Silverlight through XAML. Perhaps it's possible to do it through code?
```
<Image Height="60" HorizontalAlignment="Right"
Margin="0,122,11,0" VerticalAlignment="Top" Width="60"
Source="Images/Fish128x128.png" Stretch="Fill"
RenderTransformOrigin="0.5,0.5" x:Name="fishImage">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="1" ScaleY="1"/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform>
</Image>
```
I want to bind the ScaleX and ScaleY of the ScaleTransform element.
I'm getting a runtime error when I try to bind against a double property on my data context:
```
Message="AG_E_PARSER_BAD_PROPERTY_VALUE [Line: 1570 Position: 108]"
```
My binding looks like this:
```
<ScaleTransform ScaleX="{Binding Path=SelectedDive.Visibility}"
ScaleY="{Binding Path=SelectedDive.Visibility}"/>
```
I have triple verified that the binding path is correct - I'm binding a slidebar against the same value and that works just fine...
Visibility is of type double and is a number between 0.0 and 30.0. I have a value converter that scales that number down to 0.5 and 1 - I want to scale the size of the fish depending on the clarity of the water. So I don't think it's a problem with the type I'm binding against... | ScaleTransform doesn't have a data context so most likely the binding is looking for SelectedDive.Visibility off it's self and not finding it. There is much in Silverlight xaml and databinding that is different from WPF...
Anyway to solve this you will want to set up the binding in code\*\*, or manually listen for the PropertyChanged event of your data object and set the Scale in code behind.
I would choose the latter if you wanted to do an animation/storyboard for the scale change.
\*\* i need to check but you may not be able to bind to it. as i recall if the RenderTransform is not part of an animation it gets turned into a matrix transform and all bets are off. |
27,359 | <p>I want to setup a cron job to rsync a remote system to a backup partition, something like:</p>
<pre><code>bash -c 'rsync -avz --delete --exclude=proc --exclude=sys root@remote1:/ /mnt/remote1/'
</code></pre>
<p>I would like to be able to "set it and forget it" but what if <code>/mnt/remote1</code> becomes unmounted? (After a reboot or something) I'd like to error out if <code>/mnt/remote1</code> isn't mounted, rather than filling up the local filesystem.</p>
<p><strong>Edit:</strong><br />
Here is what I came up with for a script, cleanup improvements appreciated (especially for the empty then ... else, I couldn't leave them empty or bash errors)</p>
<pre><code>#!/bin/bash
DATA=data
ERROR="0"
if cut -d' ' -f2 /proc/mounts | grep -q "^/mnt/$1\$"; then
ERROR=0
else
if mount /dev/vg/$1 /mnt/$1; then
ERROR=0
else
ERROR=$?
echo "Can't backup $1, /mnt/$1 could not be mounted: $ERROR"
fi
fi
if [ "$ERROR" = "0" ]; then
if cut -d' ' -f2 /proc/mounts | grep -q "^/mnt/$1/$DATA\$"; then
ERROR=0
else
if mount /dev/vg/$1$DATA /mnt/$1/data; then
ERROR=0
else
ERROR=$?
echo "Can't backup $1, /mnt/$1/data could not be mounted."
fi
fi
fi
if [ "$ERROR" = "0" ]; then
rsync -aqz --delete --numeric-ids --exclude=proc --exclude=sys \
root@$1.domain:/ /mnt/$1/
RETVAL=$?
echo "Backup of $1 completed, return value of rsync: $RETVAL"
fi
</code></pre>
| [
{
"answer_id": 27370,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 2,
"selected": false,
"text": "<p>A quick google led me to this bash script that can check if a filesystem is mounted. It seems that grepping the o... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163/"
] | I want to setup a cron job to rsync a remote system to a backup partition, something like:
```
bash -c 'rsync -avz --delete --exclude=proc --exclude=sys root@remote1:/ /mnt/remote1/'
```
I would like to be able to "set it and forget it" but what if `/mnt/remote1` becomes unmounted? (After a reboot or something) I'd like to error out if `/mnt/remote1` isn't mounted, rather than filling up the local filesystem.
**Edit:**
Here is what I came up with for a script, cleanup improvements appreciated (especially for the empty then ... else, I couldn't leave them empty or bash errors)
```
#!/bin/bash
DATA=data
ERROR="0"
if cut -d' ' -f2 /proc/mounts | grep -q "^/mnt/$1\$"; then
ERROR=0
else
if mount /dev/vg/$1 /mnt/$1; then
ERROR=0
else
ERROR=$?
echo "Can't backup $1, /mnt/$1 could not be mounted: $ERROR"
fi
fi
if [ "$ERROR" = "0" ]; then
if cut -d' ' -f2 /proc/mounts | grep -q "^/mnt/$1/$DATA\$"; then
ERROR=0
else
if mount /dev/vg/$1$DATA /mnt/$1/data; then
ERROR=0
else
ERROR=$?
echo "Can't backup $1, /mnt/$1/data could not be mounted."
fi
fi
fi
if [ "$ERROR" = "0" ]; then
rsync -aqz --delete --numeric-ids --exclude=proc --exclude=sys \
root@$1.domain:/ /mnt/$1/
RETVAL=$?
echo "Backup of $1 completed, return value of rsync: $RETVAL"
fi
``` | ```
if cut -d' ' -f2 /proc/mounts | grep '^/mnt/remote1$' >/dev/null; then
rsync -avz ...
fi
```
Get the list of mounted partitions from `/proc/mounts`, only match `/mnt/remote1` (and if it is mounted, send grep's output to `/dev/null`), then run your `rsync` job.
Recent `grep`s have a `-q` option that you can use instead of sending the output to `/dev/null`. |
27,405 | <p>On an 8-bit micro controller I would like to do the following:</p>
<pre><code>16bit_integer = another_16bit_integer * 0.997;</code></pre>
<p>with the least possible number of instructions.</p>
| [
{
"answer_id": 27415,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 2,
"selected": false,
"text": "<p>How about integer arithmetic in 32 bits?</p>\n\n<pre><code>16bit_integer = (int16_t) (another_16bit_integer * (int32_t) 9... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/609/"
] | On an 8-bit micro controller I would like to do the following:
```
16bit_integer = another_16bit_integer * 0.997;
```
with the least possible number of instructions. | How about integer arithmetic in 32 bits?
```
16bit_integer = (int16_t) (another_16bit_integer * (int32_t) 997 / 1000);
```
32 bits will be enough to store (INT16\_MAX × 997), do the sum on values 1000 times larger then divide back to your 16 bit scale. |
27,442 | <p>Is there a rake task for backing up the data in your database? </p>
<p>I already have my schema backed up, but I want to make a backup of the data. It's a small MySQL database. </p>
| [
{
"answer_id": 27448,
"author": "thelsdj",
"author_id": 163,
"author_profile": "https://Stackoverflow.com/users/163",
"pm_score": 4,
"selected": true,
"text": "<p>The below script is a simplified version taken from <a href=\"http://github.com/engineyard/eycap/tree/master\" rel=\"nofollow... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
] | Is there a rake task for backing up the data in your database?
I already have my schema backed up, but I want to make a backup of the data. It's a small MySQL database. | The below script is a simplified version taken from [eycap](http://github.com/engineyard/eycap/tree/master), specifically from [this file](http://github.com/engineyard/eycap/tree/master/lib/eycap/recipes/database.rb).
```
set :dbuser "user"
set :dbhost "host"
set :database "db"
namespace :db do
desc "Get the database password from user"
task :get_password do
set(:dbpass) do
Capistrano::CLI.ui.ask "Enter mysql password: "
end
end
task :backup_name, :only => { :primary => true } do
now = Time.now
run "mkdir -p #{shared_path}/db_backups"
backup_time = [now.year,now.month,now.day,now.hour,now.min,now.sec].join('-')
set :backup_file, "#{shared_path}/db_backups/#{database}-snapshot-#{backup_time}.sql"
end
desc "Dump database to backup file"
task :dump, :roles => :db, :only => {:primary => true} do
backup_name
run "mysqldump --add-drop-table -u #{dbuser} -h #{dbhost} -p#{dbpass} #{database} | bzip2 -c > #{backup_file}.bz2"
end
end
```
Edit: Yeah, I guess I missed the point that you were looking for a rake task and not a capistrano task, but I don't have a rake one on hand, sorry. |
27,455 | <p>I'm attempting to use Mono to load a bitmap and print it on Linux but I'm getting an exception. Does Mono support printing on Linux? The code/exception are below:</p>
<p><strong>EDIT:</strong> No longer getting the exception, but I'm still curious what kind of support there is. Leaving the code for posterity or something.</p>
<pre><code>private void btnPrintTest_Click(object sender, EventArgs e)
{
_printDocTest.DefaultPageSettings.Landscape = true;
_printDocTest.DefaultPageSettings.Margins = new Margins(50,50,50,50);
_printDocTest.Print();
}
void _printDocTest_PrintPage(object sender, PrintPageEventArgs e)
{
var bmp = new Bitmap("test.bmp");
// Determine center of graph
var xCenter = e.MarginBounds.X + (e.MarginBounds.Width - bmp.Width) / 2;
var yCenter = e.MarginBounds.Y + (e.MarginBounds.Height - bmp.Height) / 2;
e.Graphics.DrawImage(bmp, xCenter, yCenter);
e.HasMorePages = false;
}
</code></pre>
| [
{
"answer_id": 27459,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 4,
"selected": true,
"text": "<p>From the <a href=\"http://www.mono-project.com/FAQ:_General\" rel=\"noreferrer\">Mono docs</a>, I think yes:</p>\n\n<blockquote>\... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] | I'm attempting to use Mono to load a bitmap and print it on Linux but I'm getting an exception. Does Mono support printing on Linux? The code/exception are below:
**EDIT:** No longer getting the exception, but I'm still curious what kind of support there is. Leaving the code for posterity or something.
```
private void btnPrintTest_Click(object sender, EventArgs e)
{
_printDocTest.DefaultPageSettings.Landscape = true;
_printDocTest.DefaultPageSettings.Margins = new Margins(50,50,50,50);
_printDocTest.Print();
}
void _printDocTest_PrintPage(object sender, PrintPageEventArgs e)
{
var bmp = new Bitmap("test.bmp");
// Determine center of graph
var xCenter = e.MarginBounds.X + (e.MarginBounds.Width - bmp.Width) / 2;
var yCenter = e.MarginBounds.Y + (e.MarginBounds.Height - bmp.Height) / 2;
e.Graphics.DrawImage(bmp, xCenter, yCenter);
e.HasMorePages = false;
}
``` | From the [Mono docs](http://www.mono-project.com/FAQ:_General), I think yes:
>
> Managed.Windows.Forms (aka
> System.Windows.Forms): A complete and
> cross platform, System.Drawing based
> Winforms implementation.
>
>
>
It also useful if you run the [Mono Migration Analyzer](http://www.mono-project.com/Moma) first. |
27,509 | <p>How do I check if an object property in JavaScript is undefined?</p>
| [
{
"answer_id": 27510,
"author": "tslocum",
"author_id": 1662,
"author_profile": "https://Stackoverflow.com/users/1662",
"pm_score": -1,
"selected": false,
"text": "<pre><code>if (somevariable == undefined) {\n alert('the variable is not defined!');\n}\n</code></pre>\n\n<p>You can also m... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | How do I check if an object property in JavaScript is undefined? | The usual way to check if the value of a property is the special value `undefined`, is:
```js
if(o.myProperty === undefined) {
alert("myProperty value is the special value `undefined`");
}
```
To check if an object does not actually have such a property, and will therefore return `undefined` by default when you try to access it:
```js
if(!o.hasOwnProperty('myProperty')) {
alert("myProperty does not exist");
}
```
To check if the value associated with an identifier is the special value `undefined`, *or* if that identifier has not been declared:
```js
if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}
```
Note: this last method is the only way to refer to an **undeclared** identifier without an early error, which is different from having a value of `undefined`.
In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check `foo === undefined` might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.
However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.
If you are worried about this (unlikely) edge case, you can use [the void operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) to get at the special `undefined` value itself:
```js
if(myVariable === void 0) {
alert("myVariable is the special value `undefined`");
}
``` |
27,532 | <p>Given 2 rgb colors and a rectangular area, I'd like to generate a basic linear gradient between the colors. I've done a quick search and the only thing I've been able to find is <a href="http://jtauber.com/blog/2008/05/18/creating_gradients_programmatically_in_python/" rel="noreferrer">this blog entry</a>, but the example code seems to be missing, or at least it was as of this posting. Anything helps, algorithms, code examples, whatever. This will be written in Java, but the display layer is already taken care of, I just need to figure out how to figure out what to display.</p>
| [
{
"answer_id": 27536,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": true,
"text": "<p>you want an interpolation between the first and the second colour. Interpolating colours is easy by calculating the ... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] | Given 2 rgb colors and a rectangular area, I'd like to generate a basic linear gradient between the colors. I've done a quick search and the only thing I've been able to find is [this blog entry](http://jtauber.com/blog/2008/05/18/creating_gradients_programmatically_in_python/), but the example code seems to be missing, or at least it was as of this posting. Anything helps, algorithms, code examples, whatever. This will be written in Java, but the display layer is already taken care of, I just need to figure out how to figure out what to display. | you want an interpolation between the first and the second colour. Interpolating colours is easy by calculating the same interpolation for each of its components (R, G, B). There are many ways to interpolate. The easiest is to use linear interpolation: just take percentage *p* of the first colour and percentage 1 - *p* of the second:
```
R = firstCol.R * p + secondCol.R * (1 - p)
```
There's [another question](https://stackoverflow.com/questions/25007/conditional-formatting-percentage-to-color-conversion) related to this.
There are other methods of interpolation that sometimes work better. For example, using a [bell-shaped (sigmoidal)](http://en.wikipedia.org/wiki/Sigmoid_function) interpolation function makes the transition smoother.
/EDIT: Oops, you mean using a predefined function. OK, even easier. The blog post you linked now has an example code in Python.
In Java, you could use the [`GradientPaint`](http://docs.oracle.com/javase/7/docs/api/java/awt/GradientPaint.html). |
27,559 | <p>The ones that stick out and make life usefull.</p>
| [
{
"answer_id": 27563,
"author": "chrissie1",
"author_id": 2936,
"author_profile": "https://Stackoverflow.com/users/2936",
"pm_score": 1,
"selected": false,
"text": "<p>Here is one for a testClass with Nunit support.</p>\n\n<pre><code>\n Imports Nunit.FrameWork\n\n Namespace $NAMESP... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2936/"
] | The ones that stick out and make life usefull. | Here is one for a testClass with Nunit support.
```
Imports Nunit.FrameWork
Namespace $NAMESPACE$
'''
''' A TestClass
'''
'''
_
Public Class $CLASSNAME$
#Region " Setup and TearDown "
'''
''' Sets up the Tests
'''
'''
_
Public Sub Setup()
End Sub
'''
''' Tears down the test. Is executed after the Test is Completed
'''
'''
_
Public Sub TearDown()
End Sub
#End Region
#Region " Tests "
'''
''' A Test
'''
'''
_
Public Sub $Test_Name$()
End Sub
#End Region
End Class
End Namespace
``` |
27,570 | <p>Is there a way to find the number of files of a specific type without having to loop through all results inn a Directory.GetFiles() or similar method? I am looking for something like this:</p>
<pre><code>int ComponentCount = MagicFindFileCount(@"c:\windows\system32", "*.dll");
</code></pre>
<p>I know that I can make a recursive function to call Directory.GetFiles , but it would be much cleaner if I could do this without all the iterating.</p>
<p><strong>EDIT:</strong> If it is not possible to do this without recursing and iterating yourself, what would be the best way to do it?</p>
| [
{
"answer_id": 27574,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>Someone has to do the iterating part.</p>\n\n<p>AFAIK, there is no such method present in .NET already, so I guess ... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2257/"
] | Is there a way to find the number of files of a specific type without having to loop through all results inn a Directory.GetFiles() or similar method? I am looking for something like this:
```
int ComponentCount = MagicFindFileCount(@"c:\windows\system32", "*.dll");
```
I know that I can make a recursive function to call Directory.GetFiles , but it would be much cleaner if I could do this without all the iterating.
**EDIT:** If it is not possible to do this without recursing and iterating yourself, what would be the best way to do it? | You should use the [Directory.GetFiles(path, searchPattern, SearchOption)](http://msdn.microsoft.com/en-us/library/ms143316.aspx) overload of Directory.GetFiles().
Path specifies the path, searchPattern specifies your wildcards (e.g., \*, \*.format) and SearchOption provides the option to include subdirectories.
The Length property of the return array of this search will provide the proper file count for your particular search pattern and option:
```
string[] files = directory.GetFiles(@"c:\windows\system32", "*.dll", SearchOption.AllDirectories);
return files.Length;
```
**EDIT:** Alternatively you can use [Directory.EnumerateFiles method](https://msdn.microsoft.com/en-us/library/system.io.directory.enumeratefiles(v=vs.110).aspx)
```
return Directory.EnumerateFiles(@"c:\windows\system32", "*.dll", SearchOption.AllDirectories).Count();
``` |
27,581 | <p>What issues / pitfalls must be considered when overriding <code>equals</code> and <code>hashCode</code>?</p>
| [
{
"answer_id": 27609,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 12,
"selected": true,
"text": "<h3>The theory (for the language lawyers and the mathematically inclined):</h3>\n\n<p><code>equals()</code> (<a href... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | What issues / pitfalls must be considered when overriding `equals` and `hashCode`? | ### The theory (for the language lawyers and the mathematically inclined):
`equals()` ([javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object))) must define an equivalence relation (it must be *reflexive*, *symmetric*, and *transitive*). In addition, it must be *consistent* (if the objects are not modified, then it must keep returning the same value). Furthermore, `o.equals(null)` must always return false.
`hashCode()` ([javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode())) must also be *consistent* (if the object is not modified in terms of `equals()`, it must keep returning the same value).
The **relation** between the two methods is:
>
> *Whenever `a.equals(b)`, then `a.hashCode()` must be same as `b.hashCode()`.*
>
>
>
### In practice:
If you override one, then you should override the other.
Use the same set of fields that you use to compute `equals()` to compute `hashCode()`.
Use the excellent helper classes [EqualsBuilder](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/EqualsBuilder.html) and [HashCodeBuilder](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html) from the [Apache Commons Lang](http://commons.apache.org/lang/) library. An example:
```
public class Person {
private String name;
private int age;
// ...
@Override
public int hashCode() {
return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
// if deriving: appendSuper(super.hashCode()).
append(name).
append(age).
toHashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Person))
return false;
if (obj == this)
return true;
Person rhs = (Person) obj;
return new EqualsBuilder().
// if deriving: appendSuper(super.equals(obj)).
append(name, rhs.name).
append(age, rhs.age).
isEquals();
}
}
```
### Also remember:
When using a hash-based [Collection](http://download.oracle.com/javase/1.4.2/docs/api/java/util/Collection.html) or [Map](http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html) such as [HashSet](http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashSet.html), [LinkedHashSet](http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashSet.html), [HashMap](http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html), [Hashtable](http://download.oracle.com/javase/1.4.2/docs/api/java/util/Hashtable.html), or [WeakHashMap](http://download.oracle.com/javase/1.4.2/docs/api/java/util/WeakHashMap.html), make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, [which has also other benefits](http://www.javapractices.com/topic/TopicAction.do?Id=29). |
27,599 | <p>(<strong>Updated a little</strong>)</p>
<p>I'm not very experienced with internationalization using PHP, it must be said, and a deal of searching didn't really provide the answers I was looking for.</p>
<p>I'm in need of working out a reliable way to convert only 'relevant' text to Unicode to send in an SMS message, using PHP (just temporarily, whilst service is rewritten using C#) - obviously, messages sent at the moment are sent as plain text.</p>
<p>I could conceivably convert everything to the Unicode charset (as opposed to using the standard GSM charset), but that would mean that <em>all</em> messages would be limited to 70 characters (instead of 160).</p>
<p>So, I guess my real question is: <em>what is the most reliable way to detect the requirement for a message to be Unicode-encoded, so I only have to do it when it's</em> <strong><em>absolutely necessary</em></strong> <em>(e.g. for non-Latin-language characters)?</em></p>
<h2>Added Info:</h2>
<p>Okay, so I've spent the morning working on this, and I'm still no further on than when I started (certainly due to my complete lack of competency when it comes to charset conversion). So here's the revised scenario:</p>
<p>I have text SMS messages coming from an external source, this external source provides the responses to me in plain text + Unicode slash-escaped characters. E.g. the 'displayed' text:</p>
<blockquote>
<p>Let's test öäü éàè אין תמיכה בעברית</p>
</blockquote>
<p>Returns:</p>
<blockquote>
<p>Let's test \u00f6\u00e4\u00fc \u00e9\u00e0\u00e8 \u05d0\u05d9\u05df \u05ea\u05de\u05d9\u05db\u05d4 \u05d1\u05e2\u05d1\u05e8\u05d9\u05ea</p>
</blockquote>
<p>Now, I can send on to my SMS provider in plaintext, GSM 03.38 or Unicode. Obviously, sending the above as plaintext results in a lot of missing characters (they're replaced by spaces by my provider) - I need to adopt relating to what content there is. What I want to <em>do</em> with this is the following:</p>
<ol>
<li><p>If all text is within the <a href="http://www.dreamfabric.com/sms/default_alphabet.html" rel="nofollow noreferrer">GSM 03.38 codepage</a>, send it as-is. (All but the Hebrew characters above fit into this category, but need to be converted.)</p></li>
<li><p>Otherwise, convert it to Unicode, and send it over multiple messages (as the Unicode limit is 70 chars not 160 for an SMS).</p></li>
</ol>
<p>As I said above, I'm stumped on doing this in PHP (C# wasn't much of an issue due to some simple conversion functions built-in), but it's quite probable I'm just missing the obvious, here. I couldn't find any pre-made conversion classes for 7-bit encoding in PHP, either - and my attempts to convert the string myself and send it on seemed futile.</p>
<p><strong>Any help would be greatly appreciated.</strong></p>
| [
{
"answer_id": 27603,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 0,
"selected": false,
"text": "<p>PHP6 will have better unicode support but there are a few functions you can use.</p>\n\n<p>My first thought was <a href=\"htt... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2951/"
] | (**Updated a little**)
I'm not very experienced with internationalization using PHP, it must be said, and a deal of searching didn't really provide the answers I was looking for.
I'm in need of working out a reliable way to convert only 'relevant' text to Unicode to send in an SMS message, using PHP (just temporarily, whilst service is rewritten using C#) - obviously, messages sent at the moment are sent as plain text.
I could conceivably convert everything to the Unicode charset (as opposed to using the standard GSM charset), but that would mean that *all* messages would be limited to 70 characters (instead of 160).
So, I guess my real question is: *what is the most reliable way to detect the requirement for a message to be Unicode-encoded, so I only have to do it when it's* ***absolutely necessary*** *(e.g. for non-Latin-language characters)?*
Added Info:
-----------
Okay, so I've spent the morning working on this, and I'm still no further on than when I started (certainly due to my complete lack of competency when it comes to charset conversion). So here's the revised scenario:
I have text SMS messages coming from an external source, this external source provides the responses to me in plain text + Unicode slash-escaped characters. E.g. the 'displayed' text:
>
> Let's test öäü éàè אין תמיכה בעברית
>
>
>
Returns:
>
> Let's test \u00f6\u00e4\u00fc \u00e9\u00e0\u00e8 \u05d0\u05d9\u05df \u05ea\u05de\u05d9\u05db\u05d4 \u05d1\u05e2\u05d1\u05e8\u05d9\u05ea
>
>
>
Now, I can send on to my SMS provider in plaintext, GSM 03.38 or Unicode. Obviously, sending the above as plaintext results in a lot of missing characters (they're replaced by spaces by my provider) - I need to adopt relating to what content there is. What I want to *do* with this is the following:
1. If all text is within the [GSM 03.38 codepage](http://www.dreamfabric.com/sms/default_alphabet.html), send it as-is. (All but the Hebrew characters above fit into this category, but need to be converted.)
2. Otherwise, convert it to Unicode, and send it over multiple messages (as the Unicode limit is 70 chars not 160 for an SMS).
As I said above, I'm stumped on doing this in PHP (C# wasn't much of an issue due to some simple conversion functions built-in), but it's quite probable I'm just missing the obvious, here. I couldn't find any pre-made conversion classes for 7-bit encoding in PHP, either - and my attempts to convert the string myself and send it on seemed futile.
**Any help would be greatly appreciated.** | To deal with it conceptually before getting into mechanisms, and apologies if any of this is obvious, a string can be defined as a sequence of Unicode characters, Unicode being a database that gives an id number known as a code point to every character you might need to work with. GSM-338 contains a subset of the Unicode characters, so what you're doing is extracting a set of codepoints from your string, and checking to see if that set is contained in GSM-338.
```
// second column of http://unicode.org/Public/MAPPINGS/ETSI/GSM0338.TXT
$gsm338_codepoints = array(0x0040, 0x0000, ..., 0x00fc, 0x00e0)
$can_use_gsm338 = true;
foreach(codepoints($mystring) as $codepoint){
if(!in_array($codepoint, $gsm338_codepoints)){
$can_use_gsm338 = false;
break;
}
}
```
That leaves the definition of the function codepoints($string), which isn't built in to PHP. PHP understands a string to be a sequence of bytes rather than a sequence of Unicode characters. The best way of bridging the gap is to get your strings into UTF8 as quickly as you can and keep them in UTF8 as long as you can - you'll have to use other encodings when dealing with external systems, but isolate the conversion to the interface to that system and deal only with utf8 internally.
The functions you need to convert between php strings in utf8 and sequences of codepoints can be found at <http://hsivonen.iki.fi/php-utf8/> , so that's your codepoints() function.
If you're taking data from an external source that gives you Unicode slash-escaped characters ("Let's test \u00f6\u00e4\u00fc..."), that string escape format should be converted to utf8. I don't know offhand of a function to do this, if one can't be found, it's a matter of string/regex processing + the use of the hsivonen.iki.fi functions, for example when you hit \u00f6, replace it with the utf8 representation of the codepoint 0xf6. |
27,607 | <p>Let's say I have a list of server names stored in a vector, and I would like to contact them one at a time until one has successfully responded. I was thinking about using STL's find_if algorithm in the following way:</p>
<pre><code>find_if(serverNames.begin(), serverNames.end(), ContactServer());
</code></pre>
<p>Where ContactServer is a predicate function object.<br>
On one hand, there's a problem since the predicate will not always return the same result for the same server name (because of server downtime, network problems, etc...). However, the same result will be returned regardless of which copy of the predicate is used (<em>i.e.</em> the predicate has no real state), so the original problem with state-keeping predicates is not relevant in this case.</p>
<p>What do you say?</p>
| [
{
"answer_id": 27614,
"author": "Magnus Hoff",
"author_id": 2971,
"author_profile": "https://Stackoverflow.com/users/2971",
"pm_score": 2,
"selected": false,
"text": "<p>I think I would go for it.</p>\n\n<p>The only thing I would worry about is the readability (and therefore maintainabil... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2150/"
] | Let's say I have a list of server names stored in a vector, and I would like to contact them one at a time until one has successfully responded. I was thinking about using STL's find\_if algorithm in the following way:
```
find_if(serverNames.begin(), serverNames.end(), ContactServer());
```
Where ContactServer is a predicate function object.
On one hand, there's a problem since the predicate will not always return the same result for the same server name (because of server downtime, network problems, etc...). However, the same result will be returned regardless of which copy of the predicate is used (*i.e.* the predicate has no real state), so the original problem with state-keeping predicates is not relevant in this case.
What do you say? | I think I would go for it.
The only thing I would worry about is the readability (and therefore maintainability) of it. To me, it reads something like "Find the first server I can contact", which makes perfect sense.
You might want to rename `ContactServer` to indicate that it is a predicate; `CanContactServer`? (But then people would complain about hidden side effects. Hmm...) |
27,610 | <p>I want to introduce some tracing to a C# application I am writing. Sadly, I can never really remember how it works and would like a tutorial with reference qualities to check up on every now and then. It should include:</p>
<ul>
<li>App.config / Web.config stuff to add for registering TraceListeners</li>
<li>how to set it up in the calling application</li>
</ul>
<p>Do you know the über tutorial that we should link to?</p>
<hr/>
<p>Glenn Slaven pointed me in the right direction. Add this to your App.config/Web.config inside <code><configuration/></code>:</p>
<pre><code><system.diagnostics>
<trace autoflush="true">
<listeners>
<add type="System.Diagnostics.TextWriterTraceListener" name="TextWriter"
initializeData="trace.log" />
</listeners>
</trace>
</system.diagnostics>
</code></pre>
<p>This will add a <code>TextWriterTraceListener</code> that will catch everything you send to with <code>Trace.WriteLine</code>, etc.</p>
<p>@DanEsparza pointed out that you should use <code>Trace.TraceInformation</code>, <code>Trace.TraceWarning</code> and <code>Trace.TraceError</code> instead of <code>Trace.WriteLine</code>, as they allow you to format messages the same way as <code>string.Format</code>.</p>
<p><strong>Tip:</strong> If you don't add any listeners, then you can still see the trace output with the Sysinternals program <a href="https://learn.microsoft.com/en-us/sysinternals/downloads/debugview" rel="nofollow noreferrer">DebugView</a> (<code>Dbgview.exe</code>):</p>
| [
{
"answer_id": 27659,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 2,
"selected": false,
"text": "<p>DotNetCoders has a starter article on it: <a href=\"http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] | I want to introduce some tracing to a C# application I am writing. Sadly, I can never really remember how it works and would like a tutorial with reference qualities to check up on every now and then. It should include:
* App.config / Web.config stuff to add for registering TraceListeners
* how to set it up in the calling application
Do you know the über tutorial that we should link to?
---
Glenn Slaven pointed me in the right direction. Add this to your App.config/Web.config inside `<configuration/>`:
```
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add type="System.Diagnostics.TextWriterTraceListener" name="TextWriter"
initializeData="trace.log" />
</listeners>
</trace>
</system.diagnostics>
```
This will add a `TextWriterTraceListener` that will catch everything you send to with `Trace.WriteLine`, etc.
@DanEsparza pointed out that you should use `Trace.TraceInformation`, `Trace.TraceWarning` and `Trace.TraceError` instead of `Trace.WriteLine`, as they allow you to format messages the same way as `string.Format`.
**Tip:** If you don't add any listeners, then you can still see the trace output with the Sysinternals program [DebugView](https://learn.microsoft.com/en-us/sysinternals/downloads/debugview) (`Dbgview.exe`): | I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the `TraceSource.TraceEvent(TraceEventType, Int32, String)` method where the `TraceSource` object was initialised with a string making it a 'named source'.
For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called `tracelog.txt`. For the following code:
```
TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");
```
I successfully managed to log with the following diagnostics configuration:
```html
<system.diagnostics>
<sources>
<source name="sourceName" switchName="switchName">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="tracelog.txt" />
</listeners>
</source>
</sources>
<switches>
<add name="switchName" value="Verbose" />
</switches>
</system.diagnostics>
``` |
27,621 | <p>On the UNIX bash shell (specifically Mac OS X Leopard) what would be the simplest way to copy every file having a specific extension from a folder hierarchy (including subdirectories) to the same destination folder (without subfolders)?</p>
<p>Obviously there is the problem of having duplicates in the source hierarchy. I wouldn't mind if they are overwritten.</p>
<p>Example: I need to copy every .txt file in the following hierarchy</p>
<pre><code>/foo/a.txt
/foo/x.jpg
/foo/bar/a.txt
/foo/bar/c.jpg
/foo/bar/b.txt
</code></pre>
<p>To a folder named 'dest' and get:</p>
<pre><code>/dest/a.txt
/dest/b.txt
</code></pre>
| [
{
"answer_id": 27625,
"author": "Magnus Hoff",
"author_id": 2971,
"author_profile": "https://Stackoverflow.com/users/2971",
"pm_score": 7,
"selected": true,
"text": "<p>In bash:</p>\n\n<pre><code>find /foo -iname '*.txt' -exec cp \\{\\} /dest/ \\;\n</code></pre>\n\n<p><code>find</code> w... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954/"
] | On the UNIX bash shell (specifically Mac OS X Leopard) what would be the simplest way to copy every file having a specific extension from a folder hierarchy (including subdirectories) to the same destination folder (without subfolders)?
Obviously there is the problem of having duplicates in the source hierarchy. I wouldn't mind if they are overwritten.
Example: I need to copy every .txt file in the following hierarchy
```
/foo/a.txt
/foo/x.jpg
/foo/bar/a.txt
/foo/bar/c.jpg
/foo/bar/b.txt
```
To a folder named 'dest' and get:
```
/dest/a.txt
/dest/b.txt
``` | In bash:
```
find /foo -iname '*.txt' -exec cp \{\} /dest/ \;
```
`find` will find all the files under the path `/foo` matching the wildcard `*.txt`, case insensitively (That's what `-iname` means). For each file, `find` will execute `cp {} /dest/`, with the found file in place of `{}`. |
27,622 | <p>The <strong><a href="http://msdn.microsoft.com/en-us/library/4wyz8787(VS.80).aspx" rel="noreferrer">TRACE macro</a></strong> can be used to output diagnostic messages to the debugger when the code is compiled in <strong>Debug</strong> mode. I need the same messages while in <strong>Release</strong> mode. Is there a way to achieve this?</p>
<p>(Please do <strong>not</strong> waste your time discussing why I should not be using TRACE in Release mode :-)</p>
| [
{
"answer_id": 27628,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 1,
"selected": false,
"text": "<p>In MFC, TRACE is defined as ATLTRACE. And in release mode that is defined as:</p>\n\n<pre><code>#define ATLTRACE ... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | The **[TRACE macro](http://msdn.microsoft.com/en-us/library/4wyz8787(VS.80).aspx)** can be used to output diagnostic messages to the debugger when the code is compiled in **Debug** mode. I need the same messages while in **Release** mode. Is there a way to achieve this?
(Please do **not** waste your time discussing why I should not be using TRACE in Release mode :-) | Actually, the TRACE macro is a lot more flexible than OutputDebugString. It takes a printf() style format string and parameter list whereas OutputDebugString just takes a single string. In order to implement the full TRACE functionality in release mode you need to do something like this:
```
void trace(const char* format, ...)
{
char buffer[1000];
va_list argptr;
va_start(argptr, format);
wvsprintf(buffer, format, argptr);
va_end(argptr);
OutputDebugString(buffer);
}
``` |
27,670 | <p>On my Vista machine I cannot install the .Net framework 3.5 SP1. Setup ends few moments after ending the download of the required files, stating in the log that: </p>
<pre><code>[08/26/08,09:46:11] Microsoft .NET Framework 2.0SP1 (CBS): [2] Error: Installation failed for component Microsoft .NET Framework 2.0SP1 (CBS). MSI returned error code 1
[08/26/08,09:46:13] WapUI: [2] DepCheck indicates Microsoft .NET Framework 2.0SP1 (CBS) is not installed.
</code></pre>
<p>First thing I did was trying to install 2.0 SP1, but this time setup states that the "product is not supported on Vista system". Uhm.</p>
<p>The real big problem is that this setup fails also when it is called by the Visual Studio 2008 SP1.</p>
<p>Now, I searched the net for this, but I'm not finding a real solution... Any idea / hint? Did anybody have problems during SP1 install?</p>
<p>Thanks</p>
| [
{
"answer_id": 27677,
"author": "Magnus Westin",
"author_id": 2957,
"author_profile": "https://Stackoverflow.com/users/2957",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"http://blogs.msdn.com/astebner/archive/2007/08/24/4548657.aspx\" rel=\"nofollow noreferrer\">Here is an art... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1178/"
] | On my Vista machine I cannot install the .Net framework 3.5 SP1. Setup ends few moments after ending the download of the required files, stating in the log that:
```
[08/26/08,09:46:11] Microsoft .NET Framework 2.0SP1 (CBS): [2] Error: Installation failed for component Microsoft .NET Framework 2.0SP1 (CBS). MSI returned error code 1
[08/26/08,09:46:13] WapUI: [2] DepCheck indicates Microsoft .NET Framework 2.0SP1 (CBS) is not installed.
```
First thing I did was trying to install 2.0 SP1, but this time setup states that the "product is not supported on Vista system". Uhm.
The real big problem is that this setup fails also when it is called by the Visual Studio 2008 SP1.
Now, I searched the net for this, but I'm not finding a real solution... Any idea / hint? Did anybody have problems during SP1 install?
Thanks | [Here is an article describing what might be your problem.](http://blogs.msdn.com/astebner/archive/2007/08/24/4548657.aspx) |
27,711 | <p>I'm having a problem obtaining the total row count for items displayed in a Gridview using Paging and with a LinqDataSource as the source of data.</p>
<p>I've tried several approaches:</p>
<pre><code>protected void GridDataSource_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
totalLabel.Text = e.TotalRowCount.ToString();
}
</code></pre>
<p>returns -1 every time.</p>
<pre><code>protected void LinqDataSource1_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
System.Collections.Generic.List<country> lst = e.Result as System.Collections.Generic.List<country>;
int count = lst.Count;
}
</code></pre>
<p>only gives me the count for the current page, and not the total.</p>
<p>Any other suggestions?</p>
| [
{
"answer_id": 27739,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 2,
"selected": false,
"text": "<p>The LinqDataSourceEventArgs returned in those events return -1 on these occasions:</p>\n\n<blockquote>\n <p>-1 if the... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2841/"
] | I'm having a problem obtaining the total row count for items displayed in a Gridview using Paging and with a LinqDataSource as the source of data.
I've tried several approaches:
```
protected void GridDataSource_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
totalLabel.Text = e.TotalRowCount.ToString();
}
```
returns -1 every time.
```
protected void LinqDataSource1_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
System.Collections.Generic.List<country> lst = e.Result as System.Collections.Generic.List<country>;
int count = lst.Count;
}
```
only gives me the count for the current page, and not the total.
Any other suggestions? | The LinqDataSourceEventArgs returned in those events return -1 on these occasions:
>
> -1 if the LinqDataSourceStatusEventArgs object was created during a data modification operation; -1 if you enabled customized paging by setting AutoPage to true and by setting RetrieveTotalRowCount to false.
>
>
>
[Check here for more information](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linqdatasourcestatuseventargs.totalrowcount.aspx) - the table towards the bottom, shows different properties to set to get the rowcount back, but it looks like you either have to set AutoPage and AllowPage properties to either both true or both false.
Judging by the table in the link above and the example you provide you have Autopage set to false, but AllowPaging set to true, therefore it is returning the amount of rows in the page.
HTH |
27,743 | <p>My RubyOnRails app is set up with the usual pack of mongrels behind Apache configuration. We've noticed that our Mongrel web server memory usage can grow quite large on certain operations and we'd really like to be able to dynamically do a graceful restart of selected Mongrel processes at any time.</p>
<p>However, for reasons I won't go into here it can sometimes be <em>very</em> important that we don't interrupt a Mongrel while it is servicing a request, so I assume a simple process kill isn't the answer.</p>
<p>Ideally, I want to send the Mongrel a signal that says "finish whatever you're doing and then quit before accepting any more connections".</p>
<p>Is there a standard technique or best practice for this?</p>
| [
{
"answer_id": 27787,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 0,
"selected": false,
"text": "<p>Try using:</p>\n\n<pre><code>mongrel_cluster_ctl stop\n</code></pre>\n\n<p>You can also use:</p>\n\n<pre><code>mongrel... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2994/"
] | My RubyOnRails app is set up with the usual pack of mongrels behind Apache configuration. We've noticed that our Mongrel web server memory usage can grow quite large on certain operations and we'd really like to be able to dynamically do a graceful restart of selected Mongrel processes at any time.
However, for reasons I won't go into here it can sometimes be *very* important that we don't interrupt a Mongrel while it is servicing a request, so I assume a simple process kill isn't the answer.
Ideally, I want to send the Mongrel a signal that says "finish whatever you're doing and then quit before accepting any more connections".
Is there a standard technique or best practice for this? | I've done a little more investigation into the Mongrel source and it turns out that Mongrel installs a signal handler to catch an standard process kill (TERM) and do a graceful shutdown, so I don't need a special procedure after all.
You can see this working from the log output you get when killing a Mongrel while it's processing a request. For example:
```
** TERM signal received.
Thu Aug 28 00:52:35 +0000 2008: Reaping 2 threads for slow workers because of 'shutdown'
Waiting for 2 requests to finish, could take 60 seconds.Thu Aug 28 00:52:41 +0000 2008: Reaping 2 threads for slow workers because of 'shutdown'
Waiting for 2 requests to finish, could take 60 seconds.Thu Aug 28 00:52:43 +0000 2008 (13051) Rendering layoutfalsecontent_typetext/htmlactionindex within layouts/application
``` |
27,745 | <p>Given the URL (single line):<br>
<a href="http://test.example.com/dir/subdir/file.html" rel="noreferrer">http://test.example.com/dir/subdir/file.html</a></p>
<p>How can I extract the following parts using regular expressions:</p>
<ol>
<li>The Subdomain (test)</li>
<li>The Domain (example.com)</li>
<li>The path without the file (/dir/subdir/)</li>
<li>The file (file.html)</li>
<li>The path with the file (/dir/subdir/file.html)</li>
<li>The URL without the path (<a href="http://test.example.com" rel="noreferrer">http://test.example.com</a>)</li>
<li>(add any other that you think would be useful)</li>
</ol>
<p>The regex should work correctly even if I enter the following URL: </p>
<pre><code>http://example.example.com/example/example/example.html
</code></pre>
| [
{
"answer_id": 27755,
"author": "hometoast",
"author_id": 2009,
"author_profile": "https://Stackoverflow.com/users/2009",
"pm_score": 8,
"selected": true,
"text": "<blockquote>\n <p>A single regex to parse and breakup a\n full URL including query parameters\n and anchors e.g.</p>\n \... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
] | Given the URL (single line):
<http://test.example.com/dir/subdir/file.html>
How can I extract the following parts using regular expressions:
1. The Subdomain (test)
2. The Domain (example.com)
3. The path without the file (/dir/subdir/)
4. The file (file.html)
5. The path with the file (/dir/subdir/file.html)
6. The URL without the path (<http://test.example.com>)
7. (add any other that you think would be useful)
The regex should work correctly even if I enter the following URL:
```
http://example.example.com/example/example/example.html
``` | >
> A single regex to parse and breakup a
> full URL including query parameters
> and anchors e.g.
>
>
> <https://www.google.com/dir/1/2/search.html?arg=0-a&arg1=1-b&arg3-c#hash>
>
>
> `^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$`
>
>
> RexEx positions:
>
>
> url: RegExp['$&'],
>
>
> protocol:RegExp.$2,
>
>
> host:RegExp.$3,
>
>
> path:RegExp.$4,
>
>
> file:RegExp.$6,
>
>
> query:RegExp.$7,
>
>
> hash:RegExp.$8
>
>
>
you could then further parse the host ('.' delimited) quite easily.
What **I** would do is use something like this:
```
/*
^(.*:)//([A-Za-z0-9\-\.]+)(:[0-9]+)?(.*)$
*/
proto $1
host $2
port $3
the-rest $4
```
the further parse 'the rest' to be as specific as possible. Doing it in one regex is, well, a bit crazy. |
27,757 | <p>I am storing a PNG as an embedded resource in an assembly. From within the same assembly I have some code like this:</p>
<pre><code>Bitmap image = new Bitmap(typeof(MyClass), "Resources.file.png");
</code></pre>
<p>The file, named "file.png" is stored in the "Resources" folder (within Visual Studio), and is marked as an embedded resource.</p>
<p>The code fails with an exception saying: </p>
<blockquote>
<p>Resource MyNamespace.Resources.file.png cannot be found in class MyNamespace.MyClass</p>
</blockquote>
<p>I have identical code (in a different assembly, loading a different resource) which works. So I know the technique is sound. My problem is I end up spending a lot of time trying to figure out what the correct path is. If I could simply query (eg. in the debugger) the assembly to find the correct path, that would save me a load of headaches.</p>
| [
{
"answer_id": 27769,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "<p>I'm guessing that your class is in a different namespace. The canonical way to solve this would be to use the resou... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1006/"
] | I am storing a PNG as an embedded resource in an assembly. From within the same assembly I have some code like this:
```
Bitmap image = new Bitmap(typeof(MyClass), "Resources.file.png");
```
The file, named "file.png" is stored in the "Resources" folder (within Visual Studio), and is marked as an embedded resource.
The code fails with an exception saying:
>
> Resource MyNamespace.Resources.file.png cannot be found in class MyNamespace.MyClass
>
>
>
I have identical code (in a different assembly, loading a different resource) which works. So I know the technique is sound. My problem is I end up spending a lot of time trying to figure out what the correct path is. If I could simply query (eg. in the debugger) the assembly to find the correct path, that would save me a load of headaches. | This will get you a string array of all the resources:
```
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
``` |
27,758 | <p>OK, I know what you're thinking, "why write a method you do not want people to use?" Right?</p>
<p>Well, in short, I have a class that needs to be serialized to XML. In order for the <a href="https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer%28v=vs.110%29.aspx" rel="noreferrer"><code>XmlSerializer</code></a> to do its magic, the class must have a default, empty constructor:</p>
<pre><code>public class MyClass
{
public MyClass()
{
// required for xml serialization
}
}
</code></pre>
<p>So, I need to have it, but I don't want people to <em>use</em> it, so <strong>is there any attribute that can be use to mark the method as "DO NOT USE"?</strong></p>
<p>I was thinking of using the <em>Obsolete</em> attribute (since this can stop the build), but that just seems kinda "wrong", is there any other way of doing this, or do I need to go ahead and bite the bullet? :)</p>
<h2>Update</h2>
<p>OK, I have accepted Keith's answer, since I guess in my heart of hearts, I totally agree. This is why I asked the question in the first place, I don't like the notion of having the <em>Obsolete</em> attribute.</p>
<h3>However...</h3>
<p>There <em>is</em> still a problem, while we are being notified in intellisense, ideally, we would like to break the build, so is there any way to do this? Perhaps create a custom attribute?</p>
<p><strong>More focused question has been created <a href="https://stackoverflow.com/questions/28150/create-an-attribute-to-break-the-build">here</a>.</strong></p>
| [
{
"answer_id": 27763,
"author": "hometoast",
"author_id": 2009,
"author_profile": "https://Stackoverflow.com/users/2009",
"pm_score": 2,
"selected": false,
"text": "<p>I read the heading and immediately thought \"obsolete atribute\". How about</p>\n\n<pre><code> /// <summary>\n... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] | OK, I know what you're thinking, "why write a method you do not want people to use?" Right?
Well, in short, I have a class that needs to be serialized to XML. In order for the [`XmlSerializer`](https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer%28v=vs.110%29.aspx) to do its magic, the class must have a default, empty constructor:
```
public class MyClass
{
public MyClass()
{
// required for xml serialization
}
}
```
So, I need to have it, but I don't want people to *use* it, so **is there any attribute that can be use to mark the method as "DO NOT USE"?**
I was thinking of using the *Obsolete* attribute (since this can stop the build), but that just seems kinda "wrong", is there any other way of doing this, or do I need to go ahead and bite the bullet? :)
Update
------
OK, I have accepted Keith's answer, since I guess in my heart of hearts, I totally agree. This is why I asked the question in the first place, I don't like the notion of having the *Obsolete* attribute.
### However...
There *is* still a problem, while we are being notified in intellisense, ideally, we would like to break the build, so is there any way to do this? Perhaps create a custom attribute?
**More focused question has been created [here](https://stackoverflow.com/questions/28150/create-an-attribute-to-break-the-build).** | If a class is [`[Serialisable]`](https://msdn.microsoft.com/en-us/library/system.serializableattribute%28v=vs.110%29.aspx) (i.e. it can be copied around the place as needed) the param-less constructor is needed to deserialise.
I'm guessing that you want to force your code's access to pass defaults for your properties to a parameterised constructor.
Basically you're saying that it's OK for the [`XmlSerializer`](https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer%28v=vs.110%29.aspx) to make a copy and then set properties, but you don't want your own code to.
To some extent I think this is over-designing.
Just add XML comments that detail what properties need initialising (and what to).
Don't use [`[Obsolete]`](https://msdn.microsoft.com/en-us/library/system.obsoleteattribute%28v=vs.110%29.aspx), because it isn't. Reserve that for genuinely deprecated methods. |
27,774 | <p>Effectively I want to give numeric scores to alphabetic grades and sum them. In Excel, putting the <code>LOOKUP</code> function into an array formula works:</p>
<pre><code>{=SUM(LOOKUP(grades, scoringarray))}
</code></pre>
<p>With the <code>VLOOKUP</code> function this does not work (only gets the score for the first grade). Google Spreadsheets does not appear to have the <code>LOOKUP</code> function and <code>VLOOKUP</code> fails in the same way using:</p>
<pre><code>=SUM(ARRAYFORMULA(VLOOKUP(grades, scoresarray, 2, 0)))
</code></pre>
<p>or</p>
<pre><code>=ARRAYFORMULA(SUM(VLOOKUP(grades, scoresarray, 2, 0)))
</code></pre>
<p>Is it possible to do this (but I have the syntax wrong)? Can you suggest a method that allows having the calculation in one simple cell like this rather than hiding the lookups somewhere else and summing them afterwards?</p>
| [
{
"answer_id": 28132,
"author": "paulmorriss",
"author_id": 2983,
"author_profile": "https://Stackoverflow.com/users/2983",
"pm_score": 2,
"selected": false,
"text": "<p>I'm afraid I think the answer is no. From the help text on\n<a href=\"http://docs.google.com/support/spreadsheets/bin/... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2492/"
] | Effectively I want to give numeric scores to alphabetic grades and sum them. In Excel, putting the `LOOKUP` function into an array formula works:
```
{=SUM(LOOKUP(grades, scoringarray))}
```
With the `VLOOKUP` function this does not work (only gets the score for the first grade). Google Spreadsheets does not appear to have the `LOOKUP` function and `VLOOKUP` fails in the same way using:
```
=SUM(ARRAYFORMULA(VLOOKUP(grades, scoresarray, 2, 0)))
```
or
```
=ARRAYFORMULA(SUM(VLOOKUP(grades, scoresarray, 2, 0)))
```
Is it possible to do this (but I have the syntax wrong)? Can you suggest a method that allows having the calculation in one simple cell like this rather than hiding the lookups somewhere else and summing them afterwards? | I still can't see the formulae in your example (just values), but that is exactly what I'm trying to do in terms of the result; obviously I can already do it "by the side" and sum separately - the key for me is doing it in one cell.
I have looked at it again this morning - using the `MATCH` function for the lookup works in an array formula. But then the `INDEX` function does not. I have also tried using it with `OFFSET` and `INDIRECT` without success. Finally, the `CHOOSE` function does not seem to accept a cell range as its list to choose from - the range degrades to a single value (the first cell in the range). It should also be noted that the `CHOOSE` function only accepts 30 values to choose from (according to the documentation). All very annoying. However, I do now have a working solution in one cell: using the `CHOOSE` function and explicitly listing the result cells one by one in the arguments like this:
```
=ARRAYFORMULA(SUM(CHOOSE(MATCH(D1:D8,Lookups!$A$1:$A$3,0),
Lookups!$B$1,Lookups!$B$2,Lookups!$B$3)))
```
Obviously this doesn't extend very well but hopefully the lookup tables are by nature quite fixed. For larger lookup tables it's a pain to type all the cells individually and some people may exceed the limit of 30 cells.
I would certainly welcome a more elegant solution! |
27,818 | <p>We've embedded an OSGi runtime (Equinox) into out custom client-server application to facilitate plugin development and so far things are going great. We've been using Eclipse to build plugins due to the built-in manifest editor, dependency management, and export wizard. Using Eclipse to manager builds isn't very conducive to continuous integration via Hudson.</p>
<p>We have OSGi bundles which depend on other OSGi bundles. I'd really hate to hardcode build order in a custom ANT build. We've done this is the past and it's pretty horrible. Is there any build tool that can EASILY manage OSGi dependencies, if not automatically resolve them? Are there any DECENT examples of how to this?</p>
<p>CLARIFICATION:</p>
<p>The generated build scripts are only usable via Eclipse. They require manually running pieces of Eclipse. We've also got some standard targets which the Eclipse build won't have, and I don't want to modify the generated file since I may regenerate (I know I can do includes, but I want to avoid the Eclipse gen file all together)</p>
<p>Here is my project layout:</p>
<pre><code>/
-PluginA
-PluginB
-PluginC
.
.
.
</code></pre>
<p>In using the Eclipse PDE, each plugin has a Manifest, but no build.xml as the PDE does that for me. Hard to automate a gui driven process w/ Hudson. I'd like to setup my own build.xml to build each, BUT there are dependencies and build order issues. These issues are driven by the Manifest files (which describe OSGi imports). For example, PluginC depends on PluginB which depends on PluginA. They must be built in the correct order. I realize that I can manually control the build order, I'm looking for a tool to help automate the build order dependency management.</p>
| [
{
"answer_id": 45671,
"author": "jamesh",
"author_id": 4737,
"author_profile": "https://Stackoverflow.com/users/4737",
"pm_score": 1,
"selected": false,
"text": "<p>We use <a href=\"http://www.eclipse.org/buckminster/\" rel=\"nofollow noreferrer\">Buckminster</a>. It's a build and assemb... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287/"
] | We've embedded an OSGi runtime (Equinox) into out custom client-server application to facilitate plugin development and so far things are going great. We've been using Eclipse to build plugins due to the built-in manifest editor, dependency management, and export wizard. Using Eclipse to manager builds isn't very conducive to continuous integration via Hudson.
We have OSGi bundles which depend on other OSGi bundles. I'd really hate to hardcode build order in a custom ANT build. We've done this is the past and it's pretty horrible. Is there any build tool that can EASILY manage OSGi dependencies, if not automatically resolve them? Are there any DECENT examples of how to this?
CLARIFICATION:
The generated build scripts are only usable via Eclipse. They require manually running pieces of Eclipse. We've also got some standard targets which the Eclipse build won't have, and I don't want to modify the generated file since I may regenerate (I know I can do includes, but I want to avoid the Eclipse gen file all together)
Here is my project layout:
```
/
-PluginA
-PluginB
-PluginC
.
.
.
```
In using the Eclipse PDE, each plugin has a Manifest, but no build.xml as the PDE does that for me. Hard to automate a gui driven process w/ Hudson. I'd like to setup my own build.xml to build each, BUT there are dependencies and build order issues. These issues are driven by the Manifest files (which describe OSGi imports). For example, PluginC depends on PluginB which depends on PluginA. They must be built in the correct order. I realize that I can manually control the build order, I'm looking for a tool to help automate the build order dependency management. | Closing out some old questions...
Our setup was not conducive to maven due to lack of network connectivity and timing. I know there are offline maven setups, but it was all too much given the time. Hopefully we'll get to use a proper setup when we've got time to reorganize the build process.
The solution involved Ant, BND, and some custom ant tasks. The various bundle dependencies are manually managed. We were already using Ant; BND and custom tasks tied it all together. The custom tasks just made sure our bnd/eclipse projects were in sync. |
27,832 | <p>I have a DirectShow graph to render MPEG2/4 movies from a network stream. When I assemble the graph by connecting the pins manually it doesn't render. But when I call Render on the GraphBuilder it renders fine. </p>
<p>Obviously there is some setup step that I'm not performing on some filter in the graph that GraphBuilder is performing. </p>
<p>Is there any way to see debug output from GraphBuilder when it assembles a graph?</p>
<p>Is there a way to dump a working graph to see how it was put together?</p>
<p>Any other ideas for unraveling the mystery that lives in the DirectShow box?</p>
<p>Thanks!
-Z</p>
| [
{
"answer_id": 27858,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 5,
"selected": true,
"text": "<p>You can watch the graph you created using GraphEdit, a tool from the DirectShow SDK. In GraphEdit, select File->Connect to re... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2587612/"
] | I have a DirectShow graph to render MPEG2/4 movies from a network stream. When I assemble the graph by connecting the pins manually it doesn't render. But when I call Render on the GraphBuilder it renders fine.
Obviously there is some setup step that I'm not performing on some filter in the graph that GraphBuilder is performing.
Is there any way to see debug output from GraphBuilder when it assembles a graph?
Is there a way to dump a working graph to see how it was put together?
Any other ideas for unraveling the mystery that lives in the DirectShow box?
Thanks!
-Z | You can watch the graph you created using GraphEdit, a tool from the DirectShow SDK. In GraphEdit, select File->Connect to remote Graph...
In order to find your graph in the list, you have to register it in the running object table:
```
void AddToRot( IUnknown *pUnkGraph, DWORD *pdwRegister )
{
IMoniker* pMoniker;
IRunningObjectTable* pROT;
GetRunningObjectTable( 0, &pROT );
WCHAR wsz[256];
swprintf_s( wsz, L"FilterGraph %08p pid %08x", (DWORD_PTR)pUnkGraph, GetCurrentProcessId() );
CreateItemMoniker( L"!", wsz, &pMoniker );
pROT->Register( 0, pUnkGraph, pMoniker, pdwRegister );
// Clean up any COM stuff here ...
}
```
After destroying your graph, you should remove it from the ROT by calling IRunningObjectTable::Revoke |
27,846 | <p>What is the configuration setting for modifying the default homepage in a Grails application to no longer be appName/index.gsp? Of course you can set that page to be a redirect but there must be a better way.</p>
| [
{
"answer_id": 62067,
"author": "dahernan",
"author_id": 6435,
"author_profile": "https://Stackoverflow.com/users/6435",
"pm_score": 4,
"selected": false,
"text": "<p>Edit UrlMappings.groovy</p>\n\n<p>Add for example add this rule, to handle the root with a HomeController.</p>\n\n<p>\"/\... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3014/"
] | What is the configuration setting for modifying the default homepage in a Grails application to no longer be appName/index.gsp? Of course you can set that page to be a redirect but there must be a better way. | Add this in UrlMappings.groovy
```
"/" {
controller = "yourController"
action = "yourAction"
}
```
By configuring the URLMappings this way, the home-page of the app will be yourWebApp/yourController/yourAction.
(cut/pasted from [IntelliGrape Blog](http://blog.intelligrape.com/?p=18)) |
27,894 | <p>In SQL Server 2005, we can create temp tables one of two ways:</p>
<pre><code>declare @tmp table (Col1 int, Col2 int);
</code></pre>
<p>or</p>
<pre><code>create table #tmp (Col1 int, Col2 int);
</code></pre>
<p>What are the differences between these two? I have read conflicting opinions on whether @tmp still uses tempdb, or if everything happens in memory. </p>
<p>In which scenarios does one out-perform the other? </p>
| [
{
"answer_id": 27905,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 4,
"selected": false,
"text": "<p>@wcm - actually to nit pick the Table Variable isn't Ram only - it can be partially stored on disk.</p>\n\n<p>A temp t... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] | In SQL Server 2005, we can create temp tables one of two ways:
```
declare @tmp table (Col1 int, Col2 int);
```
or
```
create table #tmp (Col1 int, Col2 int);
```
What are the differences between these two? I have read conflicting opinions on whether @tmp still uses tempdb, or if everything happens in memory.
In which scenarios does one out-perform the other? | There are a few differences between Temporary Tables (#tmp) and Table Variables (@tmp), although using tempdb isn't one of them, as spelt out in the MSDN link below.
As a rule of thumb, for small to medium volumes of data and simple usage scenarios you should use table variables. (This is an overly broad guideline with of course lots of exceptions - see below and following articles.)
Some points to consider when choosing between them:
* Temporary Tables are real tables so you can do things like CREATE INDEXes, etc. If you have large amounts of data for which accessing by index will be faster then temporary tables are a good option.
* Table variables can have indexes by using PRIMARY KEY or UNIQUE constraints. (If you want a non-unique index just include the primary key column as the last column in the unique constraint. If you don't have a unique column, you can use an identity column.) [SQL 2014 has non-unique indexes too](https://stackoverflow.com/questions/886050/sql-server-creating-an-index-on-a-table-variable/17385085#17385085).
* Table variables don't participate in transactions and `SELECT`s are implicitly with `NOLOCK`. The transaction behaviour can be very helpful, for instance if you want to ROLLBACK midway through a procedure then table variables populated during that transaction will still be populated!
* Temp tables might result in stored procedures being recompiled, perhaps often. Table variables will not.
* You can create a temp table using SELECT INTO, which can be quicker to write (good for ad-hoc querying) and may allow you to deal with changing datatypes over time, since you don't need to define your temp table structure upfront.
* You can pass table variables back from functions, enabling you to encapsulate and reuse logic much easier (eg make a function to split a string into a table of values on some arbitrary delimiter).
* Using Table Variables within user-defined functions enables those functions to be used more widely (see CREATE FUNCTION documentation for details). If you're writing a function you should use table variables over temp tables unless there's a compelling need otherwise.
* Both table variables and temp tables are stored in tempdb. But table variables (since 2005) default to the collation of the current database versus temp tables which take the default collation of tempdb ([ref](https://learn.microsoft.com/sql/t-sql/language-elements/declare-local-variable-transact-sql)). This means you should be aware of collation issues if using temp tables and your db collation is different to tempdb's, causing problems if you want to compare data in the temp table with data in your database.
* Global Temp Tables (##tmp) are another type of temp table available to all sessions and users.
Some further reading:
* [Martin Smith's great answer](https://dba.stackexchange.com/a/16386) on dba.stackexchange.com
* MSDN FAQ on difference between the two: <https://support.microsoft.com/en-gb/kb/305977>
* MDSN blog article: <https://learn.microsoft.com/archive/blogs/sqlserverstorageengine/tempdb-table-variable-vs-local-temporary-table>
* Article: <https://searchsqlserver.techtarget.com/tip/Temporary-tables-in-SQL-Server-vs-table-variables>
* Unexpected behaviors and performance implications of temp tables and temp variables: [Paul White on SQLblog.com](https://sql.kiwi/2012/08/temporary-tables-in-stored-procedures.html) |
27,899 | <p>Is there a way to make S3 default to an index.html page? E.g.: My bucket object listing:</p>
<pre><code>/index.html
/favicon.ico
/images/logo.gif
</code></pre>
<p>A call to <strong>www.example.com/<em>index.html</em></strong> works great! But if one were to call <strong>www.example.com/</strong> we'd either get a 403 or a REST object listing XML document depending on how bucket-level ACL was configured.</p>
<p>So, the question: Is there a way to have index.html functionality with content hosted on S3?</p>
| [
{
"answer_id": 27922,
"author": "yoavf",
"author_id": 1011,
"author_profile": "https://Stackoverflow.com/users/1011",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest reading <a href=\"http://developer.amazonwebservices.com/connect/thread.jspa?threadID=10849&start=0&... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2961/"
] | Is there a way to make S3 default to an index.html page? E.g.: My bucket object listing:
```
/index.html
/favicon.ico
/images/logo.gif
```
A call to **www.example.com/*index.html*** works great! But if one were to call **www.example.com/** we'd either get a 403 or a REST object listing XML document depending on how bucket-level ACL was configured.
So, the question: Is there a way to have index.html functionality with content hosted on S3? | Amazon S3 now supports [Index Documents](http://docs.amazonwebservices.com/AmazonS3/latest/dev/IndexDocumentSupport.html)
The *index document* for a bucket can be set to something like `index.html`. When accessing the root of the site or a sub-directory containing a document of that name that document is returned.
It is extremely easy to do using the aws cli:
```
aws s3 website $MY_BUCKET_NAME --index-document index.html
```
You can set the *index document* from the AWS Management Console:
 |
27,910 | <p>The <a href="http://doi.org/" rel="noreferrer">DOI</a> system places basically no useful limitations on what constitutes <a href="http://doi.org/handbook_2000/enumeration.html#2.2" rel="noreferrer">a reasonable identifier</a>. However, being able to pull DOIs out of PDFs, web pages, etc. is quite useful for citation information, etc.</p>
<p>Is there a reliable way to identify a DOI in a block of text without assuming the 'doi:' prefix? (any language acceptable, regexes preferred, and avoiding false positives a must)</p>
| [
{
"answer_id": 29639,
"author": "Silas Snider",
"author_id": 2933,
"author_profile": "https://Stackoverflow.com/users/2933",
"pm_score": 1,
"selected": false,
"text": "<p>The following regex should do the job (Perl regex syntax):</p>\n\n<pre><code>/(10\\.\\d+\\/\\d+)/\n</code></pre>\n\n<... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2963/"
] | The [DOI](http://doi.org/) system places basically no useful limitations on what constitutes [a reasonable identifier](http://doi.org/handbook_2000/enumeration.html#2.2). However, being able to pull DOIs out of PDFs, web pages, etc. is quite useful for citation information, etc.
Is there a reliable way to identify a DOI in a block of text without assuming the 'doi:' prefix? (any language acceptable, regexes preferred, and avoiding false positives a must) | Ok, I'm currently extracting thousands of DOIs from free form text (XML) and I realized that [my previous approach](https://stackoverflow.com/a/10300246/89771) had a few problems, namely regarding encoded entities and trailing punctuation, so I went on reading [the specification](http://www.doi.org/doi_handbook/2_Numbering.html) and this is the best I could come with.
---
>
> The DOI prefix shall be composed of a directory indicator followed by
> a registrant code. These two components shall be separated by a full
> stop (period).
>
>
> The directory indicator shall be "10". The directory indicator
> distinguishes the entire set of character strings (prefix and suffix)
> as digital object identifiers within the resolution system.
>
>
>
Easy enough, the initial `\b` prevents us from "matching" a "DOI" that doesn't start with `10.`:
```
$pattern = '\b(10[.]';
```
---
>
> The second element of the DOI prefix shall be the registrant code. The
> registrant code is a unique string assigned to a registrant.
>
>
>
Also, all assigned registrant code are numeric, and at least 4 digits long, so:
```
$pattern = '\b(10[.][0-9]{4,}';
```
---
>
> The registrant code may be further divided into sub-elements for
> administrative convenience if desired. Each sub-element of the
> registrant code shall be preceded by a full stop.
>
>
>
`$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*';`
---
>
> The DOI syntax shall be made up of a DOI prefix and a DOI suffix
> separated by a forward slash.
>
>
>
However, this isn't absolutely necessary, section 2.2.3 states that uncommon suffix systems may use other conventions (such as `10.1000.123456` instead of `10.1000/123456`), but lets cut some slack.
`$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/';`
---
>
> The DOI name is case-insensitive and can incorporate any printable
> characters from the legal graphic characters of Unicode. The DOI
> suffix shall consist of a character string of any length chosen by the
> registrant. Each suffix shall be unique to the prefix element that
> precedes it. The unique suffix can be a sequential number, or it might
> incorporate an identifier generated from or based on another system.
>
>
>
Now this is where it gets trickier, from all the DOIs I have processed, I saw the following characters (besides `[0-9a-zA-Z]` of course) in their **suffixes**: `.-()/:-` -- so, while it doesn't exist, the DOI `10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7` is completely plausible.
The logical choice would be to use `\S` or the `[[:graph:]]` PCRE POSIX class, so lets do that:
`$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/\S+'; // or`
`$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/[[:graph:]]+';`
---
Now we have a difficult problem, the `[[:graph:]]` class is a super-set of the `[[:punct:]]` class, which includes characters easily found in free text or any markup language: `"'&<>` among others.
Lets just filter the markup ones for now using a negative lookahead:
`$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])\S)+'; // or`
`$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])[[:graph:]])+';`
---
The above should cover encoded entities (`&`), attribute quotes (`["']`) and open / close tags (`[<>]`).
Unlike markup languages, free text usually doesn't employ punctuation characters unless they are bounded by at least one space ***or*** placed at the end of a sentence, for instance:
>
> This is a long DOI:
> `10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7`**!!!**
>
>
>
The solution here is to close our capture group and assert another word boundary:
`$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])\S)+)\b'; // or`
`$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])[[:graph:]])+)\b';`
And *voilá*, [here is a demo](http://regexpal.com/?flags=g®ex=%5Cb(10%5B.%5D%5B0-9%5D%7B4%2C%7D(%3F%3A%5B.%5D%5B0-9%5D%2B)*%2F(%3F%3A(%3F!%5B%22%26%5C%27%3C%3E%5D)%5CS)%2B)%5Cb&input=This%20is%20a%20short%20DOI%3A%2010.1000%2F123456.%0AThis%20is%20NOT%20a%20DOI%3A%204210.1000%2F123456.%0AThis%20is%20a%20long%20DOI%3A%2010.1016.12.31%2Fnature.S0735-1097(98)2000%2F12%2F31%2F34%3A7-7!!!%0A%0A10.1007%2F978-3-642-28108-2_19%0A10.1007.10%2F978-3-642-28108-2_19%20(fictitious%20example%2C%20see%20%40Ju9OR%20comment)%0A10.1016%2FS0735-1097(98)00347-7%0A10.1579%2F0044-7447(2006)35%5C%5B89%3ARDUICP%5C%5D2.0.CO%3B2%0A%0AAlso%2C%20correctly%20discards%20some%20falsy%20(X%7CHT)ML%20stuff%20like%3A%0A%0A%3Cgeo%20coords%3D%2210.4515260%2C51.1656910%22%3E%3C%2Fgeo%3E). |
27,921 | <p>Story: The user uploads an image that will be added to a photo gallery. As part of the upload process, we need to A) store the image on the web server's hard drive and B) store a thumbnail of the image on the web server's hard drive.</p>
<p>"Best" here is defined as </p>
<ul>
<li>Relatively easy to implement, understand, and maintain</li>
<li>Results in a thumbnail of reasonable quality</li>
</ul>
<p>Performance and high-quality thumbnails are secondary.</p>
| [
{
"answer_id": 27938,
"author": "Huppie",
"author_id": 1830,
"author_profile": "https://Stackoverflow.com/users/1830",
"pm_score": 5,
"selected": true,
"text": "<p>I suppose your best solution would be using the <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.image.getth... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/308/"
] | Story: The user uploads an image that will be added to a photo gallery. As part of the upload process, we need to A) store the image on the web server's hard drive and B) store a thumbnail of the image on the web server's hard drive.
"Best" here is defined as
* Relatively easy to implement, understand, and maintain
* Results in a thumbnail of reasonable quality
Performance and high-quality thumbnails are secondary. | I suppose your best solution would be using the [GetThumbnailImage](http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage.aspx) from the .NET [Image](http://msdn.microsoft.com/en-us/library/system.drawing.image.aspx) class.
```
// Example in C#, should be quite alike in ASP.NET
// Assuming filename as the uploaded file
using ( Image bigImage = new Bitmap( filename ) )
{
// Algorithm simplified for purpose of example.
int height = bigImage.Height / 10;
int width = bigImage.Width / 10;
// Now create a thumbnail
using ( Image smallImage = image.GetThumbnailImage( width,
height,
new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero) )
{
smallImage.Save("thumbnail.jpg", ImageFormat.Jpeg);
}
}
``` |
27,928 | <p>How do I calculate the distance between two points specified by latitude and longitude?</p>
<p>For clarification, I'd like the distance in kilometers; the points use the WGS84 system and I'd like to understand the relative accuracies of the approaches available.</p>
| [
{
"answer_id": 27943,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 11,
"selected": true,
"text": "<p>This <a href=\"http://www.movable-type.co.uk/scripts/latlong.html\" rel=\"noreferrer\">link</a> might be helpful to you, as ... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1456/"
] | How do I calculate the distance between two points specified by latitude and longitude?
For clarification, I'd like the distance in kilometers; the points use the WGS84 system and I'd like to understand the relative accuracies of the approaches available. | This [link](http://www.movable-type.co.uk/scripts/latlong.html) might be helpful to you, as it details the use of the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) to calculate the distance.
Excerpt:
>
> This script [in Javascript] calculates great-circle distances between the two points –
> that is, the shortest distance over the earth’s surface – using the
> ‘Haversine’ formula.
>
>
>
```js
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
``` |
27,972 | <p>JavaScript needs access to cookies if AJAX is used on a site with access restrictions based on cookies. Will HttpOnly cookies work on an AJAX site? </p>
<p><em>Edit:</em> Microsoft created a way to prevent XSS attacks by disallowing JavaScript access to cookies if HttpOnly is specified. FireFox later adopted this. So my question is: If you are using AJAX on a site, like StackOverflow, are Http-Only cookies an option?</p>
<p><em>Edit 2:</em> Question 2. If the purpose of HttpOnly is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, <strong>what is the point of HttpOnly</strong>?</p>
<p><em>Edit 3:</em> Here is a quote from Wikipedia:</p>
<blockquote>
<p>When the browser receives such a cookie, it is supposed to use it as usual in the following HTTP exchanges, but not to make it visible to client-side scripts.[32] The <code>HttpOnly</code> flag is not part of any standard, and is not implemented in all browsers. Note that there is currently no prevention of reading or writing the session cookie via a XMLHTTPRequest. [33].</p>
</blockquote>
<p>I understand that <code>document.cookie</code> is blocked when you use HttpOnly. But it seems that you can still read cookie values in the XMLHttpRequest object, allowing for XSS. How does HttpOnly make you any safer than? By making cookies essentially read only? </p>
<p>In your example, I cannot write to your <code>document.cookie</code>, but I can still steal your cookie and post it to my domain using the XMLHttpRequest object.</p>
<pre><code><script type="text/javascript">
var req = null;
try { req = new XMLHttpRequest(); } catch(e) {}
if (!req) try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
if (!req) try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
req.open('GET', 'http://stackoverflow.com/', false);
req.send(null);
alert(req.getAllResponseHeaders());
</script>
</code></pre>
<p><em>Edit 4:</em> Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated...</p>
<p><em>Final Edit:</em> Ahh, apparently both sites are wrong, this is actually a <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=380418" rel="noreferrer">bug in FireFox</a>. IE6 & 7 are actually the only browsers that currently fully support HttpOnly.</p>
<p>To reiterate everything I've learned:</p>
<ul>
<li>HttpOnly restricts all access to document.cookie in IE7 & and FireFox (not sure about other browsers)</li>
<li>HttpOnly removes cookie information from the response headers in XMLHttpObject.getAllResponseHeaders() in IE7.</li>
<li>XMLHttpObjects may only be submitted to the domain they originated from, so there is no cross-domain posting of the cookies.</li>
</ul>
<p><em>edit: This information is likely no longer up to date.</em></p>
| [
{
"answer_id": 28000,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 2,
"selected": false,
"text": "<p>Not necessarily, it depends what you want to do. Could you elaborate a bit? AJAX doesn't need access to cookies to w... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] | JavaScript needs access to cookies if AJAX is used on a site with access restrictions based on cookies. Will HttpOnly cookies work on an AJAX site?
*Edit:* Microsoft created a way to prevent XSS attacks by disallowing JavaScript access to cookies if HttpOnly is specified. FireFox later adopted this. So my question is: If you are using AJAX on a site, like StackOverflow, are Http-Only cookies an option?
*Edit 2:* Question 2. If the purpose of HttpOnly is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, **what is the point of HttpOnly**?
*Edit 3:* Here is a quote from Wikipedia:
>
> When the browser receives such a cookie, it is supposed to use it as usual in the following HTTP exchanges, but not to make it visible to client-side scripts.[32] The `HttpOnly` flag is not part of any standard, and is not implemented in all browsers. Note that there is currently no prevention of reading or writing the session cookie via a XMLHTTPRequest. [33].
>
>
>
I understand that `document.cookie` is blocked when you use HttpOnly. But it seems that you can still read cookie values in the XMLHttpRequest object, allowing for XSS. How does HttpOnly make you any safer than? By making cookies essentially read only?
In your example, I cannot write to your `document.cookie`, but I can still steal your cookie and post it to my domain using the XMLHttpRequest object.
```
<script type="text/javascript">
var req = null;
try { req = new XMLHttpRequest(); } catch(e) {}
if (!req) try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
if (!req) try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
req.open('GET', 'http://stackoverflow.com/', false);
req.send(null);
alert(req.getAllResponseHeaders());
</script>
```
*Edit 4:* Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated...
*Final Edit:* Ahh, apparently both sites are wrong, this is actually a [bug in FireFox](https://bugzilla.mozilla.org/show_bug.cgi?id=380418). IE6 & 7 are actually the only browsers that currently fully support HttpOnly.
To reiterate everything I've learned:
* HttpOnly restricts all access to document.cookie in IE7 & and FireFox (not sure about other browsers)
* HttpOnly removes cookie information from the response headers in XMLHttpObject.getAllResponseHeaders() in IE7.
* XMLHttpObjects may only be submitted to the domain they originated from, so there is no cross-domain posting of the cookies.
*edit: This information is likely no longer up to date.* | Yes, HTTP-Only cookies would be fine for this functionality. They will still be provided with the XmlHttpRequest's request to the server.
In the case of Stack Overflow, the cookies are automatically provided as part of the XmlHttpRequest request. I don't know the implementation details of the Stack Overflow authentication provider, but that cookie data is probably automatically used to verify your identity at a lower level than the "vote" controller method.
More generally, cookies are **not** required for AJAX. XmlHttpRequest support (or even iframe remoting, on older browsers) is all that is technically required.
However, if you want to provide security for AJAX enabled functionality, then the same rules apply as with traditional sites. You need some method for identifying the user behind each request, and cookies are almost always the means to that end.
>
> In your example, I cannot write to your document.cookie, but I can still steal your cookie and post it to my domain using the XMLHttpRequest object.
>
>
>
XmlHttpRequest won't make cross-domain requests (for exactly the sorts of reasons you're touching on).
You could normally inject script to send the cookie to your domain using iframe remoting or JSONP, but then HTTP-Only protects the cookie again since it's inaccessible.
Unless you had compromised StackOverflow.com on the server side, you wouldn't be able to steal my cookie.
>
> Edit 2: Question 2. If the purpose of Http-Only is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, what is the point of Http-Only?
>
>
>
Consider this scenario:
* I find an avenue to inject JavaScript code into the page.
* Jeff loads the page and my malicious JavaScript modifies his cookie to match mine.
* Jeff submits a stellar answer to your question.
* Because he submits it with my cookie data instead of his, the answer will become mine.
* You vote up "my" stellar answer.
* My real account gets the point.
With HTTP-Only cookies, the second step would be impossible, thereby defeating my XSS attempt.
>
> Edit 4: Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated...
>
>
>
That's correct. You can still session hijack that way. It does significantly thin the herd of people who can successfully execute even that XSS hack against you though.
However, if you go back to my example scenario, you can see where HTTP-Only *does* successfully cut off the XSS attacks which rely on modifying the client's cookies (not uncommon).
It boils down to the fact that a) no single improvement will solve *all* vulnerabilities and b) no system will *ever* be completely secure. HTTP-Only **is** a useful tool in shoring up against XSS.
Similarly, even though the cross domain restriction on XmlHttpRequest isn't 100% successful in preventing all XSS exploits, you'd still never dream of removing the restriction. |
27,983 | <p>I have a table of tags and want to get the highest count tags from the list.</p>
<p>Sample data looks like this</p>
<pre><code>id (1) tag ('night')
id (2) tag ('awesome')
id (3) tag ('night')
</code></pre>
<p>using</p>
<pre><code>SELECT COUNT(*), `Tag` from `images-tags`
GROUP BY `Tag`
</code></pre>
<p>gets me back the data I'm looking for perfectly. However, I would like to organize it, so that the highest tag counts are first, and limit it to only send me the first 20 or so.</p>
<p>I tried this...</p>
<pre><code>SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY COUNT(id) DESC
LIMIT 20
</code></pre>
<p>and I keep getting an "Invalid use of group function - ErrNr 1111"</p>
<p>What am I doing wrong?</p>
<p>I'm using MySQL 4.1.25-Debian</p>
| [
{
"answer_id": 27992,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 6,
"selected": false,
"text": "<p>MySQL prior to version 5 did not allow aggregate functions in ORDER BY clauses.</p>\n\n<p>You can get around this l... | 2008/08/26 | [
"https://Stackoverflow.com/questions/27983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1477/"
] | I have a table of tags and want to get the highest count tags from the list.
Sample data looks like this
```
id (1) tag ('night')
id (2) tag ('awesome')
id (3) tag ('night')
```
using
```
SELECT COUNT(*), `Tag` from `images-tags`
GROUP BY `Tag`
```
gets me back the data I'm looking for perfectly. However, I would like to organize it, so that the highest tag counts are first, and limit it to only send me the first 20 or so.
I tried this...
```
SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY COUNT(id) DESC
LIMIT 20
```
and I keep getting an "Invalid use of group function - ErrNr 1111"
What am I doing wrong?
I'm using MySQL 4.1.25-Debian | In all versions of MySQL, simply alias the aggregate in the SELECT list, and order by the alias:
```
SELECT COUNT(id) AS theCount, `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY theCount DESC
LIMIT 20
``` |
28,002 | <p>I've been writing C and C++ code for almost twenty years, but there's one aspect of these languages that I've never really understood. I've obviously used regular casts i.e.</p>
<pre><code>MyClass *m = (MyClass *)ptr;
</code></pre>
<p>all over the place, but there seem to be two other types of casts, and I don't know the difference. What's the difference between the following lines of code?</p>
<pre><code>MyClass *m = (MyClass *)ptr;
MyClass *m = static_cast<MyClass *>(ptr);
MyClass *m = dynamic_cast<MyClass *>(ptr);
</code></pre>
| [
{
"answer_id": 28020,
"author": "Inisheer",
"author_id": 2982,
"author_profile": "https://Stackoverflow.com/users/2982",
"pm_score": 4,
"selected": false,
"text": "<p><code>dynamic_cast</code> has runtime type checking and only works with references and pointers, whereas <code>static_cas... | 2008/08/26 | [
"https://Stackoverflow.com/questions/28002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1821/"
] | I've been writing C and C++ code for almost twenty years, but there's one aspect of these languages that I've never really understood. I've obviously used regular casts i.e.
```
MyClass *m = (MyClass *)ptr;
```
all over the place, but there seem to be two other types of casts, and I don't know the difference. What's the difference between the following lines of code?
```
MyClass *m = (MyClass *)ptr;
MyClass *m = static_cast<MyClass *>(ptr);
MyClass *m = dynamic_cast<MyClass *>(ptr);
``` | static\_cast
------------
`static_cast` is used for cases where you basically want to reverse an implicit conversion, with a few restrictions and additions. `static_cast` performs no runtime checks. This should be used if you know that you refer to an object of a specific type, and thus a check would be unnecessary. Example:
```
void func(void *data) {
// Conversion from MyClass* -> void* is implicit
MyClass *c = static_cast<MyClass*>(data);
...
}
int main() {
MyClass c;
start_thread(&func, &c) // func(&c) will be called
.join();
}
```
In this example, you know that you passed a `MyClass` object, and thus there isn't any need for a runtime check to ensure this.
dynamic\_cast
-------------
`dynamic_cast` is useful when you don't know what the dynamic type of the object is. It returns a null pointer if the object referred to doesn't contain the type casted to as a base class (when you cast to a reference, a `bad_cast` exception is thrown in that case).
```
if (JumpStm *j = dynamic_cast<JumpStm*>(&stm)) {
...
} else if (ExprStm *e = dynamic_cast<ExprStm*>(&stm)) {
...
}
```
You can **not** use `dynamic_cast` for downcast (casting to a derived class) **if** the argument type is not polymorphic. For example, the following code is not valid, because `Base` doesn't contain any virtual function:
```
struct Base { };
struct Derived : Base { };
int main() {
Derived d; Base *b = &d;
dynamic_cast<Derived*>(b); // Invalid
}
```
An "up-cast" (cast to the base class) is always valid with both `static_cast` and `dynamic_cast`, and also without any cast, as an "up-cast" is an implicit conversion (assuming the base class is accessible, i.e. it's a `public` inheritance).
Regular Cast
------------
These casts are also called C-style cast. A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering `dynamic_cast`. Needless to say, this is much more powerful as it combines all of `const_cast`, `static_cast` and `reinterpret_cast`, but it's also unsafe, because it does not use `dynamic_cast`.
In addition, C-style casts not only allow you to do this, but they also allow you to safely cast to a private base-class, while the "equivalent" `static_cast` sequence would give you a compile-time error for that.
Some people prefer C-style casts because of their brevity. I use them for numeric casts only, and use the appropriate C++ casts when user defined types are involved, as they provide stricter checking. |
28,003 | <p>I have a large database and would like to select table names that have a certain column name. I have done something like this in MySQL, but can't find any info on SQL Server.</p>
<p>I want to do something like:</p>
<pre><code>select [table]
from [db]
where table [has column 'classtypeid']
</code></pre>
<p>How can I do something like this?</p>
| [
{
"answer_id": 28008,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 4,
"selected": true,
"text": "<p>Use the ANSI information_schema views, this will also work in MySQL</p>\n\n<pre><code>select table_name \nfrom information_... | 2008/08/26 | [
"https://Stackoverflow.com/questions/28003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | I have a large database and would like to select table names that have a certain column name. I have done something like this in MySQL, but can't find any info on SQL Server.
I want to do something like:
```
select [table]
from [db]
where table [has column 'classtypeid']
```
How can I do something like this? | Use the ANSI information\_schema views, this will also work in MySQL
```
select table_name
from information_schema.columns
where column_name = 'classtypeid'
``` |
28,029 | <p>How can I have it so Visual Studio doesn't keep re-creating this folder that I never use. It's annoying ot keep looking and unnecessary.</p>
| [
{
"answer_id": 29442,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": -1,
"selected": true,
"text": "<pre><code>Tools->Options->Addin/Macro Security\n</code></pre>\n\n<p>Change Paths there.</p>\n"
},
{
"answer_id... | 2008/08/26 | [
"https://Stackoverflow.com/questions/28029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2993/"
] | How can I have it so Visual Studio doesn't keep re-creating this folder that I never use. It's annoying ot keep looking and unnecessary. | ```
Tools->Options->Addin/Macro Security
```
Change Paths there. |
28,092 | <p>I have a ListBox that has a style defined for ListBoxItems. Inside this style, I have some labels and a button. One that button, I want to define a click event that can be handled on my page (or any page that uses that style). How do I create an event handler on my WPF page to handle the event from my ListBoxItems style?</p>
<p>Here is my style (affected code only):</p>
<pre><code><Style x:Key="UsersTimeOffList" TargetType="{x:Type ListBoxItem}">
...
<Grid>
<Button x:Name="btnRemove" Content="Remove" Margin="0,10,40,0" Click="btnRemove_Click" />
</Grid>
</Style>
</code></pre>
<p>Thanks! </p>
| [
{
"answer_id": 28187,
"author": "Jas",
"author_id": 777,
"author_profile": "https://Stackoverflow.com/users/777",
"pm_score": 0,
"selected": false,
"text": "<p>You could create a user control (.ascx) to house the listbox. Then add a public event for the page.</p>\n\n<pre><code>Public Eve... | 2008/08/26 | [
"https://Stackoverflow.com/questions/28092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] | I have a ListBox that has a style defined for ListBoxItems. Inside this style, I have some labels and a button. One that button, I want to define a click event that can be handled on my page (or any page that uses that style). How do I create an event handler on my WPF page to handle the event from my ListBoxItems style?
Here is my style (affected code only):
```
<Style x:Key="UsersTimeOffList" TargetType="{x:Type ListBoxItem}">
...
<Grid>
<Button x:Name="btnRemove" Content="Remove" Margin="0,10,40,0" Click="btnRemove_Click" />
</Grid>
</Style>
```
Thanks! | Take a look at [RoutedCommand](http://msdn.microsoft.com/en-us/library/system.windows.input.routedcommand.aspx)s.
Define your command in myclass somewhere as follows:
```
public static readonly RoutedCommand Login = new RoutedCommand();
```
Now define your button with this command:
```
<Button Command="{x:Static myclass.Login}" />
```
You can use CommandParameter for extra information..
Now last but not least, start listening to your command:
In the constructor of the class you wish to do some nice stuff, you place:
```
CommandBindings.Add(new CommandBinding(myclass.Login, ExecuteLogin));
```
or in XAML:
```
<UserControl.CommandBindings>
<CommandBinding Command="{x:Static myclass.Login}" Executed="ExecuteLogin" />
</UserControl.CommandBindings>
```
And you implement the delegate the CommandBinding needs:
```
private void ExecuteLogin(object sender, ExecutedRoutedEventArgs e)
{
//Your code goes here... e has your parameter!
}
```
You can start listening to this command everywhere in your visual tree!
Hope this helps
PS You can also define the CommandBinding with a CanExecute delegate which will even disable your command if the CanExecute says so :)
PPS Here is another example: [RoutedCommands in WPF](http://www.wpfwiki.com/Default.aspx?Page=WPF%20Q13.8&AspxAutoDetectCookieSupport=1) |
28,098 | <p>How do I convert the value of a PHP variable to string?</p>
<p>I was looking for something better than concatenating with an empty string:</p>
<pre><code>$myText = $myVar . '';
</code></pre>
<p>Like the <code>ToString()</code> method in Java or .NET.</p>
| [
{
"answer_id": 28101,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 4,
"selected": false,
"text": "<p>Putting it in double quotes should work:</p>\n\n<pre><code>$myText = \"$myVar\";\n</code></pre>\n"
},
{
"answer_id... | 2008/08/26 | [
"https://Stackoverflow.com/questions/28098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2680/"
] | How do I convert the value of a PHP variable to string?
I was looking for something better than concatenating with an empty string:
```
$myText = $myVar . '';
```
Like the `ToString()` method in Java or .NET. | You can use the [casting operators](http://us3.php.net/manual/en/language.types.type-juggling.php):
```
$myText = (string)$myVar;
```
There are more details for string casting and conversion in the [Strings section](http://us3.php.net/manual/en/language.types.string.php#language.types.string.casting) of the PHP manual, including special handling for booleans and nulls. |