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 |
|---|---|---|---|---|---|---|
121,722 | <pre><code>string percentage = e.Row.Cells[7].Text;
</code></pre>
<p>I am trying to do some dynamic stuff with my GridView, so I have wired up some code to the RowDataBound event. I am trying to get the value from a particular cell, which is a TemplateField. But the code above always seems to be returning an empty string. </p>
<p>Any ideas?</p>
<p>To clarify, here is a bit the offending cell:</p>
<pre><code><asp:TemplateField HeaderText="# Percentage click throughs">
<ItemTemplate>
<%# AddPercentClickThroughs((int)Eval("EmailSummary.pLinksClicked"), (int)Eval("NumberOfSends")) %>
</ItemTemplate>
</asp:TemplateField>
</code></pre>
<p>On a related note, does anyone know if there is a better way of selecting the cell in the row. It sucks putting in <code>cell[1]</code>. Couldn't I do <code>cell["mycellname"]</code>, so if I decide to change the order of my cells, bugs wont appear?</p>
| [
{
"answer_id": 121740,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 5,
"selected": true,
"text": "<p>First you need to wrap your code in a <code>Label</code> or <code>Literal</code> control so that you can reference it... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3193/"
] | ```
string percentage = e.Row.Cells[7].Text;
```
I am trying to do some dynamic stuff with my GridView, so I have wired up some code to the RowDataBound event. I am trying to get the value from a particular cell, which is a TemplateField. But the code above always seems to be returning an empty string.
Any ideas?
To clarify, here is a bit the offending cell:
```
<asp:TemplateField HeaderText="# Percentage click throughs">
<ItemTemplate>
<%# AddPercentClickThroughs((int)Eval("EmailSummary.pLinksClicked"), (int)Eval("NumberOfSends")) %>
</ItemTemplate>
</asp:TemplateField>
```
On a related note, does anyone know if there is a better way of selecting the cell in the row. It sucks putting in `cell[1]`. Couldn't I do `cell["mycellname"]`, so if I decide to change the order of my cells, bugs wont appear? | First you need to wrap your code in a `Label` or `Literal` control so that you can reference it properly. What's happening is that there's no way for the system to keep track of it, because there's no control associated with the text. It's the control's responsibility to add its contents to viewstate.
You need to use gridView.FindControl("controlName"); to get the control in the row. From there you can get at its properties including `Text`.
You can also get at the DataItem property of the Row in question and cast it to the appropriate type and extract the information directly. |
121,762 | <p>I have two threads in an Android application, one is the view thread, and the other is the worker thread. What I want to do is, sleep the worker thread until the view thread terminates the handling of the onDraw method.</p>
<p>How i can do this? is there any wait for the signal or something?</p>
| [
{
"answer_id": 121853,
"author": "Paul Brinkley",
"author_id": 18160,
"author_profile": "https://Stackoverflow.com/users/18160",
"pm_score": 6,
"selected": true,
"text": "<p>Share a java.lang.Object between the two threads, whose sole purpose is to tell the worker thread when it can cont... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7363/"
] | I have two threads in an Android application, one is the view thread, and the other is the worker thread. What I want to do is, sleep the worker thread until the view thread terminates the handling of the onDraw method.
How i can do this? is there any wait for the signal or something? | Share a java.lang.Object between the two threads, whose sole purpose is to tell the worker thread when it can continue its work. Whenever the worker thread reaches a point where it should sleep, it does this:
```
stick.wait();
```
When the view thread finishes its onDraw work, it calls this:
```
stick.notify();
```
Note the requirement that the view thread owns the monitor on the object. In your case, this should be fairly simple to enforce with a small sync block:
```
void onDraw() {
...
synchronized (stick) {
stick.notify();
}
} // end onDraw()
```
Consult the javadoc for java.lang.Object on these methods (and notifyAll, just in case); they're very well written. |
121,810 | <p><strong>Is there any way that I can remove the Print item from the context menu when you right-click on an email with VBA?</strong></p>
<p>I am forever right-clicking to reply to an email, only to accidentally click <code>Print</code> and have Outlook send it directly to the printer quicker than I can stop it.</p>
<p><img src="https://farm4.static.flickr.com/3221/2882658372_496d6e7a11_o.jpg" alt="alt text"></p>
<p><strong>NB:</strong> I am using Outlook 2007.</p>
| [
{
"answer_id": 121899,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 3,
"selected": false,
"text": "<p>Thera is sample how to programaticly working with Outlook:\n<a href=\"http://msdn.microsoft.com/en-us/library/bb176426.asp... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | **Is there any way that I can remove the Print item from the context menu when you right-click on an email with VBA?**
I am forever right-clicking to reply to an email, only to accidentally click `Print` and have Outlook send it directly to the printer quicker than I can stop it.

**NB:** I am using Outlook 2007. | Based on the link TcKs provide, that was pretty simple.
In the example below I check the type of the item so that it only affects e-mails and not calendar items.
To enter the code in outlook, Type Alt + F11, then expand the Microsoft Office Outlook Objects in the Project pane. Then double click the ThisOutlookSession. Then paste this code into the code window. I don't like to check captions like this as you can run into issues with internationalization. But I didn't see an ActionID or anything on the Command. There was a FaceID but that is just the id of the printer icon.
```vb
Private Sub Application_ItemContextMenuDisplay(ByVal CommandBar As Office.CommandBar, ByVal Selection As Selection)
Dim cmdTemp As Office.CommandBarControl
If Selection.Count > 0 Then
Select Case TypeName(Selection.Item(1))
Case "MailItem"
For Each cmdTemp In CommandBar.Controls
If cmdTemp.Caption = "&Print" Then
cmdTemp.Delete
Exit For
End If
Next cmdTemp
Case Else
'Debug.Print TypeName(Selection.Item(1))
End Select
End If
End Sub
``` |
121,813 | <p>We have redesigned the structure to a website which has several business units. Now I want to redirect (301) to the new page.</p>
<p>IE: <br />
was www.example.com/abc <br />
now www.example.com/default.aspx?article=abc <br /></p>
<p>I have tried to use Global.asax to do this, and it works properly when I debug through it.</p>
<pre><code> if (Request.RawUrl.Contains("abc"))
{
Response.RedirectLocation = "/default.aspx?article=abc";
Response.StatusCode = 301;
Response.StatusDescription = "Moved";
Response.End();
}
</code></pre>
<p>So <a href="http://localhost:1234/example/abc" rel="nofollow noreferrer">http://localhost:1234/example/abc</a> redirects properly, but (where 1234 is the port for the debugging server)<br/>
<a href="http://localhost/example/abc" rel="nofollow noreferrer">http://localhost/example/abc</a> does not redirect, it gives me a 404.</p>
<p>Any ideas?</p>
<hr>
<p>Additional info:
If I go to <a href="http://localhost/example/abc/default.aspx" rel="nofollow noreferrer">http://localhost/example/abc/default.aspx</a> then it redirects properly.</p>
| [
{
"answer_id": 121834,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "<p>Have you made sure the web.config files are the same for each website (assuming :1234 is different to :80)</p>\n\n<p>Als... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18821/"
] | We have redesigned the structure to a website which has several business units. Now I want to redirect (301) to the new page.
IE:
was www.example.com/abc
now www.example.com/default.aspx?article=abc
I have tried to use Global.asax to do this, and it works properly when I debug through it.
```
if (Request.RawUrl.Contains("abc"))
{
Response.RedirectLocation = "/default.aspx?article=abc";
Response.StatusCode = 301;
Response.StatusDescription = "Moved";
Response.End();
}
```
So <http://localhost:1234/example/abc> redirects properly, but (where 1234 is the port for the debugging server)
<http://localhost/example/abc> does not redirect, it gives me a 404.
Any ideas?
---
Additional info:
If I go to <http://localhost/example/abc/default.aspx> then it redirects properly. | Well, if the port indicates you are using the built-in web server (the one that comes with VS), this probably works because that *always* routes requests through the ASP.NET framework.
Requests ending with /abc will not automatically route through the ASP.NET framework because IIS may not "know" you want them to. You need to check your IIS settings to make sure such requests are routed to the aspnet\_isapi.dll
---
**EDIT:** To accomplish this, you need to add a [**wildcard mapping**](http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5c5ae5e0-f4f9-44b0-a743-f4c3a5ff68ec.mspx):
1. In IIS Manager, expand the local computer, expand the Web Sites folder, right-click the Web site or virtual directory that you want, and then click Properties.
2. Click the appropriate tab: Home Directory, Virtual Directory, or Directory.
3. In the Application settings area, click Configuration, and then click the Mappings tab.
4. To install a wildcard application map, do the following:
* On the Mappings tab, click Add or Insert.
* Type the path to the DLL in the Executable text box or click Browse to navigate to it (for example, the ASP.NET 2.0 dll is at c:\windows\microsoft.net\framework\v2.0.50727\aspnet\_isapi.dll on my machine)
* For extension, use ".\*" without quotes, of course
* Select which verbs you want to look for (GET,HEAD,POST,DEBUG are the usual for ASP.NET, you decide)
* Make sure "Script engine" or "Application engine" is selected
* Uncheck "Check that file exists"
* Click okay.
I may be off on this, but if I am, hopefully someone will correct me. :) |
121,817 | <p>I need to set the text within a DIV element dynamically. What is the best, browser safe approach? I have prototypejs and scriptaculous available.</p>
<pre><code><div id="panel">
<div id="field_name">TEXT GOES HERE</div>
</div>
</code></pre>
<p>Here's what the function will look like:</p>
<pre><code>function showPanel(fieldName) {
var fieldNameElement = document.getElementById('field_name');
//Make replacement here
}
</code></pre>
| [
{
"answer_id": 121822,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 4,
"selected": false,
"text": "<pre><code>$('field_name').innerHTML = 'Your text.';\n</code></pre>\n\n<p>One of the nifty features of Prototype is t... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] | I need to set the text within a DIV element dynamically. What is the best, browser safe approach? I have prototypejs and scriptaculous available.
```
<div id="panel">
<div id="field_name">TEXT GOES HERE</div>
</div>
```
Here's what the function will look like:
```
function showPanel(fieldName) {
var fieldNameElement = document.getElementById('field_name');
//Make replacement here
}
``` | I would use Prototype's `update` method which supports plain text, an HTML snippet or any JavaScript object that defines a `toString` method.
```
$("field_name").update("New text");
```
* [Element.update documentation](http://www.prototypejs.org/api/element/update) |
121,864 | <p>As compared to say:</p>
<pre><code>REPLICATE(@padchar, @len - LEN(@str)) + @str
</code></pre>
| [
{
"answer_id": 121890,
"author": "AlexCuse",
"author_id": 794,
"author_profile": "https://Stackoverflow.com/users/794",
"pm_score": 9,
"selected": true,
"text": "<p>This is simply an inefficient use of SQL, no matter how you do it. </p>\n\n<p>perhaps something like </p>\n\n<pre><code>rig... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18255/"
] | As compared to say:
```
REPLICATE(@padchar, @len - LEN(@str)) + @str
``` | This is simply an inefficient use of SQL, no matter how you do it.
perhaps something like
```
right('XXXXXXXXXXXX'+ rtrim(@str), @n)
```
where X is your padding character and @n is the number of characters in the resulting string (assuming you need the padding because you are dealing with a fixed length).
But as I said you should really avoid doing this in your database. |
121,866 | <p>I'm preparing to deploy my Django app and I noticed that when I change the "DEBUG" setting to False, all references to static files (i.e., JavaScript, CSS, etc..) result in <code>HTTP 500</code> errors.</p>
<p>Any idea what's causing that issue (and how to fix it)?</p>
| [
{
"answer_id": 122052,
"author": "Peter Shinners",
"author_id": 17209,
"author_profile": "https://Stackoverflow.com/users/17209",
"pm_score": 5,
"selected": true,
"text": "<p>I would highly recommend letting your web server handle the static requests, without getting to Django. In my <co... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10040/"
] | I'm preparing to deploy my Django app and I noticed that when I change the "DEBUG" setting to False, all references to static files (i.e., JavaScript, CSS, etc..) result in `HTTP 500` errors.
Any idea what's causing that issue (and how to fix it)? | I would highly recommend letting your web server handle the static requests, without getting to Django. In my `urls.py`, I only add the static request handler when debug is set to True.
Technically, Django serving the static works fine though. Definitely read the short docs page, <http://docs.djangoproject.com/en/dev/howto/static-files/>. You'll want to use an entry like this in `urls.py`
```
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/path/to/media'})
``` |
121,922 | <p>I am currently suffering a brain fart. I've done this before but I can't remember the exact syntax and I can't look at the code I wrote because I was working at another company at the time. I have this arrangement:</p>
<pre><code>class P
{
// stuff
};
class PW : public P
{
// more stuff
};
class PR : public P
{
// more stuff
};
class C
{
public:
P GetP() const { return p; }
private:
P p;
};
// ...
P p = c.GetP( ); // valid
PW p = c.GetP( ); // invalid
PR p = c.GetP( ); // invalid
// ...
</code></pre>
<p>Now I would like to make P interchangeable with PW and PR (and thus PW and PR can be interchanged). I could probably get away with casts but this code change has occurred quite a few times in this module alone. I am pretty sure it is a operator but for the life of me I can't remember what.</p>
<p><strong>How do I make P interchangeable with PW and PR with minimal amount of code?</strong></p>
<p><strong>Update:</strong> To give a bit more clarification. P stands for Project and the R and W stands for Reader and Writer respectively. All the Reader has is the code for loading - no variables, and the writer has code for simply Writing. It needs to be separate because the Reading and Writing sections has various manager classes and dialogs which is none of Projects real concern which is the manipulation of project files.</p>
<p><strong>Update:</strong> I also need to be able to call the methods of P and PW. So if P has a method a() and PW as a method call b() then I could :</p>
<pre><code>PW p = c.GetP();
p.a();
p.b();
</code></pre>
<p>It's basically to make the conversion transparent.</p>
| [
{
"answer_id": 121944,
"author": "Carl Seleborg",
"author_id": 2095,
"author_profile": "https://Stackoverflow.com/users/2095",
"pm_score": 2,
"selected": false,
"text": "<p>In the code above, you have the opposite of the <strong>slicing</strong> problem.</p>\n\n<p>What you're trying to d... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/342/"
] | I am currently suffering a brain fart. I've done this before but I can't remember the exact syntax and I can't look at the code I wrote because I was working at another company at the time. I have this arrangement:
```
class P
{
// stuff
};
class PW : public P
{
// more stuff
};
class PR : public P
{
// more stuff
};
class C
{
public:
P GetP() const { return p; }
private:
P p;
};
// ...
P p = c.GetP( ); // valid
PW p = c.GetP( ); // invalid
PR p = c.GetP( ); // invalid
// ...
```
Now I would like to make P interchangeable with PW and PR (and thus PW and PR can be interchanged). I could probably get away with casts but this code change has occurred quite a few times in this module alone. I am pretty sure it is a operator but for the life of me I can't remember what.
**How do I make P interchangeable with PW and PR with minimal amount of code?**
**Update:** To give a bit more clarification. P stands for Project and the R and W stands for Reader and Writer respectively. All the Reader has is the code for loading - no variables, and the writer has code for simply Writing. It needs to be separate because the Reading and Writing sections has various manager classes and dialogs which is none of Projects real concern which is the manipulation of project files.
**Update:** I also need to be able to call the methods of P and PW. So if P has a method a() and PW as a method call b() then I could :
```
PW p = c.GetP();
p.a();
p.b();
```
It's basically to make the conversion transparent. | If you want to get this part to compile:
```
// ...
P p = c.GetP( ); // valid
PW p = c.GetP( ); // invalid
PR p = c.GetP( ); // invalid
// ...
```
You need to be able to construct/convert a P into a PW or a PR.
You need to do something like this:
```
class PW : public P
{
PW(const P &);
// more stuff
};
class PR : public P
{
PR(const P &);
// more stuff
};
```
Or did you mean something more like:
```
class P
{
operator PW() const;
operator PR() const;
// stuff
};
``` |
121,946 | <p>Ok, so I just ran into the following problem that raised an eyebrow.</p>
<p>For various reasons I have a testing setup where Testing classes in a TestingAssembly.dll depend on the TestingBase class in a BaseTestingAssembly.dll.
One of the things the TestBase does in the meantime is look for a certain embedded resource in its own and the calling assembly</p>
<p>So my BaseTestingAssembly contained the following lines...</p>
<pre><code>public class TestBase {
private static Assembly _assembly;
private static Assembly _calling_assembly;
static TestBase() {
_assembly = Assembly.GetExecutingAssembly();
_calling_assembly = Assembly.GetCallingAssembly();
}
}
</code></pre>
<p>Static since I figured, these assemblies would be the same over the application's lifetime so why bother recalculating them on every single test.</p>
<p>When running this however I noticed that both _assembly and _calling_assembly were being set to BaseTestingAssembly rather than BaseTestingAssembly and TestingAssembly respectively.</p>
<p>Setting the variables to non-static and having them initialized in a regular constructor fixed this but I am confused why this happened to begin this. I thought static constructors run the first time a static member gets referenced. This could only have been from my TestingAssembly which should then have been the caller. Does anyone know what might have happened?</p>
| [
{
"answer_id": 122049,
"author": "Harper Shelby",
"author_id": 21196,
"author_profile": "https://Stackoverflow.com/users/21196",
"pm_score": 1,
"selected": false,
"text": "<p>I think the answer is here in the discussion of <a href=\"http://msdn.microsoft.com/en-us/library/k9x6w0hc(VS.80)... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | Ok, so I just ran into the following problem that raised an eyebrow.
For various reasons I have a testing setup where Testing classes in a TestingAssembly.dll depend on the TestingBase class in a BaseTestingAssembly.dll.
One of the things the TestBase does in the meantime is look for a certain embedded resource in its own and the calling assembly
So my BaseTestingAssembly contained the following lines...
```
public class TestBase {
private static Assembly _assembly;
private static Assembly _calling_assembly;
static TestBase() {
_assembly = Assembly.GetExecutingAssembly();
_calling_assembly = Assembly.GetCallingAssembly();
}
}
```
Static since I figured, these assemblies would be the same over the application's lifetime so why bother recalculating them on every single test.
When running this however I noticed that both \_assembly and \_calling\_assembly were being set to BaseTestingAssembly rather than BaseTestingAssembly and TestingAssembly respectively.
Setting the variables to non-static and having them initialized in a regular constructor fixed this but I am confused why this happened to begin this. I thought static constructors run the first time a static member gets referenced. This could only have been from my TestingAssembly which should then have been the caller. Does anyone know what might have happened? | The static constructor is called by the runtime and not directly by user code. You can see this by setting a breakpoint in the constructor and then running in the debugger. The function immediately above it in the call chain is native code.
**Edit:** There are a lot of ways in which static initializers run in a different environment than other user code. Some other ways are
1. They're implicitly protected against race conditions resulting from multithreading
2. You can't catch exceptions from outside the initializer
In general, it's probably best not to use them for anything too sophisticated. You can implement single-init with the following pattern:
```
private static Assembly _assembly;
private static Assembly Assembly {
get {
if (_assembly == null) _assembly = Assembly.GetExecutingAssembly();
return _assembly;
}
}
private static Assembly _calling_assembly;
private static Assembly CallingAssembly {
get {
if (_calling_assembly == null) _calling_assembly = Assembly.GetCallingAssembly();
return _calling_assembly;
}
}
```
Add locking if you expect multithreaded access. |
121,962 | <p>How can I consistently get the absolute, fully-qualified root or base url of the site regardless of whether the site is in a virtual directory and regardless of where my code is in the directory structure? I've tried every variable and function I can think of and haven't found a good way.</p>
<p>I want to be able to get the url of the current site, i.e. <a href="http://www.example.com" rel="nofollow noreferrer">http://www.example.com</a> or if it's a virtual directory, <a href="http://www.example.com/DNN/" rel="nofollow noreferrer">http://www.example.com/DNN/</a></p>
<hr>
<p>Here's some of the things I've tried and the result. The only one that includes the whole piece that I want (<a href="http://localhost:4471/DNN441" rel="nofollow noreferrer">http://localhost:4471/DNN441</a>) is Request.URI.AbsoluteURI:</p>
<ul>
<li>Request.PhysicalPath: C:\WebSites\DNN441\Default.aspx</li>
<li>Request.ApplicationPath: /DNN441</li>
<li>Request.PhysicalApplicationPath: C:\WebSites\DNN441\</li>
<li>MapPath:
C:\WebSites\DNN441\DesktopModules\Articles\Templates\Default.aspx</li>
<li>RawURL:
/DNN441/ModuleTesting/Articles/tabid/56/ctl/Details/mid/374/ItemID/1/Default.aspx</li>
<li>Request.Url.AbsoluteUri: <a href="http://localhost:4471/DNN441/Default.aspx" rel="nofollow noreferrer">http://localhost:4471/DNN441/Default.aspx</a></li>
<li>Request.Url.AbsolutePath: /DNN441/Default.aspx</li>
<li>Request.Url.LocalPath: /DNN441/Default.aspx Request.Url.Host: localhost</li>
<li>Request.Url.PathAndQuery:
/DNN441/Default.aspx?TabId=56&ctl=Details&mid=374&ItemID=1</li>
</ul>
| [
{
"answer_id": 121970,
"author": "Dave Neeley",
"author_id": 9660,
"author_profile": "https://Stackoverflow.com/users/9660",
"pm_score": 3,
"selected": false,
"text": "<p>There is some excellent discussion and ideas on <a href=\"http://www.west-wind.com/Weblog/posts/154812.aspx\" rel=\"n... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4318/"
] | How can I consistently get the absolute, fully-qualified root or base url of the site regardless of whether the site is in a virtual directory and regardless of where my code is in the directory structure? I've tried every variable and function I can think of and haven't found a good way.
I want to be able to get the url of the current site, i.e. <http://www.example.com> or if it's a virtual directory, <http://www.example.com/DNN/>
---
Here's some of the things I've tried and the result. The only one that includes the whole piece that I want (<http://localhost:4471/DNN441>) is Request.URI.AbsoluteURI:
* Request.PhysicalPath: C:\WebSites\DNN441\Default.aspx
* Request.ApplicationPath: /DNN441
* Request.PhysicalApplicationPath: C:\WebSites\DNN441\
* MapPath:
C:\WebSites\DNN441\DesktopModules\Articles\Templates\Default.aspx
* RawURL:
/DNN441/ModuleTesting/Articles/tabid/56/ctl/Details/mid/374/ItemID/1/Default.aspx
* Request.Url.AbsoluteUri: <http://localhost:4471/DNN441/Default.aspx>
* Request.Url.AbsolutePath: /DNN441/Default.aspx
* Request.Url.LocalPath: /DNN441/Default.aspx Request.Url.Host: localhost
* Request.Url.PathAndQuery:
/DNN441/Default.aspx?TabId=56&ctl=Details&mid=374&ItemID=1 | In reading through the answer provided in Rick Strahl's Blog I found what I really needed was quite simple. First you need to determine the relative path (which for me was the easy part), and pass that into the function defined below:
VB.NET
```
Public Shared Function GetFullyQualifiedURL(ByVal s as string) As String
Dim Result as URI = New URI(HttpContext.Current.Request.Url, s)
Return Result.ToString
End Function
```
C#
```
public static string GetFullyQualifiedURL(string s) {
Uri Result = new Uri(HttpContext.Current.Request.Url, s);
return Result.ToString();
}
``` |
122,033 | <p>Yesterday, I asked <a href="https://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby">this</a> question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.</p>
<p>Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ:</p>
<pre><code>
static void Main(string[] args)
{
var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q;
}
private static IEnumerable GetRandomNumbers(int max)
{
Random r = new Random();
while (true)
{
yield return r.Next(max);
}
}
</code></pre>
<p>Can you translate my LINQ to Ruby? Python? Any other functional programming language?</p>
<p><strong>Note:</strong> Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.</p>
<p>I know I'm being picky, but I'd really like to see some elegant solutions to this problem.
Thanks!</p>
<p><strong>Edit:</strong><br />
Why all the downvotes?</p>
<p>Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.</p>
<p><strong>Apology:</strong><br />
I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.</p>
| [
{
"answer_id": 122047,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 0,
"selected": false,
"text": "<p>Python with Numeric Python:</p>\n\n<pre><code>from numpy import *\na = random.random_integers(0, 100, 5)\nb = unique... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] | Yesterday, I asked [this](https://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby) question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.
Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ:
```
static void Main(string[] args)
{
var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q;
}
private static IEnumerable GetRandomNumbers(int max)
{
Random r = new Random();
while (true)
{
yield return r.Next(max);
}
}
```
Can you translate my LINQ to Ruby? Python? Any other functional programming language?
**Note:** Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.
I know I'm being picky, but I'd really like to see some elegant solutions to this problem.
Thanks!
**Edit:**
Why all the downvotes?
Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.
**Apology:**
I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk. | In Ruby:
```
a = (0..100).entries.sort_by {rand}.slice! 0, 5
```
**Update**: Here is a slightly different way:
a = (0...100).entries.sort\_by{rand}[0...5]
**EDIT:**
and In Ruby 1.9 you can do this:
```
Array(0..100).sample(5)
``` |
122,067 | <p>I have a site using a custom favicon.ico. The favicon displays as expected in all browsers except IE. When trying to display the favicon in IE, I get the big red x; when displaying the favicon in another browser, it displays just fine. The page source includes
and it does work in other browsers. Thanks for your thoughts.</p>
<p><strong>EDIT: SOLVED: The source of the issue was the file was a jpg renamed to ico. I created the file as an ico and it is working as expected. Thanks for your input.</strong></p>
| [
{
"answer_id": 122111,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 7,
"selected": true,
"text": "<p>Right you've not been that helpful (providing source would be have been really useful!) but here you go... Some things to ch... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13465/"
] | I have a site using a custom favicon.ico. The favicon displays as expected in all browsers except IE. When trying to display the favicon in IE, I get the big red x; when displaying the favicon in another browser, it displays just fine. The page source includes
and it does work in other browsers. Thanks for your thoughts.
**EDIT: SOLVED: The source of the issue was the file was a jpg renamed to ico. I created the file as an ico and it is working as expected. Thanks for your input.** | Right you've not been that helpful (providing source would be have been really useful!) but here you go... Some things to check:
Is the code like this:
```
<link rel="icon" href="http://www.example.com/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="http://www.example.com/favicon.ico" type="image/x-icon" />
```
Is it in the `<head>`?
Is the image a *real* ico file? (renaming a bitmap is not a real .ico! Mildly different format)
Does it work when you add the page as a bookmark? |
122,088 | <p>I have a table in a MSSQL database that looks like this:</p>
<pre><code>Timestamp (datetime)
Message (varchar(20))
</code></pre>
<p>Once a day, a particular process inserts the current time and the message 'Started' when it starts. When it is finished it inserts the current time and the message 'Finished'.</p>
<p>What is a good query or set of statements that, given a particular date, returns:</p>
<ul>
<li>0 if the process never started</li>
<li>1 if the process started but did not finish</li>
<li>2 if the process started and finished</li>
</ul>
<p>There are other messages in the table, but 'Started' and 'Finished' are unique to this one process.</p>
<p>EDIT: For bonus karma, raise an error if the data is invalid, for example there are two 'Started' messages, or there is a 'Finished' without a 'Started'.</p>
| [
{
"answer_id": 122129,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": 3,
"selected": true,
"text": "<pre><code>Select Count(Message) As Status\nFrom Process_monitor\nWhere TimeStamp >= '20080923'\n An... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16881/"
] | I have a table in a MSSQL database that looks like this:
```
Timestamp (datetime)
Message (varchar(20))
```
Once a day, a particular process inserts the current time and the message 'Started' when it starts. When it is finished it inserts the current time and the message 'Finished'.
What is a good query or set of statements that, given a particular date, returns:
* 0 if the process never started
* 1 if the process started but did not finish
* 2 if the process started and finished
There are other messages in the table, but 'Started' and 'Finished' are unique to this one process.
EDIT: For bonus karma, raise an error if the data is invalid, for example there are two 'Started' messages, or there is a 'Finished' without a 'Started'. | ```
Select Count(Message) As Status
From Process_monitor
Where TimeStamp >= '20080923'
And TimeStamp < '20080924'
And (Message = 'Started' or Message = 'Finished')
```
You could modify this slightly to detect invalid conditions, like multiple starts, finishes, starts without a finish, etc...
```
Select Case When SumStarted = 0 And SumFinished = 0 Then 'Not Started'
When SumStarted = 1 And SumFinished = 0 Then 'Started'
When SumStarted = 1 And SumFinished = 1 Then 'Finished'
When SumStarted > 1 Then 'Multiple Starts'
When SumFinished > 1 Then 'Multiple Finish'
When SumFinished > 0 And SumStarted = 0 Then 'Finish Without Start'
End As StatusMessage
From (
Select Sum(Case When Message = 'Started' Then 1 Else 0 End) As SumStarted,
Sum(Case When Message = 'Finished' Then 1 Else 0 End) As SumFinished
From Process_monitor
Where TimeStamp >= '20080923'
And TimeStamp < '20080924'
And (Message = 'Started' or Message = 'Finished')
) As AliasName
``` |
122,089 | <p>A brief search shows that all available (uUnix command line) tools that convert from xsd (XML Schema) to rng (RelaxNG) or rnc (compact RelaxNG) have problems of some sort.</p>
<p>First, if I use rngconv:</p>
<pre><code>$ wget https://msv.dev.java.net/files/documents/61/31333/rngconv.20060319.zip
$ unzip rngconv.20060319.zip
$ cd rngconv-20060319/
$ java -jar rngconv.jar my.xsd > my.rng
</code></pre>
<p>It does not have a way to de-normalize elements so all end up being alternative start elements (it also seems to be a bit buggy).</p>
<p>Trang is an alternative, but it doesn't support xsd files on the input only on the output (why?). It supports DTD, however. Converting to DTD first comes to mind, but a solid xsd2dtd is hard to find as well. The one below:</p>
<pre><code> $ xsltproc http://crism.maden.org/consulting/pub/xsl/xsd2dtd.xsl in.xsd > out.dtd
</code></pre>
<p>Seems to be buggy.</p>
<p>All this is very surprising. For all these years of XML (ab)use, there no decent command line tools for these trivial basic tasks? Are people using only editors? Do those work? I much prefer command line, especially because I'd like to automate these tasks.</p>
<p>Any enlightening comments on this?</p>
| [
{
"answer_id": 122434,
"author": "Adrian Mouat",
"author_id": 4332,
"author_profile": "https://Stackoverflow.com/users/4332",
"pm_score": 2,
"selected": false,
"text": "<p>Converting XSD is a very hard task; the XSD specification is a bit of a nightmare and extremely complex. From some q... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21205/"
] | A brief search shows that all available (uUnix command line) tools that convert from xsd (XML Schema) to rng (RelaxNG) or rnc (compact RelaxNG) have problems of some sort.
First, if I use rngconv:
```
$ wget https://msv.dev.java.net/files/documents/61/31333/rngconv.20060319.zip
$ unzip rngconv.20060319.zip
$ cd rngconv-20060319/
$ java -jar rngconv.jar my.xsd > my.rng
```
It does not have a way to de-normalize elements so all end up being alternative start elements (it also seems to be a bit buggy).
Trang is an alternative, but it doesn't support xsd files on the input only on the output (why?). It supports DTD, however. Converting to DTD first comes to mind, but a solid xsd2dtd is hard to find as well. The one below:
```
$ xsltproc http://crism.maden.org/consulting/pub/xsl/xsd2dtd.xsl in.xsd > out.dtd
```
Seems to be buggy.
All this is very surprising. For all these years of XML (ab)use, there no decent command line tools for these trivial basic tasks? Are people using only editors? Do those work? I much prefer command line, especially because I'd like to automate these tasks.
Any enlightening comments on this? | Converting XSD is a very hard task; the XSD specification is a bit of a nightmare and extremely complex. From some quick [research,](http://www.tbray.org/ongoing/When/200x/2006/11/27/Choose-Relax) it seems that it is easy to go from RelaxNG to XSD, but that the reverse may not be true or even possible (which explains your question about Trang).
I don't understand your question about editors - if you are asking if most people end up converting between XSD and RNG by hand, then yes, I expect so.
The best advice may be to avoid XSD if possible, or at least use RNG as the definitive document and generate the XSD from that. You might also want to take a look at [schematron](http://www.schematron.com/). |
122,098 | <p>I have a Google Web Toolkit (GWT) application and when I link to it, I want to pass some arguments/parameters that it can use to dynamically retrieve data. E.g. if it were a stock chart application, I would want my link to contain the symbol and then have the GWT app read that and make a request to some stock service. E.g. <a href="http://myapp/gwt/StockChart?symbol=GOOG" rel="noreferrer">http://myapp/gwt/StockChart?symbol=GOOG</a> would be the link to my StockChart GWT app and it would make a request to my stock info web service for the GOOG stock. </p>
<p>So far, I've been using the server-side code to add Javascript variables to the page and then I've read those variables using JSNI (JavaScript Native Interface). </p>
<p>For example:</p>
<p>In the host HTML:</p>
<pre><code><script type="text/javascript">
var stockSymbol = '<%= request.getParameter("symbol") %>';
</script>
</code></pre>
<p>In the GWT code:</p>
<pre><code>public static native String getSymbol() /*-{
return $wnd.stockSymbol;
}-*/;
</code></pre>
<p>(Although this code is based on real code that works, I've modified it for this question so I might have goofed somewhere)</p>
<p>However, this doesn't always work well in hosted mode (especially with arrays) and since JSNI wasn't around in version 1.4 and previous, I'm guessing there's another/better way. </p>
| [
{
"answer_id": 122833,
"author": "Drejc",
"author_id": 6482,
"author_profile": "https://Stackoverflow.com/users/6482",
"pm_score": 4,
"selected": true,
"text": "<p>If you want to read query string parameters from the request you can use the <strong>com.google.gwt.user.client.Window</stro... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9910/"
] | I have a Google Web Toolkit (GWT) application and when I link to it, I want to pass some arguments/parameters that it can use to dynamically retrieve data. E.g. if it were a stock chart application, I would want my link to contain the symbol and then have the GWT app read that and make a request to some stock service. E.g. <http://myapp/gwt/StockChart?symbol=GOOG> would be the link to my StockChart GWT app and it would make a request to my stock info web service for the GOOG stock.
So far, I've been using the server-side code to add Javascript variables to the page and then I've read those variables using JSNI (JavaScript Native Interface).
For example:
In the host HTML:
```
<script type="text/javascript">
var stockSymbol = '<%= request.getParameter("symbol") %>';
</script>
```
In the GWT code:
```
public static native String getSymbol() /*-{
return $wnd.stockSymbol;
}-*/;
```
(Although this code is based on real code that works, I've modified it for this question so I might have goofed somewhere)
However, this doesn't always work well in hosted mode (especially with arrays) and since JSNI wasn't around in version 1.4 and previous, I'm guessing there's another/better way. | If you want to read query string parameters from the request you can use the **com.google.gwt.user.client.Window** class:
```
// returns whole query string
public static String getQueryString()
{
return Window.Location.getQueryString();
}
// returns specific parameter
public static String getQueryString(String name)
{
return Window.Location.getParameter(name);
}
``` |
122,102 | <p>What is the most efficient way to clone a JavaScript object? I've seen <code>obj = eval(uneval(o));</code> being used, but <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/uneval" rel="noreferrer">that's non-standard and only supported by Firefox</a>.<br/><br/> I've done things like <code>obj = JSON.parse(JSON.stringify(o));</code> but question the efficiency. <br/><br/> I've also seen recursive copying functions with various flaws.
<br />
I'm surprised no canonical solution exists.</p>
| [
{
"answer_id": 122190,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 9,
"selected": false,
"text": "<p>If there wasn't any builtin one, you could try:</p>\n\n<pre><code>function clone(obj) {\n if (obj === null || typeof (... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12694/"
] | What is the most efficient way to clone a JavaScript object? I've seen `obj = eval(uneval(o));` being used, but [that's non-standard and only supported by Firefox](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/uneval).
I've done things like `obj = JSON.parse(JSON.stringify(o));` but question the efficiency.
I've also seen recursive copying functions with various flaws.
I'm surprised no canonical solution exists. | Native deep cloning
===================
There's now a JS standard called ["structured cloning"](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone), that works experimentally in Node 11 and later, will land in browsers, and which has [polyfills for existing systems](https://www.npmjs.com/package/@ungap/structured-clone).
```
structuredClone(value)
```
If needed, loading the polyfill first:
```
import structuredClone from '@ungap/structured-clone';
```
See [this answer](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript/10916838#10916838) for more details.
Older answers
=============
Fast cloning with data loss - JSON.parse/stringify
--------------------------------------------------
If you do not use `Date`s, functions, `undefined`, `Infinity`, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays or other complex types within your object, a very simple one liner to deep clone an object is:
`JSON.parse(JSON.stringify(object))`
```js
const a = {
string: 'string',
number: 123,
bool: false,
nul: null,
date: new Date(), // stringified
undef: undefined, // lost
inf: Infinity, // forced to 'null'
re: /.*/, // lost
}
console.log(a);
console.log(typeof a.date); // Date object
const clone = JSON.parse(JSON.stringify(a));
console.log(clone);
console.log(typeof clone.date); // result of .toISOString()
```
See [Corban's answer](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript/5344074#5344074) for benchmarks.
Reliable cloning using a library
--------------------------------
Since cloning objects is not trivial (complex types, circular references, function etc.), most major libraries provide function to clone objects. **Don't reinvent the wheel** - if you're already using a library, check if it has an object cloning function. For example,
* lodash - [`cloneDeep`](https://lodash.com/docs#cloneDeep); can be imported separately via the [lodash.clonedeep](https://www.npmjs.com/package/lodash.clonedeep) module and is probably your best choice if you're not already using a library that provides a deep cloning function
* AngularJS - [`angular.copy`](https://docs.angularjs.org/api/ng/function/angular.copy)
* jQuery - [`jQuery.extend(true, { }, oldObject)`](https://api.jquery.com/jquery.extend/#jQuery-extend-deep-target-object1-objectN); `.clone()` only clones DOM elements
* just library - [`just-clone`](https://www.npmjs.com/package/just-clone); Part of a library of zero-dependency npm modules that do just do one thing.
Guilt-free utilities for every occasion. |
122,104 | <p>Say I have a page that display search results. I search for stackoverflow and it returns 5000 results, 10 per page. Now I find myself doing this when building links on that page:</p>
<pre><code><%=Html.ActionLink("Page 1", "Search", new { query=ViewData["query"], page etc..%>
<%=Html.ActionLink("Page 2", "Search", new { query=ViewData["query"], page etc..%>
<%=Html.ActionLink("Page 3", "Search", new { query=ViewData["query"], page etc..%>
<%=Html.ActionLink("Next", "Search", new { query=ViewData["query"], page etc..%>
</code></pre>
<p>I dont like this, I have to build my links with careful consideration to what was posted previously etc.. </p>
<p>What I'd like to do is</p>
<pre><code><%=Html.BuildActionLinkUsingCurrentActionPostData
("Next", "Search", new { Page = 1});
</code></pre>
<p>where the anonymous dictionary overrides anything currently set by previous action. </p>
<p>Essentially I care about what the previous action parameters were, because I want to reuse, it sounds simple, but start adding sort and loads of advance search options and it starts getting messy.</p>
<p>Im probably missing something obvious</p>
| [
{
"answer_id": 122439,
"author": "Craig Stuntz",
"author_id": 7714,
"author_profile": "https://Stackoverflow.com/users/7714",
"pm_score": 1,
"selected": false,
"text": "<p>Whenever you find yourself writing redundant code in your Views, <a href=\"http://blog.wekeroad.com/blog/asp-net-mvc... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Say I have a page that display search results. I search for stackoverflow and it returns 5000 results, 10 per page. Now I find myself doing this when building links on that page:
```
<%=Html.ActionLink("Page 1", "Search", new { query=ViewData["query"], page etc..%>
<%=Html.ActionLink("Page 2", "Search", new { query=ViewData["query"], page etc..%>
<%=Html.ActionLink("Page 3", "Search", new { query=ViewData["query"], page etc..%>
<%=Html.ActionLink("Next", "Search", new { query=ViewData["query"], page etc..%>
```
I dont like this, I have to build my links with careful consideration to what was posted previously etc..
What I'd like to do is
```
<%=Html.BuildActionLinkUsingCurrentActionPostData
("Next", "Search", new { Page = 1});
```
where the anonymous dictionary overrides anything currently set by previous action.
Essentially I care about what the previous action parameters were, because I want to reuse, it sounds simple, but start adding sort and loads of advance search options and it starts getting messy.
Im probably missing something obvious | I had a similar problem inside an HtmlHelper; I wanted to generate links that linked backed to the current page, with a small adjustment in parameters (think incrementing the page number). So if I had URL /Item/?sort=Name&page=0, I wanted to be able to create links to the same page, but just change the page parameter, and have the sort parameter automatically included (ie /Item/?sort=Name&page=1).
My solution was this (for use in an HtmlHelper extension method, but since you can access the same data almost anywhere in MVC, you can adapt it easily to your uses):
```
private static RouteValueDictionary CreateRouteToCurrentPage(HtmlHelper html)
{
RouteValueDictionary routeValues
= new RouteValueDictionary(html.ViewContext.RouteData.Values);
NameValueCollection queryString
= html.ViewContext.HttpContext.Request.QueryString;
foreach (string key in queryString.Cast<string>())
{
routeValues[key] = queryString[key];
}
return routeValues;
}
```
What the method does is take the RouteValueDictionary for the current request and create a copy of it. Then it adds each of the query parameters found in the query string to this route. It does this because, for some reason, the current request's RouteValueDictionary does not contain them (you'd think it would, but it doesn't).
You can then take the resultant dictionary, modify only a part of it, for example:
```
routeValues["page"] = 2;
```
and then give that dictionary to the out-of-the-box HtmlHelper methods for them to generate you a URL/etc. |
122,105 | <p>I want to filter a <code>java.util.Collection</code> based on a predicate.</p>
| [
{
"answer_id": 122128,
"author": "Kevin Wong",
"author_id": 4792,
"author_profile": "https://Stackoverflow.com/users/4792",
"pm_score": 7,
"selected": false,
"text": "<p>Use <a href=\"https://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collection... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792/"
] | I want to filter a `java.util.Collection` based on a predicate. | Java 8 ([2014](https://www.oracle.com/java/technologies/javase/8-whats-new.html "What's New in JDK 8")) solves this problem using streams and lambdas in one line of code:
```
List<Person> beerDrinkers = persons.stream()
.filter(p -> p.getAge() > 16).collect(Collectors.toList());
```
Here's a [tutorial](http://zeroturnaround.com/rebellabs/java-8-explained-applying-lambdas-to-java-collections/ "Java 8 collections and lambdas").
Use [`Collection#removeIf`](https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeIf-java.util.function.Predicate-) to modify the collection in place. (Notice: In this case, the predicate will remove objects who satisfy the predicate):
```
persons.removeIf(p -> p.getAge() <= 16);
```
---
[lambdaj](https://code.google.com/archive/p/lambdaj/) allows filtering collections without writing loops or inner classes:
```
List<Person> beerDrinkers = select(persons, having(on(Person.class).getAge(),
greaterThan(16)));
```
Can you imagine something more readable?
**Disclaimer:** I am a contributor on lambdaj |
122,107 | <p><strong>"It is not possible to check out a single file. The finest level of checkouts you can do is at the directory level."</strong></p>
<p>How do I get around this issue when using Subversion?</p>
<p>We have this folder in Subversion where we keep all our images. I just want to check out one file (image) from that. This folder is really big and has ton of other stuff which I don't need now.</p>
| [
{
"answer_id": 122126,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 6,
"selected": false,
"text": "<p>Use <code>svn cat</code> or <code>svn export</code>.</p>\n\n<p>For that, you don't need to fetch the working dir... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175964/"
] | **"It is not possible to check out a single file. The finest level of checkouts you can do is at the directory level."**
How do I get around this issue when using Subversion?
We have this folder in Subversion where we keep all our images. I just want to check out one file (image) from that. This folder is really big and has ton of other stuff which I don't need now. | The simple answer is that you `svn export` the file instead of checking it out.
But that might not be what you want. You might want to work on the file and check it back in, without having to download GB of junk you don't need.
If you have Subversion 1.5+, then do a sparse checkout:
```
svn checkout <url_of_big_dir> <target> --depth empty
cd <target>
svn up <file_you_want>
```
For an older version of SVN, you might benefit from the following:
* Checkout the directory using a revision back in the distant past, when it was less full of junk you don't need.
* Update the file you want, to create a mixed revision. This works even if the file didn't exist in the revision you checked out.
* Profit!
An alternative (for instance if the directory has too much junk right from the revision in which it was created) is to do a URL->URL copy of the file you want into a new place in the repository (effectively this is a working branch of the file). Check out that directory and do your modifications.
I'm not sure whether you can then merge your modified copy back entirely in the repository without a working copy of the target - I've never needed to. If so then do that.
If not then unfortunately you may have to find someone else who does have the whole directory checked out and get them to do it. Or maybe by the time you've made your modifications, the rest of it will have finished downloading... |
122,108 | <p>I have implemented the WMD control that Stack Overflow uses into a project of mine, it <strong>almost</strong> works like a charm, but when I save the changes to the database it is saving the HTML version and not the Markdown version.</p>
<p>So where I have this in my text box:</p>
<pre><code>**boldtext**
</code></pre>
<p>It is really saving this:</p>
<pre><code><b>boldtext</b>
</code></pre>
<p>How do I make it save the Markdown version?</p>
| [
{
"answer_id": 122572,
"author": "Clinton Dreisbach",
"author_id": 6262,
"author_profile": "https://Stackoverflow.com/users/6262",
"pm_score": 4,
"selected": true,
"text": "<p>Before you include <code>wmd.js</code>, or whatever you've named the WMD editor JavaScript code locally, add one... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768/"
] | I have implemented the WMD control that Stack Overflow uses into a project of mine, it **almost** works like a charm, but when I save the changes to the database it is saving the HTML version and not the Markdown version.
So where I have this in my text box:
```
**boldtext**
```
It is really saving this:
```
<b>boldtext</b>
```
How do I make it save the Markdown version? | Before you include `wmd.js`, or whatever you've named the WMD editor JavaScript code locally, add one line of JavaScript code:
```
wmd_options = {"output": "Markdown"};
```
This will force the output of the editor to Markdown. |
122,115 | <p>Ruby's standard popen3 module does not work on Windows. Is there a maintained replacement that allows for separating stdin, stdout, and stderr?</p>
| [
{
"answer_id": 122222,
"author": "Max Caceres",
"author_id": 4842,
"author_profile": "https://Stackoverflow.com/users/4842",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://popen4.rubyforge.org/\" rel=\"nofollow noreferrer\">POpen4</a> gem has a common interface between uni... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4842/"
] | Ruby's standard popen3 module does not work on Windows. Is there a maintained replacement that allows for separating stdin, stdout, and stderr? | [POpen4](http://popen4.rubyforge.org/) gem has a common interface between unix and Windows. The following example (from their website) works like a charm.
```
require 'rubygems'
require 'popen4'
status =
POpen4::popen4("cmd") do |stdout, stderr, stdin, pid|
stdin.puts "echo hello world!"
stdin.puts "echo ERROR! 1>&2"
stdin.puts "exit"
stdin.close
puts "pid : #{ pid }"
puts "stdout : #{ stdout.read.strip }"
puts "stderr : #{ stderr.read.strip }"
end
puts "status : #{ status.inspect }"
puts "exitstatus : #{ status.exitstatus }"
``` |
122,127 | <p>In order to create the proper queries I need to be able to run a query against the same datasource that the report is using. How do I get that information <strong>programatically</strong>? Preferably the connection string or pieces of data used to build the connection string.</p>
| [
{
"answer_id": 122171,
"author": "Erikk Ross",
"author_id": 18772,
"author_profile": "https://Stackoverflow.com/users/18772",
"pm_score": 0,
"selected": false,
"text": "<p>If you have the right privileges you can can go to <a href=\"http://servername/reports/\" rel=\"nofollow noreferrer\... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7756/"
] | In order to create the proper queries I need to be able to run a query against the same datasource that the report is using. How do I get that information **programatically**? Preferably the connection string or pieces of data used to build the connection string. | ```
DataSourceDefinition dataSourceDefinition
= reportingService.GetDataSourceContents("DataSourceName");
string connectionString = dataSourceDefinition.ConnectString;
``` |
122,144 | <p>Im calling a locally hosted wcf service from silverlight and I get the exception below.</p>
<p>Iv created a clientaccesspolicy.xml, which is situated in the route of my host.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
</code></pre>
<blockquote>
<p>An error occurred while trying to make
a request to URI
'<a href="http://localhost:8005/Service1.svc" rel="nofollow noreferrer">http://localhost:8005/Service1.svc</a>'.
This could be due to a cross domain
configuration error. Please see the
inner exception for more details. ---></p>
<p>{System.Security.SecurityException
---> System.Security.SecurityException:
Security error. at
MS.Internal.InternalWebRequest.Send()
at
System.Net.BrowserHttpWebRequest.BeginGetResponseImplementation()
at
System.Net.BrowserHttpWebRequest.InternalBeginGetResponse(AsyncCallback
callback, Object state) at
System.Net.AsyncHelper.<>c__DisplayClass4.b__3(Object sendState) --- End of inner
exception stack trace --- at
System.Net.AsyncHelper.BeginOnUI(BeginMethod
beginMethod, AsyncCallback callback,
Object state) at
System.Net.BrowserHttpWebRequest.BeginGetResponse(AsyncCallback
callback, Object state) at
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteSend(IAsyncResult
result) at
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.OnSend(IAsyncResult
result)}</p>
</blockquote>
<p>Any ideas on how to progress?</p>
| [
{
"answer_id": 122165,
"author": "C. Dragon 76",
"author_id": 5682,
"author_profile": "https://Stackoverflow.com/users/5682",
"pm_score": 0,
"selected": false,
"text": "<p>I'd start by making sure Silverlight is actually finding your client access policy file by inspecting the network ca... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] | Im calling a locally hosted wcf service from silverlight and I get the exception below.
Iv created a clientaccesspolicy.xml, which is situated in the route of my host.
```
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
```
>
> An error occurred while trying to make
> a request to URI
> '<http://localhost:8005/Service1.svc>'.
> This could be due to a cross domain
> configuration error. Please see the
> inner exception for more details. --->
>
>
> {System.Security.SecurityException
> ---> System.Security.SecurityException:
> Security error. at
> MS.Internal.InternalWebRequest.Send()
> at
> System.Net.BrowserHttpWebRequest.BeginGetResponseImplementation()
> at
> System.Net.BrowserHttpWebRequest.InternalBeginGetResponse(AsyncCallback
> callback, Object state) at
> System.Net.AsyncHelper.<>c\_\_DisplayClass4.b\_\_3(Object sendState) --- End of inner
> exception stack trace --- at
> System.Net.AsyncHelper.BeginOnUI(BeginMethod
> beginMethod, AsyncCallback callback,
> Object state) at
> System.Net.BrowserHttpWebRequest.BeginGetResponse(AsyncCallback
> callback, Object state) at
> System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteSend(IAsyncResult
> result) at
> System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.OnSend(IAsyncResult
> result)}
>
>
>
Any ideas on how to progress? | there are some debugging techniques [listed here](http://timheuer.com/blog/archive/2008/06/10/silverlight-services-cross-domain-404-not-found.aspx)..one more [useful post](http://timheuer.com/blog/archive/2008/04/09/silverlight-cannot-access-web-service.aspx).. |
122,154 | <p>I'm using Team Foundation Build but we aren't yet using TFS for problem tracking, so I would like to disable the work item creation on a failed build. Is there any way to do this? I tried commenting out the work item info in the TFSBuild.proj file for the build type but that didn't do the trick.</p>
| [
{
"answer_id": 122660,
"author": "Tim Booker",
"author_id": 10046,
"author_profile": "https://Stackoverflow.com/users/10046",
"pm_score": 6,
"selected": true,
"text": "<p>Try adding this inside the PropertyGroup in your TFSBuild.proj:</p>\n\n<pre><code><SkipWorkItemCreation>true<... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] | I'm using Team Foundation Build but we aren't yet using TFS for problem tracking, so I would like to disable the work item creation on a failed build. Is there any way to do this? I tried commenting out the work item info in the TFSBuild.proj file for the build type but that didn't do the trick. | Try adding this inside the PropertyGroup in your TFSBuild.proj:
```
<SkipWorkItemCreation>true</SkipWorkItemCreation>
```
---
If you are curious as to how this works, Microsoft.TeamFoundation.Build.targets contians the following:
```
<Target Name="CoreCreateWorkItem"
Condition=" '$(SkipWorkItemCreation)'!='true' and '$(IsDesktopBuild)'!='true' "
DependsOnTargets="$(CoreCreateWorkItemDependsOn)">
<PropertyGroup>
<WorkItemTitle>$(WorkItemTitle) $(BuildNumber)</WorkItemTitle>
<BuildLogText>$(BuildlogText) <a href='file:///$(DropLocation)\$(BuildNumber)\BuildLog.txt'>$(DropLocation)\$(BuildNumber)\BuildLog.txt</a >.</BuildLogText>
<ErrorWarningLogText Condition="!Exists('$(MSBuildProjectDirectory)\ErrorsWarningsLog.txt')"></ErrorWarningLogText>
<ErrorWarningLogText Condition="Exists('$(MSBuildProjectDirectory)\ErrorsWarningsLog.txt')">$(ErrorWarningLogText) <a href='file:///$(DropLocation)\$(BuildNumber)\ErrorsWarningsLog.txt'>$(DropLocation)\$(BuildNumber)\ErrorsWarningsLog.txt</a >.</ErrorWarningLogText>
<WorkItemDescription>$(DescriptionText) %3CBR%2F%3E $(BuildlogText) %3CBR%2F%3E $(ErrorWarningLogText)</WorkItemDescription>
</PropertyGroup>
<CreateNewWorkItem
TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
BuildUri="$(BuildUri)"
BuildNumber="$(BuildNumber)"
Description="$(WorkItemDescription)"
TeamProject="$(TeamProject)"
Title="$(WorkItemTitle)"
WorkItemFieldValues="$(WorkItemFieldValues)"
WorkItemType="$(WorkItemType)"
ContinueOnError="true" />
</Target>
```
You can override any of this functionality in your own build script, but Microsoft provide the handy SkipWorkItemCreation condition at the top, which you can use to cancel execution of the whole target. |
122,160 | <p>I'm a big fan of the way Visual Studio will give you the comment documentation / parameter names when completing code that you have written and ALSO code that you are referencing (various libraries/assemblies).</p>
<p>Is there an easy way to get inline javadoc/parameter names in Eclipse when doing code complete or hovering over methods? Via plugin? Via some setting? It's extremely annoying to use a lot of libraries (as happens often in Java) and then have to go to the website or local javadoc location to lookup information when you have it in the source jars right there!</p>
| [
{
"answer_id": 122182,
"author": "Henry B",
"author_id": 6414,
"author_profile": "https://Stackoverflow.com/users/6414",
"pm_score": 7,
"selected": false,
"text": "<p>Short answer would be yes.</p>\n\n<p>You can attach source using the properties for a project.</p>\n\n<p>Go to Properties... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5885/"
] | I'm a big fan of the way Visual Studio will give you the comment documentation / parameter names when completing code that you have written and ALSO code that you are referencing (various libraries/assemblies).
Is there an easy way to get inline javadoc/parameter names in Eclipse when doing code complete or hovering over methods? Via plugin? Via some setting? It's extremely annoying to use a lot of libraries (as happens often in Java) and then have to go to the website or local javadoc location to lookup information when you have it in the source jars right there! | Short answer would be yes.
You can attach source using the properties for a project.
Go to Properties (for the Project) -> Java Build Path -> Libraries
Select the Library you want to attach source/javadoc for and then expand it, you'll see a list like so:
```
Source Attachment: (none)
Javadoc location: (none)
Native library location: (none)
Access rules: (No restrictions)
```
Select Javadoc location and then click Edit on the right hahnd side. It should be quite straight forward from there.
Good luck :) |
122,175 | <p>I'm trying to setup some friendly URLs on a SharePoint website. I know that I can do the ASP.Net 2.0 friendly URLs using RewritePath, but I was wondering if it was possible to make use of the System.Web.Routing that comes with ASP.NET 3.5 SP1. </p>
<p>I think I've figured out how to get my route table loaded, but I'm not clear on what method to use to get the correct IHttpHandler to pass out.</p>
<p>Thanks!</p>
| [
{
"answer_id": 127897,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>It should be as easy as the below.</p>\n\n<pre><code>var route = new Route(\"blah/{*path}\", new MyRouteHandler());\nRouteT... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10893/"
] | I'm trying to setup some friendly URLs on a SharePoint website. I know that I can do the ASP.Net 2.0 friendly URLs using RewritePath, but I was wondering if it was possible to make use of the System.Web.Routing that comes with ASP.NET 3.5 SP1.
I think I've figured out how to get my route table loaded, but I'm not clear on what method to use to get the correct IHttpHandler to pass out.
Thanks! | I ended up taking what Ryan had:
```
var route = new Route("blah/{*path}", new MyRouteHandler());
RouteTable.Routes.Add(route);
public class MyRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
//rewrite to some know sharepoint path
HttpContext.Current.RewritePath("~/Pages/Default.aspx");
// return some HTTP handler here
return new DefaultHttpHandler();
}}
```
That seems to work ok for me. |
122,208 | <p>In C++, what's the easiest way to get the local computer's IP address and subnet mask?</p>
<p>I want to be able to detect the local machine's IP address in my local network. In my particular case, I have a network with a subnet mask of 255.255.255.0 and my computer's IP address is 192.168.0.5. I need to get these had two values programmatically in order to send a broadcast message to my network (in the form 192.168.0.255, for my particular case)</p>
<p>Edit: Many answers were not giving the results I expected because I had two different network IP's. <a href="https://stackoverflow.com/questions/122208/get-the-ip-address-of-local-computer#122235">Torial</a>'s code did the trick (it gave me both IP addresses).</p>
<p>Edit 2: Thanks to <a href="https://stackoverflow.com/questions/122208/get-the-ip-address-of-local-computer#122225">Brian R. Bondy</a> for the info about the subnet mask.</p>
| [
{
"answer_id": 122225,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 4,
"selected": false,
"text": "<p>You can use gethostname followed by gethostbyname to get your local interface internal IP. </p>\n\n<p>This return... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4880/"
] | In C++, what's the easiest way to get the local computer's IP address and subnet mask?
I want to be able to detect the local machine's IP address in my local network. In my particular case, I have a network with a subnet mask of 255.255.255.0 and my computer's IP address is 192.168.0.5. I need to get these had two values programmatically in order to send a broadcast message to my network (in the form 192.168.0.255, for my particular case)
Edit: Many answers were not giving the results I expected because I had two different network IP's. [Torial](https://stackoverflow.com/questions/122208/get-the-ip-address-of-local-computer#122235)'s code did the trick (it gave me both IP addresses).
Edit 2: Thanks to [Brian R. Bondy](https://stackoverflow.com/questions/122208/get-the-ip-address-of-local-computer#122225) for the info about the subnet mask. | The question is trickier than it appears, because in many cases there isn't "an IP address for the local computer" so much as a number of different IP addresses. For example, the Mac I'm typing on right now (which is a pretty basic, standard Mac setup) has the following IP addresses associated with it:
```
fe80::1%lo0
127.0.0.1
::1
fe80::21f:5bff:fe3f:1b36%en1
10.0.0.138
172.16.175.1
192.168.27.1
```
... and it's not just a matter of figuring out which of the above is "the real IP address", either... they are all "real" and useful; some more useful than others depending on what you are going to use the addresses for.
In my experience often the best way to get "an IP address" for your local computer is not to query the local computer at all, but rather to ask the computer your program is talking to what it sees your computer's IP address as. e.g. if you are writing a client program, send a message to the server asking the server to send back as data the IP address that your request came from. That way you will know what the *relevant* IP address is, given the context of the computer you are communicating with.
That said, that trick may not be appropriate for some purposes (e.g. when you're not communicating with a particular computer) so sometimes you just need to gather the list of all the IP addresses associated with your machine. The best way to do that under Unix/Mac (AFAIK) is by calling getifaddrs() and iterating over the results. Under Windows, try GetAdaptersAddresses() to get similar functionality. For example usages of both, see the GetNetworkInterfaceInfos() function in [this file](https://public.msli.com/lcs/muscle/muscle/util/NetworkUtilityFunctions.cpp). |
122,215 | <p>In my tests I need to test what happens when an OracleException is thrown (due to a stored procedure failure). I am trying to setup Rhino Mocks to </p>
<pre><code>Expect.Call(....).Throw(new OracleException());
</code></pre>
<p>For whatever reason however, OracleException seems to be sealed with no public constructor. What can I do to test this?</p>
<p><strong>Edit:</strong> Here is exactly what I'm trying to instantiate:</p>
<pre><code>public sealed class OracleException : DbException {
private OracleException(string message, int code) { ...}
}
</code></pre>
| [
{
"answer_id": 122224,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": -1,
"selected": false,
"text": "<p>Can you write a trivial stored procedure that fails/errors each time, then use that to test?</p>\n"
},
{
"an... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | In my tests I need to test what happens when an OracleException is thrown (due to a stored procedure failure). I am trying to setup Rhino Mocks to
```
Expect.Call(....).Throw(new OracleException());
```
For whatever reason however, OracleException seems to be sealed with no public constructor. What can I do to test this?
**Edit:** Here is exactly what I'm trying to instantiate:
```
public sealed class OracleException : DbException {
private OracleException(string message, int code) { ...}
}
``` | It seems that Oracle changed their constructors in later versions, therefore the solution above will not work.
If you only want to set the error code, the following will do the trick for 2.111.7.20:
```
ConstructorInfo ci = typeof(OracleException)
.GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
new Type[] { typeof(int) },
null
);
Exception ex = (OracleException)ci.Invoke(new object[] { 3113 });
``` |
122,216 | <p>So I have a large 2d array that i serialize, but when I attempt to unserialize the array it just throws the same error to the point of nearly crashing Firefox.</p>
<p>The error is:</p>
<pre><code>Warning: unserialize() [function.unserialize]: Node no longer exists in /var/www/dev/wc_paul/inc/analyzerTester.php on line 24
</code></pre>
<p>I would include the entire serialized array that I echo out but last time I tried that on this form it crashed my Firefox.</p>
<p>Does anyone have any idea why this might be happening?</p>
<p>I'm sure this is an array. However, it was originally an XML response from another server that I then pulled values from to build the array. If it can't be serialized I can accept that I guess... but how should I go about saving it then?</p>
| [
{
"answer_id": 122241,
"author": "JimmyJ",
"author_id": 2083,
"author_profile": "https://Stackoverflow.com/users/2083",
"pm_score": 0,
"selected": false,
"text": "<p>to answer your second question about how else you could save the data</p>\n\n<p>why not output the xml responce directly t... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20895/"
] | So I have a large 2d array that i serialize, but when I attempt to unserialize the array it just throws the same error to the point of nearly crashing Firefox.
The error is:
```
Warning: unserialize() [function.unserialize]: Node no longer exists in /var/www/dev/wc_paul/inc/analyzerTester.php on line 24
```
I would include the entire serialized array that I echo out but last time I tried that on this form it crashed my Firefox.
Does anyone have any idea why this might be happening?
I'm sure this is an array. However, it was originally an XML response from another server that I then pulled values from to build the array. If it can't be serialized I can accept that I guess... but how should I go about saving it then? | Usually, when you get an error message, you can figure out a great deal by simply searching the web for that very message. For example, when you put [Node no longer exists](http://www.google.co.uk/search?q=Node+no+longer+exists) into Google, you end up with [a concise explanation of why this is happening, along with a solution](http://www.rhinocerus.net/node/16347), as the very first hit. |
122,229 | <p>I'm the only developer supporting a website that's a mix of classic asp and .NET. I had to add some .net pages to a classic asp application. This application requires users to login. The login page, written in classic asp, creates a cookie that .net pages use to identify the logged in user and stores information in session vars for the other classic asp pages to use. In classic asp the cookie code is as follows:</p>
<pre><code>response.cookies("foo")("value1") = value1
response.cookies("foo")("value2") = value2
response.cookies("foo").Expires = DateAdd("N", 15, Now())
response.cookies("foo").Path = "/"
</code></pre>
<p>In the .NET codebehind Page_Load code, I check for the cookie using the code below.</p>
<blockquote>
<p>if(!IsPostBack) {<br>
if(Request.Cookies["foo"] != null) {
... } else { //redirect to cookie creation page, cookiefoo.asp
} }</p>
</blockquote>
<p>The vast majority of the time this works with no problems. However, we have some users that get redirected to a cookie creation page because the Page_Load code can't find the cookie. No matter how many times the user is redirected to the cookie creation page, the referring page still can find the cookie, foo. The problem is happening in IE7 and I've tried modifying the privacy and cookie settings in the browser but can't seem to recreate the problem the user is having.</p>
<p>Does anyone have any ideas why this could be happening with IE7?</p>
<p>Thanks.</p>
| [
{
"answer_id": 122252,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "<p>Using <a href=\"http://www.fiddlertool.com/fiddler/\" rel=\"nofollow noreferrer\">Fiddler</a> is a good way to try to ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9809/"
] | I'm the only developer supporting a website that's a mix of classic asp and .NET. I had to add some .net pages to a classic asp application. This application requires users to login. The login page, written in classic asp, creates a cookie that .net pages use to identify the logged in user and stores information in session vars for the other classic asp pages to use. In classic asp the cookie code is as follows:
```
response.cookies("foo")("value1") = value1
response.cookies("foo")("value2") = value2
response.cookies("foo").Expires = DateAdd("N", 15, Now())
response.cookies("foo").Path = "/"
```
In the .NET codebehind Page\_Load code, I check for the cookie using the code below.
>
> if(!IsPostBack) {
>
> if(Request.Cookies["foo"] != null) {
> ... } else { //redirect to cookie creation page, cookiefoo.asp
> } }
>
>
>
The vast majority of the time this works with no problems. However, we have some users that get redirected to a cookie creation page because the Page\_Load code can't find the cookie. No matter how many times the user is redirected to the cookie creation page, the referring page still can find the cookie, foo. The problem is happening in IE7 and I've tried modifying the privacy and cookie settings in the browser but can't seem to recreate the problem the user is having.
Does anyone have any ideas why this could be happening with IE7?
Thanks. | Using [Fiddler](http://www.fiddlertool.com/fiddler/) is a good way to try to figure out what's going on. You can see the exact Set-Cookie that the browser is getting. |
122,238 | <p>JSF is setting the ID of an input field to <code>search_form:expression</code>. I need to specify some styling on that element, but that colon looks like the beginning of a pseudo-element to the browser so it gets marked invalid and ignored. Is there anyway to escape the colon or something?</p>
<pre><code>input#search_form:expression {
///...
}
</code></pre>
| [
{
"answer_id": 122266,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 8,
"selected": true,
"text": "<p>Backslash: </p>\n\n<pre><code>input#search_form\\:expression { ///...}\n</code></pre>\n\n<ul>\n<li>See also <em><a hr... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] | JSF is setting the ID of an input field to `search_form:expression`. I need to specify some styling on that element, but that colon looks like the beginning of a pseudo-element to the browser so it gets marked invalid and ignored. Is there anyway to escape the colon or something?
```
input#search_form:expression {
///...
}
``` | Backslash:
```
input#search_form\:expression { ///...}
```
* See also *[Using Namespaces with CSS](http://msdn.microsoft.com/en-us/library/ms762307(VS.85).aspx)* (MSDN) |
122,239 | <p>Within a table cell that is vertical-align:bottom, I have one or two divs. Each div is floated right.<br>
Supposedly, the divs should not align to the bottom, but they do (which I don't understand, but is good).<br>
However, when I have two floated divs in the cell, they align themselves to the same top line.<br>
I want the first, smaller, div to sit all the way at the bottom. Another acceptable solution is to make it full height of the table cell.</p>
<p>It's difficult to explain, so here's the code:</p>
<blockquote>
<pre><code><style type="text/css">
table {
border-collapse: collapse;
}
td {
border:1px solid black;
vertical-align:bottom;
}
.h {
float:right;
background: #FFFFCC;
}
.ha {
float:right;
background: #FFCCFF;
}
</style>
<table>
<tr>
<td>
<div class="ha">@</div>
<div class="h">Title Text<br />Line 2</div>
</td>
<td>
<div class="ha">@</div>
<div class="h">Title Text<br />Line 2<br />Line 3</div>
</td>
<td>
<div class="h">Title Text<br />Line 2</div>
</td>
<td>
<div class="h">Title Text<br />Line 2</div>
</td>
<td>
<div class="h">Title Text<br />Line 2</div>
</td>
</tr>
<tr>
<td>
<div class="d">123456789</div>
</td>
<td>
<div class="d">123456789</div>
</td>
<td>
<div class="d">123456789</div>
</td>
<td>
<div class="d">123456789</div>
</td>
<td>
<div class="d">123456789</div>
</td>
</tr>
</table>
</code></pre>
</blockquote>
<p>Here are the problems:</p>
<ol>
<li>Why does the @ sign sit at the same level as the yellow div?</li>
<li>Supposedly vertical-align doesn't apply to block elements (like a floated div) 1. But it does!</li>
<li>How can I make the @ sit at the bottom or make it full height of the table cell?</li>
</ol>
<p>I am testing in IE7 and FF2. Target support is IE6/7, FF2/3.</p>
<p><strong>Clarification:</strong> The goal is to have the red @ on the bottom line of the table cell, <em>next</em> to the yellow box. Using clear on either div will put them on different lines.
Additionally, the cells can have variable lines of text - therefore, <em>line-height</em> will not help.</p>
| [
{
"answer_id": 122263,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>Add <code>clear: both</code> to the second element. If you want to @ to be below the yellow box, put it last in HTML cod... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8435/"
] | Within a table cell that is vertical-align:bottom, I have one or two divs. Each div is floated right.
Supposedly, the divs should not align to the bottom, but they do (which I don't understand, but is good).
However, when I have two floated divs in the cell, they align themselves to the same top line.
I want the first, smaller, div to sit all the way at the bottom. Another acceptable solution is to make it full height of the table cell.
It's difficult to explain, so here's the code:
>
>
> ```
> <style type="text/css">
> table {
> border-collapse: collapse;
> }
> td {
> border:1px solid black;
> vertical-align:bottom;
> }
> .h {
> float:right;
> background: #FFFFCC;
> }
> .ha {
> float:right;
> background: #FFCCFF;
> }
> </style>
>
> <table>
> <tr>
> <td>
> <div class="ha">@</div>
> <div class="h">Title Text<br />Line 2</div>
> </td>
> <td>
> <div class="ha">@</div>
> <div class="h">Title Text<br />Line 2<br />Line 3</div>
> </td>
> <td>
> <div class="h">Title Text<br />Line 2</div>
> </td>
> <td>
> <div class="h">Title Text<br />Line 2</div>
> </td>
> <td>
> <div class="h">Title Text<br />Line 2</div>
> </td>
> </tr>
> <tr>
> <td>
> <div class="d">123456789</div>
> </td>
> <td>
> <div class="d">123456789</div>
> </td>
> <td>
> <div class="d">123456789</div>
> </td>
> <td>
> <div class="d">123456789</div>
> </td>
> <td>
> <div class="d">123456789</div>
> </td>
> </tr>
> </table>
>
> ```
>
>
Here are the problems:
1. Why does the @ sign sit at the same level as the yellow div?
2. Supposedly vertical-align doesn't apply to block elements (like a floated div) 1. But it does!
3. How can I make the @ sit at the bottom or make it full height of the table cell?
I am testing in IE7 and FF2. Target support is IE6/7, FF2/3.
**Clarification:** The goal is to have the red @ on the bottom line of the table cell, *next* to the yellow box. Using clear on either div will put them on different lines.
Additionally, the cells can have variable lines of text - therefore, *line-height* will not help. | I never answered the first two questions, so feel free to give your answers below. But I *did* solve the last problem, of how to make it work.
I added a containing div to the two divs inside the table cells like so:
>
>
> ```
> <table>
> <tr>
> <td>
> <div class="t">
> <div class="h">Title Text<br />Line 2</div>
> <div class="ha">@</div>
> </div>
> </td>
>
> ```
>
>
Then I used the following CSS
>
>
> ```
> <style type="text/css">
> table {
> border-collapse: collapse;
> }
> td {
> border:1px solid black;
> vertical-align:bottom;
> }
> .t {
> position: relative;
> width:150px;
> }
> .h {
> background: #FFFFCC;
> width:135px;
> margin-right:15px;
> text-align:right;
> }
> .ha {
> background: #FFCCFF;
> width:15px;
> height:18px;
> position:absolute;
> right:0px;
> bottom:0px;
> }
> </style>
>
> ```
>
>
The key to it all is **for a div to be position absolutely relative to it's *parent* the parent must be declared position:relative** |
122,253 | <p>After installing a third-party SDK, it very discourteously makes one if its templates the default item in "Add New Item..." dialog in Visual Studio 2005. This is also the case for all other similar dialogs - "Add Class...", "Add User Control..." etc.</p>
<p>Is there a way to change this behavior?</p>
| [
{
"answer_id": 122270,
"author": "Asaf R",
"author_id": 6827,
"author_profile": "https://Stackoverflow.com/users/6827",
"pm_score": -1,
"selected": false,
"text": "<p>Try looking at the registry under </p>\n\n<pre><code>HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\\n</code></pre... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15497/"
] | After installing a third-party SDK, it very discourteously makes one if its templates the default item in "Add New Item..." dialog in Visual Studio 2005. This is also the case for all other similar dialogs - "Add Class...", "Add User Control..." etc.
Is there a way to change this behavior? | You may have to manually modify the SortOrder on the Item templates yourself. You can do this by following these directions:
1) Find the Item Template(s)
Item Templates for VS2005 are stored in the following locations:
```
(Installed Templates) <VisualStudioInstallDir>\Common7\IDE\ItemTemplates\Language\Locale\
(Custom Templates) My Documents\Visual Studio 2005\Templates\ItemTemplates\Language\
```
2) Open the template zip file to modify the .vstemplate file.
Each Item Template is stored in a .zip file, so you will need to open the zip file that pertains to the template you want to modify.
Open the template's .vstemplate file and find the SortOrder property under the TemplateData section. The following is a sample file:
<TemplateData>
<Name>SomeITem</Name>
<Description>Description</Description>
<ProjectType>>CSharp</ProjectType>
**<SortOrder>1000</SortOrder>**
<DefaultName></DefaultName>
<ProvideDefaultName>true</ProvideDefaultName>
</TemplateData>
Modify the SortOrder value using the following rules:
* The default value is 100, and all values must be multiples of 10.
* The SortOrder element is ignored for user-created templates. All user-created templates are sorted alphabetically.
* Templates that have low sort order values appear in either the New Project or New Add Item dialog box before templates that have high sort order values.
Once you've made edits to the template definitions you'll need to open a command prompt and navigate to the directory that contains devenv.exe, and type "devenv /setup". This presumably rebuilds some internal settings and until you do this you won't see any difference. |
122,254 | <p>I have a class that defines the names of various session attributes, e.g.</p>
<pre><code>class Constants {
public static final String ATTR_CURRENT_USER = "current.user";
}
</code></pre>
<p>I would like to use these constants within a JSP to test for the presence of these attributes, something like:</p>
<pre><code><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="com.example.Constants" %>
<c:if test="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}">
<%-- Do somthing --%>
</c:if>
</code></pre>
<p>But I can't seem to get the sytax correct. Also, to avoid repeating the rather lengthy tests above in multiple places, I'd like to assign the result to a local (page-scoped) variable, and refer to that instead. I believe I can do this with <code><c:set></code>, but again I'm struggling to find the correct syntax.</p>
<p><strong>UPDATE:</strong> Further to the suggestion below, I tried:</p>
<pre><code><c:set var="nullUser" scope="session"
value="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}" />
</code></pre>
<p>which didn't work. So instead, I tried substituting the literal value of the constant. I also added the constant to the content of the page, so I could verify the constant's value when the page is being rendered</p>
<pre><code><c:set var="nullUser" scope="session"
value="${sessionScope['current.user'] eq null}" />
<%= "Constant value: " + WebHelper.ATTR_CURRENT_PARTNER %>
</code></pre>
<p>This worked fine and it printed the expected value "current.user" on the page. I'm at a loss to explain why using the String literal works, but a reference to the constant doesn't, when the two appear to have the same value. Help.....</p>
| [
{
"answer_id": 122863,
"author": "Matt N",
"author_id": 20605,
"author_profile": "https://Stackoverflow.com/users/20605",
"pm_score": -1,
"selected": false,
"text": "<p>First, your syntax had an extra \"]\" which was causing an error. </p>\n\n<p>To fix that, and to set a variable you wo... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] | I have a class that defines the names of various session attributes, e.g.
```
class Constants {
public static final String ATTR_CURRENT_USER = "current.user";
}
```
I would like to use these constants within a JSP to test for the presence of these attributes, something like:
```
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="com.example.Constants" %>
<c:if test="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}">
<%-- Do somthing --%>
</c:if>
```
But I can't seem to get the sytax correct. Also, to avoid repeating the rather lengthy tests above in multiple places, I'd like to assign the result to a local (page-scoped) variable, and refer to that instead. I believe I can do this with `<c:set>`, but again I'm struggling to find the correct syntax.
**UPDATE:** Further to the suggestion below, I tried:
```
<c:set var="nullUser" scope="session"
value="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}" />
```
which didn't work. So instead, I tried substituting the literal value of the constant. I also added the constant to the content of the page, so I could verify the constant's value when the page is being rendered
```
<c:set var="nullUser" scope="session"
value="${sessionScope['current.user'] eq null}" />
<%= "Constant value: " + WebHelper.ATTR_CURRENT_PARTNER %>
```
This worked fine and it printed the expected value "current.user" on the page. I'm at a loss to explain why using the String literal works, but a reference to the constant doesn't, when the two appear to have the same value. Help..... | It's not working in your example because the `ATTR_CURRENT_USER` constant is not visible to the JSTL tags, which expect properties to be exposed by getter functions. I haven't tried it, but the cleanest way to expose your constants appears to be the [unstandard tag library](http://jakarta.apache.org/taglibs/sandbox/doc/unstandard-doc/index.html#useConstants "Unstandard tag library from Apache").
ETA: Old link I gave didn't work. New links can be found in this answer: [Java constants in JSP](https://stackoverflow.com/questions/127328/java-constants-in-jsp)
Code snippets to clarify the behavior you're seeing:
Sample class:
```
package com.example;
public class Constants
{
// attribute, visible to the scriptlet
public static final String ATTR_CURRENT_USER = "current.user";
// getter function;
// name modified to make it clear, later on,
// that I am calling this function
// and not accessing the constant
public String getATTR_CURRENT_USER_FUNC()
{
return ATTR_CURRENT_USER;
}
}
```
Snippet of the JSP page, showing sample usage:
```
<%-- Set up the current user --%>
<%
session.setAttribute("current.user", "Me");
%>
<%-- scriptlets --%>
<%@ page import="com.example.Constants" %>
<h1>Using scriptlets</h1>
<h3>Constants.ATTR_CURRENT_USER</h3>
<%=Constants.ATTR_CURRENT_USER%> <br />
<h3>Session[Constants.ATTR_CURRENT_USER]</h3>
<%=session.getAttribute(Constants.ATTR_CURRENT_USER)%>
<%-- JSTL --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:useBean id="cons" class="com.example.Constants" scope="session"/>
<h1>Using JSTL</h1>
<h3>Constants.getATTR_CURRENT_USER_FUNC()</h3>
<c:out value="${cons.ATTR_CURRENT_USER_FUNC}"/>
<h3>Session[Constants.getATTR_CURRENT_USER_FUNC()]</h3>
<c:out value="${sessionScope[cons.ATTR_CURRENT_USER_FUNC]}"/>
<h3>Constants.ATTR_CURRENT_USER</h3>
<c:out value="${sessionScope[Constants.ATTR_CURRENT_USER]}"/>
<%--
Commented out, because otherwise will error:
The class 'com.example.Constants' does not have the property 'ATTR_CURRENT_USER'.
<h3>cons.ATTR_CURRENT_USER</h3>
<c:out value="${sessionScope[cons.ATTR_CURRENT_USER]}"/>
--%>
<hr />
```
This outputs:
Using scriptlets
================
### Constants.ATTR\_CURRENT\_USER
current.user
### Session[Constants.ATTR\_CURRENT\_USER]
Me
---
Using JSTL
==========
### Constants.getATTR\_CURRENT\_USER\_FUNC()
current.user
### Session[Constants.getATTR\_CURRENT\_USER\_FUNC()]
Me
### Constants.ATTR\_CURRENT\_USER
--- |
122,267 | <p>(using the IMAP commands, not with the assistance of any other mail package)</p>
| [
{
"answer_id": 122289,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 2,
"selected": false,
"text": "<p>I guess you COPY the message to the new folder and then delete (EXPUNGE) it in the old one.</p>\n\n<p><a href=\"http://... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] | (using the IMAP commands, not with the assistance of any other mail package) | I'm not sure how well-versed you are in imap-speak, but basically after login, "SELECT" the source mailbox, "COPY" the messages, and "EXPUNGE" the messages (or "DELETE" the old mailbox if it is empty now :-).
```
a login a s
b select source
c copy 1 othermbox
d store 1 +flags (\Deleted)
e expunge
```
would be an example of messages to send. (**Note**: imap messages require a uniqe prefix before each command, thus the "a b c" in front)
See [RFC 2060](http://james.apache.org/server/rfclist/imap4/rfc2060.txt) for details. |
122,273 | <p>Does anyone have any code examples on how to create controllers that have parameters other than using a Dependency Injection Container? </p>
<p>I see plenty of samples with using containers like StructureMap, but nothing if you wanted to pass in the dependency class yourself.</p>
| [
{
"answer_id": 122361,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 5,
"selected": true,
"text": "<p>You can use poor-man's dependency injection:</p>\n\n<pre><code>public ProductController() : this( new Foo() )\n{\n ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17902/"
] | Does anyone have any code examples on how to create controllers that have parameters other than using a Dependency Injection Container?
I see plenty of samples with using containers like StructureMap, but nothing if you wanted to pass in the dependency class yourself. | You can use poor-man's dependency injection:
```
public ProductController() : this( new Foo() )
{
//the framework calls this
}
public ProductController(IFoo foo)
{
_foo = foo;
}
``` |
122,276 | <p>I want to be able to quickly check whether I both have sudo access and my password is already authenticated. I'm not worried about having sudo access specifically for the operation I'm about to perform, but that would be a nice bonus.</p>
<p>Specifically what I'm trying to use this for is a script that I want to be runnable by a range of users. Some have sudo access. All know the root password.</p>
<p>When they run my script, I want it to use sudo permissions without prompting for a password if that is possible, and otherwise to fall back to asking for the <em>root</em> password (because they might not have sudo access).</p>
<p>My first non-working attempt was to fork off <code>sudo -S true</code> with STDIN closed or reading from /dev/null. But that still prompts for the password and waits a couple of seconds.</p>
<p>I've tried several other things, including waiting 0.3sec to see whether it succeeded immediately, but everything I try ends up failing in some situation. (And not because my timeout is too short.) It's difficult to figure out what goes on, because I can't just strace like I normally would.</p>
<p>One thing I <em>know</em> doesn't work is to close STDIN or attach it to a pipe before running <code>sudo -S true</code>. I was hoping that would make the password prompt immediately fail, but it still prompts and behaves strangely. I think it might want a terminal.</p>
| [
{
"answer_id": 122300,
"author": "dirtside",
"author_id": 20903,
"author_profile": "https://Stackoverflow.com/users/20903",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know what the ultimate reason is for needing to do this, but I think maybe you might need to rethink whatever ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14528/"
] | I want to be able to quickly check whether I both have sudo access and my password is already authenticated. I'm not worried about having sudo access specifically for the operation I'm about to perform, but that would be a nice bonus.
Specifically what I'm trying to use this for is a script that I want to be runnable by a range of users. Some have sudo access. All know the root password.
When they run my script, I want it to use sudo permissions without prompting for a password if that is possible, and otherwise to fall back to asking for the *root* password (because they might not have sudo access).
My first non-working attempt was to fork off `sudo -S true` with STDIN closed or reading from /dev/null. But that still prompts for the password and waits a couple of seconds.
I've tried several other things, including waiting 0.3sec to see whether it succeeded immediately, but everything I try ends up failing in some situation. (And not because my timeout is too short.) It's difficult to figure out what goes on, because I can't just strace like I normally would.
One thing I *know* doesn't work is to close STDIN or attach it to a pipe before running `sudo -S true`. I was hoping that would make the password prompt immediately fail, but it still prompts and behaves strangely. I think it might want a terminal. | With newer versions of [`sudo`](http://www.sudo.ws/sudo/sudo.man.html) there's an option for this purpose:
```
sudo -n true
```
I use `true` here for a no-op, but you could use any command. |
122,277 | <p>I switched from Perl to Python about a year ago and haven't looked back. There is only <i>one</i> idiom that I've ever found I can do more easily in Perl than in Python:</p>
<pre><code>if ($var =~ /foo(.+)/) {
# do something with $1
} elsif ($var =~ /bar(.+)/) {
# do something with $1
} elsif ($var =~ /baz(.+)/) {
# do something with $1
}
</code></pre>
<p>The corresponding Python code is not so elegant since the if statements keep getting nested:</p>
<pre><code>m = re.search(r'foo(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'bar(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'baz(.+)', var)
if m:
# do something with m.group(2)
</code></pre>
<p>Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...</p>
| [
{
"answer_id": 122294,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 4,
"selected": false,
"text": "<p>Using named groups and a dispatch table:</p>\n\n<pre><code>r = re.compile(r'(?P<cmd>foo|bar|baz)(?P<dat... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20789/"
] | I switched from Perl to Python about a year ago and haven't looked back. There is only *one* idiom that I've ever found I can do more easily in Perl than in Python:
```
if ($var =~ /foo(.+)/) {
# do something with $1
} elsif ($var =~ /bar(.+)/) {
# do something with $1
} elsif ($var =~ /baz(.+)/) {
# do something with $1
}
```
The corresponding Python code is not so elegant since the if statements keep getting nested:
```
m = re.search(r'foo(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'bar(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'baz(.+)', var)
if m:
# do something with m.group(2)
```
Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions... | Starting `Python 3.8`, and the introduction of [assignment expressions (PEP 572)](https://www.python.org/dev/peps/pep-0572/) (`:=` operator), we can now capture the condition value `re.search(pattern, text)` in a variable `match` in order to both check if it's not `None` and then re-use it within the body of the condition:
```
if match := re.search(r'foo(.+)', text):
# do something with match.group(1)
elif match := re.search(r'bar(.+)', text):
# do something with match.group(1)
elif match := re.search(r'baz(.+)', text)
# do something with match.group(1)
``` |
122,301 | <p>Is there an easy way to get a conflict summary after running a <code>cvs update</code>? </p>
<p>I work on a large project and after doing some work I need to do an update. The list of changes coming back from the cvs update command is several pages long and I'd like to see only the list of conflicts (starts with 'C') repeated at the end of the cvs update command output.</p>
<p>The solution needs to work from the command line.</p>
<p>If my normal output is:</p>
<pre><code>M src/file1.txt
M src/file2.txt
cvs server: conflicts found ...
C src/file3.txt
M src/file4.txt
M src/file5.txt
</code></pre>
<p>I want my new output to be:</p>
<pre><code>M src/file1.txt
M src/file2.txt
cvs server: conflicts found ...
C src/file3.txt
M src/file4.txt
M src/file5.txt
Conflict Summary:
C src/file3.txt
</code></pre>
<p>I want this to be a single command (possibly a short script or alias) that outputs the normal cvs output as it happens followed by a summary of conflicts.</p>
| [
{
"answer_id": 122337,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 1,
"selected": false,
"text": "<p>I don't have cvs handy what is the exact format of the output of cvs update</p>\n\n<p>I seem to remember C <file... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6180/"
] | Is there an easy way to get a conflict summary after running a `cvs update`?
I work on a large project and after doing some work I need to do an update. The list of changes coming back from the cvs update command is several pages long and I'd like to see only the list of conflicts (starts with 'C') repeated at the end of the cvs update command output.
The solution needs to work from the command line.
If my normal output is:
```
M src/file1.txt
M src/file2.txt
cvs server: conflicts found ...
C src/file3.txt
M src/file4.txt
M src/file5.txt
```
I want my new output to be:
```
M src/file1.txt
M src/file2.txt
cvs server: conflicts found ...
C src/file3.txt
M src/file4.txt
M src/file5.txt
Conflict Summary:
C src/file3.txt
```
I want this to be a single command (possibly a short script or alias) that outputs the normal cvs output as it happens followed by a summary of conflicts. | Given the specification, it seems that you need a minor adaptation of Martin York's solution (because that only shows the conflicts and not the normal log information). Something like this - which might be called 'cvsupd':
```
tmp=${TMPDIR:-/tmp}/cvsupd.$$
trap "rm -f $tmp; exit 1" 0 1 2 3 13 15
cvs update "$@" | tee $tmp
if grep -s '^C' $tmp
then
echo
echo Conflict Summary:
grep '^C' $tmp
fi
rm -f $tmp
trap 0
exit 0
```
The trap commands ensure that the log file is not left around. It catches the normal signals - HUP, INT, QUIT, PIPE and TERM (respectively) and 0 traps any other exit from the shell. |
122,302 | <p>According to select name from system_privilege_map System has been granted:</p>
<pre><code>SELECT ANY TABLE
</code></pre>
<p>...and lots of other * ANY TABLES.</p>
<p>Plainly running</p>
<pre><code>select * from the_table;
select * from the_table;
</code></pre>
<p>...nets the given response:</p>
<blockquote>
<p>ERROR at line 1:
ORA-00942: table or view does not exist</p>
</blockquote>
<p>I can log in as that user and run the same command just fine.</p>
<p>I'm running under the assumption I should be able to run queries (select in this case) agaisnt a general user's DB table. Is my assumption correct, and if so, how do I do it?</p>
| [
{
"answer_id": 122309,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 4,
"selected": true,
"text": "<p>If the_table is owned by user \"some_user\" then:</p>\n\n<pre><code>select * from some_user.the_table;\n</code></pr... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | According to select name from system\_privilege\_map System has been granted:
```
SELECT ANY TABLE
```
...and lots of other \* ANY TABLES.
Plainly running
```
select * from the_table;
select * from the_table;
```
...nets the given response:
>
> ERROR at line 1:
> ORA-00942: table or view does not exist
>
>
>
I can log in as that user and run the same command just fine.
I'm running under the assumption I should be able to run queries (select in this case) agaisnt a general user's DB table. Is my assumption correct, and if so, how do I do it? | If the\_table is owned by user "some\_user" then:
```
select * from some_user.the_table;
``` |
122,313 | <p>I'm getting confused with the include/exclude jargon, and my actual SVN client doesn't seem to have (or I've been unable to find it easily) a simple option to add or remove a certain type of files for version control.</p>
<p>Let's say for example I've added the entire Visual Studio folder, with its solutions, projects, debug files, etc., but I only want to version the actual source files. What would be the simplest way to do that?</p>
| [
{
"answer_id": 122328,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 1,
"selected": false,
"text": "<p>At the lowest level, SVN allows you to ignore certain files or patterns with <a href=\"http://www.petefreitag.com/i... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6992/"
] | I'm getting confused with the include/exclude jargon, and my actual SVN client doesn't seem to have (or I've been unable to find it easily) a simple option to add or remove a certain type of files for version control.
Let's say for example I've added the entire Visual Studio folder, with its solutions, projects, debug files, etc., but I only want to version the actual source files. What would be the simplest way to do that? | You're probably safest excluding particular filetypes, rather than picking those you want to include, as you could then add a new type and not realize it wasn't versioned.
On a per-directory basis, you can edit the [svn:ignore](http://svnbook.red-bean.com/en/1.1/ch07s02.html#svn-ch-7-sect-2.3.3) property.
Run
```
svn propedit svn:ignore .
```
for each relevant directory to bring up an editor with a list of patterns to ignore.
Then put a pattern on each line corresponding to the filetype you'd like to ignore:
```
*.user
*.exe
*.dll
```
and what have you.
Alternatively, as has been suggested, you can add those patterns to the `global-ignores` property in your ~/.subversion/config file (or `"%APPDATA%\Subversion\config"` on Windows - see [Configuration Area Layout in the red bean book for more information](http://svnbook.red-bean.com/en/1.1/ch07.html#svn-ch-7-sect-1.1)). In that case, separate the patterns with spaces. Here's mine. `#` at the beginning of the line introduces a comment. I've ignored Ankh .Load files and all \*.resharper.user files:
```
### Set global-ignores to a set of whitespace-delimited globs
### which Subversion will ignore in its 'status' output, and
### while importing or adding files and directories.
# global-ignores = *.o *.lo *.la #*# .*.rej *.rej .*~ *~ .#* .DS_Store
global-ignores = Ankh.Load *.resharper.user
``` |
122,316 | <p>In C# we can define a generic type that imposes constraints on the types that can be used as the generic parameter. The following example illustrates the usage of generic constraints:</p>
<pre><code>interface IFoo
{
}
class Foo<T> where T : IFoo
{
}
class Bar : IFoo
{
}
class Simpson
{
}
class Program
{
static void Main(string[] args)
{
Foo<Bar> a = new Foo<Bar>();
Foo<Simpson> b = new Foo<Simpson>(); // error CS0309
}
}
</code></pre>
<p>Is there a way we can impose constraints for template parameters in C++.</p>
<hr>
<p>C++0x has native support for this but I am talking about current standard C++.</p>
| [
{
"answer_id": 122347,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 1,
"selected": false,
"text": "<p>Only implicitly.<br>\nAny method you use in a method that is actually called is imposed on the template parameter. </p>\n... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6508/"
] | In C# we can define a generic type that imposes constraints on the types that can be used as the generic parameter. The following example illustrates the usage of generic constraints:
```
interface IFoo
{
}
class Foo<T> where T : IFoo
{
}
class Bar : IFoo
{
}
class Simpson
{
}
class Program
{
static void Main(string[] args)
{
Foo<Bar> a = new Foo<Bar>();
Foo<Simpson> b = new Foo<Simpson>(); // error CS0309
}
}
```
Is there a way we can impose constraints for template parameters in C++.
---
C++0x has native support for this but I am talking about current standard C++. | As someone else has mentioned, C++0x is getting this built into the language. Until then, I'd recommend [Bjarne Stroustrup](http://en.wikipedia.org/wiki/Bjarne_Stroustrup)'s [suggestions for template constraints](http://www.stroustrup.com/bs_faq2.html#constraints).
Edit: [Boost](http://boost.org) also has an [alternative of its own](http://www.boost.org/doc/libs/1_36_0/libs/concept_check/concept_check.htm).
Edit2: Looks like [concepts have been removed from C++0x](http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=441). |
122,324 | <p>Would having a nice little feature that makes it quicker to write code like Automatic Properties fit very nicely with the mantra of VB.NET?</p>
<p>Something like this would work perfect:</p>
<pre><code>Public Property FirstName() As String
Get
Set
End Property
</code></pre>
<p><strong>UPDATE:</strong> VB.NET 10 (coming with Visual Studio 2010 and .NET 4.0) will have Automatic Properties. Here's a link that shows a little info about the feature: <a href="https://web.archive.org/web/20200119055303/http://geekswithblogs.net:80/DarrenFieldhouse/archive/2008/12/01/new-features-in-vb.net-10-.net-4.0.aspx" rel="nofollow noreferrer">http://geekswithblogs.net/DarrenFieldhouse/archive/2008/12/01/new-features-in-vb.net-10-.net-4.0.aspx</a></p>
<p>In VB.NET 10 Automatic Properties will be defines like this:</p>
<pre><code>Public Property CustomerID As Integer
</code></pre>
| [
{
"answer_id": 122339,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 1,
"selected": false,
"text": "<p>C# and VB.NET don't exactly line up on new features in their first versions. Usually, by the next version C# catches ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7831/"
] | Would having a nice little feature that makes it quicker to write code like Automatic Properties fit very nicely with the mantra of VB.NET?
Something like this would work perfect:
```
Public Property FirstName() As String
Get
Set
End Property
```
**UPDATE:** VB.NET 10 (coming with Visual Studio 2010 and .NET 4.0) will have Automatic Properties. Here's a link that shows a little info about the feature: [http://geekswithblogs.net/DarrenFieldhouse/archive/2008/12/01/new-features-in-vb.net-10-.net-4.0.aspx](https://web.archive.org/web/20200119055303/http://geekswithblogs.net:80/DarrenFieldhouse/archive/2008/12/01/new-features-in-vb.net-10-.net-4.0.aspx)
In VB.NET 10 Automatic Properties will be defines like this:
```
Public Property CustomerID As Integer
``` | One reason many features get delayed in VB is that the development structure is much different than in C# and additionally, that often more thought goes into details. The same seems to be true in this case, as suggested by [Paul Vick's post](http://www.panopticoncentral.net/archive/2008/03/27/23050.aspx) on the matter. This is unfortunate because it means a delay in many cases (automatic properties, iterator methods, multiline lambdas, to name but a few) but on the other hand, the VB developers usually get a much more mature feature in the long run (looking at the discussion, this will be especially true for iterator methods).
So, long story short: VB 10 will (hopefully!) see automatic properties. |
122,327 | <p>How do I find the location of my <code>site-packages</code> directory?</p>
| [
{
"answer_id": 122340,
"author": "Daryl Spitzer",
"author_id": 4766,
"author_profile": "https://Stackoverflow.com/users/4766",
"pm_score": 9,
"selected": false,
"text": "<p>A solution that:</p>\n\n<ul>\n<li>outside of virtualenv - provides the path of <strong>global</strong> site-package... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4766/"
] | How do I find the location of my `site-packages` directory? | There are two types of site-packages directories, *global* and *per user*.
1. **Global** site-packages ("[dist-packages](https://stackoverflow.com/questions/9387928/whats-the-difference-between-dist-packages-and-site-packages)") directories are listed in `sys.path` when you run:
```
python -m site
```
For a more concise list run `getsitepackages` from the [site module](https://docs.python.org/3/library/site.html#site.getsitepackages) in Python code:
```
python -c 'import site; print(site.getsitepackages())'
```
*Caution:* In virtual environments [getsitepackages is not available](https://github.com/pypa/virtualenv/issues/228) with [older versions of `virtualenv`](https://github.com/pypa/virtualenv/pull/2379/files), `sys.path` from above will list the virtualenv's site-packages directory correctly, though. In Python 3, you may use the [sysconfig module](https://docs.python.org/3/library/sysconfig.html#using-sysconfig-as-a-script) instead:
```
python3 -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])'
```
2. The **per user** site-packages directory ([PEP 370](https://www.python.org/dev/peps/pep-0370/)) is where Python installs your local packages:
```
python -m site --user-site
```
If this points to a non-existing directory check the exit status of Python and see `python -m site --help` for explanations.
*Hint:* Running `pip list --user` or `pip freeze --user` gives you a list of all installed *per user* site-packages.
---
Practical Tips
--------------
* `<package>.__path__` lets you identify the location(s) of a specific package: ([details](https://stackoverflow.com/questions/2699287/what-is-path-useful-for))
```
$ python -c "import setuptools as _; print(_.__path__)"
['/usr/lib/python2.7/dist-packages/setuptools']
```
* `<module>.__file__` lets you identify the location of a specific module: ([difference](https://softwareengineering.stackexchange.com/questions/111871/module-vs-package))
```
$ python3 -c "import os as _; print(_.__file__)"
/usr/lib/python3.6/os.py
```
* Run `pip show <package>` to show Debian-style package information:
```
$ pip show pytest
Name: pytest
Version: 3.8.2
Summary: pytest: simple powerful testing with Python
Home-page: https://docs.pytest.org/en/latest/
Author: Holger Krekel, Bruno Oliveira, Ronny Pfannschmidt, Floris Bruynooghe, Brianna Laugher, Florian Bruhin and others
Author-email: None
License: MIT license
Location: /home/peter/.local/lib/python3.4/site-packages
Requires: more-itertools, atomicwrites, setuptools, attrs, pathlib2, six, py, pluggy
``` |
122,348 | <p>I have a command which includes an includegraphics command - I can pass an image to my command, and it will do some standard formatting for me before actually including the image. Some of the images that I'm including via this command are smaller than \textwidth, while some are larger. I'd like to scale the larger images down to \textwidth, while not scaling the smaller images up - this means I can't just do </p>
<pre><code>\includegraphics[width=\textwidth]{img}
</code></pre>
<p>Is there a way to specify a maxwidth? Or, can I get the width of the image somehow so I can do something like </p>
<pre><code>\ifthenelse{\imagewidth > \textwidth}{%
\includegraphics[width=\textwidth]{img}}{%
\includegraphics{img}}
</code></pre>
| [
{
"answer_id": 122653,
"author": "Steve Landey",
"author_id": 8061,
"author_profile": "https://Stackoverflow.com/users/8061",
"pm_score": -1,
"selected": false,
"text": "<p>After a few minutes of searching through CTAN manuals and Google results, I think I can safely say that what you wa... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1322/"
] | I have a command which includes an includegraphics command - I can pass an image to my command, and it will do some standard formatting for me before actually including the image. Some of the images that I'm including via this command are smaller than \textwidth, while some are larger. I'd like to scale the larger images down to \textwidth, while not scaling the smaller images up - this means I can't just do
```
\includegraphics[width=\textwidth]{img}
```
Is there a way to specify a maxwidth? Or, can I get the width of the image somehow so I can do something like
```
\ifthenelse{\imagewidth > \textwidth}{%
\includegraphics[width=\textwidth]{img}}{%
\includegraphics{img}}
``` | To get the width of the image you can use this code:
```
\newlength{\imgwidth}
\settowidth{\imgwidth}{\includegraphics{img}}
```
You could use this in the document preamble to create a new command to automatically set the width:
```
\usepackage{graphicx}
\usepackage{calc}
\newlength{\imgwidth}
\newcommand\scalegraphics[1]{%
\settowidth{\imgwidth}{\includegraphics{#1}}%
\setlength{\imgwidth}{\minof{\imgwidth}{\textwidth}}%
\includegraphics[width=\imgwidth]{#1}%
}
```
and then, in your document:
```
\scalegraphics{img}
```
I hope this helps! |
122,407 | <p>I have a method that's about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code. This is a perfect application for passing in a function pointer to replace that one line, but Java doesn't have function pointers. What's my best alternative?</p>
| [
{
"answer_id": 122414,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 9,
"selected": true,
"text": "<p>Anonymous inner class</p>\n\n<p>Say you want to have a function passed in with a <code>String</code> param that returns an... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] | I have a method that's about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code. This is a perfect application for passing in a function pointer to replace that one line, but Java doesn't have function pointers. What's my best alternative? | Anonymous inner class
Say you want to have a function passed in with a `String` param that returns an `int`.
First you have to define an interface with the function as its only member, if you can't reuse an existing one.
```
interface StringFunction {
int func(String param);
}
```
A method that takes the pointer would just accept `StringFunction` instance like so:
```
public void takingMethod(StringFunction sf) {
int i = sf.func("my string");
// do whatever ...
}
```
And would be called like so:
```
ref.takingMethod(new StringFunction() {
public int func(String param) {
// body
}
});
```
*EDIT:* In Java 8, you could call it with a lambda expression:
```
ref.takingMethod(param -> bodyExpression);
``` |
122,422 | <p>Is there any way to change the default datatype when importing an Excel file into Access? (I'm using Access 2003, by the way).</p>
<p>I know that I sometimes have the freedom to assign any datatype to each column that is being imported, but that could only be when I'm importing non-Excel files. </p>
<p><strong>EDIT:</strong> To be clear, I understand that there is a step in the import process where you are allowed to change the datatype of the imported column. </p>
<p>In fact, that's what I'm asking about. For some reason - maybe it's always Excel files, maybe there's something else - I am sometimes not allowed to change the datatype: the dropdown box is grayed out and I just have to live with whatever datatype Access assumes is correct.</p>
<p>For example, I just tried importing a large-ish Excel file (<strong>12000+ rows, ~200 columns</strong>) in Access where column #105 (or something similar) was filled with mostly numbers (codes: <code>1=foo, 2=bar</code>, etc), though there are a handful of alpha codes in there too (A=boo, B=far, etc). Access assumed it was a <code>Number</code> datatype (even after I changed the <code>Format</code> value in the Excel file itself) and so gave me errors on those alpha codes. If I had been allowed to change the datatype on import, it would have saved me some trouble.</p>
<p>Am I asking for something that Access just won't do, or am I missing something? Thanks.</p>
<p><strong>EDIT:</strong> There are two answers below that give useful advice. Saving the Excel file as a CSV and then importing that works well and is straightforward like <a href="https://stackoverflow.com/questions/122422/change-datatype-when-importing-excel-file-into-access#122588">Chris OC</a> says. The advice for saving an import specification is very helpful too. However, I chose the registry setting answer by <a href="https://stackoverflow.com/questions/122422/change-datatype-when-importing-excel-file-into-access#122504">DK</a> as the "Accepted Answer". I liked it as an answer because it's a <em>one-time-only step</em> that can be used to solve my major problem (having Access incorrectly assign a datatype). In short, this solution doesn't allow me to change the datatype myself, but it makes Access accurately guess the datatype so that there are fewer issues.</p>
| [
{
"answer_id": 122442,
"author": "theo",
"author_id": 7870,
"author_profile": "https://Stackoverflow.com/users/7870",
"pm_score": -1,
"selected": false,
"text": "<p>Access will do this.</p>\n\n<p>In your import process you can define what the data type of each column is.</p>\n"
},
{
... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3930756/"
] | Is there any way to change the default datatype when importing an Excel file into Access? (I'm using Access 2003, by the way).
I know that I sometimes have the freedom to assign any datatype to each column that is being imported, but that could only be when I'm importing non-Excel files.
**EDIT:** To be clear, I understand that there is a step in the import process where you are allowed to change the datatype of the imported column.
In fact, that's what I'm asking about. For some reason - maybe it's always Excel files, maybe there's something else - I am sometimes not allowed to change the datatype: the dropdown box is grayed out and I just have to live with whatever datatype Access assumes is correct.
For example, I just tried importing a large-ish Excel file (**12000+ rows, ~200 columns**) in Access where column #105 (or something similar) was filled with mostly numbers (codes: `1=foo, 2=bar`, etc), though there are a handful of alpha codes in there too (A=boo, B=far, etc). Access assumed it was a `Number` datatype (even after I changed the `Format` value in the Excel file itself) and so gave me errors on those alpha codes. If I had been allowed to change the datatype on import, it would have saved me some trouble.
Am I asking for something that Access just won't do, or am I missing something? Thanks.
**EDIT:** There are two answers below that give useful advice. Saving the Excel file as a CSV and then importing that works well and is straightforward like [Chris OC](https://stackoverflow.com/questions/122422/change-datatype-when-importing-excel-file-into-access#122588) says. The advice for saving an import specification is very helpful too. However, I chose the registry setting answer by [DK](https://stackoverflow.com/questions/122422/change-datatype-when-importing-excel-file-into-access#122504) as the "Accepted Answer". I liked it as an answer because it's a *one-time-only step* that can be used to solve my major problem (having Access incorrectly assign a datatype). In short, this solution doesn't allow me to change the datatype myself, but it makes Access accurately guess the datatype so that there are fewer issues. | This *may* be caused by Excel Jet driver default settings. Check out the following registry key and change it's value from default 8 to 0, meaning "guess column data type based on all values, not just first 8 rows."
```
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Excel]
"TypeGuessRows"=dword:00000000
```
Please, tell if this works. |
122,424 | <p>Right now, we are using Perforce for version control. It has the handy feature of a strictly increasing change number that we can use to refer to builds, eg "you'll get the bugfix if your build is at least 44902".</p>
<p>I'd like to switch over to using a distributed system (probably git) to make it easier to branch and to work from home. (Both of which are perfectly possible with Perforce, but the git workflow has some advantages.) So although "tributary development" would be distributed and not refer to a common revision sequencing, we'd still maintain a master git repo that all changes would need to feed into before a build was created.</p>
<p>What's the best way to preserve strictly increasing build ids? The most straightforward way I can think of is to have some sort of post-commit hook that fires off whenever the master repo gets updated, and it registers (the hash of) the new tree object (or commit object? I'm new to git) with a centralized database that hands out ids. (I say "database", but I'd probably do it with git tags, and just look for the next available tag number or something. So the "database" would really be .git/refs/tags/build-id/.)</p>
<p>This is workable, but I'm wondering if there is an easier, or already-implemented, or standard/"best practice" way of accomplishing this.</p>
| [
{
"answer_id": 122508,
"author": "foxxtrot",
"author_id": 10369,
"author_profile": "https://Stackoverflow.com/users/10369",
"pm_score": 1,
"selected": false,
"text": "<p>I'd use \"Labels\" Create a label whenever you have a successful (or even unsuccessful) build, and you'll be able to ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14528/"
] | Right now, we are using Perforce for version control. It has the handy feature of a strictly increasing change number that we can use to refer to builds, eg "you'll get the bugfix if your build is at least 44902".
I'd like to switch over to using a distributed system (probably git) to make it easier to branch and to work from home. (Both of which are perfectly possible with Perforce, but the git workflow has some advantages.) So although "tributary development" would be distributed and not refer to a common revision sequencing, we'd still maintain a master git repo that all changes would need to feed into before a build was created.
What's the best way to preserve strictly increasing build ids? The most straightforward way I can think of is to have some sort of post-commit hook that fires off whenever the master repo gets updated, and it registers (the hash of) the new tree object (or commit object? I'm new to git) with a centralized database that hands out ids. (I say "database", but I'd probably do it with git tags, and just look for the next available tag number or something. So the "database" would really be .git/refs/tags/build-id/.)
This is workable, but I'm wondering if there is an easier, or already-implemented, or standard/"best practice" way of accomplishing this. | I second the suggestion of using `git describe`. Provided that you have a sane versioning policy, and you don't do any crazy stuff with your repository, `git describe` will always be monotonic (at least as monotonic as you can be, when your revision history is a DAG instead of a tree) and unique.
A little demonstration:
```
git init
git commit --allow-empty -m'Commit One.'
git tag -a -m'Tag One.' 1.2.3
git describe # => 1.2.3
git commit --allow-empty -m'Commit Two.'
git describe # => 1.2.3-1-gaac161d
git commit --allow-empty -m'Commit Three.'
git describe # => 1.2.3-2-g462715d
git tag -a -m'Tag Two.' 2.0.0
git describe # => 2.0.0
```
The output of `git describe` consists of the following components:
1. The newest tag reachable from the commit you are asking to describe
2. The number of commits between the commit and the tag (if non-zero)
3. The (abbreviated) id of the commit (if #2 is non-zero)
#2 is what makes the output monotonic, #3 is what makes it unique. #2 and #3 are omitted, when the commit *is* the tag, making `git describe` also suitable for production releases. |
122,445 | <p>I'm implementing charts using <a href="http://www.ziya.liquidrail.com/" rel="nofollow noreferrer">The Ziya Charts Gem</a>. Unfortunately, the documentation isn't really helpful or I haven't had enough coffee to figure out theming. I know I can set a theme using</p>
<pre><code>chart.add(:theme, 'whatever')
</code></pre>
<p>Problem: I haven't found any predefined themes, nor have I found a reference to the required format. </p>
| [
{
"answer_id": 122491,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 0,
"selected": false,
"text": "<p>To partly answer my own question, there are some themes in the website sources which can be checked out at </... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4494/"
] | I'm implementing charts using [The Ziya Charts Gem](http://www.ziya.liquidrail.com/). Unfortunately, the documentation isn't really helpful or I haven't had enough coffee to figure out theming. I know I can set a theme using
```
chart.add(:theme, 'whatever')
```
Problem: I haven't found any predefined themes, nor have I found a reference to the required format. | As I understand it, the themes are used by initializing the theme directory in your ziya.rb file like so:
`Ziya.initialize(:themes_dir => File.join( File.dirname(__FILE__), %w[.. .. public charts themes]) )`
And you'll need to set up the proper directory, in this case public/charts/themes. It doesn't come with any in there to start with as I recall. Are you having problems past this? |
122,463 | <p>I have an XML file that starts like this:</p>
<pre><code><Elements name="Entities" xmlns="XS-GenerationToolElements">
</code></pre>
<p>I'll have to open a lot of these files. Each of these have a different namespace but will only have one namespace at a time (I'll never find two namespaces defined in one xml file).</p>
<p>Using XPath I'd like to have an automatic way to add the given namespace to the namespace manager.
So far, i could only get the namespace by parsing the xml file but I have a XPathNavigator instance and it should have a nice and clean way to get the namespaces, right?</p>
<p>-- OR --</p>
<p>Given that I only have one namespace, somehow make XPath use the only one that is present in the xml, thus avoiding cluttering the code by always appending the namespace.</p>
| [
{
"answer_id": 122786,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 2,
"selected": false,
"text": "<p>Unfortunately, XPath doesn't have any concept of \"default namespace\". You need to register namespaces with prefixes... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20335/"
] | I have an XML file that starts like this:
```
<Elements name="Entities" xmlns="XS-GenerationToolElements">
```
I'll have to open a lot of these files. Each of these have a different namespace but will only have one namespace at a time (I'll never find two namespaces defined in one xml file).
Using XPath I'd like to have an automatic way to add the given namespace to the namespace manager.
So far, i could only get the namespace by parsing the xml file but I have a XPathNavigator instance and it should have a nice and clean way to get the namespaces, right?
-- OR --
Given that I only have one namespace, somehow make XPath use the only one that is present in the xml, thus avoiding cluttering the code by always appending the namespace. | There are a few techniques that you might try; which you use will depend on exactly what information you need to get out of the document, how rigorous you want to be, and how conformant the XPath implementation you're using is.
One way to get the namespace URI associated with a particular prefix is using the `namespace::` axis. This will give you a namespace node whose name is the prefix and whose value is the namespace URI. For example, you could get the default namespace URI on the document element using the path:
```
/*/namespace::*[name()='']
```
You might be able to use that to set up the namespace associations for your XPathNavigator. Be warned, though, that the `namespace::` axis is one of those corners of XPath 1.0 that isn't always implemented.
A second way of getting that namespace URI is to use the `namespace-uri()` function on the document element (which you've said will always be in that namespace). The expression:
```
namespace-uri(/*)
```
will give you that namespace.
An alternative would be to forget about associating a prefix with that namespace, and just make your path namespace-free. You can do this by using the `local-name()` function whenever you need to refer to an element whose namespace you don't know. For example:
```
//*[local-name() = 'Element']
```
You could go one step further and test the namespace URI of the element against the one of the document element, if you really wanted:
```
//*[local-name() = 'Element' and namespace-uri() = namespace-uri(/*)]
```
A final option, given that the namespace seems to mean nothing to you, would be to run your XML through a filter that strips out the namespaces. Then you won't have to worry about them in your XPath at all. The easiest way to do that would be simply to remove the `xmlns` attribute with a regular expression, but you could do something more complex if you needed to do other tidying at the same time. |
122,483 | <p>In crontab, I can use an asterisk to mean every value, or "*/2" to mean every even value.</p>
<p>Is there a way to specify every <strong>odd</strong> value? (Would something like "1+*/2" work?)</p>
| [
{
"answer_id": 122496,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 2,
"selected": false,
"text": "<p>Try</p>\n\n<pre><code>1-23/2\n</code></pre>\n\n<p>From your question, I'm assuming Vixie Cron. I doubt this will wo... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4465/"
] | In crontab, I can use an asterisk to mean every value, or "\*/2" to mean every even value.
Is there a way to specify every **odd** value? (Would something like "1+\*/2" work?) | Depending on your version of cron, you should be able to do (for hours, say):
```
1-23/2
```
Going by the EXTENSIONS section in the crontab(5) manpage:
```
Ranges can include "steps", so "1-9/2" is the same as "1,3,5,7,9".
```
For a more portable solution, I suspect you just have to use the simple list:
```
1,3,5,7,9,11,13,15,17,19,21,23
```
But it might be easier to wrap your command in a shell script that will immediately exit if it's not called in an odd minute. |
122,514 | <p>I have already posted something similar <a href="https://stackoverflow.com/questions/118051/c-grid-binding-not-update">here</a> but I would like to ask the question more general over here.</p>
<p>Have you try to serialize an object that implement INotifyPropertyChanged and to get it back from serialization and to bind it to a DataGridView? When I do it, I have no refresh from the value that change (I need to minimize the windows and open it back).</p>
<p>Do you have any trick? </p>
| [
{
"answer_id": 122522,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 0,
"selected": false,
"text": "<p>The trick of having it's own <a href=\"https://stackoverflow.com/questions/118051/c-grid-binding-not-update#... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] | I have already posted something similar [here](https://stackoverflow.com/questions/118051/c-grid-binding-not-update) but I would like to ask the question more general over here.
Have you try to serialize an object that implement INotifyPropertyChanged and to get it back from serialization and to bind it to a DataGridView? When I do it, I have no refresh from the value that change (I need to minimize the windows and open it back).
Do you have any trick? | Use the `DataContractSerializer` and create a method for OnDeserialized
```
[OnDeserialized]
private void OnDeserialized(StreamingContext c) {}
```
This will let you raise the PropertyChanged event when deserialization is complete |
122,523 | <p>Howdy, I have a DataRow pulled out of a DataTable from a DataSet. I am accessing a column that is defined in SQL as a float datatype. I am trying to assign that value to a local variable (c# float datatype) but am getting an InvalidCastExecption </p>
<pre><code>DataRow exercise = _exerciseDataSet.Exercise.FindByExerciseID(65);
_AccelLimit = (float)exercise["DefaultAccelLimit"];
</code></pre>
<p>Now, playing around with this I did make it work but it did not make any sense and it didn't feel right. </p>
<pre><code>_AccelLimit = (float)(double)exercise["DefaultAccelLimit"];
</code></pre>
<p>Can anyone explain what I am missing here?</p>
| [
{
"answer_id": 122536,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 7,
"selected": true,
"text": "<p>A SQL float is a double according to <a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqldbtype.aspx#M... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048/"
] | Howdy, I have a DataRow pulled out of a DataTable from a DataSet. I am accessing a column that is defined in SQL as a float datatype. I am trying to assign that value to a local variable (c# float datatype) but am getting an InvalidCastExecption
```
DataRow exercise = _exerciseDataSet.Exercise.FindByExerciseID(65);
_AccelLimit = (float)exercise["DefaultAccelLimit"];
```
Now, playing around with this I did make it work but it did not make any sense and it didn't feel right.
```
_AccelLimit = (float)(double)exercise["DefaultAccelLimit"];
```
Can anyone explain what I am missing here? | A SQL float is a double according to [the documentation for SQLDbType](http://msdn.microsoft.com/en-us/library/system.data.sqldbtype.aspx#Mtps_DropDownFilterText). |
122,533 | <p>Is there any way to down-format a Subversion repository to avoid messages like this:</p>
<pre>
svn: Expected format '3' of repository; found format '5'
</pre>
<p>This happens when you access repositories from more than one machine, and you aren't able to use a consistent version of Subversion across all of those machines. </p>
<p>Worse still, there are multiple repositories with various formats on different servers, and I'm not at liberty to upgrade some of these servers.
~~~</p>
| [
{
"answer_id": 122549,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 2,
"selected": false,
"text": "<p>I suspect you have to export the repository and re-import it into the older version. There might be some format incompati... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7255/"
] | Is there any way to down-format a Subversion repository to avoid messages like this:
```
svn: Expected format '3' of repository; found format '5'
```
This happens when you access repositories from more than one machine, and you aren't able to use a consistent version of Subversion across all of those machines.
Worse still, there are multiple repositories with various formats on different servers, and I'm not at liberty to upgrade some of these servers.
~~~ | If you can't use the same version of Subversion across all machines, then you should set up a server process (either svnserve or Apache) and access the repository only through the server. The server can mediate between different versions of Subversion; it's only when you're using direct repository access that you run into this issue.
If the server will be an older version than the current repository format (which I don't recommend), then you'll need to export the repository using the newer version and import it using the older version. |
122,546 | <p>We've written a plugin to the Xinha text editor to handle footnotes. You can take a look at:
<a href="http://www.nicholasbs.com/xinha/examples/Newbie.html" rel="nofollow noreferrer">http://www.nicholasbs.com/xinha/examples/Newbie.html</a></p>
<p>In order to handle some problems with the way Webkit and IE handle links at the end of lines (there's no way to use the cursor to get out of the link on the same line) we insert a blank element and move the selection to that, than collapse right. This works fine in Webkit and Gecko, but for some reason moveToElementText is spitting out an Invalid Argument exception. It doesn't matter which element we pass to it, the function seems to be completely broken. In other code paths, however, this function seems to work.</p>
<p>To reproduce the error using the link above, click in the main text input area, type anything, then click on the yellow page icon with the green plus sign, type anything into the lightbox dialog, and click on Insert. An example of the code that causes the problem is below:</p>
<pre><code> if (Xinha.is_ie)
{
var mysel = editor.getSelection();
var myrange = doc.body.createTextRange();
myrange.moveToElementText(newel);
} else
{
editor.selectNodeContents(newel, false);
}
</code></pre>
<p>The code in question lives in svn at:
<a href="https://svn.openplans.org/svn/xinha_dev/InsertNote" rel="nofollow noreferrer">https://svn.openplans.org/svn/xinha_dev/InsertNote</a></p>
<p>This plugin is built against a branch of Xinha available from svn at:
<a href="http://svn.xinha.webfactional.com/branches/new-dialogs" rel="nofollow noreferrer">http://svn.xinha.webfactional.com/branches/new-dialogs</a></p>
| [
{
"answer_id": 122876,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 4,
"selected": true,
"text": "<p>It's not visible in the snippet above, but newel has been appended to the dom using another element that was itself ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8458/"
] | We've written a plugin to the Xinha text editor to handle footnotes. You can take a look at:
<http://www.nicholasbs.com/xinha/examples/Newbie.html>
In order to handle some problems with the way Webkit and IE handle links at the end of lines (there's no way to use the cursor to get out of the link on the same line) we insert a blank element and move the selection to that, than collapse right. This works fine in Webkit and Gecko, but for some reason moveToElementText is spitting out an Invalid Argument exception. It doesn't matter which element we pass to it, the function seems to be completely broken. In other code paths, however, this function seems to work.
To reproduce the error using the link above, click in the main text input area, type anything, then click on the yellow page icon with the green plus sign, type anything into the lightbox dialog, and click on Insert. An example of the code that causes the problem is below:
```
if (Xinha.is_ie)
{
var mysel = editor.getSelection();
var myrange = doc.body.createTextRange();
myrange.moveToElementText(newel);
} else
{
editor.selectNodeContents(newel, false);
}
```
The code in question lives in svn at:
<https://svn.openplans.org/svn/xinha_dev/InsertNote>
This plugin is built against a branch of Xinha available from svn at:
<http://svn.xinha.webfactional.com/branches/new-dialogs> | It's not visible in the snippet above, but newel has been appended to the dom using another element that was itself appended to the DOM. When inserting a dom element, you have to re-retrieve your handle if you wish to reference its siblings, since the handle is invalid (I'm not sure, but I think it refers to a DOM element inside of a document fragment and not the one inside of the document.) After re-retrieving the handle from the insert operation, moveToElementText stopped throwing an exception. |
122,571 | <p>Right now I'm making an extremely simple website- about 5 pages. Question is if it's overkill and worth the time to integrate some sort of database mapping solution or if it would be better to just use plain old JNDI. I'll have maybe a dozen things I need to read/write from the database. I guess I have a basic understanding of these technologies but it would still take a lot of referring to the documentation. Anyone else faced with the decision before?</p>
<p>EDIT: Sorry, I should've specified JNDI to lookup the DB connection and JDBC to perform the operations.</p>
| [
{
"answer_id": 122709,
"author": "ColinD",
"author_id": 13792,
"author_profile": "https://Stackoverflow.com/users/13792",
"pm_score": 1,
"selected": false,
"text": "<p>It does seem like it would be overkill for a very simple application, especially if you don't have plans to expand on it... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17614/"
] | Right now I'm making an extremely simple website- about 5 pages. Question is if it's overkill and worth the time to integrate some sort of database mapping solution or if it would be better to just use plain old JNDI. I'll have maybe a dozen things I need to read/write from the database. I guess I have a basic understanding of these technologies but it would still take a lot of referring to the documentation. Anyone else faced with the decision before?
EDIT: Sorry, I should've specified JNDI to lookup the DB connection and JDBC to perform the operations. | Short answer: It depends on the complexity you want to support.
Long answer:
First of all, ORM ( object relational mapping - database mapping as you call it - ) and JNDI ( Java Naming and Directory Interfaces ) are two different things.
The first as you already know, is used to map the Database tables to classes and objects. The second is to provide a lookup mechanism for resources, they may be DataSources, Ejb, Queues or others.
Maybe your mean "JDBC".
Now as for your question: If it is that simple may be it wouldn't be necessary to implement an ORM. The number tables would be around 5 - 10 at most, and the operations really simple, I guess.
Probably using plain JDBC would be enough.
If you use the DAO pattern you may change it later to support the ORM strategy if needed.
Like this:
Say you have the Employee table
You create the Employee.java with all the fields of the DB by hand ( it should not take too long ) and a EmployeeDaO.java with methods like:
```
+findById( id ): Employee
+insert( Employee )
+update( Employee )
+delete( Employee )
+findAll():List<Employee>
```
And the implementation is quite straight forward:
```
select * from employee where id = ?
insert into employee ( bla, bla, bla ) values ( ? , ? , ? )
update etc. etc
```
When ( and If ) your application becomes too complex you may change the DAO implementation . For instance in the "select" method you change the code to use the ORM object that performs the operation.
```
public Employee selectById( int id ) {
// Commenting out the previous implementation...
// String query = select * from employee where id = ?
// execute( query )
// Using the ORM solution
Session session = getSession();
Employee e = ( Employee ) session.get( Employee.clas, id );
return e;
}
```
This is just an example, in real life you may let the abstact factory create the ORM DAO, but that is offtopic. The point is you may start simple and by using the desing patterns you may change the implementation later if needed.
Of course if you want to learn the technology you may start rigth away with even 1 table.
The choice of one or another ( ORM solution that is ) depend basically on the technology you're using. For instance for JBoss or other opensource products Hibernate is great. It is opensource, there's a lot of resources where to learn from. But if you're using something that already has Toplink ( like the oracle application server ) or if the base is already built on Toplink you should stay with that framework.
By the way, since Oracle bought BEA, they said they're replacing Kodo ( weblogic peresistence framework ) with toplink in the now called "Oracle Weblogic Application Server".
I leave you some resources where you can get more info about this:
---
In this "Patterns of Enterprise Application Architecture" book, Martin Fowler, explains where to use one or another, here is the catalog. Take a look at Data Source Architectural Patterns vs. Object-Relational Behavioral Patterns:
[PEAA Catalog](http://martinfowler.com/eaaCatalog/index.html)
---
DAO ( Data Access Object ) is part of the core J2EE patterns catalog:
[The DAO pattern](http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html)
---
This is a starter tutorial for Hibernate:
[Hibernate](http://hibernate.org/152.html)
---
The official page of Toplink:
[Toplink](http://www.oracle.com/technology/products/ias/toplink/index.html)
---
Finally I "think" the good think of JPA is that you may change providers lately.
Start simple and then evolve.
I hope this helps. |
122,582 | <p>I'm using a lat/long SRID in my PostGIS database (-4326). I would like to find the nearest points to a given point in an efficient manner. I tried doing an</p>
<pre><code>ORDER BY ST_Distance(point, ST_GeomFromText(?,-4326))
</code></pre>
<p>which gives me ok results in the lower 48 states, but up in Alaska it gives me garbage. Is there a way to do real distance calculations in PostGIS, or am I going to have to give a reasonable sized buffer and then calculate the great circle distances and sort the results in the code afterwards?</p>
| [
{
"answer_id": 123166,
"author": "nathaniel",
"author_id": 11947,
"author_profile": "https://Stackoverflow.com/users/11947",
"pm_score": 2,
"selected": false,
"text": "<p>This is from SQL Server, and I use Haversine for a ridiculously fast distance that may suffer from your Alaska issue ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3333/"
] | I'm using a lat/long SRID in my PostGIS database (-4326). I would like to find the nearest points to a given point in an efficient manner. I tried doing an
```
ORDER BY ST_Distance(point, ST_GeomFromText(?,-4326))
```
which gives me ok results in the lower 48 states, but up in Alaska it gives me garbage. Is there a way to do real distance calculations in PostGIS, or am I going to have to give a reasonable sized buffer and then calculate the great circle distances and sort the results in the code afterwards? | You are looking for ST\_distance\_sphere(point,point) or st\_distance\_spheroid(point,point).
See:
<http://postgis.refractions.net/documentation/manual-1.3/ch06.html#distance_sphere>
<http://postgis.refractions.net/documentation/manual-1.3/ch06.html#distance_spheroid>
This is normally referred to a geodesic or geodetic distance... while the two terms have slightly different meanings, they tend to be used interchangably.
Alternatively, you can project the data and use the standard st\_distance function... this is only practical over short distances (using UTM or state plane) or if all distances are relative to a one or two points (equidistant projections). |
122,589 | <p>I have a ASP.NET application running on a remote web server and I just started getting this error. I can't seem to reproduce it in my development environment:</p>
<pre><code>Method not found: 'Void System.Collections.Generic.ICollection`1..ctor()'.
</code></pre>
<p>Could this be due to some misconfiguration of .NET Framework or IIS 6?</p>
<p>Update:
I disassembled the code in the DLL and it seems like the compiler is incorrectly optimizing the code. (Note that Set is a class that implements a set of unique objects. It inherits from IEnumerable.) This line:</p>
<pre><code>Set<int> set = new Set<int>();
</code></pre>
<p>Is compiled into this line:</p>
<pre><code>Set<int> set = (Set<int>) new ICollection<CalendarModule>();
</code></pre>
<p>The Calendar class is a totally unrelated class!! Has anyone ever noticed .NET incorrectly compiling code like this before?</p>
| [
{
"answer_id": 122604,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 0,
"selected": false,
"text": "<p>Is your IIS setup to use .NET 2.0? If not, change it to 2.0. If you can't see 2.0 in the list then you'll need to... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10475/"
] | I have a ASP.NET application running on a remote web server and I just started getting this error. I can't seem to reproduce it in my development environment:
```
Method not found: 'Void System.Collections.Generic.ICollection`1..ctor()'.
```
Could this be due to some misconfiguration of .NET Framework or IIS 6?
Update:
I disassembled the code in the DLL and it seems like the compiler is incorrectly optimizing the code. (Note that Set is a class that implements a set of unique objects. It inherits from IEnumerable.) This line:
```
Set<int> set = new Set<int>();
```
Is compiled into this line:
```
Set<int> set = (Set<int>) new ICollection<CalendarModule>();
```
The Calendar class is a totally unrelated class!! Has anyone ever noticed .NET incorrectly compiling code like this before? | This was caused by a bug in the aspnet merge tool which incorrectly merged optimized assemblies. It can be solved by either not merging the assemblies or not optimizing them. |
122,607 | <p>I need to consume an external web service from my VB6 program. I want to be able to deploy my program without the SOAP toolkit, if possible, but that's not a requirement. I do not have the web service source and I didn't create it. It is a vendor-provided service.</p>
<p>So outside of the SOAP toolkit, what is the best way to consume a web service from VB6?</p>
| [
{
"answer_id": 122625,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 0,
"selected": false,
"text": "<p>The SOAP toolkit is arguably the best you could get. Trying to do the same thing without it would require conside... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7565/"
] | I need to consume an external web service from my VB6 program. I want to be able to deploy my program without the SOAP toolkit, if possible, but that's not a requirement. I do not have the web service source and I didn't create it. It is a vendor-provided service.
So outside of the SOAP toolkit, what is the best way to consume a web service from VB6? | I use this function to get data from a web service.
```
Private Function HttpGetRequest(url As String) As DOMDocument
Dim req As XMLHTTP60
Set req = New XMLHTTP60
req.Open "GET", url, False
req.send ""
Dim resp As DOMDocument
If req.responseText <> vbNullString Then
Set resp = New DOMDocument60
resp.loadXML req.responseText
Else
Set resp = req.responseXML
End If
Set HttpGetRequest = resp
End Function
``` |
122,616 | <p>Is there a clean, preferably standard method of trimming leading and trailing whitespace from a string in C? I'd roll my own, but I would think this is a common problem with an equally common solution.</p>
| [
{
"answer_id": 122721,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 9,
"selected": true,
"text": "<p>If you can modify the string:</p>\n\n<pre><code>// Note: This function returns a pointer to a substring of the ori... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14463/"
] | Is there a clean, preferably standard method of trimming leading and trailing whitespace from a string in C? I'd roll my own, but I would think this is a common problem with an equally common solution. | If you can modify the string:
```
// Note: This function returns a pointer to a substring of the original string.
// If the given string was allocated dynamically, the caller must not overwrite
// that pointer with the returned value, since the original pointer must be
// deallocated using the same allocator with which it was allocated. The return
// value must NOT be deallocated using free() etc.
char *trimwhitespace(char *str)
{
char *end;
// Trim leading space
while(isspace((unsigned char)*str)) str++;
if(*str == 0) // All spaces?
return str;
// Trim trailing space
end = str + strlen(str) - 1;
while(end > str && isspace((unsigned char)*end)) end--;
// Write new null terminator character
end[1] = '\0';
return str;
}
```
If you can't modify the string, then you can use basically the same method:
```
// Stores the trimmed input string into the given output buffer, which must be
// large enough to store the result. If it is too small, the output is
// truncated.
size_t trimwhitespace(char *out, size_t len, const char *str)
{
if(len == 0)
return 0;
const char *end;
size_t out_size;
// Trim leading space
while(isspace((unsigned char)*str)) str++;
if(*str == 0) // All spaces?
{
*out = 0;
return 1;
}
// Trim trailing space
end = str + strlen(str) - 1;
while(end > str && isspace((unsigned char)*end)) end--;
end++;
// Set output size to minimum of trimmed string length and buffer size minus 1
out_size = (end - str) < len-1 ? (end - str) : len-1;
// Copy trimmed string and add null terminator
memcpy(out, str, out_size);
out[out_size] = 0;
return out_size;
}
``` |
122,639 | <p>I have a temp table with the exact structure of a concrete table <code>T</code>. It was created like this: </p>
<pre><code>select top 0 * into #tmp from T
</code></pre>
<p>After processing and filling in content into <code>#tmp</code>, I want to copy the content back to <code>T</code> like this: </p>
<pre><code>insert into T select * from #tmp
</code></pre>
<p>This is okay as long as <code>T</code> doesn't have identity column, but in my case it does. Is there any way I can ignore the auto-increment identity column from <code>#tmp</code> when I copy to <code>T</code>? My motivation is to avoid having to spell out every column name in the Insert Into list. </p>
<p>EDIT: toggling identity_insert wouldn't work because the pkeys in <code>#tmp</code> may collide with those in <code>T</code> if rows were inserted into <code>T</code> outside of my script, that's if <code>#tmp</code> has auto-incremented the pkey to sync with T's in the first place. </p>
| [
{
"answer_id": 122655,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 4,
"selected": false,
"text": "<p>SET IDENTITY_INSERT ON</p>\n\n<p>INSERT command</p>\n\n<p>SET IDENTITY_INSERT OFF</p>\n"
},
{
"answer_id": 1... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10088/"
] | I have a temp table with the exact structure of a concrete table `T`. It was created like this:
```
select top 0 * into #tmp from T
```
After processing and filling in content into `#tmp`, I want to copy the content back to `T` like this:
```
insert into T select * from #tmp
```
This is okay as long as `T` doesn't have identity column, but in my case it does. Is there any way I can ignore the auto-increment identity column from `#tmp` when I copy to `T`? My motivation is to avoid having to spell out every column name in the Insert Into list.
EDIT: toggling identity\_insert wouldn't work because the pkeys in `#tmp` may collide with those in `T` if rows were inserted into `T` outside of my script, that's if `#tmp` has auto-incremented the pkey to sync with T's in the first place. | As identity will be generated during insert anyway, could you simply remove this column from #tmp before inserting the data back to T?
```
alter table #tmp drop column id
```
**UPD:** Here's an example I've tested in SQL Server 2008:
```
create table T(ID int identity(1,1) not null, Value nvarchar(50))
insert into T (Value) values (N'Hello T!')
select top 0 * into #tmp from T
alter table #tmp drop column ID
insert into #tmp (Value) values (N'Hello #tmp')
insert into T select * from #tmp
drop table #tmp
select * from T
drop table T
``` |
122,688 | <p>We use BigIP to load balance between our two IIS servers. We recently deployed a WCF service hosted on by IIS 6 onto these two Windows Server 2003R2 servers.</p>
<p>Each server is configured with two host headers: one for the load balancer address, and then a second host header that points only to that server. That way we can reference a specific server in the load balanced group for debugging.</p>
<p>So when we run We immediately got the error:</p>
<blockquote>
<p><strong>This collection already contains an address with scheme http. There can be at most one address per scheme in this collection.
Parameter name: item</strong></p>
</blockquote>
<p>I did some research and we can implement a filter to tell it to ignore the one of the hosts, but then we cannot access the server from that address. </p>
<pre><code><serviceHostingEnvironment>
<baseAddressPrefixFilters>
<add prefix="http://domain.com:80"/>
</baseAddressPrefixFilters>
</serviceHostingEnvironment>
</code></pre>
<p>What is the best solution in this scenario which would allow us to hit a WCF service via <a href="http://domain.com/service.svc" rel="nofollow noreferrer">http://domain.com/service.svc</a> and <a href="http://server1.domain.com/service.svc" rel="nofollow noreferrer">http://server1.domain.com/service.svc</a>?</p>
<p>If we should create our own ServiceFactory as some sites suggest, does anyone have any sample code on this?</p>
<p>Any help is much appreciated.</p>
<p>EDIT: We will need to be able to access the WCF service from either of the two addresses, if at all possible.</p>
<p>Thank you.</p>
| [
{
"answer_id": 122754,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>The URL it uses is based on the bindings in IIS. Does the website have more than one binding? If it does, or is the WCF s... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13368/"
] | We use BigIP to load balance between our two IIS servers. We recently deployed a WCF service hosted on by IIS 6 onto these two Windows Server 2003R2 servers.
Each server is configured with two host headers: one for the load balancer address, and then a second host header that points only to that server. That way we can reference a specific server in the load balanced group for debugging.
So when we run We immediately got the error:
>
> **This collection already contains an address with scheme http. There can be at most one address per scheme in this collection.
> Parameter name: item**
>
>
>
I did some research and we can implement a filter to tell it to ignore the one of the hosts, but then we cannot access the server from that address.
```
<serviceHostingEnvironment>
<baseAddressPrefixFilters>
<add prefix="http://domain.com:80"/>
</baseAddressPrefixFilters>
</serviceHostingEnvironment>
```
What is the best solution in this scenario which would allow us to hit a WCF service via <http://domain.com/service.svc> and <http://server1.domain.com/service.svc>?
If we should create our own ServiceFactory as some sites suggest, does anyone have any sample code on this?
Any help is much appreciated.
EDIT: We will need to be able to access the WCF service from either of the two addresses, if at all possible.
Thank you. | On your bigIP Create 2 new virtual servers
<http://server1.domain.com/>
<http://server2.domain.com/>
create a pool for each VS with only the specific server in it - so there will be no actual load balancing and access it that way. If you are short on external IP'S you can still use the same IP as your production domain name and just use an irule to direct traffic to the appropriate pool
Hope this helps |
122,690 | <p>I've been too lax with performing DB backups on our internal servers. </p>
<p>Is there a simple command line program that I can use to backup certain databases in SQL Server 2005? Or is there a simple VBScript? </p>
| [
{
"answer_id": 122705,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 3,
"selected": false,
"text": "<p>Schedule the following to backup all Databases:</p>\n\n<pre><code>Use Master\n\nDeclare @ToExecute VarChar(8000)\n\nSele... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
] | I've been too lax with performing DB backups on our internal servers.
Is there a simple command line program that I can use to backup certain databases in SQL Server 2005? Or is there a simple VBScript? | To backup a single database from the command line, use [osql](https://msdn.microsoft.com/en-us/library/ms162806.aspx) or [sqlcmd](https://msdn.microsoft.com/en-us/library/ms162773.aspx).
```
"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\osql.exe"
-E -Q "BACKUP DATABASE mydatabase TO DISK='C:\tmp\db.bak' WITH FORMAT"
```
You'll also want to read the documentation on [BACKUP](https://msdn.microsoft.com/en-us/library/ms186865.aspx) and [RESTORE](https://msdn.microsoft.com/en-us/library/ms190372.aspx) and [general procedures](https://msdn.microsoft.com/en-us/library/ms187048.aspx). |
122,695 | <p>For example, I have an ASP.NET form that is called by another aspx:</p>
<pre><code>string url = "http://somewhere.com?P1=" + Request["param"];
Response.Write(url);
</code></pre>
<p>I want to do something like this:</p>
<pre><code>string url = "http://somewhere.com?P1=" + Request["param"];
string str = GetResponse(url);
if (str...) {}
</code></pre>
<p>I need to get whatever Response.Write is getting as a result or going to url, manipulate that response, and send something else back.</p>
<p>Any help or a point in the right direction would be greatly appreciated.</p>
| [
{
"answer_id": 122707,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 3,
"selected": false,
"text": "<pre><code>WebClient client = new WebClient();\nstring response = client.DownloadString(url);\n</code></pre>\n"
},
... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20682/"
] | For example, I have an ASP.NET form that is called by another aspx:
```
string url = "http://somewhere.com?P1=" + Request["param"];
Response.Write(url);
```
I want to do something like this:
```
string url = "http://somewhere.com?P1=" + Request["param"];
string str = GetResponse(url);
if (str...) {}
```
I need to get whatever Response.Write is getting as a result or going to url, manipulate that response, and send something else back.
Any help or a point in the right direction would be greatly appreciated. | Webclient.DownloadString() is probably want you want. |
122,714 | <p>When I try the following lookup in my code:</p>
<pre><code>Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
return (DataSource) envCtx.lookup("jdbc/mydb");
</code></pre>
<p>I get the following exception:</p>
<pre><code>java.sql.SQLException: QueryResults: Unable to initialize naming context:
Name java:comp is not bound in this Context at
com.onsitemanager.database.ThreadLocalConnection.getConnection
(ThreadLocalConnection.java:130) at
...
</code></pre>
<p>I installed embedded JBoss following the JBoss <a href="http://wiki.jboss.org/wiki/Tomcat5.5.x?action=e&windowstate=normal&mode=view" rel="nofollow noreferrer">wiki instructions</a>. And I configured Tomcat using the "Scanning every WAR by default" deployment as specified in the <a href="http://wiki.jboss.org/wiki/EmbeddedAndTomcat" rel="nofollow noreferrer">configuration wiki page</a>.</p>
<p>Quoting the config page:</p>
<blockquote>
<p>JNDI</p>
<p>Embedded JBoss components like connection pooling, EJB, JPA, and transactions make
extensive use of JNDI to publish services. Embedded JBoss overrides Tomcat's JNDI
implementation by layering itself on top of Tomcat's JNDI instantiation. There are a few > reasons for this:</p>
<ol>
<li>To avoid having to declare each and every one of these services within server.xml</li>
<li>To allow seemeless integration of the java:comp namespace between web apps and
EJBs.</li>
<li>Tomcat's JNDI implementation has a few critical bugs in it that hamper some JBoss
components ability to work</li>
<li>We want to provide the option for you of remoting EJBs and other services that can > be remotely looked up</li>
</ol>
</blockquote>
<p>Anyone have any thoughts on how I can configure the JBoss naming service which according to the above quote is overriding Tomcat's JNDI implementation so that I can do a lookup on java:comp/env? </p>
<p>FYI - My environment Tomcat 5.5.9, Seam 2.0.2sp, Embedded JBoss (Beta 3), </p>
<p>Note: I do have a -ds.xml file for my database connection properly setup and accessible on the class path per the instructions.</p>
<p>Also note: I have posted this question in embedded Jboss forum and seam user forum. </p>
| [
{
"answer_id": 122820,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 1,
"selected": false,
"text": "<p>java:comp/env is known as the Enterprise Naming Context (ENC) and is not globally visible. See <a href=\"http://www.infor... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5917/"
] | When I try the following lookup in my code:
```
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
return (DataSource) envCtx.lookup("jdbc/mydb");
```
I get the following exception:
```
java.sql.SQLException: QueryResults: Unable to initialize naming context:
Name java:comp is not bound in this Context at
com.onsitemanager.database.ThreadLocalConnection.getConnection
(ThreadLocalConnection.java:130) at
...
```
I installed embedded JBoss following the JBoss [wiki instructions](http://wiki.jboss.org/wiki/Tomcat5.5.x?action=e&windowstate=normal&mode=view). And I configured Tomcat using the "Scanning every WAR by default" deployment as specified in the [configuration wiki page](http://wiki.jboss.org/wiki/EmbeddedAndTomcat).
Quoting the config page:
>
> JNDI
>
>
> Embedded JBoss components like connection pooling, EJB, JPA, and transactions make
> extensive use of JNDI to publish services. Embedded JBoss overrides Tomcat's JNDI
> implementation by layering itself on top of Tomcat's JNDI instantiation. There are a few > reasons for this:
>
>
> 1. To avoid having to declare each and every one of these services within server.xml
> 2. To allow seemeless integration of the java:comp namespace between web apps and
> EJBs.
> 3. Tomcat's JNDI implementation has a few critical bugs in it that hamper some JBoss
> components ability to work
> 4. We want to provide the option for you of remoting EJBs and other services that can > be remotely looked up
>
>
>
Anyone have any thoughts on how I can configure the JBoss naming service which according to the above quote is overriding Tomcat's JNDI implementation so that I can do a lookup on java:comp/env?
FYI - My environment Tomcat 5.5.9, Seam 2.0.2sp, Embedded JBoss (Beta 3),
Note: I do have a -ds.xml file for my database connection properly setup and accessible on the class path per the instructions.
Also note: I have posted this question in embedded Jboss forum and seam user forum. | Thanks for the response toolkit.... yes, I can access my datasource by going directly to java:jdbc/mydb, but I'm using an existing code base that connects via the ENC. Here's some interesting info that I've found out ....
1. The above code works with **JBoss 4.2.2.GA** and here's the JNDI ctx parameters being used:
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces:
org.jboss.naming:org.jnp.interfaces
2. The above code works with **Tomcat 5.5.x** and here's the JNDI ctx parameters being used:
java.naming.factory.initial=org.apache.naming.java.javaURLContextFactory
java.naming.factory.url.pkgs=org.apache.naming
3. The above code fails with **Embedded JBoss (Beta 3)** in Tomcat 5.5.x with the above error message.
java.naming.factory.initial=org.apache.naming.java.javaURLContextFactory
java.naming.factory.url.pkgs=org.apache.namingThe above code fails with the above error using JBoss Embedded in tomcat 5.5.x
Anyone have any thoughts I what I need to do with configuring embedded JBoss JNDI configuration? |
122,728 | <p>I have a dilemma, I'm using Java and Oracle and trying to keep queries on PL/SQL side. Everything is OK, until I have these complex queries which may and may not have conditions. <br></p>
<p>It's not hard in Java to put together <code>WHERE</code> clause with conditions, but it's not nice.
And on PL/SQL side I also found out that the only possibility for <code>dynamic queries</code> is string manipulations like</p>
<pre><code>IF inputname IS NOT NULL THEN
query := query ||' and NAME=' || inputname;
END IF;
</code></pre>
<p>Now I'm thinking, I'm leaving query in PL/SQL and sending <code>WHERE</code> clause with function parameter.
Any good recommendations or examples please?</p>
| [
{
"answer_id": 122759,
"author": "Kyle Burton",
"author_id": 19784,
"author_profile": "https://Stackoverflow.com/users/19784",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://openhms.sourceforge.net/sqlbuilder/\" rel=\"nofollow noreferrer\">SQLBuilder</a> might be useful t... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13114/"
] | I have a dilemma, I'm using Java and Oracle and trying to keep queries on PL/SQL side. Everything is OK, until I have these complex queries which may and may not have conditions.
It's not hard in Java to put together `WHERE` clause with conditions, but it's not nice.
And on PL/SQL side I also found out that the only possibility for `dynamic queries` is string manipulations like
```
IF inputname IS NOT NULL THEN
query := query ||' and NAME=' || inputname;
END IF;
```
Now I'm thinking, I'm leaving query in PL/SQL and sending `WHERE` clause with function parameter.
Any good recommendations or examples please? | [SQLBuilder](http://openhms.sourceforge.net/sqlbuilder/) might be useful to you from the Java side. It allows you to write compile-time checked Java code that dynamically builds sql:
```
String selectQuery =
(new SelectQuery())
.addColumns(t1Col1, t1Col2, t2Col1)
.addJoin(SelectQuery.JoinType.INNER_JOIN, joinOfT1AndT2)
.addOrderings(t1Col1)
.validate().toString();
``` |
122,736 | <p>I have a stored procedure that consists of a single select query used to insert into another table based on some minor math that is done to the arguments in the procedure. Can I generate the plan used for this query by referencing the procedure somehow, or do I have to copy and paste the query and create bind variables for the input parameters?</p>
| [
{
"answer_id": 122790,
"author": "Jasmine",
"author_id": 5255,
"author_profile": "https://Stackoverflow.com/users/5255",
"pm_score": 1,
"selected": false,
"text": "<p>From what I understand, this was done on purpose. The idea is that individual queries within the procedure are considered... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9940/"
] | I have a stored procedure that consists of a single select query used to insert into another table based on some minor math that is done to the arguments in the procedure. Can I generate the plan used for this query by referencing the procedure somehow, or do I have to copy and paste the query and create bind variables for the input parameters? | Use [SQL Trace and TKPROF](http://68.142.116.68/docs/cd/B19306_01/server.102/b14211/sqltrace.htm#i4640). For example, open SQL\*Plus, and then issue the following code:-
```
alter session set tracefile_identifier = 'something-unique'
alter session set sql_trace = true;
alter session set events '10046 trace name context forever, level 8';
select 'right-before-my-sp' from dual;
exec your_stored_procedure
alter session set sql_trace = false;
```
Once this has been done, go look in your database's UDUMP directory for a TRC file with "something-unique" in the filename. Format this TRC file with TKPROF, and then open the formatted file and search for the string "right-before-my-sp". The SQL command issued by your stored procedure should be shortly after this section, and immediately under that SQL statement will be the plan for the SQL statement.
**Edit:** For the purposes of full disclosure, I should thank all those who gave me answers on [this thread](https://stackoverflow.com/questions/104066/how-do-i-troubleshoot-performance-problems-with-an-oracle-sql-statement) last week that helped me learn how to do this. |
122,741 | <p>OK, I have been working on a random image selector and queue system (so you don't see the same images too often).</p>
<p>All was going swimmingly (as far as my crappy code does) <strong>until</strong> I got to the random bit. I wanted to test it, but how do you test for it? There is no <code>Debug.Assert(i.IsRandom)</code> (sadly) :D</p>
<p>So, I got my brain on it after watering it with some tea and came up with the following, I was just wondering if I could have your thoughts?</p>
<ul>
<li>Basically I knew the <strong>random</strong> bit was the problem, so I ripped that out to a delegate (which would then be passed to the objects constructor).</li>
<li>I then created a class that pretty much performs the same logic as the <em>live</em> code, but remembers the value selected in a private variable.</li>
<li>I then threw that delegate to the live class and tested against that:</li>
</ul>
<p>i.e.</p>
<pre><code>Debug.Assert(myObj.RndVal == RndIntTester.ValuePassed);
</code></pre>
<p>But I couldn't help but think, <strong>was I wasting my time?</strong> I ran that through lots of iterations to see if it fell over at any time etc.</p>
<p>Do you think I was wasting my time with this? Or could I have got away with:</p>
<p><img src="https://imgs.xkcd.com/comics/random_number.png" alt="Awesome Random Number Generator" /></p>
<p><a href="https://stackoverflow.com/questions/122741/testing-for-random-value-thoughts-on-this-approach#122765">GateKiller's answer</a> reminded me of this:</p>
<p><img src="https://www.random.org/analysis/dilbert.jpg" alt="Dilbert Random" /></p>
<h2>Update to Clarify</h2>
<ul>
<li><strong>I should add that I basically never want to see the same result more than X number of times from a pool of Y size.</strong></li>
<li>The addition of the test container basically allowed me to see if any of the previously selected images were "randomly" selected.</li>
<li>I guess technically the thing here being tested in not the RNG (since I never wrote that code) but the fact that am I expecting <em>random</em> results from a limited pool, and I want to track them.</li>
</ul>
| [
{
"answer_id": 122765,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "<p>Random is Random. Even if the same picture shows up 4 times in a row, it could still be considered random.</p>\n"
},
... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] | OK, I have been working on a random image selector and queue system (so you don't see the same images too often).
All was going swimmingly (as far as my crappy code does) **until** I got to the random bit. I wanted to test it, but how do you test for it? There is no `Debug.Assert(i.IsRandom)` (sadly) :D
So, I got my brain on it after watering it with some tea and came up with the following, I was just wondering if I could have your thoughts?
* Basically I knew the **random** bit was the problem, so I ripped that out to a delegate (which would then be passed to the objects constructor).
* I then created a class that pretty much performs the same logic as the *live* code, but remembers the value selected in a private variable.
* I then threw that delegate to the live class and tested against that:
i.e.
```
Debug.Assert(myObj.RndVal == RndIntTester.ValuePassed);
```
But I couldn't help but think, **was I wasting my time?** I ran that through lots of iterations to see if it fell over at any time etc.
Do you think I was wasting my time with this? Or could I have got away with:

[GateKiller's answer](https://stackoverflow.com/questions/122741/testing-for-random-value-thoughts-on-this-approach#122765) reminded me of this:

Update to Clarify
-----------------
* **I should add that I basically never want to see the same result more than X number of times from a pool of Y size.**
* The addition of the test container basically allowed me to see if any of the previously selected images were "randomly" selected.
* I guess technically the thing here being tested in not the RNG (since I never wrote that code) but the fact that am I expecting *random* results from a limited pool, and I want to track them. | Test from the requirement : "so you don't see the same images too often"
Ask for 100 images. Did you see an image too often? |
122,752 | <p>I've seen <a href="https://stackoverflow.com/questions/55622/best-tools-for-working-with-docbook-xml-documents">Best tools for working with DocBook XML documents</a>, but my question is slightly different. Which is the currently recommended formatting toolchain - as opposed to editing tool - for XML DocBook?</p>
<p>In Eric Raymond's <a href="https://rads.stackoverflow.com/amzn/click/com/0131429019" rel="nofollow noreferrer" rel="nofollow noreferrer">'The Art of Unix Programming'</a> from 2003 (an excellent book!), the suggestion is XML-FO (XML Formatting Objects), but I've since seen suggestions here that indicated that XML-FO is no longer under development (though I can no longer find that question on StackOverflow, so maybe it was erroneous).</p>
<p>Assume I'm primarily interested in Unix/Linux (including MacOS X), but I wouldn't automatically ignore Windows-only solutions.</p>
<p>Is <a href="http://xmlgraphics.apache.org/fop/" rel="nofollow noreferrer">Apache's FOP</a> the best way to go? Are there any alternatives?</p>
| [
{
"answer_id": 122791,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 2,
"selected": false,
"text": "<p>A popular approach is to use <a href=\"http://docbook.sourceforge.net/\" rel=\"nofollow noreferrer\">DocBook XSL Stylesheets<... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15168/"
] | I've seen [Best tools for working with DocBook XML documents](https://stackoverflow.com/questions/55622/best-tools-for-working-with-docbook-xml-documents), but my question is slightly different. Which is the currently recommended formatting toolchain - as opposed to editing tool - for XML DocBook?
In Eric Raymond's ['The Art of Unix Programming'](https://rads.stackoverflow.com/amzn/click/com/0131429019) from 2003 (an excellent book!), the suggestion is XML-FO (XML Formatting Objects), but I've since seen suggestions here that indicated that XML-FO is no longer under development (though I can no longer find that question on StackOverflow, so maybe it was erroneous).
Assume I'm primarily interested in Unix/Linux (including MacOS X), but I wouldn't automatically ignore Windows-only solutions.
Is [Apache's FOP](http://xmlgraphics.apache.org/fop/) the best way to go? Are there any alternatives? | I've been doing some manual writing with DocBook, under cygwin, to produce One Page HTML, Many Pages HTML, CHM and PDF.
I installed the following:
1. The [docbook](http://www.docbook.org) stylesheets (xsl) repository.
2. xmllint, to test if the xml is correct.
3. xsltproc, to process the xml with the stylesheets.
4. [Apache's fop](http://xmlgraphics.apache.org/fop/download.html), to produce PDF's.I make sure to add the installed folder to the PATH.
5. Microsoft's [HTML Help Workshop](http://www.microsoft.com/downloads/details.aspx?FamilyID=00535334-c8a6-452f-9aa0-d597d16580cc&displaylang=en), to produce CHM's. I make sure to add the installed folder to the PATH.
**Edit**: In the below code I'm using more than the 2 files. If someone wants a cleaned up version of the scripts and the folder structure, please contact me: guscarreno (squiggly/at) googlemail (period/dot) com
I then use a configure.in:
```
AC_INIT(Makefile.in)
FOP=fop.sh
HHC=hhc
XSLTPROC=xsltproc
AC_ARG_WITH(fop, [ --with-fop Where to find Apache FOP],
[
if test "x$withval" != "xno"; then
FOP="$withval"
fi
]
)
AC_PATH_PROG(FOP, $FOP)
AC_ARG_WITH(hhc, [ --with-hhc Where to find Microsoft Help Compiler],
[
if test "x$withval" != "xno"; then
HHC="$withval"
fi
]
)
AC_PATH_PROG(HHC, $HHC)
AC_ARG_WITH(xsltproc, [ --with-xsltproc Where to find xsltproc],
[
if test "x$withval" != "xno"; then
XSLTPROC="$withval"
fi
]
)
AC_PATH_PROG(XSLTPROC, $XSLTPROC)
AC_SUBST(FOP)
AC_SUBST(HHC)
AC_SUBST(XSLTPROC)
HERE=`pwd`
AC_SUBST(HERE)
AC_OUTPUT(Makefile)
cat > config.nice <<EOT
#!/bin/sh
./configure \
--with-fop='$FOP' \
--with-hhc='$HHC' \
--with-xsltproc='$XSLTPROC' \
EOT
chmod +x config.nice
```
and a Makefile.in:
```
FOP=@FOP@
HHC=@HHC@
XSLTPROC=@XSLTPROC@
HERE=@HERE@
# Subdirs that contain docs
DOCS=appendixes chapters reference
XML_CATALOG_FILES=./build/docbook-xsl-1.71.0/catalog.xml
export XML_CATALOG_FILES
all: entities.ent manual.xml html
clean:
@echo -e "\n=== Cleaning\n"
@-rm -f html/*.html html/HTML.manifest pdf/* chm/*.html chm/*.hhp chm/*.hhc chm/*.chm entities.ent .ent
@echo -e "Done.\n"
dist-clean:
@echo -e "\n=== Restoring defaults\n"
@-rm -rf .ent autom4te.cache config.* configure Makefile html/*.html html/HTML.manifest pdf/* chm/*.html chm/*.hhp chm/*.hhc chm/*.chm build/docbook-xsl-1.71.0
@echo -e "Done.\n"
entities.ent: ./build/mkentities.sh $(DOCS)
@echo -e "\n=== Creating entities\n"
@./build/mkentities.sh $(DOCS) > .ent
@if [ ! -f entities.ent ] || [ ! cmp entities.ent .ent ]; then mv .ent entities.ent ; fi
@echo -e "Done.\n"
# Build the docs in chm format
chm: chm/htmlhelp.hpp
@echo -e "\n=== Creating CHM\n"
@echo logo.png >> chm/htmlhelp.hhp
@echo arrow.gif >> chm/htmlhelp.hhp
@-cd chm && "$(HHC)" htmlhelp.hhp
@echo -e "Done.\n"
chm/htmlhelp.hpp: entities.ent build/docbook-xsl manual.xml build/chm.xsl
@echo -e "\n=== Creating input for CHM\n"
@"$(XSLTPROC)" --output ./chm/index.html ./build/chm.xsl manual.xml
# Build the docs in HTML format
html: html/index.html
html/index.html: entities.ent build/docbook-xsl manual.xml build/html.xsl
@echo -e "\n=== Creating HTML\n"
@"$(XSLTPROC)" --output ./html/index.html ./build/html.xsl manual.xml
@echo -e "Done.\n"
# Build the docs in PDF format
pdf: pdf/manual.fo
@echo -e "\n=== Creating PDF\n"
@"$(FOP)" ./pdf/manual.fo ./pdf/manual.pdf
@echo -e "Done.\n"
pdf/manual.fo: entities.ent build/docbook-xsl manual.xml build/pdf.xsl
@echo -e "\n=== Creating input for PDF\n"
@"$(XSLTPROC)" --output ./pdf/manual.fo ./build/pdf.xsl manual.xml
check: manual.xml
@echo -e "\n=== Checking correctness of manual\n"
@xmllint --valid --noout --postvalid manual.xml
@echo -e "Done.\n"
# need to touch the dir because the timestamp in the tarball
# is older than that of the tarball :)
build/docbook-xsl: build/docbook-xsl-1.71.0.tar.gz
@echo -e "\n=== Un-taring docbook-xsl\n"
@cd build && tar xzf docbook-xsl-1.71.0.tar.gz && touch docbook-xsl-1.71.0
```
to automate the production of the above mentioned file outputs.
I prefer to use a nix approach to the scripting just because the toolset is more easy to find and use, not to mention easier to chain. |
122,763 | <p>I have a dict, that looks like this:</p>
<pre><code>{
'foo': {
'opt1': 1,
'opt2': 2,
},
'foo/bar': {
'opt3': 3,
'opt4': 4,
},
'foo/bar/baz': {
'opt5': 5,
'opt6': 6,
}
}
</code></pre>
<p>And I need to get it to look like:</p>
<pre><code>{
'foo': {
'opt1': 1,
'opt2': 2,
'bar': {
'opt3': 3,
'opt4': 4,
'baz': {
'opt5': 5,
'opt6': 6,
}
}
}
}
</code></pre>
<p>I should point out that there can and will be multiple top-level keys ('foo' in this case). I could probably throw something together to get what i need, but I was hoping that there is a solution that's more efficient.</p>
| [
{
"answer_id": 122785,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 4,
"selected": true,
"text": "<p>Like this:</p>\n\n<pre><code>def nest(d):\n rv = {}\n for key, value in d.iteritems():\n node = rv\n... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18866/"
] | I have a dict, that looks like this:
```
{
'foo': {
'opt1': 1,
'opt2': 2,
},
'foo/bar': {
'opt3': 3,
'opt4': 4,
},
'foo/bar/baz': {
'opt5': 5,
'opt6': 6,
}
}
```
And I need to get it to look like:
```
{
'foo': {
'opt1': 1,
'opt2': 2,
'bar': {
'opt3': 3,
'opt4': 4,
'baz': {
'opt5': 5,
'opt6': 6,
}
}
}
}
```
I should point out that there can and will be multiple top-level keys ('foo' in this case). I could probably throw something together to get what i need, but I was hoping that there is a solution that's more efficient. | Like this:
```
def nest(d):
rv = {}
for key, value in d.iteritems():
node = rv
for part in key.split('/'):
node = node.setdefault(part, {})
node.update(value)
return rv
``` |
122,772 | <p>When I try to display the contents of a LOB (large object) column in SQL*Plus, it is truncated. How do I display the whole thing?</p>
| [
{
"answer_id": 122776,
"author": "Anonymoose",
"author_id": 2391,
"author_profile": "https://Stackoverflow.com/users/2391",
"pm_score": 7,
"selected": true,
"text": "<pre><code>SQL> set long 30000\nSQL> show long\nlong 30000\n</code></pre>\n"
},
{
"answer_id": 7272671,
... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2391/"
] | When I try to display the contents of a LOB (large object) column in SQL\*Plus, it is truncated. How do I display the whole thing? | ```
SQL> set long 30000
SQL> show long
long 30000
``` |
122,778 | <p>Under VS's external tools settings there is a "Use Output Window" check box that captures the tools command line output and dumps it to a VS tab.</p>
<p>The question is: <em>can I get the same processing for my program when I hit F5?</em></p>
<p><strong>Edit:</strong> FWIW I'm in C# but if that makes a difference to your answer then it's unlikely that your answer is what I'm looking for.</p>
<p>What I want would take the output stream of the program and transfer it to the output tab in VS using the same devices that output redirection ('|' and '>') uses in the cmd prompt.</p>
| [
{
"answer_id": 122988,
"author": "ScaleOvenStove",
"author_id": 12268,
"author_profile": "https://Stackoverflow.com/users/12268",
"pm_score": 0,
"selected": false,
"text": "<p>System.Diagnostics.Debug.Writeline() or Trace.Writeline()</p>\n"
},
{
"answer_id": 122991,
"author"... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] | Under VS's external tools settings there is a "Use Output Window" check box that captures the tools command line output and dumps it to a VS tab.
The question is: *can I get the same processing for my program when I hit F5?*
**Edit:** FWIW I'm in C# but if that makes a difference to your answer then it's unlikely that your answer is what I'm looking for.
What I want would take the output stream of the program and transfer it to the output tab in VS using the same devices that output redirection ('|' and '>') uses in the cmd prompt. | I'm going to make a few assumptions here. First, I presume that you are talking about printf output from an application (whether it be from a console app or from a windows GUI app). My second assumption is the C language.
*To my knowledge, you cannot direct printf output to the output window in dev studio, not directly anyway.* [emphasis added by OP]
There might be a way but I'm not aware of it. One thing that you could do though would be to direct printf function calls to your own routine which will
1. call printf and print the string
2. call OuputDebugString() to print the string to the output window
You could do several things to accomplish this goal. First would be to write your own printf function and then call printf and the OuputDebugString()
```
void my_printf(const char *format, ...)
{
char buf[2048];
// get the arg list and format it into a string
va_start(arglist, format);
vsprintf_s(buf, 2048, format, arglist);
va_end(arglist);
vprintf_s(buf); // prints to the standard output stream
OutputDebugString(buf); // prints to the output window
}
```
The code above is mostly untested, but it should get the concepts across.
If you are not doing this in C/C++, then this method won't work for you. :-) |
122,781 | <p>I have a page in my desktop app, and I've implemented simple grab-and-pan. It works great.</p>
<p>When you are panning in this way and you are release, the page stops dead where you dropped it.</p>
<p>I'd like it to continue slightly with some momentum, and stop eventually. Rather like the 'throw' in the iPhone UI, I guess.</p>
<p>I'm not really chasing perfection, just a very crude simple sense of being able to 'throw' that page.</p>
| [
{
"answer_id": 122988,
"author": "ScaleOvenStove",
"author_id": 12268,
"author_profile": "https://Stackoverflow.com/users/12268",
"pm_score": 0,
"selected": false,
"text": "<p>System.Diagnostics.Debug.Writeline() or Trace.Writeline()</p>\n"
},
{
"answer_id": 122991,
"author"... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15721/"
] | I have a page in my desktop app, and I've implemented simple grab-and-pan. It works great.
When you are panning in this way and you are release, the page stops dead where you dropped it.
I'd like it to continue slightly with some momentum, and stop eventually. Rather like the 'throw' in the iPhone UI, I guess.
I'm not really chasing perfection, just a very crude simple sense of being able to 'throw' that page. | I'm going to make a few assumptions here. First, I presume that you are talking about printf output from an application (whether it be from a console app or from a windows GUI app). My second assumption is the C language.
*To my knowledge, you cannot direct printf output to the output window in dev studio, not directly anyway.* [emphasis added by OP]
There might be a way but I'm not aware of it. One thing that you could do though would be to direct printf function calls to your own routine which will
1. call printf and print the string
2. call OuputDebugString() to print the string to the output window
You could do several things to accomplish this goal. First would be to write your own printf function and then call printf and the OuputDebugString()
```
void my_printf(const char *format, ...)
{
char buf[2048];
// get the arg list and format it into a string
va_start(arglist, format);
vsprintf_s(buf, 2048, format, arglist);
va_end(arglist);
vprintf_s(buf); // prints to the standard output stream
OutputDebugString(buf); // prints to the output window
}
```
The code above is mostly untested, but it should get the concepts across.
If you are not doing this in C/C++, then this method won't work for you. :-) |
122,782 | <p>I'm looking to have two versions of BOOST compiled into a project at the same time. Ideally they should be usable along these lines:</p>
<pre><code>boost_1_36_0::boost::shared_ptr<SomeClass> someClass = new SomeClass();
boost_1_35_0::boost::regex expression("[0-9]", boost_1_35_0::boost::regex_constants::basic);
</code></pre>
| [
{
"answer_id": 122801,
"author": "Matt Price",
"author_id": 852,
"author_profile": "https://Stackoverflow.com/users/852",
"pm_score": 0,
"selected": false,
"text": "<p>You'll have a world of trouble linking because the mangled names will be different. And yes, I see you knew that, but it... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8701/"
] | I'm looking to have two versions of BOOST compiled into a project at the same time. Ideally they should be usable along these lines:
```
boost_1_36_0::boost::shared_ptr<SomeClass> someClass = new SomeClass();
boost_1_35_0::boost::regex expression("[0-9]", boost_1_35_0::boost::regex_constants::basic);
``` | I read (well scanned) through the [development list discussion](http://thread.gmane.org/gmane.comp.lib.boost.devel/180008). There's no easy solution. To sum up:
1. Wrapping header files in a namespace declaration
```
namespace boost_1_36_0 {
#include <boost_1_36_0/boost/regex.hpp>
}
namespace boost_1_35_0 {
#include <boost_1_35_0/boost/shared_ptr.hpp>
}
```
* Requires modifying source files
* Doesn't allow for both versions to be included in the same translation unit, due to the fact that macros do not respect namespaces.
2. Defining boost before including headers
```
#define boost boost_1_36_0
#include <boost_1_36_0/boost/regex.hpp>
#undef boost
#define boost boost_1_35_0
#include <boost_1_35_0/boost/shared_ptr.hpp>
#undef boost
```
* Source files can simply be compiled with `-Dboost=boost_1_36_0`
* Still doesn't address macro conflicts in a single translation unit.
* Some internal header file inclusions may be messed up, since this sort of thing does happen.
```
#if defined(SOME_CONDITION)
# define HEADER <boost/some/header.hpp>
#else
# define HEADER <boost/some/other/header.hpp>
#endif
```
But it may be easy enough to work around those cases.
3. Modifying the entire boost library to replace `namespace boost {..}` with `namespace boost_1_36_0 {...}` and then providing a namespace alias. Replace all `BOOST_XYZ` macros and their uses with `BOOST_1_36_0_XYZ` macros.
* This would likely work if you were willing to put into the effort. |
122,799 | <p>There is no summary available of the big O notation for operations on the most common data structures including arrays, linked lists, hash tables etc.</p>
| [
{
"answer_id": 122894,
"author": "Jose Vega",
"author_id": 17162,
"author_profile": "https://Stackoverflow.com/users/17162",
"pm_score": 4,
"selected": false,
"text": "<p>I guess I will start you off with the time complexity of a linked list:<br></p>\n\n<p>Indexing---->O(n)<br>\nInsertin... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340748/"
] | There is no summary available of the big O notation for operations on the most common data structures including arrays, linked lists, hash tables etc. | Information on this topic is now available on Wikipedia at: [Search data structure](http://en.wikipedia.org/wiki/Search_data_structure)
```
+----------------------+----------+------------+----------+--------------+
| | Insert | Delete | Search | Space Usage |
+----------------------+----------+------------+----------+--------------+
| Unsorted array | O(1) | O(1) | O(n) | O(n) |
| Value-indexed array | O(1) | O(1) | O(1) | O(n) |
| Sorted array | O(n) | O(n) | O(log n) | O(n) |
| Unsorted linked list | O(1)* | O(1)* | O(n) | O(n) |
| Sorted linked list | O(n)* | O(1)* | O(n) | O(n) |
| Balanced binary tree | O(log n) | O(log n) | O(log n) | O(n) |
| Heap | O(log n) | O(log n)** | O(n) | O(n) |
| Hash table | O(1) | O(1) | O(1) | O(n) |
+----------------------+----------+------------+----------+--------------+
* The cost to add or delete an element into a known location in the list
(i.e. if you have an iterator to the location) is O(1). If you don't
know the location, then you need to traverse the list to the location
of deletion/insertion, which takes O(n) time.
** The deletion cost is O(log n) for the minimum or maximum, O(n) for an
arbitrary element.
``` |
122,815 | <p>I'm looking for a groovy equivalent on .NET
<a href="http://boo.codehaus.org/" rel="nofollow noreferrer">http://boo.codehaus.org/</a></p>
<p>So far Boo looks interesting, but it is statically typed, yet does include some of the metaprogramming features I'd be looking for.</p>
<p>Can anyone comment on the experience of using Boo and is it worth looking into for more than hobby purposes at a 1.0 Version? </p>
<p><em>Edit</em>: Changed BOO to Boo</p>
| [
{
"answer_id": 122894,
"author": "Jose Vega",
"author_id": 17162,
"author_profile": "https://Stackoverflow.com/users/17162",
"pm_score": 4,
"selected": false,
"text": "<p>I guess I will start you off with the time complexity of a linked list:<br></p>\n\n<p>Indexing---->O(n)<br>\nInsertin... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129162/"
] | I'm looking for a groovy equivalent on .NET
<http://boo.codehaus.org/>
So far Boo looks interesting, but it is statically typed, yet does include some of the metaprogramming features I'd be looking for.
Can anyone comment on the experience of using Boo and is it worth looking into for more than hobby purposes at a 1.0 Version?
*Edit*: Changed BOO to Boo | Information on this topic is now available on Wikipedia at: [Search data structure](http://en.wikipedia.org/wiki/Search_data_structure)
```
+----------------------+----------+------------+----------+--------------+
| | Insert | Delete | Search | Space Usage |
+----------------------+----------+------------+----------+--------------+
| Unsorted array | O(1) | O(1) | O(n) | O(n) |
| Value-indexed array | O(1) | O(1) | O(1) | O(n) |
| Sorted array | O(n) | O(n) | O(log n) | O(n) |
| Unsorted linked list | O(1)* | O(1)* | O(n) | O(n) |
| Sorted linked list | O(n)* | O(1)* | O(n) | O(n) |
| Balanced binary tree | O(log n) | O(log n) | O(log n) | O(n) |
| Heap | O(log n) | O(log n)** | O(n) | O(n) |
| Hash table | O(1) | O(1) | O(1) | O(n) |
+----------------------+----------+------------+----------+--------------+
* The cost to add or delete an element into a known location in the list
(i.e. if you have an iterator to the location) is O(1). If you don't
know the location, then you need to traverse the list to the location
of deletion/insertion, which takes O(n) time.
** The deletion cost is O(log n) for the minimum or maximum, O(n) for an
arbitrary element.
``` |
122,821 | <p>I've got a Sharepoint WebPart which loads a custom User Control. The user control contains a Repeater which in turn contains several LinkButtons. </p>
<p>In the RenderContent call in the Webpart I've got some code to add event handlers:</p>
<pre><code> ArrayList nextPages = new ArrayList();
//populate nextPages ....
AfterPageRepeater.DataSource = nextPages;
AfterPageRepeater.DataBind();
foreach (Control oRepeaterControl in AfterPageRepeater.Controls)
{
if (oRepeaterControl is RepeaterItem)
{
if (oRepeaterControl.HasControls())
{
foreach (Control oControl in oRepeaterControl.Controls)
{
if (oControl is LinkButton)
{
((LinkButton)oControl).Click += new EventHandler(PageNavigateButton_Click);
}
}
}
}
}
</code></pre>
<p>The function PageNavigateButton_Click is never called however. I can see it being added as an event handler in the debugger however.</p>
<p>Any ideas? I'm stumped how to do this. </p>
| [
{
"answer_id": 122842,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 1,
"selected": false,
"text": "<p>You need to make sure that the link button is re-added to the control tree and/or that the event is rewired up to the con... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21299/"
] | I've got a Sharepoint WebPart which loads a custom User Control. The user control contains a Repeater which in turn contains several LinkButtons.
In the RenderContent call in the Webpart I've got some code to add event handlers:
```
ArrayList nextPages = new ArrayList();
//populate nextPages ....
AfterPageRepeater.DataSource = nextPages;
AfterPageRepeater.DataBind();
foreach (Control oRepeaterControl in AfterPageRepeater.Controls)
{
if (oRepeaterControl is RepeaterItem)
{
if (oRepeaterControl.HasControls())
{
foreach (Control oControl in oRepeaterControl.Controls)
{
if (oControl is LinkButton)
{
((LinkButton)oControl).Click += new EventHandler(PageNavigateButton_Click);
}
}
}
}
}
```
The function PageNavigateButton\_Click is never called however. I can see it being added as an event handler in the debugger however.
Any ideas? I'm stumped how to do this. | By the time RenderContent() is called, all the registered event handlers have been called by the framework. You need to add the event handlers in an earlier method, like OnLoad():
```
protected override void OnLoad(EventArge e)
{ base.OnLoad(e);
EnsureChildControls();
var linkButtons = from c in AfterPageRepeater.Controls
.OfType<RepeaterItem>()
where c.HasControls()
select c into ris
from lb in ris.OfType<LinkButton>()
select lb;
foreach(var linkButton in linkButtons)
{ linkButton.Click += PageNavigateButton_Click
}
}
``` |
122,834 | <p>Suppose there are two scripts Requester.php and Provider.php, and Requester requires processing from Provider and makes an http request to it (Provider.php?data="data"). In this situation, Provider quickly finds the answer, but to maintain the system must perform various updates throughout the database. Is there a way to immediately return the value to Requester, and then continue processing in Provider. </p>
<p>Psuedo Code</p>
<pre><code>Provider.php
{
$answer = getAnswer($_GET['data']);
echo $answer;
//SIGNAL TO REQUESTER THAT WE ARE FINISHED
processDBUpdates();
return;
}
</code></pre>
| [
{
"answer_id": 122897,
"author": "Peter Olsson",
"author_id": 2703,
"author_profile": "https://Stackoverflow.com/users/2703",
"pm_score": 2,
"selected": false,
"text": "<p>You can flush the output buffer with the flush() command.<br>\nRead the comments in the <a href=\"http://se.php.net/... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8880/"
] | Suppose there are two scripts Requester.php and Provider.php, and Requester requires processing from Provider and makes an http request to it (Provider.php?data="data"). In this situation, Provider quickly finds the answer, but to maintain the system must perform various updates throughout the database. Is there a way to immediately return the value to Requester, and then continue processing in Provider.
Psuedo Code
```
Provider.php
{
$answer = getAnswer($_GET['data']);
echo $answer;
//SIGNAL TO REQUESTER THAT WE ARE FINISHED
processDBUpdates();
return;
}
``` | You basically want to signal the end of 1 process (return to the original `Requester.php`) and spawn a new process (finish `Provider.php`). There is probably a more elegant way to pull this off, but I've managed this a couple different ways. All of them basically result in exec-ing a command in order to shell off the second process.
adding the following `> /dev/null 2>&1 &` to the end of your command will allow it to run in the background without inhibiting the actual execution of your current script
Something like the following may work for you:
```
exec("wget -O - \"$url\" > /dev/null 2>&1 &");
```
-- though you could do it as a command line PHP process as well.
You could also save the information that needs to be processed and handle the remaining processing on a cron job that re-creates the same sort of functionality without the need to exec. |
122,853 | <p>I want to get the size of an http:/.../file before I download it. The file can be a webpage, image, or a media file. Can this be done with HTTP headers? How do I download just the file HTTP header?</p>
| [
{
"answer_id": 122874,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>Can this be done with HTTP headers?</p>\n</blockquote>\n\n<p>Yes, this is the way to go. <em>If</e... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I want to get the size of an http:/.../file before I download it. The file can be a webpage, image, or a media file. Can this be done with HTTP headers? How do I download just the file HTTP header? | Yes, assuming the HTTP server you're talking to supports/allows this:
```
public long GetFileSize(string url)
{
long result = -1;
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
req.Method = "HEAD";
using (System.Net.WebResponse resp = req.GetResponse())
{
if (long.TryParse(resp.Headers.Get("Content-Length"), out long ContentLength))
{
result = ContentLength;
}
}
return result;
}
```
If using the HEAD method is not allowed, or the Content-Length header is not present in the server reply, the only way to determine the size of the content on the server is to download it. Since this is not particularly reliable, most servers will include this information. |
122,855 | <p>Anyone know if it is possible to write an app that uses the Java Sound API on a system that doesn't actually have a hardware sound device?</p>
<p>I have some code I've written based on the API that manipulates some audio and plays the result but I am now trying to run this in a server environment, where the audio will be recorded to a file instead of played to line out.</p>
<p>The server I'm running on has no sound card, and I seem to be running into roadblocks with Java Sound not being able to allocate any lines if there is not a Mixer that supports it. (And with no hardware devices I'm getting no Mixers.)</p>
<p>Any info would be much appreciated -</p>
<p>thanks.</p>
| [
{
"answer_id": 122874,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>Can this be done with HTTP headers?</p>\n</blockquote>\n\n<p>Yes, this is the way to go. <em>If</e... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8063/"
] | Anyone know if it is possible to write an app that uses the Java Sound API on a system that doesn't actually have a hardware sound device?
I have some code I've written based on the API that manipulates some audio and plays the result but I am now trying to run this in a server environment, where the audio will be recorded to a file instead of played to line out.
The server I'm running on has no sound card, and I seem to be running into roadblocks with Java Sound not being able to allocate any lines if there is not a Mixer that supports it. (And with no hardware devices I'm getting no Mixers.)
Any info would be much appreciated -
thanks. | Yes, assuming the HTTP server you're talking to supports/allows this:
```
public long GetFileSize(string url)
{
long result = -1;
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
req.Method = "HEAD";
using (System.Net.WebResponse resp = req.GetResponse())
{
if (long.TryParse(resp.Headers.Get("Content-Length"), out long ContentLength))
{
result = ContentLength;
}
}
return result;
}
```
If using the HEAD method is not allowed, or the Content-Length header is not present in the server reply, the only way to determine the size of the content on the server is to download it. Since this is not particularly reliable, most servers will include this information. |
122,857 | <p>As a follow up to <a href="https://stackoverflow.com/questions/104224/how-do-you-troubleshoot-wpf-ui-problems">my previous question</a>, I am wondering how to use transparent windows correctly. If I have set my window to use transparency, the UI will occasionally appear to stop responding. What is actually happening is that the UI simply is not updating as it should. Animations do not occur, pages do not appear to navigate; however, if you watch the debugger clicking on buttons, links, etc.. do actually work. Minimizing and restoring the window "catches up" the UI again and the user can continue working until the behavior comes back.</p>
<p>If I remove the transparent borders, the behavior does not occur. Am I doing something wrong or is there some other setting, code, etc... that I need to implement to work with transparent borders properly?</p>
<p>Here is my window declaration for the code that fails.</p>
<pre><code><Window x:Class="MyProject.MainContainer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF APplication" Height="600" Width="800"
xmlns:egc="ControlLibrary" Background="{x:Null}"
BorderThickness="0"
AllowsTransparency="True"
MinHeight="300" MinWidth="400" WindowStyle="None" >
</code></pre>
<p>And the code that does not exhibit the behavior</p>
<pre><code><Window x:Class="MyProject.MainContainer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Application" Height="600" Width="800"
xmlns:egc="ControlLibrary" Background="{x:Null}"
BorderThickness="0"
AllowsTransparency="False"
MinHeight="300" MinWidth="400" WindowStyle="None" >
</code></pre>
| [
{
"answer_id": 123026,
"author": "Abe Heidebrecht",
"author_id": 9268,
"author_profile": "https://Stackoverflow.com/users/9268",
"pm_score": 2,
"selected": false,
"text": "<p>Are you using .NET 3.0, or .NET 3.5 on Windows XP SP2? If so, this is a known problem with the transparent windo... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/312/"
] | As a follow up to [my previous question](https://stackoverflow.com/questions/104224/how-do-you-troubleshoot-wpf-ui-problems), I am wondering how to use transparent windows correctly. If I have set my window to use transparency, the UI will occasionally appear to stop responding. What is actually happening is that the UI simply is not updating as it should. Animations do not occur, pages do not appear to navigate; however, if you watch the debugger clicking on buttons, links, etc.. do actually work. Minimizing and restoring the window "catches up" the UI again and the user can continue working until the behavior comes back.
If I remove the transparent borders, the behavior does not occur. Am I doing something wrong or is there some other setting, code, etc... that I need to implement to work with transparent borders properly?
Here is my window declaration for the code that fails.
```
<Window x:Class="MyProject.MainContainer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF APplication" Height="600" Width="800"
xmlns:egc="ControlLibrary" Background="{x:Null}"
BorderThickness="0"
AllowsTransparency="True"
MinHeight="300" MinWidth="400" WindowStyle="None" >
```
And the code that does not exhibit the behavior
```
<Window x:Class="MyProject.MainContainer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Application" Height="600" Width="800"
xmlns:egc="ControlLibrary" Background="{x:Null}"
BorderThickness="0"
AllowsTransparency="False"
MinHeight="300" MinWidth="400" WindowStyle="None" >
``` | I think that I've finally found a workaround. From everything I've read this problem should not be occurring with XP SP3 & .NET 3.5 SP1, but it is.
The example from [this blog post](http://jerryclin.wordpress.com/2007/11/13/creating-non-rectangular-windows-with-interop/) shows how to use the Win32 API functions to create an irregular shaped window, which is what I"m doing. After reworking my main window to use these techniques, things seem to be working as expected and the behavior has not returned.
It is also of note that the reason the author recommends this method is due to performance issues with WPF and transparent windows. While I believe it may be better in .NET 3.5 SP1 that it was, this was not that hard to implement and should perform better. |
122,865 | <p>I have a <code>div</code> and an <code>iframe</code> on the page
the <code>div</code> has</p>
<pre><code>z-index: 0;
</code></pre>
<p>the <code>iframe</code> has its content with a popup having a <code>z-index</code> of 1000</p>
<pre><code>z-index: 1000;
</code></pre>
<p>However, the <code>div</code> still overshadows the popup in IE (but works fine in Firefox).</p>
<p>Does anyone know what I can do?</p>
| [
{
"answer_id": 123037,
"author": "nathaniel",
"author_id": 11947,
"author_profile": "https://Stackoverflow.com/users/11947",
"pm_score": 1,
"selected": false,
"text": "<p>Which version of IE?</p>\n\n<p>I'm no javascript guru, but I think hiding the div when the popup pops might accomplis... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] | I have a `div` and an `iframe` on the page
the `div` has
```
z-index: 0;
```
the `iframe` has its content with a popup having a `z-index` of 1000
```
z-index: 1000;
```
However, the `div` still overshadows the popup in IE (but works fine in Firefox).
Does anyone know what I can do? | [Explorer Z-index bug](http://www.quirksmode.org/bugreports/archives/2006/01/Explorer_z_index_bug.html)
In general, <http://www.quirksmode.org/> is an excellent reference for this sort of thing. |
122,877 | <p>So I've got some C code:</p>
<pre><code>#include <stdio.h>
#include <string.h>
/* putting one of the "char*"s here causes a segfault */
void main() {
char* path = "/temp";
char* temp;
strcpy(temp, path);
}
</code></pre>
<p>This compiles, runs, and behaves as it looks. However, if one or both of the character pointers is declared as global variable, strcpy results in a segmentation fault. Why does this happen? Evidently there's an error in my understanding of scope.</p>
| [
{
"answer_id": 122885,
"author": "terminus",
"author_id": 9232,
"author_profile": "https://Stackoverflow.com/users/9232",
"pm_score": 3,
"selected": false,
"text": "<p>You forgot to allocate and initialize temp:</p>\n\n<pre><code>temp = (char *)malloc(TEMP_SIZE);\n</code></pre>\n\n<p>Jus... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12926/"
] | So I've got some C code:
```
#include <stdio.h>
#include <string.h>
/* putting one of the "char*"s here causes a segfault */
void main() {
char* path = "/temp";
char* temp;
strcpy(temp, path);
}
```
This compiles, runs, and behaves as it looks. However, if one or both of the character pointers is declared as global variable, strcpy results in a segmentation fault. Why does this happen? Evidently there's an error in my understanding of scope. | As other posters mentioned, the root of the problem is that temp is uninitialized. When declared as an automatic variable on the stack it will contain whatever garbage happens to be in that memory location. Apparently for the compiler+CPU+OS you are running, the garbage at that location is a valid pointer. The strcpy "succeeds" in that it does not segfault, but really it copied a string to some arbitrary location elsewhere in memory. This kind of memory corruption problem strikes fear into the hearts of C programmers everywhere as it is extraordinarily difficult to debug.
When you move the temp variable declaration to global scope, it is placed in the BSS section and automatically zeroed. Attempts to dereference \*temp then result in a segfault.
When you move \*path to global scope, then \*temp moves up one location on the stack. The garbage at that location is apparently not a valid pointer, and so dereferencing \*temp results in a segfault. |
122,882 | <p>What is the proper technique to have <strong>ThreadA</strong> signal <strong>ThreadB</strong> of some event, without having <strong>ThreadB</strong> sit blocked waiting for an event to happen?</p>
<p>i have a background thread that will be filling a shared List<T>. i'm trying to find a way to asynchronously signal the "main" thread that there is data available to be picked up.</p>
<hr>
<p>i considered setting an event with an EventWaitHandle object, but i can't have my main thread sitting at an Event.WaitOne().</p>
<hr>
<p>i considered having a delegate callback, but
a) i don't want the main thread doing work in the delegate: the thread needs to get back to work adding more stuff - i don't want it waiting while the delegate executes, and
b) the delegate needs to be marshalled onto the main thread, but i'm not running a UI, i have no Control to .Invoke the delegate against.</p>
<hr>
<p>i considered have a delegate callback that simply starts a zero interval System.Windows.Forms.Timer (with thread access to the timer synchronized). This way the thread only needs to be stuck as it calls</p>
<p><code>Timer.Enabled = true;</code></p>
<p>but that seems like a hack.</p>
<p>In the olden days my object would have created a hidden window and had the thread post messages to that hidden windows' HWND. i considered creating a hidden control, but i gather that you cannot .Invoke on a control with no handle created. Plus, i have no UI: my object could have been created on a web-server, service, or console, i don't want there to be a graphical control appearing - nor do i want to compile a dependency on System.Windows.Forms.</p>
<hr>
<p>i considered having my object expose an ISynchronizeInvoke interface, but then i would need to implement .Invoke(), and that's my problem.</p>
<hr>
<p>What is the proper technique to have thread A signal thread B of some event, without having thread B sit blocked waiting for an event to happen?</p>
| [
{
"answer_id": 122953,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 1,
"selected": false,
"text": "<p>If you use a backgroundworker to start the second thread and use the ProgressChanged event to notify the other ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] | What is the proper technique to have **ThreadA** signal **ThreadB** of some event, without having **ThreadB** sit blocked waiting for an event to happen?
i have a background thread that will be filling a shared List<T>. i'm trying to find a way to asynchronously signal the "main" thread that there is data available to be picked up.
---
i considered setting an event with an EventWaitHandle object, but i can't have my main thread sitting at an Event.WaitOne().
---
i considered having a delegate callback, but
a) i don't want the main thread doing work in the delegate: the thread needs to get back to work adding more stuff - i don't want it waiting while the delegate executes, and
b) the delegate needs to be marshalled onto the main thread, but i'm not running a UI, i have no Control to .Invoke the delegate against.
---
i considered have a delegate callback that simply starts a zero interval System.Windows.Forms.Timer (with thread access to the timer synchronized). This way the thread only needs to be stuck as it calls
`Timer.Enabled = true;`
but that seems like a hack.
In the olden days my object would have created a hidden window and had the thread post messages to that hidden windows' HWND. i considered creating a hidden control, but i gather that you cannot .Invoke on a control with no handle created. Plus, i have no UI: my object could have been created on a web-server, service, or console, i don't want there to be a graphical control appearing - nor do i want to compile a dependency on System.Windows.Forms.
---
i considered having my object expose an ISynchronizeInvoke interface, but then i would need to implement .Invoke(), and that's my problem.
---
What is the proper technique to have thread A signal thread B of some event, without having thread B sit blocked waiting for an event to happen? | Here's a code sample for the System.ComponentModel.BackgroundWorker class.
```
private static BackgroundWorker worker = new BackgroundWorker();
static void Main(string[] args)
{
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.ProgressChanged += worker_ProgressChanged;
worker.WorkerReportsProgress = true;
Console.WriteLine("Starting application.");
worker.RunWorkerAsync();
Console.ReadKey();
}
static void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine("Progress.");
}
static void worker_DoWork(object sender, DoWorkEventArgs e)
{
Console.WriteLine("Starting doing some work now.");
for (int i = 0; i < 5; i++)
{
Thread.Sleep(1000);
worker.ReportProgress(i);
}
}
static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine("Done now.");
}
``` |
122,883 | <p>Could someone please demystify interfaces for me or point me to some good examples? I keep seeing interfaces popup here and there, but I haven't ever really been exposed to good explanations of interfaces or when to use them.</p>
<p>I am talking about interfaces in a context of interfaces vs. abstract classes.</p>
| [
{
"answer_id": 122926,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "<p>Interfaces are a way to enforce that an object implements a certain amount of functionality, without having to use inheri... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16820/"
] | Could someone please demystify interfaces for me or point me to some good examples? I keep seeing interfaces popup here and there, but I haven't ever really been exposed to good explanations of interfaces or when to use them.
I am talking about interfaces in a context of interfaces vs. abstract classes. | Interfaces allow you to program against a "description" instead of a type, which allows you to more-loosely associate elements of your software.
Think of it this way: You want to share data with someone in the cube next to you, so you pull out your flash stick and copy/paste. You walk next door and the guy says "is that USB?" and you say yes - all set. It doesn't matter the size of the flash stick, nor the maker - all that matters is that it's USB.
In the same way, interfaces allow you to generisize your development. Using another analogy - imagine you wanted to create an application that virtually painted cars. You might have a signature like this:
```
public void Paint(Car car, System.Drawing.Color color)...
```
This would work until your client said "now I want to paint trucks" so you could do this:
```
public void Paint (Vehicle vehicle, System.Drawing.Color color)...
```
this would broaden your app... until your client said "now I want to paint houses!" What you could have done from the very beginning is created an interface:
```
public interface IPaintable{
void Paint(System.Drawing.Color color);
}
```
...and passed that to your routine:
```
public void Paint(IPaintable item, System.Drawing.Color color){
item.Paint(color);
}
```
Hopefully this makes sense - it's a pretty simplistic explanation but hopefully gets to the heart of it. |
122,909 | <p>I have a file. I want to get its contents into a blob column in my oracle database or into a blob variable in my PL/SQL program. What is the best way to do that?</p>
| [
{
"answer_id": 123017,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 0,
"selected": false,
"text": "<p>Depends a bit on your environment. In Java you could do it something like this...</p>\n\n<pre><code>// Need as Oracl... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13693/"
] | I have a file. I want to get its contents into a blob column in my oracle database or into a blob variable in my PL/SQL program. What is the best way to do that? | To do it entirely in PL/SQL, the file would need to be on the server, located in a directory which you'd need to define in the database. Create the following objects:
```
CREATE OR REPLACE DIRECTORY
BLOB_DIR
AS
'/oracle/base/lobs'
/
CREATE OR REPLACE PROCEDURE BLOB_LOAD
AS
lBlob BLOB;
lFile BFILE := BFILENAME('BLOB_DIR', 'filename');
BEGIN
INSERT INTO table (id, your_blob)
VALUES (xxx, empty_blob())
RETURNING your_blob INTO lBlob;
DBMS_LOB.OPEN(lFile, DBMS_LOB.LOB_READONLY);
DBMS_LOB.OPEN(lBlob, DBMS_LOB.LOB_READWRITE);
DBMS_LOB.LOADFROMFILE(DEST_LOB => lBlob,
SRC_LOB => lFile,
AMOUNT => DBMS_LOB.GETLENGTH(lFile));
DBMS_LOB.CLOSE(lFile);
DBMS_LOB.CLOSE(lBlob);
COMMIT;
END;
/
``` |
122,914 | <p>Does anyone know any implementation of a templated cache of objects?</p>
<ul>
<li>You use a key to find object (the same as in std::map<>)</li>
<li>You specify a maximum number of objects that can be in the cache at the same time</li>
<li>There are facilities to create an object not found in the cache</li>
<li>There are facilities to know when an object is discarded from the cache</li>
</ul>
<p>For example : </p>
<pre><code>typedef cache<int, MyObj*> MyCache;
MyCache oCache;
oCache.SetSize(1);
oCache.Insert(make_pair(1, new MyObj());
oCache.Touch(1);
MyObj* oldObj = oCache.Delete(1);
...
</code></pre>
<p>It can be as simple as a LRU or MRU cache.</p>
<p>Any suggestions are welcomed!</p>
<p>Nic</p>
| [
{
"answer_id": 123715,
"author": "jpinto3912",
"author_id": 11567,
"author_profile": "https://Stackoverflow.com/users/11567",
"pm_score": -1,
"selected": false,
"text": "<p>In an application I can hardly imagine it would speed/boost up performance to store objects that apparently can be ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18800/"
] | Does anyone know any implementation of a templated cache of objects?
* You use a key to find object (the same as in std::map<>)
* You specify a maximum number of objects that can be in the cache at the same time
* There are facilities to create an object not found in the cache
* There are facilities to know when an object is discarded from the cache
For example :
```
typedef cache<int, MyObj*> MyCache;
MyCache oCache;
oCache.SetSize(1);
oCache.Insert(make_pair(1, new MyObj());
oCache.Touch(1);
MyObj* oldObj = oCache.Delete(1);
...
```
It can be as simple as a LRU or MRU cache.
Any suggestions are welcomed!
Nic | You can use the [Boost.MultiIndex](http://www.boost.org/doc/libs/1_60_0/libs/multi_index/doc/index.html) library.
It is easy to implement a [MRU cache](http://www.boost.org/doc/libs/1_60_0/libs/multi_index/doc/examples.html#example9). |
122,919 | <p>I have this bit of javascript written with jQuery 1.2.5. It's contained inside the main function() of a plugin that I wrote. The plugin is a horizontal gallery scroller very similar to jCarousel. It does alot of auto calculating of widths and determines how many to scroll based on that and the size of the images, which is what all the calculations are that are going on.</p>
<p>What my question is, how do I prevent this from firing off before a previous execution is finished. For instance, if I get a little click happy and just frantically mash down on <code>.digi_next</code>. Things don't go so well in the UI when that happens and I'd like to fix it :) I thought the answer might lie in <code>queue</code>, but all my attempts at using it haven't turned out anything worthwhile.</p>
<pre><code> var self = this;
$(".digi_next", this.container).click(function(){
var curLeft = $(".digi_container", self.container).css("left").split("px")[0];
var newLeft = (curLeft*1) - (self.containerPad + self.containerWidth) * self.show_photos;
if (newLeft < ((self.digi_gal_width - (self.containerPad + self.containerWidth) * self.show_photos)) * -1) {
newLeft = ((self.digi_gal_width - (self.containerPad + self.containerWidth) * self.show_photos)) * -1;
}
$(".digi_container", self.container).animate({
left: newLeft + "px"
}, self.rotateSpeed);
});
</code></pre>
| [
{
"answer_id": 122995,
"author": "Davide Vosti",
"author_id": 1812,
"author_profile": "https://Stackoverflow.com/users/1812",
"pm_score": 1,
"selected": false,
"text": "<p>Since JavaScript functions calls are asyncronus, you can pass as a in parameter a callback function that's called wh... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611/"
] | I have this bit of javascript written with jQuery 1.2.5. It's contained inside the main function() of a plugin that I wrote. The plugin is a horizontal gallery scroller very similar to jCarousel. It does alot of auto calculating of widths and determines how many to scroll based on that and the size of the images, which is what all the calculations are that are going on.
What my question is, how do I prevent this from firing off before a previous execution is finished. For instance, if I get a little click happy and just frantically mash down on `.digi_next`. Things don't go so well in the UI when that happens and I'd like to fix it :) I thought the answer might lie in `queue`, but all my attempts at using it haven't turned out anything worthwhile.
```
var self = this;
$(".digi_next", this.container).click(function(){
var curLeft = $(".digi_container", self.container).css("left").split("px")[0];
var newLeft = (curLeft*1) - (self.containerPad + self.containerWidth) * self.show_photos;
if (newLeft < ((self.digi_gal_width - (self.containerPad + self.containerWidth) * self.show_photos)) * -1) {
newLeft = ((self.digi_gal_width - (self.containerPad + self.containerWidth) * self.show_photos)) * -1;
}
$(".digi_container", self.container).animate({
left: newLeft + "px"
}, self.rotateSpeed);
});
``` | Just use a global busy flag. When you enter your click handler, check it, and only proceed if it's false. Immediately set it to true, and then set it back to false when the animation ends. JavaScript is single-threaded, so there is no race condition to worry about.
```
var busy = false;
$("...").onclick(function() {
if (busy) return false;
busy = true;
$("...").animate(..., ..., ..., function() {
busy= false;
});
return false;
});
``` |
122,920 | <p>I'd like to line up items approximately like this:</p>
<pre><code>item1 item2 i3 longitemname
i4 longitemname2 anotheritem i5
</code></pre>
<p>Basically items of varying length arranged in a table like structure. The tricky part is the container for these can vary in size and I'd like to fit as many as I can in each row - in other words, I won't know beforehand how many items fit in a line, and if the page is resized the items should re-flow themselves to accommodate. E.g. initially 10 items could fit on each line, but on resize it could be reduced to 5.</p>
<p>I don't think I can use an html table since I don't know the number of columns (since I don't know how many will fit on a line). I can use css to float them, but since they're of varying size they won't line up.</p>
<p>So far the only thing I can think of is to use javascript to get the size of largest item, set the size of all items to that size, and float everything left.</p>
<p>Any better suggestions?</p>
| [
{
"answer_id": 122952,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 0,
"selected": false,
"text": "<p>You could use block level elements floated left, but you will need some javascript to check the sizes, find the l... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] | I'd like to line up items approximately like this:
```
item1 item2 i3 longitemname
i4 longitemname2 anotheritem i5
```
Basically items of varying length arranged in a table like structure. The tricky part is the container for these can vary in size and I'd like to fit as many as I can in each row - in other words, I won't know beforehand how many items fit in a line, and if the page is resized the items should re-flow themselves to accommodate. E.g. initially 10 items could fit on each line, but on resize it could be reduced to 5.
I don't think I can use an html table since I don't know the number of columns (since I don't know how many will fit on a line). I can use css to float them, but since they're of varying size they won't line up.
So far the only thing I can think of is to use javascript to get the size of largest item, set the size of all items to that size, and float everything left.
Any better suggestions? | This can be done using floated div's, calculating the max width, and setting all widths to the max. Here's jquery code to do it:
html:
```
<div class="item">something</div>
<div class="item">something else</div>
```
css:
```
div.item { float: left; }
```
jquery:
```
var max_width=0;
$('div.item').each( function() { if ($(this).width() > max_width) { max_width=$(this).width(); } } ).width(max_width);
```
Not too ugly but not too pretty either, I'm still open to better suggestions... |
122,942 | <p>I have a table <code>UserAliases</code> (<code>UserId, Alias</code>) with multiple aliases per user. I need to query it and return all aliases for a given user, the trick is to return them all in one column.</p>
<p>Example:</p>
<pre><code>UserId/Alias
1/MrX
1/MrY
1/MrA
2/Abc
2/Xyz
</code></pre>
<p>I want the query result in the following format:</p>
<pre><code>UserId/Alias
1/ MrX, MrY, MrA
2/ Abc, Xyz
</code></pre>
<p>Thank you.</p>
<p>I'm using SQL Server 2005.</p>
<p>p.s. actual T-SQL query would be appreciated :)</p>
| [
{
"answer_id": 122956,
"author": "gehsekky",
"author_id": 21310,
"author_profile": "https://Stackoverflow.com/users/21310",
"pm_score": 0,
"selected": false,
"text": "<p>group_concat() sounds like what you're looking for.</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/group-b... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661/"
] | I have a table `UserAliases` (`UserId, Alias`) with multiple aliases per user. I need to query it and return all aliases for a given user, the trick is to return them all in one column.
Example:
```
UserId/Alias
1/MrX
1/MrY
1/MrA
2/Abc
2/Xyz
```
I want the query result in the following format:
```
UserId/Alias
1/ MrX, MrY, MrA
2/ Abc, Xyz
```
Thank you.
I'm using SQL Server 2005.
p.s. actual T-SQL query would be appreciated :) | You can use a function with COALESCE.
```
CREATE FUNCTION [dbo].[GetAliasesById]
(
@userID int
)
RETURNS varchar(max)
AS
BEGIN
declare @output varchar(max)
select @output = COALESCE(@output + ', ', '') + alias
from UserAliases
where userid = @userID
return @output
END
GO
SELECT UserID, dbo.GetAliasesByID(UserID)
FROM UserAliases
GROUP BY UserID
GO
``` |
122,951 | <p>I received the following exception when I was using the Regex class with the regular expression: (?'named a'asdf)</p>
<pre><code>System.ArgumentException: parsing \"(?'named a'asdf)\" - Invalid group name: Group names must begin with a word character.
</code></pre>
<p>What is the problem with my regular expression?</p>
| [
{
"answer_id": 122973,
"author": "Simon Johnson",
"author_id": 854,
"author_profile": "https://Stackoverflow.com/users/854",
"pm_score": -1,
"selected": false,
"text": "<p>The problem is your quotes around the name of the named capture group. Try the string: (?<Named>asdf)</p>\n"
... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12834/"
] | I received the following exception when I was using the Regex class with the regular expression: (?'named a'asdf)
```
System.ArgumentException: parsing \"(?'named a'asdf)\" - Invalid group name: Group names must begin with a word character.
```
What is the problem with my regular expression? | The problem is the space in the name of the capture. Remove the space and it works fine.
From the MSDN documentation:
"The string used for name must not contain any punctuation and cannot begin with a number. You can use single quotes instead of angle brackets; for example, (?'name')."
It does not matter if you use angle brackets <> or single quotes '' to indicate a group name. |
122,990 | <p>I have several sources of tables with personal data, like this:</p>
<pre><code>SOURCE 1
ID, FIRST_NAME, LAST_NAME, FIELD1, ...
1, jhon, gates ...
SOURCE 2
ID, FIRST_NAME, LAST_NAME, ANOTHER_FIELD1, ...
1, jon, gate ...
SOURCE 3
ID, FIRST_NAME, LAST_NAME, ANOTHER_FIELD1, ...
2, jhon, ballmer ...
</code></pre>
<p>So, assuming that records with ID 1, from sources 1 and 2, are the same person, my problem <strong>is how to determine if a record in every source, represents the same person</strong>. Additionally, sure not every records exists in all sources. All the names, are written in spanish, mainly.</p>
<p>In this case, the exact matching needs to be relaxed because we assume <em>the data sources has not been rigurously checked</em> against the official bureau of identification of the country. Also we need to assume <em>typos are common</em>, because the nature of the processes to collect the data. What is more, the amount of records is around 2 or 3 millions in every source...</p>
<p>Our team had thought in something like this: first, force exact matching in selected fields like ID NUMBER, and NAMES to know how hard the problem can be. Second, relaxing the matching criteria, and count how much records more can be matched, but is here where the problem arises: <strong>how to do to relax the matching criteria without generating too noise neither restricting too much?</strong></p>
<p>What tool can be more effective to handle this?, for example, do you know about some especific extension in some database engine to support this matching?
Do you know about clever algorithms like <a href="http://en.wikipedia.org/wiki/Soundex" rel="nofollow noreferrer">soundex</a> to handle this approximate matching, but for spanish texts?</p>
<p>Any help would be appreciated!</p>
<p>Thanks.</p>
| [
{
"answer_id": 123001,
"author": "ScaleOvenStove",
"author_id": 12268,
"author_profile": "https://Stackoverflow.com/users/12268",
"pm_score": 2,
"selected": false,
"text": "<p>SSIS , try using the Fuzzy Lookup transformation</p>\n"
},
{
"answer_id": 123050,
"author": "Mike Mc... | 2008/09/23 | [
"https://Stackoverflow.com/questions/122990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18300/"
] | I have several sources of tables with personal data, like this:
```
SOURCE 1
ID, FIRST_NAME, LAST_NAME, FIELD1, ...
1, jhon, gates ...
SOURCE 2
ID, FIRST_NAME, LAST_NAME, ANOTHER_FIELD1, ...
1, jon, gate ...
SOURCE 3
ID, FIRST_NAME, LAST_NAME, ANOTHER_FIELD1, ...
2, jhon, ballmer ...
```
So, assuming that records with ID 1, from sources 1 and 2, are the same person, my problem **is how to determine if a record in every source, represents the same person**. Additionally, sure not every records exists in all sources. All the names, are written in spanish, mainly.
In this case, the exact matching needs to be relaxed because we assume *the data sources has not been rigurously checked* against the official bureau of identification of the country. Also we need to assume *typos are common*, because the nature of the processes to collect the data. What is more, the amount of records is around 2 or 3 millions in every source...
Our team had thought in something like this: first, force exact matching in selected fields like ID NUMBER, and NAMES to know how hard the problem can be. Second, relaxing the matching criteria, and count how much records more can be matched, but is here where the problem arises: **how to do to relax the matching criteria without generating too noise neither restricting too much?**
What tool can be more effective to handle this?, for example, do you know about some especific extension in some database engine to support this matching?
Do you know about clever algorithms like [soundex](http://en.wikipedia.org/wiki/Soundex) to handle this approximate matching, but for spanish texts?
Any help would be appreciated!
Thanks. | The crux of the problem is to compute one or more measures of distance between each pair of entries and then consider them to be the same when one of the distances is less than a certain acceptable threshold. The key is to setup the analysis and then vary the acceptable distance until you reach what you consider to be the best trade-off between false-positives and false-negatives.
One distance measurement could be phonetic. Another you might consider is the [Levenshtein or edit distance](http://en.wikipedia.org/wiki/Levenshtein_distance) between the entires, which would attempt to measure typos.
If you have a reasonable idea of how many persons you should have, then your goal is to find the sweet spot where you are getting about the right number of persons. Make your matching too fuzzy and you'll have too few. Make it to restrictive and you'll have too many.
If you know roughly how many entries a person should have, then you can use that as the metric to see when you are getting close. Or you can divide the number of records into the average number of records for each person and get a rough number of persons that you're shooting for.
If you don't have any numbers to use, then you're left picking out groups of records from your analysis and checking by hand whether they look like the same person or not. So it's guess and check.
I hope that helps. |
123,002 | <p>So I've got maybe 10 objects each of which has 1-3 dependencies (which I think is ok as far as loose coupling is concerned) but also some settings that can be used to define behavior (timeout, window size, etc).</p>
<p>Now before I started using an Inversion of Control container I would have created a factory and maybe even a simple ObjectSettings object for each of the objects that requires more than 1 setting to keep the size of the constructor to the recommended "less than 4" parameter size. I am now using an inversion of control container and I just don't see all that much of a point to it. Sure I might get a constructor with 7 parameters, but who cares? It's all being filled out by the IoC anyways.</p>
<p>Am I missing something here or is this basically correct?</p>
| [
{
"answer_id": 123055,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 1,
"selected": false,
"text": "<p>G'day George,</p>\n\n<p>First off, what are the dependencies between the objects?</p>\n\n<p>Lots of \"isa\" relationshi... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | So I've got maybe 10 objects each of which has 1-3 dependencies (which I think is ok as far as loose coupling is concerned) but also some settings that can be used to define behavior (timeout, window size, etc).
Now before I started using an Inversion of Control container I would have created a factory and maybe even a simple ObjectSettings object for each of the objects that requires more than 1 setting to keep the size of the constructor to the recommended "less than 4" parameter size. I am now using an inversion of control container and I just don't see all that much of a point to it. Sure I might get a constructor with 7 parameters, but who cares? It's all being filled out by the IoC anyways.
Am I missing something here or is this basically correct? | The relationship between class complexity and the size of the IoC constructor had not occurred to me before reading this question, but my analysis below suggests that having many arguments in the IoC constructor is a [code smell](https://stackoverflow.com/questions/114342/what-are-code-smells-what-is-the-best-way-to-correct-them) to be aware of when using IoC. Having a goal to stick to a short constructor argument list will help you keep the classes themselves simple. Following the [single responsibility principle](https://stackoverflow.com/questions/15412/is-single-responsibility-principle-a-rule-of-oop) will guide you towards this goal.
I work on a system that currently has 122 classes that are instantiated using the Spring.NET framework. All relationships between these classes are set up in their constructors. Admittedly, the system has its fair share of less than perfect code where I have broken a few rules. (But, hey, our failures are opportunities to learn!)
The constructors of those classes have varying numbers of arguments, which I show in the table below.
```
Number of constructor arguments Number of classes
0 57
1 19
2 25
3 9
4 3
5 1
6 3
7 2
8 2
```
The classes with zero arguments are either concrete strategy classes, or classes that respond to events by sending data to external systems.
Those with 5 or 6 arguments are all somewhat inelegant and could use some refactoring to simplify them.
The four classes with 7 or 8 arguments are excellent examples of [God objects](http://en.wikipedia.org/wiki/God_object). They ought to be broken up, and each is already on my list of trouble-spots within the system.
The remaining classes (1 to 4 arguments) are (mostly) simply designed, easy to understand, and conform to the [single responsibility principle](https://stackoverflow.com/questions/15412/is-single-responsibility-principle-a-rule-of-oop). |
123,003 | <p>I need to determine the ID of a form field from within an action handler. The field is a part of a included facelets component and so the form will vary.</p>
<p><strong>included.xhtml</strong> </p>
<pre><code><ui:component>
<h:inputText id="contained_field"/>
<h:commandButton actionListener="#{backingBean.update}" value="Submit"/>
</ui:component>
</code></pre>
<p><strong>example_containing.xhtml</strong></p>
<pre><code><h:form id="containing_form">
<ui:include src="/included.xhtml"/>
</h:form>
</code></pre>
<p>How may I determine the ID of the form in the <code>update</code> method at runtime? Or better yet, the ID of the input field directly.</p>
| [
{
"answer_id": 123208,
"author": "jsight",
"author_id": 1432,
"author_profile": "https://Stackoverflow.com/users/1432",
"pm_score": 4,
"selected": true,
"text": "<p>Bind the button to your backing bean, then use getParent() until you find the nearest form.</p>\n"
},
{
"answer_id"... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] | I need to determine the ID of a form field from within an action handler. The field is a part of a included facelets component and so the form will vary.
**included.xhtml**
```
<ui:component>
<h:inputText id="contained_field"/>
<h:commandButton actionListener="#{backingBean.update}" value="Submit"/>
</ui:component>
```
**example\_containing.xhtml**
```
<h:form id="containing_form">
<ui:include src="/included.xhtml"/>
</h:form>
```
How may I determine the ID of the form in the `update` method at runtime? Or better yet, the ID of the input field directly. | Bind the button to your backing bean, then use getParent() until you find the nearest form. |
123,007 | <p>I can't quite figure this out. Microsoft Access 2000, on the report total section I have totals for three columns that are just numbers. These <code>=Sum[(ThisColumn1)], 2, 3</code>, etc and those grand totls all work fine. </p>
<p>I want to have another column that says <code>=Sum([ThisColumn1])+Sum([ThisColumn2]) + Sum([ThisColumn3])</code> but can't figure those one out. Just get a blank so I am sure there is an error.</p>
| [
{
"answer_id": 123022,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 3,
"selected": true,
"text": "<p>Give the 3 Grand Totals meaningful Control Names and then for the Grand Grand Total use:</p>\n\n<pre><code>=[GrandTo... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I can't quite figure this out. Microsoft Access 2000, on the report total section I have totals for three columns that are just numbers. These `=Sum[(ThisColumn1)], 2, 3`, etc and those grand totls all work fine.
I want to have another column that says `=Sum([ThisColumn1])+Sum([ThisColumn2]) + Sum([ThisColumn3])` but can't figure those one out. Just get a blank so I am sure there is an error. | Give the 3 Grand Totals meaningful Control Names and then for the Grand Grand Total use:
```
=[GrandTotal1] + [GrandTotal2] + [GrandTotal3]
```
Your Grand Total formulas should be something like:
```
=Sum(Nz([ThisColumn1], 0))
``` |
123,075 | <p>How to do paging in Pervasive SQL (version 9.1)? I need to do something similar like:</p>
<pre><code>//MySQL
SELECT foo FROM table LIMIT 10, 10
</code></pre>
<p>But I can't find a way to define offset.</p>
| [
{
"answer_id": 123168,
"author": "Jasmine",
"author_id": 5255,
"author_profile": "https://Stackoverflow.com/users/5255",
"pm_score": 0,
"selected": false,
"text": "<p>I face this problem in MS Sql too... no Limit or rownumber functions. What I do is insert the keys for my final query res... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5468/"
] | How to do paging in Pervasive SQL (version 9.1)? I need to do something similar like:
```
//MySQL
SELECT foo FROM table LIMIT 10, 10
```
But I can't find a way to define offset. | I ended up doing the paging in code. I just skip the first records in loop.
I thought I made up an easy way for doing the paging, but it seems that pervasive sql doesn't allow order clauses in subqueries. But this should work on other DBs (I tested it on firebird)
```
select *
from (select top [rows] * from
(select top [rows * pagenumber] * from mytable order by id)
order by id desc)
order by id
``` |
123,078 | <p>On destruction of a restful resource, I want to guarantee a few things before I allow a destroy operation to continue? Basically, I want the ability to stop the destroy operation if I note that doing so would place the database in a invalid state? There are no validation callbacks on a destroy operation, so how does one "validate" whether a destroy operation should be accepted?</p>
| [
{
"answer_id": 123190,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 7,
"selected": true,
"text": "<p>You can raise an exception which you then catch. Rails wraps deletes in a transaction, which helps matters.</p>\n\... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21317/"
] | On destruction of a restful resource, I want to guarantee a few things before I allow a destroy operation to continue? Basically, I want the ability to stop the destroy operation if I note that doing so would place the database in a invalid state? There are no validation callbacks on a destroy operation, so how does one "validate" whether a destroy operation should be accepted? | You can raise an exception which you then catch. Rails wraps deletes in a transaction, which helps matters.
For example:
```
class Booking < ActiveRecord::Base
has_many :booking_payments
....
def destroy
raise "Cannot delete booking with payments" unless booking_payments.count == 0
# ... ok, go ahead and destroy
super
end
end
```
Alternatively you can use the before\_destroy callback. This callback is normally used to destroy dependent records, but you can throw an exception or add an error instead.
```
def before_destroy
return true if booking_payments.count == 0
errors.add :base, "Cannot delete booking with payments"
# or errors.add_to_base in Rails 2
false
# Rails 5
throw(:abort)
end
```
`myBooking.destroy` will now return false, and `myBooking.errors` will be populated on return. |
123,088 | <p><strong>C#6 Update</strong></p>
<p>In <a href="https://msdn.microsoft.com/en-us/magazine/dn802602.aspx" rel="nofollow noreferrer">C#6 <code>?.</code> is now a language feature</a>:</p>
<pre><code>// C#1-5
propertyValue1 = myObject != null ? myObject.StringProperty : null;
// C#6
propertyValue1 = myObject?.StringProperty;
</code></pre>
<p>The question below still applies to older versions, but if developing a new application using the new <code>?.</code> operator is far better practice.</p>
<p><strong>Original Question:</strong></p>
<p>I regularly want to access properties on possibly null objects:</p>
<pre><code>string propertyValue1 = null;
if( myObject1 != null )
propertyValue1 = myObject1.StringProperty;
int propertyValue2 = 0;
if( myObject2 != null )
propertyValue2 = myObject2.IntProperty;
</code></pre>
<p>And so on...</p>
<p>I use this so often that I have a snippet for it.</p>
<p>You can shorten this to some extent with an inline if:</p>
<pre><code>propertyValue1 = myObject != null ? myObject.StringProperty : null;
</code></pre>
<p>However this is a little clunky, especially if setting lots of properties or if more than one level can be null, for instance:</p>
<pre><code>propertyValue1 = myObject != null ?
(myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null : null;
</code></pre>
<p>What I really want is <code>??</code> style syntax, which works great for directly null types:</p>
<pre><code>int? i = SomeFunctionWhichMightReturnNull();
propertyValue2 = i ?? 0;
</code></pre>
<p>So I came up with the following:</p>
<pre><code>public static TResult IfNotNull<T, TResult>( this T input, Func<T, TResult> action, TResult valueIfNull )
where T : class
{
if ( input != null ) return action( input );
else return valueIfNull;
}
//lets us have a null default if the type is nullable
public static TResult IfNotNull<T, TResult>( this T input, Func<T, TResult> action )
where T : class
where TResult : class
{ return input.IfNotNull( action, null ); }
</code></pre>
<p>This lets me us this syntax:</p>
<pre><code>propertyValue1 = myObject1.IfNotNull( x => x.StringProperty );
propertyValue2 = myObject2.IfNotNull( x => x.IntProperty, 0);
//or one with multiple levels
propertyValue1 = myObject.IfNotNull(
o => o.ObjectProp.IfNotNull( p => p.StringProperty ) );
</code></pre>
<p>This simplifies these calls, but I'm not sure about checking this sort of extension method in - it does make the code a little easier to read, but at the cost of extending object. This would appear on everything, although I could put it in a specifically referenced namespace.</p>
<p>This example is a rather simple one, a slightly more complex one would be comparing two nullable object properties:</p>
<pre><code>if( ( obj1 == null && obj2 == null ) ||
( obj1 != null && obj2 != null && obj1.Property == obj2.Property ) )
...
//becomes
if( obj1.NullCompare( obj2, (x,y) => x.Property == y.Property )
...
</code></pre>
<p>What are the pitfalls of using extensions in this way? Are other coders likely to be confused? Is this just abuse of extensions?</p>
<hr>
<p>I guess what I really want here is a compiler/language extension:</p>
<pre><code>propertyValue1 = myObject != null ? myObject.StringProperty : null;
//becomes
propertyValue1 = myObject?StringProperty;
</code></pre>
<p>This would make the complex case far easier:</p>
<pre><code>propertyValue1 = myObject != null ?
(myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null
//becomes
propertyValue1 = myObject?ObjectProp?StringProperty;
</code></pre>
<p>This would only work for value types, but you could return nullable equivalents:</p>
<pre><code>int? propertyValue2 = myObject?ObjectProp?IntProperty;
//or
int propertyValue3 = myObject?ObjectProp?IntProperty ?? 0;
</code></pre>
| [
{
"answer_id": 123140,
"author": "Swati",
"author_id": 12682,
"author_profile": "https://Stackoverflow.com/users/12682",
"pm_score": 0,
"selected": false,
"text": "<p>Personally, even after all your explanation, I can't remember how the heck this works:</p>\n\n<pre><code>if( obj1.NullCom... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | **C#6 Update**
In [C#6 `?.` is now a language feature](https://msdn.microsoft.com/en-us/magazine/dn802602.aspx):
```
// C#1-5
propertyValue1 = myObject != null ? myObject.StringProperty : null;
// C#6
propertyValue1 = myObject?.StringProperty;
```
The question below still applies to older versions, but if developing a new application using the new `?.` operator is far better practice.
**Original Question:**
I regularly want to access properties on possibly null objects:
```
string propertyValue1 = null;
if( myObject1 != null )
propertyValue1 = myObject1.StringProperty;
int propertyValue2 = 0;
if( myObject2 != null )
propertyValue2 = myObject2.IntProperty;
```
And so on...
I use this so often that I have a snippet for it.
You can shorten this to some extent with an inline if:
```
propertyValue1 = myObject != null ? myObject.StringProperty : null;
```
However this is a little clunky, especially if setting lots of properties or if more than one level can be null, for instance:
```
propertyValue1 = myObject != null ?
(myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null : null;
```
What I really want is `??` style syntax, which works great for directly null types:
```
int? i = SomeFunctionWhichMightReturnNull();
propertyValue2 = i ?? 0;
```
So I came up with the following:
```
public static TResult IfNotNull<T, TResult>( this T input, Func<T, TResult> action, TResult valueIfNull )
where T : class
{
if ( input != null ) return action( input );
else return valueIfNull;
}
//lets us have a null default if the type is nullable
public static TResult IfNotNull<T, TResult>( this T input, Func<T, TResult> action )
where T : class
where TResult : class
{ return input.IfNotNull( action, null ); }
```
This lets me us this syntax:
```
propertyValue1 = myObject1.IfNotNull( x => x.StringProperty );
propertyValue2 = myObject2.IfNotNull( x => x.IntProperty, 0);
//or one with multiple levels
propertyValue1 = myObject.IfNotNull(
o => o.ObjectProp.IfNotNull( p => p.StringProperty ) );
```
This simplifies these calls, but I'm not sure about checking this sort of extension method in - it does make the code a little easier to read, but at the cost of extending object. This would appear on everything, although I could put it in a specifically referenced namespace.
This example is a rather simple one, a slightly more complex one would be comparing two nullable object properties:
```
if( ( obj1 == null && obj2 == null ) ||
( obj1 != null && obj2 != null && obj1.Property == obj2.Property ) )
...
//becomes
if( obj1.NullCompare( obj2, (x,y) => x.Property == y.Property )
...
```
What are the pitfalls of using extensions in this way? Are other coders likely to be confused? Is this just abuse of extensions?
---
I guess what I really want here is a compiler/language extension:
```
propertyValue1 = myObject != null ? myObject.StringProperty : null;
//becomes
propertyValue1 = myObject?StringProperty;
```
This would make the complex case far easier:
```
propertyValue1 = myObject != null ?
(myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null
//becomes
propertyValue1 = myObject?ObjectProp?StringProperty;
```
This would only work for value types, but you could return nullable equivalents:
```
int? propertyValue2 = myObject?ObjectProp?IntProperty;
//or
int propertyValue3 = myObject?ObjectProp?IntProperty ?? 0;
``` | We independently came up with the exact same extension method name and implementation: [Null-propagating extension method](http://code.logos.com/blog/2008/01/nullpropagating_extension_meth.html). So we don't think it's confusing or an abuse of extension methods.
I would write your "multiple levels" example with chaining as follows:
```
propertyValue1 = myObject.IfNotNull(o => o.ObjectProp).IfNotNull(p => p.StringProperty);
```
There's a [now-closed bug on Microsoft Connect](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=192177) that proposed "?." as a new C# operator that would perform this null propagation. Mads Torgersen (from the C# language team) briefly explained why they won't implement it. |
123,111 | <p>I recently moved my website to a shared hosting solution at <a href="http://asmallorange.com" rel="nofollow noreferrer">asmallorange.com</a>, but I had to set my domain to use their provided nameservers in order for the site to properly resolve. I was determined to keep control of the domain's DNS but I could find no way to make my top level domain resolve to the shared location which was in the format of </p>
<pre><code>server.asmallorange.com/~username
</code></pre>
<p>So I know I'm missing something here, my question is this: </p>
<p><strong>What in their nameservers/DNS entry makes it possible for <em>server.sharedhost.com/~username</em> to serve as a top level domain? (ie. <a href="http://topleveldomain.com" rel="nofollow noreferrer">http://topleveldomain.com</a>)</strong></p>
| [
{
"answer_id": 123133,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 4,
"selected": true,
"text": "<p>Nothing. DNS simply maps topleveldomain.com to server.sharedhost.com. It's the webserver which looks at the <code>Host: topl... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339/"
] | I recently moved my website to a shared hosting solution at [asmallorange.com](http://asmallorange.com), but I had to set my domain to use their provided nameservers in order for the site to properly resolve. I was determined to keep control of the domain's DNS but I could find no way to make my top level domain resolve to the shared location which was in the format of
```
server.asmallorange.com/~username
```
So I know I'm missing something here, my question is this:
**What in their nameservers/DNS entry makes it possible for *server.sharedhost.com/~username* to serve as a top level domain? (ie. <http://topleveldomain.com>)** | Nothing. DNS simply maps topleveldomain.com to server.sharedhost.com. It's the webserver which looks at the `Host: topleveldomain.com` header and knows that's equivalent to server.sharedhost.com/~username. |
123,127 | <p>I am running my junit tests via ant and they are running substantially slower than via the IDE. My ant call is:</p>
<pre><code> <junit fork="yes" forkmode="once" printsummary="off">
<classpath refid="test.classpath"/>
<formatter type="brief" usefile="false"/>
<batchtest todir="${test.results.dir}/xml">
<formatter type="xml"/>
<fileset dir="src" includes="**/*Test.java" />
</batchtest>
</junit>
</code></pre>
<p>The same test that runs in near instantaneously in my IDE (0.067s) takes 4.632s when run through Ant. In the past, I've been able to speed up test problems like this by using the junit fork parameter but this doesn't seem to be helping in this case. What properties or parameters can I look at to speed up these tests?</p>
<p>More info:</p>
<p>I am using the reported time from the IDE vs. the time that the junit task outputs. This is not the sum total time reported at the end of the ant run.</p>
<p>So, bizarrely, this problem has resolved itself. What could have caused this problem? The system runs on a local disk so that is not the problem.</p>
| [
{
"answer_id": 123169,
"author": "Eric Asberry",
"author_id": 20437,
"author_profile": "https://Stackoverflow.com/users/20437",
"pm_score": 1,
"selected": false,
"text": "<p>Difficult to tell with that information. First thing I would do is look at the test results and determine if all ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6180/"
] | I am running my junit tests via ant and they are running substantially slower than via the IDE. My ant call is:
```
<junit fork="yes" forkmode="once" printsummary="off">
<classpath refid="test.classpath"/>
<formatter type="brief" usefile="false"/>
<batchtest todir="${test.results.dir}/xml">
<formatter type="xml"/>
<fileset dir="src" includes="**/*Test.java" />
</batchtest>
</junit>
```
The same test that runs in near instantaneously in my IDE (0.067s) takes 4.632s when run through Ant. In the past, I've been able to speed up test problems like this by using the junit fork parameter but this doesn't seem to be helping in this case. What properties or parameters can I look at to speed up these tests?
More info:
I am using the reported time from the IDE vs. the time that the junit task outputs. This is not the sum total time reported at the end of the ant run.
So, bizarrely, this problem has resolved itself. What could have caused this problem? The system runs on a local disk so that is not the problem. | Here's a blind guess: try increasing the maximum heap size available to the forked VM by using a nested `<jvmarg>` tag to set the `-Xmx` option. |