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 |
|---|---|---|---|---|---|---|
61,366 | <p>This question is slightly related to <a href="https://stackoverflow.com/questions/61354/how-to-get-entire-chain-of-exceptions-in-applicationthreadexception-event-handl">this question about exception handling</a>. The workaround I found there consists of rolling my own message loop.</p>
<p>So my Main method now looks basically like this:</p>
<pre><code>[STAThread]
static void Main() {
// this is needed so there'll actually an exception be thrown by
// Application.Run/Application.DoEvents, instead of the ThreadException
// event being raised.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form form = new MainForm();
form.Show();
// the loop is here to keep app running if non-fatal exception is caught.
do {
try {
Application.DoEvents();
Thread.Sleep(100);
}
catch (Exception ex) {
ExceptionHandler.ConsumeException(ex);
}
}
while (!form.IsDisposed);
}
</code></pre>
<p>What I'm wondering though, <strong>is this a safe/decent way to replace the more typical
'Application.Run(new MainForm());'</strong>, whether it's used for exception handling or for whatever else, or should I always stick to using Application.Run?</p>
<p>On another app that's in testing now a similar approach is used for both loading (splashscreen) and exception handling, and I don't think it has caused any troubles (yet :-))</p>
| [
{
"answer_id": 61393,
"author": "ima",
"author_id": 5733,
"author_profile": "https://Stackoverflow.com/users/5733",
"pm_score": 2,
"selected": false,
"text": "<p>Pitfall 1: </p>\n\n<pre><code>Thread.Sleep(100);\n</code></pre>\n\n<p>Never. Use WaitMessage().</p>\n\n<p>Otherwise, it is pos... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5422/"
] | This question is slightly related to [this question about exception handling](https://stackoverflow.com/questions/61354/how-to-get-entire-chain-of-exceptions-in-applicationthreadexception-event-handl). The workaround I found there consists of rolling my own message loop.
So my Main method now looks basically like this:
```
[STAThread]
static void Main() {
// this is needed so there'll actually an exception be thrown by
// Application.Run/Application.DoEvents, instead of the ThreadException
// event being raised.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form form = new MainForm();
form.Show();
// the loop is here to keep app running if non-fatal exception is caught.
do {
try {
Application.DoEvents();
Thread.Sleep(100);
}
catch (Exception ex) {
ExceptionHandler.ConsumeException(ex);
}
}
while (!form.IsDisposed);
}
```
What I'm wondering though, **is this a safe/decent way to replace the more typical
'Application.Run(new MainForm());'**, whether it's used for exception handling or for whatever else, or should I always stick to using Application.Run?
On another app that's in testing now a similar approach is used for both loading (splashscreen) and exception handling, and I don't think it has caused any troubles (yet :-)) | Pitfall 1:
```
Thread.Sleep(100);
```
Never. Use WaitMessage().
Otherwise, it is possible roll out your own message loop, but in your scenario it seems somewhat pointless.
You may also want to examine Application.Run() code (with .Net Reflector, for instance). |
61,405 | <p>I'm about to start on a large Qt application, which is made up of smaller components (groups of classes that work together). For example, there might be a dialog that is used in the project, but should be developed on its own before being integrated into the project. Instead of working on it in another folder somewhere and then copying it into the main project folder, can I create a sub-folder which is dedicated to that dialog, and then somehow incorporate it into the main project?</p>
| [
{
"answer_id": 61423,
"author": "kokos",
"author_id": 1065,
"author_profile": "https://Stackoverflow.com/users/1065",
"pm_score": 0,
"selected": false,
"text": "<p>For Qt on Windows you can create DLLs for every subproject you want. No problem with using them from the main project (exe) ... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1585/"
] | I'm about to start on a large Qt application, which is made up of smaller components (groups of classes that work together). For example, there might be a dialog that is used in the project, but should be developed on its own before being integrated into the project. Instead of working on it in another folder somewhere and then copying it into the main project folder, can I create a sub-folder which is dedicated to that dialog, and then somehow incorporate it into the main project? | Here is what I would do. Let's say I want the following folder hierarchy :
```
/MyWholeApp
```
will contain the files for the whole application.
```
/MyWholeApp/DummyDlg/
```
will contain the files for the standalone dialogbox which will be eventually part of the whole application.
I would develop the standalone dialog box and the related classes. I would create a Qt-project file which is going to be included. It will contain only the forms and files which will eventually be part of the whole application.
File DummyDlg.pri, in /MyWholeApp/DummyDlg/ :
```
# Input
FORMS += dummydlg.ui
HEADERS += dummydlg.h
SOURCES += dummydlg.cpp
```
The above example is very simple. You could add other classes if needed.
To develop the standalone dialog box, I would then create a Qt project file dedicated to this dialog :
File DummyDlg.pro, in /MyWholeApp/DummyDlg/ :
```
TEMPLATE = app
DEPENDPATH += .
INCLUDEPATH += .
include(DummyDlg.pri)
# Input
SOURCES += main.cpp
```
As you can see, this PRO file is including the PRI file created above, and is adding an additional file (main.cpp) which will contain the basic code for running the dialog box as a standalone :
```
#include <QApplication>
#include "dummydlg.h"
int main(int argc, char* argv[])
{
QApplication MyApp(argc, argv);
DummyDlg MyDlg;
MyDlg.show();
return MyApp.exec();
}
```
Then, to include this dialog box to the whole application you need to create a Qt-Project file :
file WholeApp.pro, in /MyWholeApp/ :
```
TEMPLATE = app
DEPENDPATH += . DummyDlg
INCLUDEPATH += . DummyDlg
include(DummyDlg/DummyDlg.pri)
# Input
FORMS += OtherDlg.ui
HEADERS += OtherDlg.h
SOURCES += OtherDlg.cpp WholeApp.cpp
```
Of course, the Qt-Project file above is very simplistic, but shows how I included the stand-alone dialog box. |
61,418 | <p>I have a function that gives me the following warning:</p>
<blockquote>
<p>[DCC Warning] filename.pas(6939): W1035 Return value of function 'function' might be undefined</p>
</blockquote>
<p>The function, however, is clean, small, and does have a known, expected, return value. The first statement in the function is:</p>
<pre><code>Result := '';
</code></pre>
<p>and there is no local variable or parameter called <code>Result</code> either.</p>
<p>Is there any kind of pragma-like directive I can surround this method with to remove this warning? This is Delphi 2007.</p>
<p>Unfortunately, the help system on this Delphi installation is not working, therefore i can't pop up the help for that warning right now.</p>
<p>Anyone know off the top of their head what i can do?</p>
| [
{
"answer_id": 61424,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 1,
"selected": false,
"text": "<p>There seems to be some sort of bug in Delphi. Read this post, the last comment links to other bug-reports that may be the one... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267/"
] | I have a function that gives me the following warning:
>
> [DCC Warning] filename.pas(6939): W1035 Return value of function 'function' might be undefined
>
>
>
The function, however, is clean, small, and does have a known, expected, return value. The first statement in the function is:
```
Result := '';
```
and there is no local variable or parameter called `Result` either.
Is there any kind of pragma-like directive I can surround this method with to remove this warning? This is Delphi 2007.
Unfortunately, the help system on this Delphi installation is not working, therefore i can't pop up the help for that warning right now.
Anyone know off the top of their head what i can do? | Are you sure you have done everything to solve the warning? Maybe you could post the code for us to look at?
You can turn off the warning locally this way:
```
{$WARN NO_RETVAL OFF}
function func(...): string;
begin
...
end;
{$WARN NO_RETVAL ON}
``` |
61,421 | <p>I'm making an example for someone who hasn't yet realized that controls like <code>ListBox</code> don't have to contain strings; he had been storing formatted strings and jumping through complicated parsing hoops to get the data back out of the <code>ListBox</code> and I'd like to show him there's a better way.</p>
<p>I noticed that if I have an object stored in the <code>ListBox</code> then update a value that affects <code>ToString</code>, the <code>ListBox</code> does not update itself. I've tried calling <code>Refresh</code> and <code>Update</code> on the control, but neither works. Here's the code of the example I'm using, it requires you to drag a listbox and a button onto the form:</p>
<pre><code>Public Class Form1
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
For i As Integer = 1 To 3
Dim tempInfo As New NumberInfo()
tempInfo.Count = i
tempInfo.Number = i * 100
ListBox1.Items.Add(tempInfo)
Next
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For Each objItem As Object In ListBox1.Items
Dim info As NumberInfo = DirectCast(objItem, NumberInfo)
info.Count += 1
Next
End Sub
End Class
Public Class NumberInfo
Public Count As Integer
Public Number As Integer
Public Overrides Function ToString() As String
Return String.Format("{0}, {1}", Count, Number)
End Function
End Class</code></pre>
<p>I thought that perhaps the problem was using fields and tried implementing <em>INotifyPropertyChanged</em>, but this had no effect. (The reason I'm using fields is because it's an example and I don't feel like adding a few dozen lines that have nothing to do with the topic I'm demonstrating.)</p>
<p>Honestly I've never tried updating items in place like this before; in the past I've always been adding/removing items, not editing them. So I've never noticed that I don't know how to make this work.</p>
<p>So what am I missing?</p>
| [
{
"answer_id": 61425,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 3,
"selected": false,
"text": "<p>Use the datasource property and a BindingSource object in between the datasource and the datasource property of the li... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2547/"
] | I'm making an example for someone who hasn't yet realized that controls like `ListBox` don't have to contain strings; he had been storing formatted strings and jumping through complicated parsing hoops to get the data back out of the `ListBox` and I'd like to show him there's a better way.
I noticed that if I have an object stored in the `ListBox` then update a value that affects `ToString`, the `ListBox` does not update itself. I've tried calling `Refresh` and `Update` on the control, but neither works. Here's the code of the example I'm using, it requires you to drag a listbox and a button onto the form:
```
Public Class Form1
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
For i As Integer = 1 To 3
Dim tempInfo As New NumberInfo()
tempInfo.Count = i
tempInfo.Number = i * 100
ListBox1.Items.Add(tempInfo)
Next
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For Each objItem As Object In ListBox1.Items
Dim info As NumberInfo = DirectCast(objItem, NumberInfo)
info.Count += 1
Next
End Sub
End Class
Public Class NumberInfo
Public Count As Integer
Public Number As Integer
Public Overrides Function ToString() As String
Return String.Format("{0}, {1}", Count, Number)
End Function
End Class
```
I thought that perhaps the problem was using fields and tried implementing *INotifyPropertyChanged*, but this had no effect. (The reason I'm using fields is because it's an example and I don't feel like adding a few dozen lines that have nothing to do with the topic I'm demonstrating.)
Honestly I've never tried updating items in place like this before; in the past I've always been adding/removing items, not editing them. So I've never noticed that I don't know how to make this work.
So what am I missing? | BindingList handles updating the bindings by itself.
```
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace TestBindingList
{
public class Employee
{
public string Name { get; set; }
public int Id { get; set; }
}
public partial class Form1 : Form
{
private BindingList<Employee> _employees;
private ListBox lstEmployees;
private TextBox txtId;
private TextBox txtName;
private Button btnRemove;
public Form1()
{
InitializeComponent();
FlowLayoutPanel layout = new FlowLayoutPanel();
layout.Dock = DockStyle.Fill;
Controls.Add(layout);
lstEmployees = new ListBox();
layout.Controls.Add(lstEmployees);
txtId = new TextBox();
layout.Controls.Add(txtId);
txtName = new TextBox();
layout.Controls.Add(txtName);
btnRemove = new Button();
btnRemove.Click += btnRemove_Click;
btnRemove.Text = "Remove";
layout.Controls.Add(btnRemove);
Load+=new EventHandler(Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
_employees = new BindingList<Employee>();
for (int i = 0; i < 10; i++)
{
_employees.Add(new Employee() { Id = i, Name = "Employee " + i.ToString() });
}
lstEmployees.DisplayMember = "Name";
lstEmployees.DataSource = _employees;
txtId.DataBindings.Add("Text", _employees, "Id");
txtName.DataBindings.Add("Text", _employees, "Name");
}
private void btnRemove_Click(object sender, EventArgs e)
{
Employee selectedEmployee = (Employee)lstEmployees.SelectedItem;
if (selectedEmployee != null)
{
_employees.Remove(selectedEmployee);
}
}
}
}
``` |
61,443 | <p>I have a counter in hardware that I can observe for timing considerations. It counts miliseconds and is stored in a 16 bit unsigned value. How do I safely check if a timer value has passed a certain time and safely handle the inevitable rollover:</p>
<pre><code>//this is a bit contrived, but it illustrates what I'm trying to do
const uint16_t print_interval = 5000; // milliseconds
static uint16_t last_print_time;
if(ms_timer() - last_print_time > print_interval)
{
printf("Fault!\n");
last_print_time = ms_timer();
}
</code></pre>
<p>This code will fail when ms_timer overflows to 0.</p>
| [
{
"answer_id": 61444,
"author": "Jason Punyon",
"author_id": 6212,
"author_profile": "https://Stackoverflow.com/users/6212",
"pm_score": 1,
"selected": false,
"text": "<p>Just check if ms_timer < last_print_time and if so add 2^16 no?</p>\n\n<p>Edit: You also need to up to an uint32 ... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] | I have a counter in hardware that I can observe for timing considerations. It counts miliseconds and is stored in a 16 bit unsigned value. How do I safely check if a timer value has passed a certain time and safely handle the inevitable rollover:
```
//this is a bit contrived, but it illustrates what I'm trying to do
const uint16_t print_interval = 5000; // milliseconds
static uint16_t last_print_time;
if(ms_timer() - last_print_time > print_interval)
{
printf("Fault!\n");
last_print_time = ms_timer();
}
```
This code will fail when ms\_timer overflows to 0. | You don't actually need to do anything here. The original code listed in your question will work fine, assuming `ms_timer()` returns a value of type uint16\_t.
(Also assuming that the timer doesn't overflow twice between checks...)
To convince yourself this is the case, try the following test:
```
uint16_t t1 = 0xFFF0;
uint16_t t2 = 0x0010;
uint16_t dt = t2 - t1;
```
`dt` will equal `0x20`. |
61,446 | <p>Particularly, what is the best snippets package out there?</p>
<p>Features:</p>
<ul>
<li>easy to define new snippets (plain text, custom input with defaults)</li>
<li>simple navigation between predefined positions in the snippet</li>
<li>multiple insertion of the same custom input</li>
<li>accepts currently selected text as a custom input</li>
<li><em>cross-platform</em> (Windows, Linux)</li>
<li>dynamically evaluated expressions (embedded code) written in a concise programming language (Perl, Python, Ruby are preferred)</li>
<li>nicely coexists with others packages in Emacs</li>
</ul>
<p>Example of code template, a simple <code>for</code> loop in C:</p>
<pre><code>for (int i = 0; i < %N%; ++i) {
_
}
</code></pre>
<p>It is a lot of typing for such common code. I want to invoke a code template or snippet which inserts
that boilerplate code for me. Additionally it stops (on TAB or other keystroke) at <code>%N%</code> (my input replaces it) and final position of the cursor is <code>_</code>. </p>
| [
{
"answer_id": 61447,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"http://manual.macromates.com/en/snippets\" rel=\"nofollow noreferrer\">TextMate's snippets</a> is the most closest ma... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4279/"
] | Particularly, what is the best snippets package out there?
Features:
* easy to define new snippets (plain text, custom input with defaults)
* simple navigation between predefined positions in the snippet
* multiple insertion of the same custom input
* accepts currently selected text as a custom input
* *cross-platform* (Windows, Linux)
* dynamically evaluated expressions (embedded code) written in a concise programming language (Perl, Python, Ruby are preferred)
* nicely coexists with others packages in Emacs
Example of code template, a simple `for` loop in C:
```
for (int i = 0; i < %N%; ++i) {
_
}
```
It is a lot of typing for such common code. I want to invoke a code template or snippet which inserts
that boilerplate code for me. Additionally it stops (on TAB or other keystroke) at `%N%` (my input replaces it) and final position of the cursor is `_`. | [TextMate's snippets](http://manual.macromates.com/en/snippets) is the most closest match but it is not a cross-platform solution and not for Emacs.
The second closest thing is [YASnippet](http://github.com/joaotavora/yasnippet/ "Yet Another Snippet Package for Emacs") ([screencast](http://www.youtube.com/watch?v=vOj7btx3ATg "yasnippet screencast") shows the main capabilities). But it interferes with `hippie-expand` package in my setup and the embedded language is EmacsLisp which I'm not comfortable with outside `.emacs`.
**EDIT**: Posted my answer here to allow voting on `YASnippet`. |
61,451 | <p>Does Django have any template tags to generate common HTML markup? For example, I know that I can get a url using</p>
<pre><code>{% url mapper.views.foo %}
</code></pre>
<p>But that only gives me the URL and not the HTML code to create the link. Does Django have anything similar to Rails' link_to helper? I found <a href="http://code.google.com/p/django-helpers/" rel="noreferrer">django-helpers</a> but since this is a common thing I thought Django would have something built-in.</p>
| [
{
"answer_id": 61457,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 2,
"selected": false,
"text": "<p>it doesnt look like they're built in but here's a couple snippets. it looks like it'd be pretty easy to create these h... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/796/"
] | Does Django have any template tags to generate common HTML markup? For example, I know that I can get a url using
```
{% url mapper.views.foo %}
```
But that only gives me the URL and not the HTML code to create the link. Does Django have anything similar to Rails' link\_to helper? I found [django-helpers](http://code.google.com/p/django-helpers/) but since this is a common thing I thought Django would have something built-in. | No it doesn't.
[James Bennett](http://www.b-list.org/) answered a [similar question](http://www.b-list.org/weblog/2006/jul/02/django-and-ajax/) a while back, regarding Rails' built-in JavaScript helpers.
It's *really* unlikely that Django will ever have 'helper' functionality built-in. The reason, if I understand correctly, has to do with Django's core philosophy of keeping things [loosely coupled](http://docs.djangoproject.com/en/dev/misc/design-philosophies/#id1). Having that kind of helper functionality built-in leads to coupling Django with a specific JavaScript library or (in your case) html document type.
EG. What happens if/when HTML 5 is finally implemented and Django is generating HTML 4 or XHTML markup?
Having said that, Django's template framework is really flexible, and it wouldn't be terribly difficult to [write your own tags/filters](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/) that did what you wanted. I'm mostly a designer myself, and I've been able to put together a couple custom tags that worked like a charm. |
61,456 | <p>After trying to avoid JavaScript for years, Iv started using Query for <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/" rel="nofollow noreferrer">validation</a> in MVC asp.net, as there does not seem to be an official way of doing validation, Iv been surprised how good jQuery is. </p>
<p>Firstly is there a way to get intellisense working for jQuery and its validation plugin, so that i don have to learn the api?</p>
<p>Secondly how do I create a validation summary for this, it currently appends the error to the right of the text box.:</p>
<pre><code><script type="text/javascript">
$().ready(function() {
$("#CreateLog").validate({
rules: {
UserName: {
required: true,
minLength: 2,
}
},
messages: {
UserName: {
required: "Please enter a username",
minLength: "Your username must consist of at least 2 characters",
}
}
});
});
</script>
<form id="CreateLog" action="Create" method="post" />
<label>UserName</label><br />
<%=Html.TextBox("UserName")%>
<br />
<div class="error"> </div>
<input type=submit value=Save />
</form>
</code></pre>
<p>I tried adding this to the script:</p>
<pre><code> errorLabelContainer: $("#CreateLog div.error")
</code></pre>
<p>and this to the html:</p>
<pre><code> <div class="error"> </div>
</code></pre>
<p>But this didn't work.</p>
| [
{
"answer_id": 61460,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 2,
"selected": false,
"text": "<p>There is a Visual Studio 2008 hotfix for <a href=\"http://weblogs.asp.net/bradvincent/archive/2008/04/28/better-jquer... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] | After trying to avoid JavaScript for years, Iv started using Query for [validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) in MVC asp.net, as there does not seem to be an official way of doing validation, Iv been surprised how good jQuery is.
Firstly is there a way to get intellisense working for jQuery and its validation plugin, so that i don have to learn the api?
Secondly how do I create a validation summary for this, it currently appends the error to the right of the text box.:
```
<script type="text/javascript">
$().ready(function() {
$("#CreateLog").validate({
rules: {
UserName: {
required: true,
minLength: 2,
}
},
messages: {
UserName: {
required: "Please enter a username",
minLength: "Your username must consist of at least 2 characters",
}
}
});
});
</script>
<form id="CreateLog" action="Create" method="post" />
<label>UserName</label><br />
<%=Html.TextBox("UserName")%>
<br />
<div class="error"> </div>
<input type=submit value=Save />
</form>
```
I tried adding this to the script:
```
errorLabelContainer: $("#CreateLog div.error")
```
and this to the html:
```
<div class="error"> </div>
```
But this didn't work. | Try specifying both a wrapper and a label container in your options. I also added `display:none;` to the style of error-container to let jQuery decide when to show it.
```js
$().ready(function() {
$("#CreateLog").validate({
errorLabelContainer: $("ul", $('div.error-container')),
wrapper: 'li',
rules: {
UserName: {
required: true,
minLength: 2,
}
},
messages: {
UserName: {
required: "Please enter a username",
minLength: "Your username must consist of at least 2 characters"
}
}
});
});
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="error-container">
<ul></ul>
</div>
<form id="CreateLog" action="Create" method="post" />
<label>UserName</label><br />
<%=Html.TextBox("UserName")%>
<br />
<input type=submit value=Save />
</form>
```
That should work. |
61,480 | <p>In the past we declared properties like this:</p>
<pre><code>public class MyClass
{
private int _age;
public int Age
{
get{ return _age; }
set{ _age = value; }
}
}
</code></pre>
<p>Now we can do:</p>
<pre><code>public class MyClass
{
public int Age {get; set;}
}
</code></pre>
<p>My question is, how can I access the private variable that is created automatically using this notation? </p>
<p>I would rather access the private variable and not the public accessor 'Age'. Is there a default notation to access the private variable, or it is just not possible?</p>
| [
{
"answer_id": 61484,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 2,
"selected": false,
"text": "<p>You can't, it's a language feature as opposed to a IDE feature. To be honest i'd prefer then IDE to add the private va... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
] | In the past we declared properties like this:
```
public class MyClass
{
private int _age;
public int Age
{
get{ return _age; }
set{ _age = value; }
}
}
```
Now we can do:
```
public class MyClass
{
public int Age {get; set;}
}
```
My question is, how can I access the private variable that is created automatically using this notation?
I would rather access the private variable and not the public accessor 'Age'. Is there a default notation to access the private variable, or it is just not possible? | The aim of the new automatic properties is to reduce the amount of boilerplate code you need to write when you just have a simple property that doesn't need any special logic in the get or the set.
If you want to access the private member that these properties use, that's usually for a few reasons:
* You need to more than just a simple get/set - in this case, you should just avoid using automatic properties for this member.
* You want to avoid the performance hit of going through the get or set and just use the member directly - in this case, I'd be surprised if there really was a performance hit. The simple get/set members are very very easy to inline, and in my (admittedly limited) testing I haven't found a difference between using the automatic properties and accessing the member directly.
* You only want to have public read access (i.e. just a 'get') and the class write to the member directly - in this case, you can use a private set in your automatic property. i.e.
```
public class MyClass
{
public int Age {get; private set;}
}
```
This usually covers most the reasons for wanting to directly get to the backing field used by the automatic properties. |
61,486 | <p>I need to figure out what div is visible out of four possible divs using jQuery. Only one of those div's will be visible at any given time.</p>
<p>This is what I have that works so far:</p>
<pre><code>$("#FeatureImage1:visible, #FeatureImage2:visible, #FeatureImage3:visible, #FeatureImage4:visible").attr("id");
</code></pre>
<p>Is there a way to refactor this? Is there an easier way to figure this out?</p>
| [
{
"answer_id": 61500,
"author": "Gilean",
"author_id": 6305,
"author_profile": "https://Stackoverflow.com/users/6305",
"pm_score": 5,
"selected": true,
"text": "<p>Assign the same class to each div then:</p>\n\n<pre><code>$(\"div.myClass:visible\").attr(\"id\");\n</code></pre>\n"
},
... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/648/"
] | I need to figure out what div is visible out of four possible divs using jQuery. Only one of those div's will be visible at any given time.
This is what I have that works so far:
```
$("#FeatureImage1:visible, #FeatureImage2:visible, #FeatureImage3:visible, #FeatureImage4:visible").attr("id");
```
Is there a way to refactor this? Is there an easier way to figure this out? | Assign the same class to each div then:
```
$("div.myClass:visible").attr("id");
``` |
61,517 | <p>Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:</p>
<pre><code>>>> class Foo:
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }
</code></pre>
<p><strong>NOTE:</strong> It should not include methods. Only fields.</p>
| [
{
"answer_id": 61522,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 6,
"selected": false,
"text": "<p>The <code>dir</code> builtin will give you all the object's attributes, including special methods like <code>__str__</code>, <... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148/"
] | Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:
```
>>> class Foo:
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }
```
**NOTE:** It should not include methods. Only fields. | Note that best practice in Python 2.7 is to use *[new-style](https://www.python.org/doc/newstyle/)* classes (not needed with Python 3), i.e.
```
class Foo(object):
...
```
Also, there's a difference between an 'object' and a 'class'. To build a dictionary from an arbitrary *object*, it's sufficient to use `__dict__`. Usually, you'll declare your methods at class level and your attributes at instance level, so `__dict__` should be fine. For example:
```python
>>> class A(object):
... def __init__(self):
... self.b = 1
... self.c = 2
... def do_nothing(self):
... pass
...
>>> a = A()
>>> a.__dict__
{'c': 2, 'b': 1}
```
A better approach (suggested by [robert](https://stackoverflow.com/users/409638/robert) in comments) is the builtin [`vars`](https://docs.python.org/3/library/functions.html#vars) function:
```python
>>> vars(a)
{'c': 2, 'b': 1}
```
Alternatively, depending on what you want to do, it might be nice to inherit from `dict`. Then your class is *already* a dictionary, and if you want you can override `getattr` and/or `setattr` to call through and set the dict. For example:
```
class Foo(dict):
def __init__(self):
pass
def __getattr__(self, attr):
return self[attr]
# etc...
``` |
61,552 | <p><a href="http://www.stackoverflow.com/questions/61088/hidden-features-of-javascript#61118">Alan Storm's comments</a> in response to my answer regarding the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with" rel="noreferrer"><code>with</code> statement</a> got me thinking. I've seldom found a reason to use this particular language feature, and had never given much thought to how it might cause trouble. Now, I'm curious as to how I might make effective use of <code>with</code>, while avoiding its pitfalls.</p>
<p>Where have you found the <code>with</code> statement useful?</p>
| [
{
"answer_id": 61566,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 4,
"selected": false,
"text": "<p>Visual Basic.NET has a similar <code>With</code> statement. One of the more common ways I use it is to quickly set a ... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/811/"
] | [Alan Storm's comments](http://www.stackoverflow.com/questions/61088/hidden-features-of-javascript#61118) in response to my answer regarding the [`with` statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with) got me thinking. I've seldom found a reason to use this particular language feature, and had never given much thought to how it might cause trouble. Now, I'm curious as to how I might make effective use of `with`, while avoiding its pitfalls.
Where have you found the `with` statement useful? | Another use occurred to me today, so I searched the web excitedly and found an existing mention of it: [Defining Variables inside Block Scope](http://web.archive.org/web/20090111183416/http://www.hedgerwow.com/360/dhtml/js_block_scope.html).
### Background
JavaScript, in spite of its superficial resemblance to C and C++, does not scope variables to the block they are defined in:
```
var name = "Joe";
if ( true )
{
var name = "Jack";
}
// name now contains "Jack"
```
Declaring a closure in a loop is a common task where this can lead to errors:
```
for (var i=0; i<3; ++i)
{
var num = i;
setTimeout(function() { alert(num); }, 10);
}
```
Because the for loop does not introduce a new scope, the same `num` - with a value of `2` - will be shared by all three functions.
### A new scope: `let` and `with`
With the introduction of the `let` statement in [ES6](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let), it becomes easy to introduce a new scope when necessary to avoid these problems:
```
// variables introduced in this statement
// are scoped to each iteration of the loop
for (let i=0; i<3; ++i)
{
setTimeout(function() { alert(i); }, 10);
}
```
Or even:
```
for (var i=0; i<3; ++i)
{
// variables introduced in this statement
// are scoped to the block containing it.
let num = i;
setTimeout(function() { alert(num); }, 10);
}
```
Until ES6 is universally available, this use remains limited to the newest browsers and developers willing to use transpilers. However, we can easily simulate this behavior using `with`:
```
for (var i=0; i<3; ++i)
{
// object members introduced in this statement
// are scoped to the block following it.
with ({num: i})
{
setTimeout(function() { alert(num); }, 10);
}
}
```
The loop now works as intended, creating three separate variables with values from 0 to 2. Note that variables declared *within* the block are not scoped to it, unlike the behavior of blocks in C++ (in C, variables must be declared at the start of a block, so in a way it is similar). This behavior is actually quite similar to a [`let` block syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#let_blocks) introduced in earlier versions of Mozilla browsers, but not widely adopted elsewhere. |
61,604 | <p>Do you often see in API documentation (as in 'javadoc of public functions' for example) the description of "value limits" as well as the classic documentation ?</p>
<p><strong>Note:</strong> I am not talking about <a href="https://stackoverflow.com/questions/20922/do-you-comment-your-code">comments within the code</a></p>
<p>By "value limits", I mean:</p>
<ul>
<li>does a parameter can support a null value (or an empty String, or...) ?</li>
<li>does a 'return value' can be null or is guaranteed to never be null (or can be "empty", or...) ?</li>
</ul>
<p><strong>Sample:</strong></p>
<p>What I often see (without having access to source code) is:</p>
<pre><code>/**
* Get all readers name for this current Report. <br />
* <b>Warning</b>The Report must have been published first.
* @param aReaderNameRegexp filter in order to return only reader matching the regexp
* @return array of reader names
*/
String[] getReaderNames(final String aReaderNameRegexp);
</code></pre>
<p>What I <em>like to see</em> would be:</p>
<pre><code>/**
* Get all readers name for this current Report. <br />
* <b>Warning</b>The Report must have been published first.
* @param aReaderNameRegexp filter in order to return only reader matching the regexp
* (can be null or empty)
* @return array of reader names
* (null if Report has not yet been published,
* empty array if no reader match criteria,
* reader names array matching regexp, or all readers if regexp is null or empty)
*/
String[] getReaderNames(final String aReaderNameRegexp);
</code></pre>
<p><strong>My point is:</strong></p>
<p>When I use a library with a getReaderNames() function in it, I often do not even need to read the API documentation to guess what it does. But I need to be sure <em>how to use it</em>.</p>
<p>My only concern when I want to use this function is: what should I expect in term of parameters and return values ? That is all I need to know to safely setup my parameters and safely test the return value, yet I almost never see that kind of information in API documentation...</p>
<p><strong>Edit:</strong> </p>
<p>This can influence the usage or not for <em><a href="https://stackoverflow.com/questions/27578#73355">checked or unchecked exceptions</a></em>.</p>
<p>What do you think ? value limits and API, do they belong together or not ?</p>
| [
{
"answer_id": 61608,
"author": "Fire Lancer",
"author_id": 6266,
"author_profile": "https://Stackoverflow.com/users/6266",
"pm_score": 1,
"selected": false,
"text": "<p>I think they do, and have always placed comments in the header files (c++) arcordingly.</p>\n\n<p>In addition to valid... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6309/"
] | Do you often see in API documentation (as in 'javadoc of public functions' for example) the description of "value limits" as well as the classic documentation ?
**Note:** I am not talking about [comments within the code](https://stackoverflow.com/questions/20922/do-you-comment-your-code)
By "value limits", I mean:
* does a parameter can support a null value (or an empty String, or...) ?
* does a 'return value' can be null or is guaranteed to never be null (or can be "empty", or...) ?
**Sample:**
What I often see (without having access to source code) is:
```
/**
* Get all readers name for this current Report. <br />
* <b>Warning</b>The Report must have been published first.
* @param aReaderNameRegexp filter in order to return only reader matching the regexp
* @return array of reader names
*/
String[] getReaderNames(final String aReaderNameRegexp);
```
What I *like to see* would be:
```
/**
* Get all readers name for this current Report. <br />
* <b>Warning</b>The Report must have been published first.
* @param aReaderNameRegexp filter in order to return only reader matching the regexp
* (can be null or empty)
* @return array of reader names
* (null if Report has not yet been published,
* empty array if no reader match criteria,
* reader names array matching regexp, or all readers if regexp is null or empty)
*/
String[] getReaderNames(final String aReaderNameRegexp);
```
**My point is:**
When I use a library with a getReaderNames() function in it, I often do not even need to read the API documentation to guess what it does. But I need to be sure *how to use it*.
My only concern when I want to use this function is: what should I expect in term of parameters and return values ? That is all I need to know to safely setup my parameters and safely test the return value, yet I almost never see that kind of information in API documentation...
**Edit:**
This can influence the usage or not for *[checked or unchecked exceptions](https://stackoverflow.com/questions/27578#73355)*.
What do you think ? value limits and API, do they belong together or not ? | I think they **can** belong together but don't necessarily **have** to belong together. In your scenario, it seems like it makes sense that the limits are documented in such a way that they appear in the generated API documentation and intellisense (if the language/IDE support it).
I think it does depend on the language as well. For example, Ada has a native data type that is a "restricted integer", where you define an integer variable and explicitly indicate that it will only (and always) be within a certain numeric range. In that case, the datatype itself indicates the restriction. It should still be visible and discoverable through the API documentation and intellisense, but wouldn't be something that a developer has to specify in the comments.
However, languages like Java and C# don't have this type of restricted integer, so the developer would have to specify it in the comments if it were information that should become part of the public documentation. |
61,605 | <p>In python, you can have a function return multiple values. Here's a contrived example:</p>
<pre><code>def divide(x, y):
quotient = x/y
remainder = x % y
return quotient, remainder
(q, r) = divide(22, 7)
</code></pre>
<p>This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value. Let's have X return that value also").</p>
<p>When should you draw the line and define a different method? </p>
| [
{
"answer_id": 61629,
"author": "Jason Etheridge",
"author_id": 2193,
"author_profile": "https://Stackoverflow.com/users/2193",
"pm_score": 5,
"selected": false,
"text": "<p>Firstly, note that Python allows for the following (no need for the parenthesis):</p>\n\n<pre><code>q, r = divide(... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | In python, you can have a function return multiple values. Here's a contrived example:
```
def divide(x, y):
quotient = x/y
remainder = x % y
return quotient, remainder
(q, r) = divide(22, 7)
```
This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value. Let's have X return that value also").
When should you draw the line and define a different method? | Absolutely (for the example you provided).
### Tuples are first class citizens in Python
There is a builtin function [`divmod()`](https://docs.python.org/3/library/functions.html#divmod) that does exactly that.
```
q, r = divmod(x, y) # ((x - x%y)/y, x%y) Invariant: div*y + mod == x
```
There are other examples: `zip`, `enumerate`, `dict.items`.
```
for i, e in enumerate([1, 3, 3]):
print "index=%d, element=%s" % (i, e)
# reverse keys and values in a dictionary
d = dict((v, k) for k, v in adict.items()) # or
d = dict(zip(adict.values(), adict.keys()))
```
BTW, parentheses are not necessary most of the time.
Citation from [Python Library Reference](https://docs.python.org/3/library/stdtypes.html?highlight=type%20seq#tuple):
>
> Tuples may be constructed in a number of ways:
>
>
> * Using a pair of parentheses to denote the empty tuple: ()
> * Using a trailing comma for a singleton tuple: a, or (a,)
> * Separating items with commas: a, b, c or (a, b, c)
> * Using the tuple() built-in: tuple() or tuple(iterable)
>
>
>
### Functions should serve single purpose
Therefore they should return a single object. In your case this object is a tuple. Consider tuple as an ad-hoc compound data structure. There are languages where almost every single function returns multiple values (list in Lisp).
Sometimes it is sufficient to return `(x, y)` instead of `Point(x, y)`.
### Named tuples
With the introduction of named tuples in Python 2.6 it is preferable in many cases to return named tuples instead of plain tuples.
```
>>> import collections
>>> Point = collections.namedtuple('Point', 'x y')
>>> x, y = Point(0, 1)
>>> p = Point(x, y)
>>> x, y, p
(0, 1, Point(x=0, y=1))
>>> p.x, p.y, p[0], p[1]
(0, 1, 0, 1)
>>> for i in p:
... print(i)
...
0
1
``` |
61,638 | <p>I was wondering if anyone could suggest a utility library that has useful functions for handling dates in ASP.NET easily taking away some of the leg work you normally have to do when handling dates?</p>
<p>Subsonic Sugar has some really nice functions:</p>
<p><a href="http://subsonichelp.com/html/1413bafa-b5aa-99aa-0478-10875abe82ec.htm" rel="nofollow noreferrer">http://subsonichelp.com/html/1413bafa-b5aa-99aa-0478-10875abe82ec.htm</a>
<a href="http://subsonicproject.googlecode.com/svn/trunk/SubSonic/Sugar/" rel="nofollow noreferrer">http://subsonicproject.googlecode.com/svn/trunk/SubSonic/Sugar/</a></p>
<p>Is there anything better out there?</p>
<p>I was wanting to work out the start(mon) and end(sun) dates of the last 5 weeks.</p>
<p>I was thinking something like this:</p>
<pre><code> DateTime Now = DateTime.Now;
while(Now.DayOfWeek != DayOfWeek.Monday)
{
Now.AddDays(-1);
}
for(int i=0; i<5;i++)
{
AddToDatesList(Now, Now.AddDays(7));
Now.AddDays(-7);
}
</code></pre>
<p>but this seems crappy? Plus this is not exactly what i want because i need the time of that start date to be <code>00:00:00</code> and the time of the end date to be <code>23:59:59</code></p>
| [
{
"answer_id": 61645,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "<p>Is there a specific problem you are trying to handle with dates? If the existing date API in .NET can handle your proble... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] | I was wondering if anyone could suggest a utility library that has useful functions for handling dates in ASP.NET easily taking away some of the leg work you normally have to do when handling dates?
Subsonic Sugar has some really nice functions:
<http://subsonichelp.com/html/1413bafa-b5aa-99aa-0478-10875abe82ec.htm>
<http://subsonicproject.googlecode.com/svn/trunk/SubSonic/Sugar/>
Is there anything better out there?
I was wanting to work out the start(mon) and end(sun) dates of the last 5 weeks.
I was thinking something like this:
```
DateTime Now = DateTime.Now;
while(Now.DayOfWeek != DayOfWeek.Monday)
{
Now.AddDays(-1);
}
for(int i=0; i<5;i++)
{
AddToDatesList(Now, Now.AddDays(7));
Now.AddDays(-7);
}
```
but this seems crappy? Plus this is not exactly what i want because i need the time of that start date to be `00:00:00` and the time of the end date to be `23:59:59` | Is there a specific problem you are trying to handle with dates? If the existing date API in .NET can handle your problem cleanly, I see no reason to consider a 3rd party library to do it. When I was in .NET, we had to deal with dates quite a bit, and the standard libraries provided a fair amount of functionality to us. |
61,675 | <p>I'm reading lines of input on a TCP socket, similar to this:</p>
<pre><code>class Bla
def getcmd
@sock.gets unless @sock.closed?
end
def start
srv = TCPServer.new(5000)
@sock = srv.accept
while ! @sock.closed?
ans = getcmd
end
end
end
</code></pre>
<p>If the endpoint terminates the connection while getline() is running then gets() hangs. </p>
<p>How can I work around this? Is it necessary to do non-blocking or timed I/O?</p>
| [
{
"answer_id": 61732,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": -1,
"selected": false,
"text": "<p>If you believe the <a href=\"http://www.ruby-doc.org/stdlib/libdoc/socket/rdoc/index.html\" rel=\"nofollow noreferrer... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3796/"
] | I'm reading lines of input on a TCP socket, similar to this:
```
class Bla
def getcmd
@sock.gets unless @sock.closed?
end
def start
srv = TCPServer.new(5000)
@sock = srv.accept
while ! @sock.closed?
ans = getcmd
end
end
end
```
If the endpoint terminates the connection while getline() is running then gets() hangs.
How can I work around this? Is it necessary to do non-blocking or timed I/O? | You can use select to see whether you can safely gets from the socket, see following implementation of a TCPServer using this technique.
```
require 'socket'
host, port = 'localhost', 7000
TCPServer.open(host, port) do |server|
while client = server.accept
readfds = true
got = nil
begin
readfds, writefds, exceptfds = select([client], nil, nil, 0.1)
p :r => readfds, :w => writefds, :e => exceptfds
if readfds
got = client.gets
p got
end
end while got
end
end
```
And here a client that tries to break the server:
```
require 'socket'
host, port = 'localhost', 7000
TCPSocket.open(host, port) do |socket|
socket.puts "Hey there"
socket.write 'he'
socket.flush
socket.close
end
``` |
61,677 | <p>Suppose I have a COM object which users can access via a call such as:</p>
<pre><code>Set s = CreateObject("Server")
</code></pre>
<p>What I'd like to be able to do is allow the user to specify an event handler for the object, like so:</p>
<pre><code>Function ServerEvent
MsgBox "Event handled"
End Function
s.OnDoSomething = ServerEvent
</code></pre>
<p>Is this possible and, if so, how do I expose this in my type library in C++ (specifically BCB 2007)?</p>
| [
{
"answer_id": 61723,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 2,
"selected": false,
"text": "<p>I'm a little hazy on the details, but maybe the link below might help:</p>\n\n<p><a href=\"http://msdn.microsoft.... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5449/"
] | Suppose I have a COM object which users can access via a call such as:
```
Set s = CreateObject("Server")
```
What I'd like to be able to do is allow the user to specify an event handler for the object, like so:
```
Function ServerEvent
MsgBox "Event handled"
End Function
s.OnDoSomething = ServerEvent
```
Is this possible and, if so, how do I expose this in my type library in C++ (specifically BCB 2007)? | This is how I did it just recently. Add an interface that implements IDispatch and a coclass for that interface to your IDL:
```
[
object,
uuid(6EDA5438-0915-4183-841D-D3F0AEDFA466),
nonextensible,
oleautomation,
pointer_default(unique)
]
interface IServerEvents : IDispatch
{
[id(1)]
HRESULT OnServerEvent();
}
//...
[
uuid(FA8F24B3-1751-4D44-8258-D649B6529494),
]
coclass ServerEvents
{
[default] interface IServerEvents;
[default, source] dispinterface IServerEvents;
};
```
This is the declaration of the CServerEvents class:
```
class ATL_NO_VTABLE CServerEvents :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CServerEvents, &CLSID_ServerEvents>,
public IDispatchImpl<IServerEvents, &IID_IServerEvents , &LIBID_YourLibrary, -1, -1>,
public IConnectionPointContainerImpl<CServerEvents>,
public IConnectionPointImpl<CServerEvents,&__uuidof(IServerEvents)>
{
public:
CServerEvents()
{
}
// ...
BEGIN_COM_MAP(CServerEvents)
COM_INTERFACE_ENTRY(IServerEvents)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY(IConnectionPointContainer)
END_COM_MAP()
BEGIN_CONNECTION_POINT_MAP(CServerEvents)
CONNECTION_POINT_ENTRY(__uuidof(IServerEvents))
END_CONNECTION_POINT_MAP()
// ..
// IServerEvents
STDMETHOD(OnServerEvent)();
private:
CRITICAL_SECTION m_csLock;
};
```
The key here is the implementation of the IConnectionPointImpl and IConnectionPointContainerImpl interfaces and the connection point map. The definition of the OnServerEvent method looks like this:
```
STDMETHODIMP CServerEvents::OnServerEvent()
{
::EnterCriticalSection( &m_csLock );
IUnknown* pUnknown;
for ( unsigned i = 0; ( pUnknown = m_vec.GetAt( i ) ) != NULL; ++i )
{
CComPtr<IDispatch> spDisp;
pUnknown->QueryInterface( &spDisp );
if ( spDisp )
{
spDisp.Invoke0( CComBSTR( L"OnServerEvent" ) );
}
}
::LeaveCriticalSection( &m_csLock );
return S_OK;
}
```
You need to provide a way for your client to specify their handler for your events. You can do this with a dedicated method like "SetHandler" or something, but I prefer to make the handler an argument to the method that is called asynchronously. This way, the user only has to call one method:
```
STDMETHOD(DoSomethingAsynchronous)( IServerEvents *pCallback );
```
Store the pointer to the IServerEvents, and then when you want to fire your event, just call the method:
```
m_pCallback->OnServerEvent();
```
As for the VB code, the syntax for dealing with events is a little different than what you suggested:
```
Private m_server As Server
Private WithEvents m_serverEvents As ServerEvents
Private Sub MainMethod()
Set s = CreateObject("Server")
Set m_serverEvents = New ServerEvents
Call m_searchService.DoSomethingAsynchronous(m_serverEvents)
End Sub
Private Sub m_serverEvents_OnServerEvent()
MsgBox "Event handled"
End Sub
```
I hope this helps. |
61,680 | <p>I need to create a 2D int array of size 800x800. But doing so creates a stack overflow (ha ha).</p>
<p>I'm new to C++, so should I do something like a vector of vectors? And just encapsulate the 2d array into a class?</p>
<p>Specifically, this array is my zbuffer in a graphics program. I need to store a z value for every pixel on the screen (hence the large size of 800x800).</p>
<p>Thanks!</p>
| [
{
"answer_id": 61684,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 5,
"selected": true,
"text": "<p>You need about 2.5 megs, so just using the heap should be fine. You don't need a vector unless you need to resize it. S... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396/"
] | I need to create a 2D int array of size 800x800. But doing so creates a stack overflow (ha ha).
I'm new to C++, so should I do something like a vector of vectors? And just encapsulate the 2d array into a class?
Specifically, this array is my zbuffer in a graphics program. I need to store a z value for every pixel on the screen (hence the large size of 800x800).
Thanks! | You need about 2.5 megs, so just using the heap should be fine. You don't need a vector unless you need to resize it. See [C++ FAQ Lite](https://isocpp.org/wiki/faq/freestore-mgmt#multidim-arrays) for an example of using a "2D" heap array.
```
int *array = new int[800*800];
```
(Don't forget to `delete[]` it when you're done.) |
61,691 | <p>The .NET Setup project seems to have a lot of options, but I don't see an "Uninstall" option. </p>
<p>I'd prefer if people could "uninstall" from the standard "start menu" folder rather than send them to the control panel to uninstall my app, so can someone please tell me how to do this?</p>
<p>Also, I am aware of non Microsoft installers that have this feature, but if possible I'd like to stay with the Microsoft toolkit.</p>
| [
{
"answer_id": 61697,
"author": "Mladen Janković",
"author_id": 6300,
"author_profile": "https://Stackoverflow.com/users/6300",
"pm_score": 4,
"selected": true,
"text": "<p>You can make shortcut to:</p>\n\n<pre><code>msiexec /uninstall [path to msi or product code]\n</code></pre>\n"
},... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4050/"
] | The .NET Setup project seems to have a lot of options, but I don't see an "Uninstall" option.
I'd prefer if people could "uninstall" from the standard "start menu" folder rather than send them to the control panel to uninstall my app, so can someone please tell me how to do this?
Also, I am aware of non Microsoft installers that have this feature, but if possible I'd like to stay with the Microsoft toolkit. | You can make shortcut to:
```
msiexec /uninstall [path to msi or product code]
``` |
61,692 | <p>I have a Java application which I want to shutdown 'nicely' when the user selects Start->Shutdown. I've tried using JVM shutdown listeners via Runtime.addShutdownHook(...) but this doesn't work as I can't use any UI elements from it.</p>
<p>I've also tried using the exit handler on my main application UI window but it has no way to pause or halt shutdown as far as I can tell. How can I handle shutdown nicely?</p>
| [
{
"answer_id": 61697,
"author": "Mladen Janković",
"author_id": 6300,
"author_profile": "https://Stackoverflow.com/users/6300",
"pm_score": 4,
"selected": true,
"text": "<p>You can make shortcut to:</p>\n\n<pre><code>msiexec /uninstall [path to msi or product code]\n</code></pre>\n"
},... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1849/"
] | I have a Java application which I want to shutdown 'nicely' when the user selects Start->Shutdown. I've tried using JVM shutdown listeners via Runtime.addShutdownHook(...) but this doesn't work as I can't use any UI elements from it.
I've also tried using the exit handler on my main application UI window but it has no way to pause or halt shutdown as far as I can tell. How can I handle shutdown nicely? | You can make shortcut to:
```
msiexec /uninstall [path to msi or product code]
``` |
61,699 | <p>Until recently we were using Inno Setup for our installations, something I would like to continue doing, unless we can get an <a href="https://stackoverflow.com/questions/61691/how-to-add-uninstall-option-in-net-setup-project">uninstall option in the start menu</a> (thanks Giovanni Galbo), however we now need to GAC some external libraries, something I suspect is only doable (or at least only supported) though the .NET Setup Project.</p>
<p>Is it possible to call a GAC'ing library from another setup application?</p>
| [
{
"answer_id": 61701,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure about library, but you can call <a href=\"http://msdn.microsoft.com/en-us/library/ex0ss12c%28VS.80%29.aspx\" rel=\"no... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] | Until recently we were using Inno Setup for our installations, something I would like to continue doing, unless we can get an [uninstall option in the start menu](https://stackoverflow.com/questions/61691/how-to-add-uninstall-option-in-net-setup-project) (thanks Giovanni Galbo), however we now need to GAC some external libraries, something I suspect is only doable (or at least only supported) though the .NET Setup Project.
Is it possible to call a GAC'ing library from another setup application? | According to <http://jrsoftware.org/files/is5-whatsnew.htm> you should be able to do it with v5.3 and above
>
> Added .NET support (these cause an
> internal error if used on a system
> with no .NET Framework present):
>
>
>
> ```
> * Added new [Files] section flag: gacinstall.
> * Added new [Files] section parameter: StrongAssemblyName.
> * Added new constants: {regasmexe}, {regasmexe32}, {regasmexe64}.
>
> ```
>
> |
61,718 | <p>When you are doing integration tests with either just your data access layer or the majority of the application stack. What is the best way prevent multiple tests from clashing with each other if they are run on the same database?</p>
| [
{
"answer_id": 61720,
"author": "Free Wildebeest",
"author_id": 1849,
"author_profile": "https://Stackoverflow.com/users/1849",
"pm_score": 3,
"selected": false,
"text": "<p>For simple database applications I find using <a href=\"http://www.sqlite.org/\" rel=\"noreferrer\">SQLite</a> inv... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6369/"
] | When you are doing integration tests with either just your data access layer or the majority of the application stack. What is the best way prevent multiple tests from clashing with each other if they are run on the same database? | Transactions.
What the ruby on rails unit test framework does is this:
```
Load all fixture data.
For each test:
BEGIN TRANSACTION
# Yield control to user code
ROLLBACK TRANSACTION
End for each
```
This means that
1. Any changes your test makes to the database won't affect other threads while it's in-progress
2. The next test's data isn't polluted by prior tests
3. This is about a zillion times faster than manually reloading data for each test.
I for one think this is pretty cool |
61,733 | <p>Which of the following is better code in c# and why?</p>
<pre><code>((DateTime)g[0]["MyUntypedDateField"]).ToShortDateString()
</code></pre>
<p>or</p>
<pre><code>DateTime.Parse(g[0]["MyUntypedDateField"].ToString()).ToShortDateString()
</code></pre>
<p>Ultimately, is it better to cast or to parse?</p>
| [
{
"answer_id": 61740,
"author": "Wilka",
"author_id": 1367,
"author_profile": "https://Stackoverflow.com/users/1367",
"pm_score": 5,
"selected": true,
"text": "<p>If g[0][\"MyUntypedDateField\"] is really a DateTime object, then the cast is the better choice. If it's not really a DateTim... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4246/"
] | Which of the following is better code in c# and why?
```
((DateTime)g[0]["MyUntypedDateField"]).ToShortDateString()
```
or
```
DateTime.Parse(g[0]["MyUntypedDateField"].ToString()).ToShortDateString()
```
Ultimately, is it better to cast or to parse? | If g[0]["MyUntypedDateField"] is really a DateTime object, then the cast is the better choice. If it's not really a DateTime, then you have no choice but to use the Parse (you would get an InvalidCastException if you tried to use the cast) |
61,739 | <p>I'm drawing old school (unthemed - themed radios are a whole other problem) radio buttons myself using DrawFrameControl:</p>
<pre><code>DrawFrameControl(dc, &rectRadio, DFC_BUTTON, isChecked() ? DFCS_BUTTONRADIO | DFCS_CHECKED : DFCS_BUTTONRADIO);
</code></pre>
<p>I've never been able to figure out a sure fire way to figure out what to pass for the RECT. I've been using a 12x12 rectangle but I'de like Windows to tell me the size of a radio button.</p>
<p>DrawFrameControl seems to scale the radio button to fit the rect I pass so I have to be close to the "right" size of the radio looks off from other (non-owner drawn) radios on the screen.</p>
<p>Anyone know how to do this? </p>
| [
{
"answer_id": 124737,
"author": "David L Morris",
"author_id": 3137,
"author_profile": "https://Stackoverflow.com/users/3137",
"pm_score": 2,
"selected": false,
"text": "<p>It has been a while since I worked on this, so what I am describing is what I did, and not necessarily a direct an... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3655/"
] | I'm drawing old school (unthemed - themed radios are a whole other problem) radio buttons myself using DrawFrameControl:
```
DrawFrameControl(dc, &rectRadio, DFC_BUTTON, isChecked() ? DFCS_BUTTONRADIO | DFCS_CHECKED : DFCS_BUTTONRADIO);
```
I've never been able to figure out a sure fire way to figure out what to pass for the RECT. I've been using a 12x12 rectangle but I'de like Windows to tell me the size of a radio button.
DrawFrameControl seems to scale the radio button to fit the rect I pass so I have to be close to the "right" size of the radio looks off from other (non-owner drawn) radios on the screen.
Anyone know how to do this? | It has been a while since I worked on this, so what I am describing is what I did, and not necessarily a direct answer to the question.
I happen to use bit maps 13 x 13 rather than 12 x 12. The bitmap part of the check box seems to be passed in the WM\_DRAWITEM. However, I had also set up WM\_MEASUREITEM and fed it the same values, so my answer may well be "Begging the question" in the correct philosophical sense.
```
case WM_MEASUREITEM:
lpmis = (LPMEASUREITEMSTRUCT) lParam;
lpmis->itemHeight = 13;
lpmis->itemWidth = 13;
break;
case WM_DRAWITEM:
lpdis = (LPDRAWITEMSTRUCT) lParam;
hdcMem = CreateCompatibleDC(lpdis->hDC);
if (lpdis->itemState & ODS_CHECKED) // if selected
{
SelectObject(hdcMem, hbmChecked);
}
else
{
if (lpdis->itemState & ODS_GRAYED)
{
SelectObject(hdcMem, hbmDefault);
}
else
{
SelectObject(hdcMem, hbmUnChecked);
}
}
StretchBlt(
lpdis->hDC, // destination DC
lpdis->rcItem.left, // x upper left
lpdis->rcItem.top, // y upper left
// The next two lines specify the width and
// height.
lpdis->rcItem.right - lpdis->rcItem.left,
lpdis->rcItem.bottom - lpdis->rcItem.top,
hdcMem, // source device context
0, 0, // x and y upper left
13, // source bitmap width
13, // source bitmap height
SRCCOPY); // raster operation
DeleteDC(hdcMem);
return TRUE;
```
This seems to work well for both Win2000 and XP, though I have nbo idea what Vista might do.
It might be worth an experiment to see what leaving out WM\_MEASUREITEM does, though I usually discover with old code that I usually had perfectly good reason for doing something that looks redundant. |
61,747 | <p>How can I get PDO to work on my mac (os x 10.5)? I'm using the built in php and php in Zend/Eclipse. Can't seem to find useful drivers for it at all.</p>
| [
{
"answer_id": 61799,
"author": "Alan",
"author_id": 5878,
"author_profile": "https://Stackoverflow.com/users/5878",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure this will help with the PDO drivers specifically, but you might look into <a href=\"http://bitnami.org/stack/map... | 2008/09/15 | [
"https://Stackoverflow.com/questions/61747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6371/"
] | How can I get PDO to work on my mac (os x 10.5)? I'm using the built in php and php in Zend/Eclipse. Can't seem to find useful drivers for it at all. | I had to install the PDO\_PGSQL driver recently on Leopard, and I ran across a multitude of problems. In my search for answers, I stumbled across this question. Now I have it successfully installed, and so, even though this question is quite old, I hope that what I've found can help others (like myself) who will undoubtedly run into similar problems.
The first thing you'll need to do is [install PEAR](http://pear.php.net/manual/en/installation.getting.php), if you haven't done so already, since it doesn't come installed on Leopard by default.
Once you do that, use the PECL installer to download the PDO\_PGSQL package:
```
$ pecl download pdo_pgsql
$ tar xzf PDO_PGSQL-1.0.2.tgz
```
(Note: you may have to run `pecl` as the superuser, i.e. `sudo pecl`.)
After that, since the PECL installer can't install the extension directly, you'll need to build and install it yourself:
```
$ cd PDO_PGSQL-1.0.2
$ phpize
$ ./configure --with-pdo-pgsql=/path/to/your/PostgreSQL/installation
$ make && sudo make install
```
If all goes well, you should have a file called "`pdo_pgsql.so`" sitting in a directory that should look something like "`/usr/lib/php/extensions/no-debug-non-zts-20060613/`" (the PECL installation should have outputted the directory it installed the extension to).
To finalize the installation, you'll need to edit your `php.ini` file. Find the section labeled "Dynamic Extensions", and underneath the list of (probably commented out) extensions, add this line:
```
extension=pdo_pgsql.so
```
Now, assuming this is the first time you've installed PHP extensions, there are two additional steps you need to take in order to get this working. First, in `php.ini`, find the `extension_dir` directive (under "Paths and Directories"), and change it to the directory that the `pdo_pgsql.so` file was installed in. For example, my `extension_dir` directive looks like:
```
extension_dir = "/usr/lib/php/extensions/no-debug-non-zts-20060613"
```
The second step, if you're on a 64-bit Intel Mac, involves making Apache run in 32-bit mode. (If there's a better strategy, I'd like to know, but for now, this is the best I could find.) In order to do this, edit the property list file located at `/System/Library/LaunchDaemons/org.apache.httpd.plist`. Find these two lines:
```
<key>ProgramArguments</key>
<array>
```
Under them, add these three lines:
```
<string>arch</string>
<string>-arch</string>
<string>i386</string>
```
Now, just restart Apache, and PDO\_PGSQL will be up and running. |
61,805 | <p>I had a working solution using ASP.NET MVC Preview 3 (was upgraded from a Preview 2 solution) that uses an untyped ViewMasterPage like so:</p>
<pre><code>public partial class Home : ViewMasterPage
</code></pre>
<p>On Home.Master there is a display statement like this:</p>
<pre><code><%= ((GenericViewData)ViewData["Generic"]).Skin %>
</code></pre>
<p>However, a developer on the team just changed the assembly references to Preview 4.</p>
<p>Following this, the code will no longer populate ViewData with indexed values like the above.</p>
<p>Instead, ViewData["Generic"] is null.</p>
<p>As per <a href="https://stackoverflow.com/questions/18787/aspnet-mvc-user-control-viewdata">this question</a>, ViewData.Eval("Generic") works, and ViewData.Model is also populated correctly.</p>
<p>However, the reason this solution isn't using typed pages etc. is because it is kind of a legacy solution. As such, it is impractical to go through this fairly large solution and update all .aspx pages (especially as the compiler doesn't detect this sort of stuff).</p>
<p>I have tried reverting the assemblies by removing the reference and then adding a reference to the Preview 3 assembly in the 'bin' folder of the project. This did not change anything. I have even tried reverting the Project file to an earlier version and that still did not seem to fix the problem.</p>
<p>I have other solutions using the same technique that continue to work.</p>
<p>Is there anything you can suggest as to why this has suddenly stopped working and how I might go about fixing it (any hint in the right direction would be appreciated)?</p>
| [
{
"answer_id": 61808,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 0,
"selected": false,
"text": "<p>I've decided to replace all instances of ViewData[\"blah\"] with ViewData.Eval(\"blah\").\nHowever, I'd like to know t... | 2008/09/15 | [
"https://Stackoverflow.com/questions/61805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | I had a working solution using ASP.NET MVC Preview 3 (was upgraded from a Preview 2 solution) that uses an untyped ViewMasterPage like so:
```
public partial class Home : ViewMasterPage
```
On Home.Master there is a display statement like this:
```
<%= ((GenericViewData)ViewData["Generic"]).Skin %>
```
However, a developer on the team just changed the assembly references to Preview 4.
Following this, the code will no longer populate ViewData with indexed values like the above.
Instead, ViewData["Generic"] is null.
As per [this question](https://stackoverflow.com/questions/18787/aspnet-mvc-user-control-viewdata), ViewData.Eval("Generic") works, and ViewData.Model is also populated correctly.
However, the reason this solution isn't using typed pages etc. is because it is kind of a legacy solution. As such, it is impractical to go through this fairly large solution and update all .aspx pages (especially as the compiler doesn't detect this sort of stuff).
I have tried reverting the assemblies by removing the reference and then adding a reference to the Preview 3 assembly in the 'bin' folder of the project. This did not change anything. I have even tried reverting the Project file to an earlier version and that still did not seem to fix the problem.
I have other solutions using the same technique that continue to work.
Is there anything you can suggest as to why this has suddenly stopped working and how I might go about fixing it (any hint in the right direction would be appreciated)? | We made that change because we wanted a bit of symmetry with the [] indexer. The Eval() method uses reflection and looks into the model to retrieve values. The indexer only looks at items directly added to the dictionary. |
61,817 | <p>I am wondering what the best way to obtain the current domain is in ASP.NET?</p>
<p>For instance:</p>
<p><a href="http://www.domainname.com/subdir/" rel="noreferrer">http://www.domainname.com/subdir/</a> should yield <a href="http://www.domainname.com" rel="noreferrer">http://www.domainname.com</a>
<a href="http://www.sub.domainname.com/subdir/" rel="noreferrer">http://www.sub.domainname.com/subdir/</a> should yield <a href="http://sub.domainname.com" rel="noreferrer">http://sub.domainname.com</a></p>
<p>As a guide, I should be able to add a url like "/Folder/Content/filename.html" (say as generated by Url.RouteUrl() in ASP.NET MVC) straight onto the URL and it should work.</p>
| [
{
"answer_id": 61819,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 5,
"selected": false,
"text": "<p>As per <a href=\"http://www.velocityreviews.com/forums/t89365-get-hostdomain-name.html\" rel=\"noreferrer\">this link<... | 2008/09/15 | [
"https://Stackoverflow.com/questions/61817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | I am wondering what the best way to obtain the current domain is in ASP.NET?
For instance:
<http://www.domainname.com/subdir/> should yield <http://www.domainname.com>
<http://www.sub.domainname.com/subdir/> should yield <http://sub.domainname.com>
As a guide, I should be able to add a url like "/Folder/Content/filename.html" (say as generated by Url.RouteUrl() in ASP.NET MVC) straight onto the URL and it should work. | Same answer as MattMitchell's but with some modification.
This checks for the default port instead.
>
> Edit: Updated syntax and using `Request.Url.Authority` as suggested
>
>
>
```
$"{Request.Url.Scheme}{System.Uri.SchemeDelimiter}{Request.Url.Authority}"
``` |
61,838 | <p>If I have something like a UILabel linked to a xib file, do I need to release it on dealloc of my view? The reason I ask is because I don't alloc it, which makes me think I don't need to release it either?
eg (in the header):</p>
<pre><code>IBOutlet UILabel *lblExample;
</code></pre>
<p>in the implementation:</p>
<pre><code>....
[lblExample setText:@"whatever"];
....
-(void)dealloc{
[lblExample release];//?????????
}
</code></pre>
| [
{
"answer_id": 61841,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 0,
"selected": false,
"text": "<p>Related: <a href=\"https://stackoverflow.com/questions/6578/understanding-reference-counting-with-cocoa-objective-c\"... | 2008/09/15 | [
"https://Stackoverflow.com/questions/61838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6044/"
] | If I have something like a UILabel linked to a xib file, do I need to release it on dealloc of my view? The reason I ask is because I don't alloc it, which makes me think I don't need to release it either?
eg (in the header):
```
IBOutlet UILabel *lblExample;
```
in the implementation:
```
....
[lblExample setText:@"whatever"];
....
-(void)dealloc{
[lblExample release];//?????????
}
``` | If you follow what is now considered to be best practice, you *should* release outlet properties, because you should have retained them in the set accessor:
```
@interface MyController : MySuperclass {
Control *uiElement;
}
@property (nonatomic, retain) IBOutlet Control *uiElement;
@end
@implementation MyController
@synthesize uiElement;
- (void)dealloc {
[uiElement release];
[super dealloc];
}
@end
```
The advantage of this approach is that it makes the memory management semantics explicit and clear, *and it works consistently across all platforms for all nib files*.
Note: The following comments apply only to iOS prior to 3.0. With 3.0 and later, you should instead simply nil out property values in viewDidUnload.
One consideration here, though, is when your controller might dispose of its user interface and reload it dynamically on demand (for example, if you have a view controller that loads a view from a nib file, but on request -- say under memory pressure -- releases it, with the expectation that it can be reloaded if the view is needed again). In this situation, you want to make sure that when the main view is disposed of you also relinquish ownership of any other outlets so that they too can be deallocated. For UIViewController, you can deal with this issue by overriding `setView:` as follows:
```
- (void)setView:(UIView *)newView {
if (newView == nil) {
self.uiElement = nil;
}
[super setView:aView];
}
```
Unfortunately this gives rise to a further issue. Because UIViewController currently implements its `dealloc` method using the `setView:` accessor method (rather than simply releasing the variable directly), `self.anOutlet = nil` will be called in `dealloc` as well as in response to a memory warning... This will lead to a crash in `dealloc`.
The remedy is to ensure that outlet variables are also set to `nil` in `dealloc`:
```
- (void)dealloc {
// release outlets and set variables to nil
[anOutlet release], anOutlet = nil;
[super dealloc];
}
``` |
61,861 | <p>I would like to make my web control more readable in design mode, basically I want the tag declaration to look like:</p>
<pre><code><cc1:Ctrl ID="Value1" runat="server">
<Values>string value 1</Value>
<Values>string value 2</Value>
</cc1:Ctrl>
</code></pre>
<p>Lets say I have a private variable in the code behind:</p>
<pre><code>List<string> values = new List<string>();
</code></pre>
<p>So how can I make my user control fill out the private variable with the values that are declared in the markup?</p>
<hr>
<p>Sorry I should have been more explicit. Basically I like the functionality that the ITemplate provides (<a href="http://msdn.microsoft.com/en-us/library/aa719834.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa719834.aspx</a>)</p>
<p>But in this case you need to know at runtime how many templates can be instansitated, i.e.</p>
<pre><code>void Page_Init() {
if (messageTemplate != null) {
for (int i=0; i<5; i++) {
MessageContainer container = new MessageContainer(i);
messageTemplate.InstantiateIn(container);
msgholder.Controls.Add(container);
}
}
</code></pre>
<p>}</p>
<p>In the given example the markup looks like:</p>
<pre><code><acme:test runat=server>
<MessageTemplate>
Hello #<%# Container.Index %>.<br>
</MessageTemplate>
</acme:test>
</code></pre>
<p>Which is nice and clean, it does not have any tag prefixes etc. I really want the nice clean tags.</p>
<p>I'm probably being silly in wanting the markup to be clean, I'm just wondering if there is something simple that I'm missing.</p>
| [
{
"answer_id": 61925,
"author": "Matt",
"author_id": 4154,
"author_profile": "https://Stackoverflow.com/users/4154",
"pm_score": 0,
"selected": false,
"text": "<p>I see two options, but both depend on your web control implementing some sort of collection for your values. The first optio... | 2008/09/15 | [
"https://Stackoverflow.com/questions/61861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2758/"
] | I would like to make my web control more readable in design mode, basically I want the tag declaration to look like:
```
<cc1:Ctrl ID="Value1" runat="server">
<Values>string value 1</Value>
<Values>string value 2</Value>
</cc1:Ctrl>
```
Lets say I have a private variable in the code behind:
```
List<string> values = new List<string>();
```
So how can I make my user control fill out the private variable with the values that are declared in the markup?
---
Sorry I should have been more explicit. Basically I like the functionality that the ITemplate provides (<http://msdn.microsoft.com/en-us/library/aa719834.aspx>)
But in this case you need to know at runtime how many templates can be instansitated, i.e.
```
void Page_Init() {
if (messageTemplate != null) {
for (int i=0; i<5; i++) {
MessageContainer container = new MessageContainer(i);
messageTemplate.InstantiateIn(container);
msgholder.Controls.Add(container);
}
}
```
}
In the given example the markup looks like:
```
<acme:test runat=server>
<MessageTemplate>
Hello #<%# Container.Index %>.<br>
</MessageTemplate>
</acme:test>
```
Which is nice and clean, it does not have any tag prefixes etc. I really want the nice clean tags.
I'm probably being silly in wanting the markup to be clean, I'm just wondering if there is something simple that I'm missing. | I think what you are searching for is the attribute:
```
[PersistenceMode(PersistenceMode.InnerProperty)]
```
[Persistence Mode](http://msdn.microsoft.com/en-us/library/system.web.ui.persistencemode.aspx)
Remember that you have to register your namespace and prefix with:
```
<%@ Register Namespace="MyNamespace" TagPrefix="Pref" %>
``` |
61,872 | <p>We are rewriting our legacy <a href="https://en.wikipedia.org/wiki/Accounting_information_system" rel="nofollow noreferrer">accounting system</a> in VB.NET and SQL Server. We brought in a new team of .NET/ SQL Programmers to do the rewrite. Most of the system is already completed with the dollar amounts using floats. The legacy system language, I programmed in, did not have a float, so I probably would have used a decimal.</p>
<p>What is your recommendation?</p>
<p>Should the float or decimal data type be used for dollar amounts?</p>
<p>What are some of the pros and cons for either?</p>
<p>One <em>con</em> mentioned in our <a href="https://en.wikipedia.org/wiki/Scrum_%28software_development%29#Daily_scrum" rel="nofollow noreferrer">daily scrum</a> was you have to be careful when you calculate an amount that returns a result that is over two decimal positions. It sounds like you will have to round the amount to two decimal positions.</p>
<p>Another <em>con</em> is all displays and printed amounts have to have a <em>format statement</em> that shows two decimal positions. I noticed a few times where this was not done and the amounts did not look correct. (i.e. 10.2 or 10.2546)</p>
<p>A <em>pro</em> is the float-only approach takes up eight bytes on disk where the decimal would take up nine bytes (decimal 12,2).</p>
| [
{
"answer_id": 61875,
"author": "Niall",
"author_id": 6049,
"author_profile": "https://Stackoverflow.com/users/6049",
"pm_score": 2,
"selected": false,
"text": "<p>Floats are not exact representations, precision issues are possible, for example when adding very large and very small value... | 2008/09/15 | [
"https://Stackoverflow.com/questions/61872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4964/"
] | We are rewriting our legacy [accounting system](https://en.wikipedia.org/wiki/Accounting_information_system) in VB.NET and SQL Server. We brought in a new team of .NET/ SQL Programmers to do the rewrite. Most of the system is already completed with the dollar amounts using floats. The legacy system language, I programmed in, did not have a float, so I probably would have used a decimal.
What is your recommendation?
Should the float or decimal data type be used for dollar amounts?
What are some of the pros and cons for either?
One *con* mentioned in our [daily scrum](https://en.wikipedia.org/wiki/Scrum_%28software_development%29#Daily_scrum) was you have to be careful when you calculate an amount that returns a result that is over two decimal positions. It sounds like you will have to round the amount to two decimal positions.
Another *con* is all displays and printed amounts have to have a *format statement* that shows two decimal positions. I noticed a few times where this was not done and the amounts did not look correct. (i.e. 10.2 or 10.2546)
A *pro* is the float-only approach takes up eight bytes on disk where the decimal would take up nine bytes (decimal 12,2). | >
> Should Float or Decimal data type be used for dollar amounts?
>
>
>
The answer is easy. Never floats. *NEVER*!
Floats were according to [IEEE 754](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=4610933) always binary, only the new standard [IEEE 754R](http://www.intel.com/technology/itj/2007/v11i1/s2-decimal/1-sidebar.htm) defined decimal formats. Many of the fractional binary parts can never equal the exact decimal representation.
Any binary number can be written as `m/2^n` (`m`, `n` positive integers), any decimal number as `m/(2^n*5^n)`.
As binaries lack the prime `factor 5`, all binary numbers can be exactly represented by decimals, but not vice versa.
```
0.3 = 3/(2^1 * 5^1) = 0.3
0.3 = [0.25/0.5] [0.25/0.375] [0.25/3.125] [0.2825/3.125]
1/4 1/8 1/16 1/32
```
So you end up with a number either higher or lower than the given decimal number. Always.
Why does that matter? Rounding.
Normal rounding means 0..4 down, 5..9 up. So it *does* matter if the result is
either `0.049999999999`.... or `0.0500000000`... You may know that it means 5 cent, but the the computer does not know that and rounds `0.4999`... down (wrong) and `0.5000`... up (right).
Given that the result of floating point computations always contain small error terms, the decision is pure luck. It gets hopeless if you want decimal round-to-even handling with binary numbers.
Unconvinced? You insist that in your account system everything is perfectly ok?
Assets and liabilities equal? Ok, then take each of the given formatted numbers of each entry, parse them and sum them with an independent decimal system!
Compare that with the formatted sum. Oops, there is something wrong, isn't it?
>
> For that calculation, extreme accuracy and fidelity was required (we used Oracle's
> FLOAT) so we could record the "billionth's of a penny" being accured.
>
>
>
It doesn't help against this error. Because all people automatically assume that the computer sums right, and practically no one checks independently. |
61,893 | <p>I am attempting to copy a custom struct from kernel space to user space. inside user space errno returns 'bad address'. What is the usual cause of a bad address error?</p>
<pre><code>if(copy_to_user(info, &kernel_info, sizeof(struct prinfo)))
</code></pre>
| [
{
"answer_id": 61948,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 3,
"selected": false,
"text": "<p>Bad Address error means that the address location that you have given is invalid. With the case you have above I would guess it ... | 2008/09/15 | [
"https://Stackoverflow.com/questions/61893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am attempting to copy a custom struct from kernel space to user space. inside user space errno returns 'bad address'. What is the usual cause of a bad address error?
```
if(copy_to_user(info, &kernel_info, sizeof(struct prinfo)))
``` | Bad Address error means that the address location that you have given is invalid. With the case you have above I would guess it is because you are passing a copy of `info` instead of a pointer to `info`'s memory location.
Looking at the docs, `copy_to_user` is defined as
```
copy_to_user(void __user * to, const void * from, unsigned long n);
```
So unless your `info` variable is a pointer I would update your code to be:
```
if(copy_to_user(&info, &kernel_info, sizeof(struct prinfo)) ) {
//some stuff here i guess
}
``` |
61,894 | <p>So I've done the trivial "warmup" apps with GAE. Now I'd like to build something with a more complex directory structure. Something along the lines of:</p>
<pre><code>siteroot/
models/
controllers/
controller1/
controller2/
...
templates/
template1/
template2/
...
</code></pre>
<p>..etc. The controllers will be Python modules handling requests. They would then need to locate (Django-style) templates in associated folders. Most of the demo apps I've seen resolve template paths like this:</p>
<pre><code>path = os.path.join(os.path.dirname(__file__), 'myPage.html')
</code></pre>
<p>...the __ file __ property resolves to the currently executing script. So, in my above example, if a Python script were running in controllers/controller1/, then the 'myPage.html' would resolve to that same directory -- controllers/controller1/myPage.html -- and I would rather cleanly separate my Python code and templates.</p>
<p>The solution I've hacked together feels... hacky:</p>
<pre><code>base_paths = os.path.split(os.path.dirname(__file__))
template_dir = os.path.join(base_paths[0], "templates")
</code></pre>
<p>So, I'm just snipping off the last element of the path for the currently running script and appending the template directory to the new path. The other (non-GAE specific) solutions I've seen for resolving Python paths seem pretty heavyweight (such as splitting paths into lists and manipulating accordingly). Django seems to have an answer for this, but I'd rather stick to the GAE API, vs. creating a full Django app and modifying it for GAE.</p>
<p>I'm assuming anything hard-coded would be non-starter, since the apps live on Google's infinite server farm. So what's a better way?</p>
| [
{
"answer_id": 62121,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>dirname</code> function returns an absolute path, use relative paths. See what is the current directory when y... | 2008/09/15 | [
"https://Stackoverflow.com/questions/61894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4904/"
] | So I've done the trivial "warmup" apps with GAE. Now I'd like to build something with a more complex directory structure. Something along the lines of:
```
siteroot/
models/
controllers/
controller1/
controller2/
...
templates/
template1/
template2/
...
```
..etc. The controllers will be Python modules handling requests. They would then need to locate (Django-style) templates in associated folders. Most of the demo apps I've seen resolve template paths like this:
```
path = os.path.join(os.path.dirname(__file__), 'myPage.html')
```
...the \_\_ file \_\_ property resolves to the currently executing script. So, in my above example, if a Python script were running in controllers/controller1/, then the 'myPage.html' would resolve to that same directory -- controllers/controller1/myPage.html -- and I would rather cleanly separate my Python code and templates.
The solution I've hacked together feels... hacky:
```
base_paths = os.path.split(os.path.dirname(__file__))
template_dir = os.path.join(base_paths[0], "templates")
```
So, I'm just snipping off the last element of the path for the currently running script and appending the template directory to the new path. The other (non-GAE specific) solutions I've seen for resolving Python paths seem pretty heavyweight (such as splitting paths into lists and manipulating accordingly). Django seems to have an answer for this, but I'd rather stick to the GAE API, vs. creating a full Django app and modifying it for GAE.
I'm assuming anything hard-coded would be non-starter, since the apps live on Google's infinite server farm. So what's a better way? | You can't use relative paths, as Toni suggests, because you have no guarantee that the path from your working directory to your app's directory will remain the same.
The correct solution is to either use os.path.split, as you are, or to use something like:
```
path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'myPage.html')
```
My usual approach is to generate a path to the template directory using the above method, and store it as a member of my controller object, and provide a "getTemplatePath" method that takes the provided filename and joins it with the basename. |
61,902 | <p>I want to embed a wikipedia article into a page but I don't want all the wrapper (navigation, etc.) that sits around the articles. I saw it done here: <a href="http://www.dayah.com/periodic/" rel="nofollow noreferrer">http://www.dayah.com/periodic/</a>. Click on an element and the iframe is displayed and links to the article only (no wrapper). So how'd they do that? Seems like JavaScript handles showing the iframe and constructing the href but after browsing the pages javascript (<a href="http://www.dayah.com/periodic/Script/interactivity.js" rel="nofollow noreferrer">http://www.dayah.com/periodic/Script/interactivity.js</a>) I still can't figure out how the url is built. Thanks.</p>
| [
{
"answer_id": 61907,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": -1,
"selected": false,
"text": "<p>You could always download the site and scrap it. I think everything inside <code><div id=\"bodyContent\"></code> is th... | 2008/09/15 | [
"https://Stackoverflow.com/questions/61902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5234/"
] | I want to embed a wikipedia article into a page but I don't want all the wrapper (navigation, etc.) that sits around the articles. I saw it done here: <http://www.dayah.com/periodic/>. Click on an element and the iframe is displayed and links to the article only (no wrapper). So how'd they do that? Seems like JavaScript handles showing the iframe and constructing the href but after browsing the pages javascript (<http://www.dayah.com/periodic/Script/interactivity.js>) I still can't figure out how the url is built. Thanks. | The periodic table example loads the printer-friendly version of the wiki artice into an iframe. <http://en.wikipedia.org/wiki/Potasium>?**printable=yes**
it's done in *function click\_wiki(e)* (line 534, interactivity.js)
>
> ```
>
> var article = el.childNodes[0].childNodes[n_name].innerHTML;
> ...
> window.frames["WikiFrame"].location.replace("http://" + language + ".wikipedia.org/w/index.php?title=" + encodeURIComponent(article) + "&printable=yes");
>
> ```
> |
61,906 | <p>In Hibernate we have two classes with the following classes with JPA mapping:</p>
<pre><code>package com.example.hibernate
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class Foo {
private long id;
private Bar bar;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
public Bar getBar() {
return bar;
}
public void setBar(Bar bar) {
this.bar = bar;
}
}
package com.example.hibernate
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class Bar {
private long id;
private String title;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
</code></pre>
<p>Now when we load from the database an object from class Foo using session get e.g:</p>
<p>Foo foo = (Foo)session.get(Foo.class, 1 /* or some other id that exists in the DB*/);
the Bar member of foo is a proxy object (in our case javassist proxy but it can be cglib one depending on the bytecode provider you use), that is not initialized.
If you then use session.get to fetch the Bar object that is the member of the Foo class just loaded (we are in the same session), Hibernate does not issue another DB query and fetches the object from the session (first level) cache. The problem is this is a proxy to Bar class which is not initialized and trying to call this object getId() will return 0, and getTitle() will return null.
Our current solution is pretty ugly and checks if the object returned from get is a proxy here is the code (form a generic DAO implementation):</p>
<pre><code>@SuppressWarnings("unchecked")
@Override
@Transactional(readOnly = true)
public <T extends IEntity> T get(Class<T> clazz, Serializable primaryKey) throws DataAccessException {
T entity = (T) currentSession().get(clazz, primaryKey);
if (entity != null) {
if (LOG.isWarnEnabled()) {
LOG.warn("Object not found for class " + clazz.getName() + " with primary key " + primaryKey);
}
} else if (entity instanceof HibernateProxy){ // TODO: force initialization due to Hibernate bug
HibernateProxy proxy = (HibernateProxy)entity;
if (!Hibernate.isInitialized(proxy)) {
Hibernate.initialize(proxy);
}
entity = (T)proxy.getHibernateLazyInitializer().getImplementation();
}
return entity;
}
</code></pre>
<p>Is there a better way to do this, couldn't find a solution in the Hibernate forum, and didn't find the issue in Hibernate's JIRA.</p>
<p>Note: we cannot just use foo.getBar() (which will initialize the proxy properly) to get the Bar class object, because the session.get operation to fetch the Bar object does not know (or care for that matter) that the Bar class is also a lazy member of a Foo object that was just fetched.</p>
| [
{
"answer_id": 61935,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 0,
"selected": false,
"text": "<p>Not really seen this problem, although we do get intermittent Lazy Load errors - so perhaps we have the same probl... | 2008/09/15 | [
"https://Stackoverflow.com/questions/61906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3332/"
] | In Hibernate we have two classes with the following classes with JPA mapping:
```
package com.example.hibernate
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class Foo {
private long id;
private Bar bar;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
public Bar getBar() {
return bar;
}
public void setBar(Bar bar) {
this.bar = bar;
}
}
package com.example.hibernate
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class Bar {
private long id;
private String title;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
```
Now when we load from the database an object from class Foo using session get e.g:
Foo foo = (Foo)session.get(Foo.class, 1 /\* or some other id that exists in the DB\*/);
the Bar member of foo is a proxy object (in our case javassist proxy but it can be cglib one depending on the bytecode provider you use), that is not initialized.
If you then use session.get to fetch the Bar object that is the member of the Foo class just loaded (we are in the same session), Hibernate does not issue another DB query and fetches the object from the session (first level) cache. The problem is this is a proxy to Bar class which is not initialized and trying to call this object getId() will return 0, and getTitle() will return null.
Our current solution is pretty ugly and checks if the object returned from get is a proxy here is the code (form a generic DAO implementation):
```
@SuppressWarnings("unchecked")
@Override
@Transactional(readOnly = true)
public <T extends IEntity> T get(Class<T> clazz, Serializable primaryKey) throws DataAccessException {
T entity = (T) currentSession().get(clazz, primaryKey);
if (entity != null) {
if (LOG.isWarnEnabled()) {
LOG.warn("Object not found for class " + clazz.getName() + " with primary key " + primaryKey);
}
} else if (entity instanceof HibernateProxy){ // TODO: force initialization due to Hibernate bug
HibernateProxy proxy = (HibernateProxy)entity;
if (!Hibernate.isInitialized(proxy)) {
Hibernate.initialize(proxy);
}
entity = (T)proxy.getHibernateLazyInitializer().getImplementation();
}
return entity;
}
```
Is there a better way to do this, couldn't find a solution in the Hibernate forum, and didn't find the issue in Hibernate's JIRA.
Note: we cannot just use foo.getBar() (which will initialize the proxy properly) to get the Bar class object, because the session.get operation to fetch the Bar object does not know (or care for that matter) that the Bar class is also a lazy member of a Foo object that was just fetched. | I had a similar problem:
* I did Session.save(nastyItem) to save an object into the Session.
However, I did not fill in the property buyer which is mapped as update="false" insert="false" (this happens a lot when you have a composed primary key, then you map the many-to-one's as insert="false" update="false")
* I a query to load a list of items, and the item which I just saved, happens to be part of the result set
* now what goes wrong? Hibernate sees that the item was already in the cache, and Hibernate does not replace (probably not to break my earlier reference nastyItem) it with the newly loaded value, but uses MY nastyItem I have put into the Session cache myself. Even worse, now the lazy loading of the buyer is broken: it contains null.
To avoid these Session issues, I always do a flush and a clear after a save, merge, update or delete. Having to solve these nasty problems takes too much of my time. |
61,953 | <p>Let's say I have the following simple enum:</p>
<pre><code>enum Response
{
Yes = 1,
No = 2,
Maybe = 3
}
</code></pre>
<p>How can I bind this enum to a DropDownList control so that the descriptions are displayed in the list as well as retrieve the associated numeric value (1,2,3) once an option has been selected?</p>
| [
{
"answer_id": 61961,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 8,
"selected": true,
"text": "<p>I probably wouldn't <strong>bind</strong> the data as it's an enum, and it won't change after compile time (unless I'm ha... | 2008/09/15 | [
"https://Stackoverflow.com/questions/61953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] | Let's say I have the following simple enum:
```
enum Response
{
Yes = 1,
No = 2,
Maybe = 3
}
```
How can I bind this enum to a DropDownList control so that the descriptions are displayed in the list as well as retrieve the associated numeric value (1,2,3) once an option has been selected? | I probably wouldn't **bind** the data as it's an enum, and it won't change after compile time (unless I'm having one of those *stoopid* moments).
Better just to iterate through the enum:
```
Dim itemValues As Array = System.Enum.GetValues(GetType(Response))
Dim itemNames As Array = System.Enum.GetNames(GetType(Response))
For i As Integer = 0 To itemNames.Length - 1
Dim item As New ListItem(itemNames(i), itemValues(i))
dropdownlist.Items.Add(item)
Next
```
Or the same in C#
```
Array itemValues = System.Enum.GetValues(typeof(Response));
Array itemNames = System.Enum.GetNames(typeof(Response));
for (int i = 0; i <= itemNames.Length - 1 ; i++) {
ListItem item = new ListItem(itemNames[i], itemValues[i]);
dropdownlist.Items.Add(item);
}
``` |
61,967 | <p>Let's say I have the following simple table variable:</p>
<pre><code>declare @databases table
(
DatabaseID int,
Name varchar(15),
Server varchar(15)
)
-- insert a bunch rows into @databases
</code></pre>
<p>Is declaring and using a cursor my only option if I wanted to iterate through the rows? Is there another way?</p>
| [
{
"answer_id": 61981,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 2,
"selected": false,
"text": "<p>You can use a while loop:</p>\n\n<pre><code>While (Select Count(*) From #TempTable) > 0\nBegin\n Insert Into @Datab... | 2008/09/15 | [
"https://Stackoverflow.com/questions/61967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] | Let's say I have the following simple table variable:
```
declare @databases table
(
DatabaseID int,
Name varchar(15),
Server varchar(15)
)
-- insert a bunch rows into @databases
```
Is declaring and using a cursor my only option if I wanted to iterate through the rows? Is there another way? | First of all you should be absolutely sure you need to iterate through each row — set based operations will perform faster in every case I can think of and will normally use simpler code.
Depending on your data it may be possible to loop using just `SELECT` statements as shown below:
```
Declare @Id int
While (Select Count(*) From ATable Where Processed = 0) > 0
Begin
Select Top 1 @Id = Id From ATable Where Processed = 0
--Do some processing here
Update ATable Set Processed = 1 Where Id = @Id
End
```
Another alternative is to use a temporary table:
```
Select *
Into #Temp
From ATable
Declare @Id int
While (Select Count(*) From #Temp) > 0
Begin
Select Top 1 @Id = Id From #Temp
--Do some processing here
Delete #Temp Where Id = @Id
End
```
The option you should choose really depends on the structure and volume of your data.
**Note:** If you are using SQL Server you would be better served using:
```
WHILE EXISTS(SELECT * FROM #Temp)
```
Using `COUNT` will have to touch every single row in the table, the `EXISTS` only needs to touch the first one (see [Josef's answer](https://stackoverflow.com/a/65294/963542) below). |
61,995 | <p>Given the following XML:</p>
<pre><code><current>
<login_name>jd</login_name>
</current>
<people>
<person>
<first>John</first>
<last>Doe</last>
<login_name>jd</login_name>
</preson>
<person>
<first>Pierre</first>
<last>Spring</last>
<login_name>ps</login_name>
</preson>
</people>
</code></pre>
<p>How can I get "John Doe" from within the current/login matcher?</p>
<p>I tried the following:</p>
<pre><code><xsl:template match="current/login_name">
<xsl:value-of select="../people/first[login_name = .]"/>
<xsl:text> </xsl:text>
<xsl:value-of select="../people/last[login_name = .]"/>
</xsl:template>
</code></pre>
| [
{
"answer_id": 62010,
"author": "Kendall Helmstetter Gelner",
"author_id": 6330,
"author_profile": "https://Stackoverflow.com/users/6330",
"pm_score": 0,
"selected": false,
"text": "<p>I think what he actually wanted was the replacement in the match for the \"current\" node, not a match ... | 2008/09/15 | [
"https://Stackoverflow.com/questions/61995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1532/"
] | Given the following XML:
```
<current>
<login_name>jd</login_name>
</current>
<people>
<person>
<first>John</first>
<last>Doe</last>
<login_name>jd</login_name>
</preson>
<person>
<first>Pierre</first>
<last>Spring</last>
<login_name>ps</login_name>
</preson>
</people>
```
How can I get "John Doe" from within the current/login matcher?
I tried the following:
```
<xsl:template match="current/login_name">
<xsl:value-of select="../people/first[login_name = .]"/>
<xsl:text> </xsl:text>
<xsl:value-of select="../people/last[login_name = .]"/>
</xsl:template>
``` | I'd define a key to index the people:
```
<xsl:key name="people" match="person" use="login_name" />
```
Using a key here simply keeps the code clean, but you might also find it helpful for efficiency if you're often having to retrieve the `<person>` elements based on their `<login_name>` child.
I'd have a template that returned the formatted name of a given `<person>`:
```
<xsl:template match="person" mode="name">
<xsl:value-of select="concat(first, ' ', last)" />
</xsl:template>
```
And then I'd do:
```
<xsl:template match="current/login_name">
<xsl:apply-templates select="key('people', .)" mode="name" />
</xsl:template>
``` |
62,013 | <p>I set up a website to use SqlMembershipProvider as written on <a href="http://msdn.microsoft.com/en-us/library/ms998347.aspx" rel="nofollow noreferrer">this page</a>.</p>
<p>I followed every step. I have the database, I modified the Web.config to use this provider, with the correct connection string, and the authentication mode is set to Forms. Created some users to test with.</p>
<p>I created a Login.aspx and put the Login control on it. Everything works fine until the point that a user can log in. </p>
<p>I call Default.aspx, it gets redirected to Login.aspx, I enter the user and the correct password. No error message, nothing seems to be wrong, but I see again the Login form, to enter the user's login information. However if I check the cookies in the browser, I can see that the cookie with the specified name exists.</p>
<p>I already tried to handle the events by myself and check, what is happening in them, but no success.</p>
<p>I'm using VS2008, Website in filesystem, SQL Express 2005 to store aspnetdb, no role management, tested with K-Meleon, IE7.0 and Chrome.</p>
<p>Any ideas?</p>
<p><strong>Resolution:</strong> After some mailing with Rob we have the ideal solution, which is now the accepted answer.</p>
| [
{
"answer_id": 62036,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 1,
"selected": false,
"text": "<p>What is the role of the username you are logging in with? Have you permitted this role to access Default.aspx?</p>\n\n<p>... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/968/"
] | I set up a website to use SqlMembershipProvider as written on [this page](http://msdn.microsoft.com/en-us/library/ms998347.aspx).
I followed every step. I have the database, I modified the Web.config to use this provider, with the correct connection string, and the authentication mode is set to Forms. Created some users to test with.
I created a Login.aspx and put the Login control on it. Everything works fine until the point that a user can log in.
I call Default.aspx, it gets redirected to Login.aspx, I enter the user and the correct password. No error message, nothing seems to be wrong, but I see again the Login form, to enter the user's login information. However if I check the cookies in the browser, I can see that the cookie with the specified name exists.
I already tried to handle the events by myself and check, what is happening in them, but no success.
I'm using VS2008, Website in filesystem, SQL Express 2005 to store aspnetdb, no role management, tested with K-Meleon, IE7.0 and Chrome.
Any ideas?
**Resolution:** After some mailing with Rob we have the ideal solution, which is now the accepted answer. | I have checked the code over in the files you have sent me (thanks again for sending them through).
**Note: I have not tested this since I have not installed the database etc..**
However, I am pretty sure this is the issue.
You need to set the *MembershipProvider* Property for your ASP.NET controls. Making the definitions for them:
```
<asp:Login ID="Login1" runat="server"
MembershipProvider="MySqlMembershipProvider">
<LayoutTemplate>
<!-- template code snipped for brevity -->
</LayoutTemplate>
</asp:Login>
```
And..
```
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server"
MembershipProvider="MySqlMembershipProvider">
<WizardSteps>
<asp:CreateUserWizardStep runat="server" />
<asp:CompleteWizardStep runat="server" />
</WizardSteps>
</asp:CreateUserWizard>
```
This then binds the controls to the Membership Provider with the given name (which you have specified in the Web.Config.
Give this a whirl in your solution and let me know how you get on.
I hope this works for you :)
### Edit
I should also add, I know you shouldn't need to do this as the default provider is set, but I *have* had problems in the past with this.. I ended up setting them all to manual and all worked fine. |
62,044 | <p>I'm trying to construct a find command to process a bunch of files in a directory using two different executables. Unfortunately, <code>-exec</code> on find doesn't allow to use pipe or even <code>\|</code> because the shell interprets that character first. </p>
<p>Here is specifically what I'm trying to do (which doesn't work because pipe ends the find command):</p>
<pre><code>find /path/to/jpgs -type f -exec jhead -v {} | grep 123 \; -print
</code></pre>
| [
{
"answer_id": 62054,
"author": "Xetius",
"author_id": 274,
"author_profile": "https://Stackoverflow.com/users/274",
"pm_score": 1,
"selected": false,
"text": "<p>As this outputs a list would you not :</p>\n\n<pre><code>find /path/to/jpgs -type f -exec jhead -v {} \\; | grep 123\n</code>... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3499/"
] | I'm trying to construct a find command to process a bunch of files in a directory using two different executables. Unfortunately, `-exec` on find doesn't allow to use pipe or even `\|` because the shell interprets that character first.
Here is specifically what I'm trying to do (which doesn't work because pipe ends the find command):
```
find /path/to/jpgs -type f -exec jhead -v {} | grep 123 \; -print
``` | Try this
```
find /path/to/jpgs -type f -exec sh -c 'jhead -v {} | grep 123' \; -print
```
Alternatively you could try to embed your exec statement inside a sh script and then do:
```
find -exec some_script {} \;
``` |
62,079 | <p>I am trying to get some accurate runtime comparisons of PHP vs Python (and potentially any other language that I have to include). Timing within a script is not my problem but timing within a script does not account for everything from the moment the request is made to run the script to output.</p>
<blockquote>
<p>1) Is it actually worth taking such things into account?</p>
<p>2) Assuming it is worth taking it into account, how do I do this?</p>
</blockquote>
<p>I'm using a Mac so I've got access to Linux commands and I'm not afraid to compile/create a command to help me, I just don't know how to write such a command.</p>
| [
{
"answer_id": 62094,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "<p>If your idea is to compare the languages, I'd say anything outside them is not relevant for comparison purposes. </... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] | I am trying to get some accurate runtime comparisons of PHP vs Python (and potentially any other language that I have to include). Timing within a script is not my problem but timing within a script does not account for everything from the moment the request is made to run the script to output.
>
> 1) Is it actually worth taking such things into account?
>
>
> 2) Assuming it is worth taking it into account, how do I do this?
>
>
>
I'm using a Mac so I've got access to Linux commands and I'm not afraid to compile/create a command to help me, I just don't know how to write such a command. | If your idea is to compare the languages, I'd say anything outside them is not relevant for comparison purposes.
Nonetheless you can use the time command to measure everything and can compare it with the timing within a script.
Like this:
```
$ time script.php
HI!
real 0m3.218s
user 0m0.080s
sys 0m0.064s
```
It will give you clock time, user time (php interpreter) and sys time (OS time)
If you are thinking web, then it gets a lot harder because you would be mixing webserver overhead and that is not always easy to compare if, say, you are using WSGI v/s mod\_php. Then you'd have to hook probes into the webserving parts of the chain as well |
62,086 | <p>I am using Adobe Flex/Air here, but as far as I know this applies to all of JavaScript. I have come across this problem a few times, and there must be an easy solution out there!</p>
<p>Suppose I have the following XML (using e4x):</p>
<pre><code>var xml:XML = <root><example>foo</example></root>
</code></pre>
<p>I can change the contents of the example node using the following code:</p>
<pre><code>xml.example = "bar";
</code></pre>
<p>However, if I have this:</p>
<pre><code>var xml:XML = <root>foo</root>
</code></pre>
<p>How do i change the contents of the root node?</p>
<pre><code>xml = "bar";
</code></pre>
<p>Obviously doesn't work as I'm attempting to assign a string to an XML object.</p>
| [
{
"answer_id": 62165,
"author": "Loren Segal",
"author_id": 6436,
"author_profile": "https://Stackoverflow.com/users/6436",
"pm_score": 0,
"selected": false,
"text": "<p>If you're trying to change the root element of a document, you don't really need to-- just throw out the existing docu... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6448/"
] | I am using Adobe Flex/Air here, but as far as I know this applies to all of JavaScript. I have come across this problem a few times, and there must be an easy solution out there!
Suppose I have the following XML (using e4x):
```
var xml:XML = <root><example>foo</example></root>
```
I can change the contents of the example node using the following code:
```
xml.example = "bar";
```
However, if I have this:
```
var xml:XML = <root>foo</root>
```
How do i change the contents of the root node?
```
xml = "bar";
```
Obviously doesn't work as I'm attempting to assign a string to an XML object. | It seems you confuse variables for the values they contain. The assignment
```
node = textInput.text;
```
changes the value the *variable* `node` points to, it doesn't change anything with the object that `node` currently points to. To do what you want to do you can use the `setChildren` method of the `XML` class:
```
node.setChildren(textInput.text)
``` |
62,137 | <p>I've just heard the term covered index in some database discussion - what does it mean?</p>
| [
{
"answer_id": 62140,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 7,
"selected": true,
"text": "<p>A <em>covering index</em> is an index that contains all of, and possibly more, the columns you need for your query.<... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5466/"
] | I've just heard the term covered index in some database discussion - what does it mean? | A *covering index* is an index that contains all of, and possibly more, the columns you need for your query.
For instance, this:
```
SELECT *
FROM tablename
WHERE criteria
```
will typically use indexes to speed up the resolution of which rows to retrieve using *criteria*, but then it will go to the full table to retrieve the rows.
However, if the index contained the columns *column1, column2* and *column3*, then this sql:
```
SELECT column1, column2
FROM tablename
WHERE criteria
```
and, provided that particular index could be used to speed up the resolution of which rows to retrieve, the index already contains the values of the columns you're interested in, so it won't have to go to the table to retrieve the rows, but can produce the results directly from the index.
This can also be used if you see that a typical query uses 1-2 columns to resolve which rows, and then typically adds another 1-2 columns, it could be beneficial to append those extra columns (if they're the same all over) to the index, so that the query processor can get everything from the index itself.
Here's an [article: Index Covering Boosts SQL Server Query Performance](http://www.devx.com/dbzone/Article/29530) on the subject. |
62,153 | <p>Several times now I've been faced with plans from a team that wants to build their own bug tracking system - Not as a product, but as an internal tool.</p>
<p>The arguments I've heard in favous are usually along the lines of :</p>
<ul>
<li>Wanting to 'eat our own dog food' in terms of some internally built web framework</li>
<li>Needing some highly specialised report, or the ability to tweak some feature in some allegedly unique way</li>
<li>Believing that it isn't difficult to build a bug tracking system</li>
</ul>
<p>What arguments might you use to support buying an existing bug tracking system? In particular, what features sound easy but turn out hard to implement, or are difficult and important but often overlooked?</p>
| [
{
"answer_id": 62162,
"author": "Slavo",
"author_id": 1801,
"author_profile": "https://Stackoverflow.com/users/1801",
"pm_score": 3,
"selected": false,
"text": "<p>The most basic argument for me would be the time loss. I doubt it could be completed in less than a month or two. Why spend ... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | Several times now I've been faced with plans from a team that wants to build their own bug tracking system - Not as a product, but as an internal tool.
The arguments I've heard in favous are usually along the lines of :
* Wanting to 'eat our own dog food' in terms of some internally built web framework
* Needing some highly specialised report, or the ability to tweak some feature in some allegedly unique way
* Believing that it isn't difficult to build a bug tracking system
What arguments might you use to support buying an existing bug tracking system? In particular, what features sound easy but turn out hard to implement, or are difficult and important but often overlooked? | First, look at these [Ohloh](http://ohloh.net) metrics:
```
Trac: 44 KLoC, 10 Person Years, $577,003
Bugzilla: 54 KLoC, 13 Person Years, $714,437
Redmine: 171 KLoC, 44 Person Years, $2,400,723
Mantis: 182 KLoC, 47 Person Years, $2,562,978
```
What do we learn from these numbers? We learn that building Yet Another Bug Tracker is a great way to waste resources!
So here are my reasons to build your own internal bug tracking system:
1. You need to neutralize all the bozocoders for a decade or two.
2. You need to flush some money to avoid budget reduction next year.
Otherwise don't. |
62,188 | <p>To commemorate the public launch of Stack Overflow, what's the shortest code to cause a stack overflow? Any language welcome.</p>
<p>ETA: Just to be clear on this question, seeing as I'm an occasional Scheme user: tail-call "recursion" is really iteration, and any solution which can be converted to an iterative solution relatively trivially by a decent compiler won't be counted. :-P</p>
<p>ETA2: I've now selected a “best answer”; see <a href="https://stackoverflow.com/questions/62188/stack-overflow-code-golf/71833#71833">this post</a> for rationale. Thanks to everyone who contributed! :-)</p>
| [
{
"answer_id": 62189,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 7,
"selected": false,
"text": "<p>My current best (in x86 assembly) is:</p>\n\n<pre><code>push eax\njmp short $-1\n</code></pre>\n\n<p>which results in 3 by... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13/"
] | To commemorate the public launch of Stack Overflow, what's the shortest code to cause a stack overflow? Any language welcome.
ETA: Just to be clear on this question, seeing as I'm an occasional Scheme user: tail-call "recursion" is really iteration, and any solution which can be converted to an iterative solution relatively trivially by a decent compiler won't be counted. :-P
ETA2: I've now selected a “best answer”; see [this post](https://stackoverflow.com/questions/62188/stack-overflow-code-golf/71833#71833) for rationale. Thanks to everyone who contributed! :-) | All these answers and no Befunge? I'd wager a fair amount it's shortest solution of them all:
```
1
```
Not kidding. Try it yourself: <http://www.quirkster.com/iano/js/befunge.html>
EDIT: I guess I need to explain this one. The 1 operand pushes a 1 onto Befunge's internal stack and the lack of anything else puts it in a loop under the rules of the language.
Using the interpreter provided, you will eventually--and I mean *eventually*--hit a point where the Javascript array that represents the Befunge stack becomes too large for the browser to reallocate. If you had a simple Befunge interpreter with a smaller and bounded stack--as is the case with most of the languages below--this program would cause a more noticeable overflow faster. |
62,226 | <p>An instance of class A instantiates a couple of other objects, say for example from class B:</p>
<pre><code>$foo = new B();
</code></pre>
<p>I would like to access A's public class variables from methods within B.</p>
<p>Unless I'm missing something, the only way to do this is to pass the current object to the instances of B:</p>
<pre><code>$foo = new B($this);
</code></pre>
<p>Is this best practice or is there another way to do this?</p>
| [
{
"answer_id": 62242,
"author": "Hanno Fietz",
"author_id": 2077,
"author_profile": "https://Stackoverflow.com/users/2077",
"pm_score": 1,
"selected": false,
"text": "<p>I would first check if you are not using the wrong pattern: From your application logic, should B really know about A?... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6260/"
] | An instance of class A instantiates a couple of other objects, say for example from class B:
```
$foo = new B();
```
I would like to access A's public class variables from methods within B.
Unless I'm missing something, the only way to do this is to pass the current object to the instances of B:
```
$foo = new B($this);
```
Is this best practice or is there another way to do this? | That looks fine to me, I tend to use a rule of thumb of "would someone maintaining this understand it?" and that's an easily understood solution.
If there's only one "A", you could consider using the registry pattern, see for example <http://www.phppatterns.com/docs/design/the_registry> |
62,230 | <p>How do I save a jpg image to database and then load it in Delphi using FIBplus and TImage?</p>
| [
{
"answer_id": 62271,
"author": "Roger Ween",
"author_id": 6143,
"author_profile": "https://Stackoverflow.com/users/6143",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"http://delphi.about.com/od/database/l/aa030601a.htm\" rel=\"nofollow noreferrer\">Take a look here.</a>\nI t... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6155/"
] | How do I save a jpg image to database and then load it in Delphi using FIBplus and TImage? | ```
var
S : TMemoryStream;
begin
S := TMemoryStream.Create;
try
TBlobField(AdoQuery1.FieldByName('ImageField')).SaveToStream(S);
S.Position := 0;
Image1.Picture.Graphic.LoadFromStream(S);
finally
S.Free;
end;
end;
```
if you are using JPEG images, add JPG unit to **uses** clause of your unit file. |
62,245 | <p>I am trying to refactor some code I have for software that collects current status of agents in a call queue. Currently, for each of the 6 or so events that I listen to, I check in a Mnesia table if an agent exists and change some values in the row depending on the event or add it as new if the agent doesn't exist. Currently I have this Mnesia transaction in each event and of course that is a bunch of repeated code for checking the existence of agents and so on. </p>
<p>I'm trying to change it so that there is one function like <em>change_agent/2</em> that I call from the events that handles this for me. </p>
<p>My problems are of course records.... I find no way of dynamically creating them or merging 2 of them together or anything. Preferably there would be a function I could call like:</p>
<pre><code>change_agent("001", #agent(id = "001", name = "Steve")).
change_agent("001", #agent(id = "001", paused = 0, talking_to = "None")).
</code></pre>
| [
{
"answer_id": 62556,
"author": "uwiger",
"author_id": 6834,
"author_profile": "https://Stackoverflow.com/users/6834",
"pm_score": 2,
"selected": false,
"text": "<p>It is difficult to write generic access functions for records.\nOne workaround for this is the <a href=\"http://forum.trape... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5601/"
] | I am trying to refactor some code I have for software that collects current status of agents in a call queue. Currently, for each of the 6 or so events that I listen to, I check in a Mnesia table if an agent exists and change some values in the row depending on the event or add it as new if the agent doesn't exist. Currently I have this Mnesia transaction in each event and of course that is a bunch of repeated code for checking the existence of agents and so on.
I'm trying to change it so that there is one function like *change\_agent/2* that I call from the events that handles this for me.
My problems are of course records.... I find no way of dynamically creating them or merging 2 of them together or anything. Preferably there would be a function I could call like:
```
change_agent("001", #agent(id = "001", name = "Steve")).
change_agent("001", #agent(id = "001", paused = 0, talking_to = "None")).
``` | I wrote some code a while ago that merges two records. Is not entirely dynamic, but whith macros you could easily use it for several records.
It works like this: The merge/2 function takes two records and converts them to lists together with the empty record for reference (the record type is defined at compile time, and must be. This is the "undynamic" part). These are then run through the generic function merge/4 which works with lists and takes elements from A if they are defined, otherwise from B if they are defined, or lastly from Default (which is always defined).
Here's the code (please excuse StackOverflow's poor Erlang syntax highlighting):
```
%%%----------------------------------------------------------------------------
%%% @spec merge(RecordA, RecordB) -> #my_record{}
%%% RecordA = #my_record{}
%%% RecordB = #my_record{}
%%%
%%% @doc Merges two #my_record{} instances. The first takes precedence.
%%% @end
%%%----------------------------------------------------------------------------
merge(RecordA, RecordB) when is_record(RecordA, my_record),
is_record(RecordB, my_record) ->
list_to_tuple(
lists:append([my_record],
merge(tl(tuple_to_list(RecordA)),
tl(tuple_to_list(RecordB)),
tl(tuple_to_list(#my_record{})),
[]))).
%%%----------------------------------------------------------------------------
%%% @spec merge(A, B, Default, []) -> [term()]
%%% A = [term()]
%%% B = [term()]
%%% Default = [term()]
%%%
%%% @doc Merges the lists `A' and `B' into to a new list taking
%%% default values from `Default'.
%%%
%%% Each element of `A' and `B' are compared against the elements in
%%% `Default'. If they match the default, the default is used. If one
%%% of them differs from the other and the default value, that element is
%%% chosen. If both differs, the element from `A' is chosen.
%%% @end
%%%----------------------------------------------------------------------------
merge([D|ATail], [D|BTail], [D|DTail], To) ->
merge(ATail, BTail, DTail, [D|To]); % If default, take from D
merge([D|ATail], [B|BTail], [D|DTail], To) ->
merge(ATail, BTail, DTail, [B|To]); % If only A default, take from B
merge([A|ATail], [_|BTail], [_|DTail], To) ->
merge(ATail, BTail, DTail, [A|To]); % Otherwise take from A
merge([], [], [], To) ->
lists:reverse(To).
```
Feel free to use it in any way you want. |
62,264 | <p>I recently asked about <a href="https://stackoverflow.com/questions/39742/does-git-have-anything-like-svn-propset-svnkeywords-or-pre-post-commit-hooks">keyword expansion in Git</a> and I'm willing to accept the design not to really support this idea in Git. </p>
<p>For better or worse, the project I'm working on at the moment requires SVN keyword expansion like this:</p>
<pre><code>svn propset svn:keywords "Id" expl3.dtx
</code></pre>
<p>to keep this string up-to-date:</p>
<pre><code>$Id: expl3.dtx 803 2008-09-11 14:01:58Z will $
</code></pre>
<p>But I would quite like to use Git to do my version control. Unfortunately, git-svn doesn't support this, according to the docs:</p>
<blockquote>
<p>"We ignore all SVN properties except svn:executable"</p>
</blockquote>
<p>But it doesn't seem too tricky to have this keyword stuff emulated by a couple of pre/post commit hooks. Am I the first person to want this? Does anyone have some code to do this?</p>
| [
{
"answer_id": 62288,
"author": "Lily Ballard",
"author_id": 582,
"author_profile": "https://Stackoverflow.com/users/582",
"pm_score": 1,
"selected": false,
"text": "<p>You could set the ident attribute on your files, but that would produce strings like</p>\n\n<pre><code>$Id: deadbeefdea... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4161/"
] | I recently asked about [keyword expansion in Git](https://stackoverflow.com/questions/39742/does-git-have-anything-like-svn-propset-svnkeywords-or-pre-post-commit-hooks) and I'm willing to accept the design not to really support this idea in Git.
For better or worse, the project I'm working on at the moment requires SVN keyword expansion like this:
```
svn propset svn:keywords "Id" expl3.dtx
```
to keep this string up-to-date:
```
$Id: expl3.dtx 803 2008-09-11 14:01:58Z will $
```
But I would quite like to use Git to do my version control. Unfortunately, git-svn doesn't support this, according to the docs:
>
> "We ignore all SVN properties except svn:executable"
>
>
>
But it doesn't seem too tricky to have this keyword stuff emulated by a couple of pre/post commit hooks. Am I the first person to want this? Does anyone have some code to do this? | What's going on here: Git is optimized to switch between branches as quickly as possible. In particular, `git checkout` is designed to not touch any files that are identical in both branches.
Unfortunately, RCS keyword substitution breaks this. For example, using `$Date$` would require `git checkout` to touch every file in the tree when switching branches. For a repository the size of the Linux kernel, this would bring everything to a screeching halt.
In general, your best bet is to tag at least one version:
```
$ git tag v0.5.whatever
```
...and then call the following command from your Makefile:
```
$ git describe --tags
v0.5.15.1-6-g61cde1d
```
Here, git is telling me that I'm working on an anonymous version 6 commits past v0.5.15.1, with an SHA1 hash beginning with `g61cde1d`. If you stick the output of this command into a `*.h` file somewhere, you're in business, and will have no problem linking the released software back to the source code. This is the preferred way of doing things.
If you can't possibly avoid using RCS keywords, you may want to start with this [explanation by Lars Hjemli](http://kerneltrap.org/mailarchive/git/2007/10/12/335953). Basically, `$Id$` is pretty easy, and you if you're using `git archive`, you can also use `$Format$`.
But, if you absolutely cannot avoid RCS keywords, the following should get you started:
```
git config filter.rcs-keyword.clean 'perl -pe "s/\\\$Date[^\\\$]*\\\$/\\\$Date\\\$/"'
git config filter.rcs-keyword.smudge 'perl -pe "s/\\\$Date[^\\\$]*\\\$/\\\$Date: `date`\\\$/"'
echo '$Date$' > test.html
echo 'test.html filter=rcs-keyword' >> .gitattributes
git add test.html .gitattributes
git commit -m "Experimental RCS keyword support for git"
rm test.html
git checkout test.html
cat test.html
```
On my system, I get:
```
$Date: Tue Sep 16 10:15:02 EDT 2008$
```
If you have trouble getting the shell escapes in the `smudge` and `clean` commands to work, just write your own Perl scripts for expanding and removing RCS keywords, respectively, and use those scripts as your filter.
Note that you *really* don't want to do this for more files than absolutely necessary, or git will lose most of its speed. |
62,289 | <p>How is it possible to read/write to the Windows registry using Java?</p>
| [
{
"answer_id": 62291,
"author": "Epaga",
"author_id": 6583,
"author_profile": "https://Stackoverflow.com/users/6583",
"pm_score": 4,
"selected": false,
"text": "<p>Yes, using the java.util.Preferences API, since the Windows implementation of it uses the Registry as a backend.</p>\n<p>In ... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | How is it possible to read/write to the Windows registry using Java? | I know this question is old, but it is the first search result on google to "java read/write to registry". Recently I found this amazing piece of code which:
* Can read/write to ANY part of the registry.
* DOES NOT USE JNI.
* DOES NOT USE ANY 3rd PARTY/EXTERNAL APPLICATIONS TO WORK.
* DOES NOT USE THE WINDOWS API (directly)
This is pure, Java code.
It uses reflection to work, by actually accessing the private methods in the `java.util.prefs.Preferences` class. The internals of this class are complicated, but the class itself is very easy to use.
For example, the following code obtains the exact windows distribution **from the registry**:
```
String value = WinRegistry.readString (
WinRegistry.HKEY_LOCAL_MACHINE, //HKEY
"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", //Key
"ProductName"); //ValueName
System.out.println("Windows Distribution = " + value);
```
Here is the original class. Just copy paste it and it should work:
```
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;
public class WinRegistry {
public static final int HKEY_CURRENT_USER = 0x80000001;
public static final int HKEY_LOCAL_MACHINE = 0x80000002;
public static final int REG_SUCCESS = 0;
public static final int REG_NOTFOUND = 2;
public static final int REG_ACCESSDENIED = 5;
private static final int KEY_ALL_ACCESS = 0xf003f;
private static final int KEY_READ = 0x20019;
private static final Preferences userRoot = Preferences.userRoot();
private static final Preferences systemRoot = Preferences.systemRoot();
private static final Class<? extends Preferences> userClass = userRoot.getClass();
private static final Method regOpenKey;
private static final Method regCloseKey;
private static final Method regQueryValueEx;
private static final Method regEnumValue;
private static final Method regQueryInfoKey;
private static final Method regEnumKeyEx;
private static final Method regCreateKeyEx;
private static final Method regSetValueEx;
private static final Method regDeleteKey;
private static final Method regDeleteValue;
static {
try {
regOpenKey = userClass.getDeclaredMethod("WindowsRegOpenKey",
new Class[] { int.class, byte[].class, int.class });
regOpenKey.setAccessible(true);
regCloseKey = userClass.getDeclaredMethod("WindowsRegCloseKey",
new Class[] { int.class });
regCloseKey.setAccessible(true);
regQueryValueEx = userClass.getDeclaredMethod("WindowsRegQueryValueEx",
new Class[] { int.class, byte[].class });
regQueryValueEx.setAccessible(true);
regEnumValue = userClass.getDeclaredMethod("WindowsRegEnumValue",
new Class[] { int.class, int.class, int.class });
regEnumValue.setAccessible(true);
regQueryInfoKey = userClass.getDeclaredMethod("WindowsRegQueryInfoKey1",
new Class[] { int.class });
regQueryInfoKey.setAccessible(true);
regEnumKeyEx = userClass.getDeclaredMethod(
"WindowsRegEnumKeyEx", new Class[] { int.class, int.class,
int.class });
regEnumKeyEx.setAccessible(true);
regCreateKeyEx = userClass.getDeclaredMethod(
"WindowsRegCreateKeyEx", new Class[] { int.class,
byte[].class });
regCreateKeyEx.setAccessible(true);
regSetValueEx = userClass.getDeclaredMethod(
"WindowsRegSetValueEx", new Class[] { int.class,
byte[].class, byte[].class });
regSetValueEx.setAccessible(true);
regDeleteValue = userClass.getDeclaredMethod(
"WindowsRegDeleteValue", new Class[] { int.class,
byte[].class });
regDeleteValue.setAccessible(true);
regDeleteKey = userClass.getDeclaredMethod(
"WindowsRegDeleteKey", new Class[] { int.class,
byte[].class });
regDeleteKey.setAccessible(true);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
private WinRegistry() { }
/**
* Read a value from key and value name
* @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @param valueName
* @return the value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static String readString(int hkey, String key, String valueName)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
return readString(systemRoot, hkey, key, valueName);
}
else if (hkey == HKEY_CURRENT_USER) {
return readString(userRoot, hkey, key, valueName);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Read value(s) and value name(s) form given key
* @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @return the value name(s) plus the value(s)
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static Map<String, String> readStringValues(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
return readStringValues(systemRoot, hkey, key);
}
else if (hkey == HKEY_CURRENT_USER) {
return readStringValues(userRoot, hkey, key);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Read the value name(s) from a given key
* @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @return the value name(s)
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static List<String> readStringSubKeys(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
return readStringSubKeys(systemRoot, hkey, key);
}
else if (hkey == HKEY_CURRENT_USER) {
return readStringSubKeys(userRoot, hkey, key);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Create a key
* @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void createKey(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int [] ret;
if (hkey == HKEY_LOCAL_MACHINE) {
ret = createKey(systemRoot, hkey, key);
regCloseKey.invoke(systemRoot, new Object[] { new Integer(ret[0]) });
}
else if (hkey == HKEY_CURRENT_USER) {
ret = createKey(userRoot, hkey, key);
regCloseKey.invoke(userRoot, new Object[] { new Integer(ret[0]) });
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
if (ret[1] != REG_SUCCESS) {
throw new IllegalArgumentException("rc=" + ret[1] + " key=" + key);
}
}
/**
* Write a value in a given key/value name
* @param hkey
* @param key
* @param valueName
* @param value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void writeStringValue
(int hkey, String key, String valueName, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
writeStringValue(systemRoot, hkey, key, valueName, value);
}
else if (hkey == HKEY_CURRENT_USER) {
writeStringValue(userRoot, hkey, key, valueName, value);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Delete a given key
* @param hkey
* @param key
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void deleteKey(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int rc = -1;
if (hkey == HKEY_LOCAL_MACHINE) {
rc = deleteKey(systemRoot, hkey, key);
}
else if (hkey == HKEY_CURRENT_USER) {
rc = deleteKey(userRoot, hkey, key);
}
if (rc != REG_SUCCESS) {
throw new IllegalArgumentException("rc=" + rc + " key=" + key);
}
}
/**
* delete a value from a given key/value name
* @param hkey
* @param key
* @param value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void deleteValue(int hkey, String key, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int rc = -1;
if (hkey == HKEY_LOCAL_MACHINE) {
rc = deleteValue(systemRoot, hkey, key, value);
}
else if (hkey == HKEY_CURRENT_USER) {
rc = deleteValue(userRoot, hkey, key, value);
}
if (rc != REG_SUCCESS) {
throw new IllegalArgumentException("rc=" + rc + " key=" + key + " value=" + value);
}
}
// =====================
private static int deleteValue
(Preferences root, int hkey, String key, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS) });
if (handles[1] != REG_SUCCESS) {
return handles[1]; // can be REG_NOTFOUND, REG_ACCESSDENIED
}
int rc =((Integer) regDeleteValue.invoke(root,
new Object[] {
new Integer(handles[0]), toCstr(value)
})).intValue();
regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
return rc;
}
private static int deleteKey(Preferences root, int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int rc =((Integer) regDeleteKey.invoke(root,
new Object[] { new Integer(hkey), toCstr(key) })).intValue();
return rc; // can REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS
}
private static String readString(Preferences root, int hkey, String key, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
new Integer(hkey), toCstr(key), new Integer(KEY_READ) });
if (handles[1] != REG_SUCCESS) {
return null;
}
byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {
new Integer(handles[0]), toCstr(value) });
regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
return (valb != null ? new String(valb).trim() : null);
}
private static Map<String,String> readStringValues
(Preferences root, int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
HashMap<String, String> results = new HashMap<String,String>();
int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
new Integer(hkey), toCstr(key), new Integer(KEY_READ) });
if (handles[1] != REG_SUCCESS) {
return null;
}
int[] info = (int[]) regQueryInfoKey.invoke(root,
new Object[] { new Integer(handles[0]) });
int count = info[0]; // count
int maxlen = info[3]; // value length max
for(int index=0; index<count; index++) {
byte[] name = (byte[]) regEnumValue.invoke(root, new Object[] {
new Integer
(handles[0]), new Integer(index), new Integer(maxlen + 1)});
String value = readString(hkey, key, new String(name));
results.put(new String(name).trim(), value);
}
regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
return results;
}
private static List<String> readStringSubKeys
(Preferences root, int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
List<String> results = new ArrayList<String>();
int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
new Integer(hkey), toCstr(key), new Integer(KEY_READ)
});
if (handles[1] != REG_SUCCESS) {
return null;
}
int[] info = (int[]) regQueryInfoKey.invoke(root,
new Object[] { new Integer(handles[0]) });
int count = info[0]; // Fix: info[2] was being used here with wrong results. Suggested by davenpcj, confirmed by Petrucio
int maxlen = info[3]; // value length max
for(int index=0; index<count; index++) {
byte[] name = (byte[]) regEnumKeyEx.invoke(root, new Object[] {
new Integer
(handles[0]), new Integer(index), new Integer(maxlen + 1)
});
results.add(new String(name).trim());
}
regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
return results;
}
private static int [] createKey(Preferences root, int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
return (int[]) regCreateKeyEx.invoke(root,
new Object[] { new Integer(hkey), toCstr(key) });
}
private static void writeStringValue
(Preferences root, int hkey, String key, String valueName, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS) });
regSetValueEx.invoke(root,
new Object[] {
new Integer(handles[0]), toCstr(valueName), toCstr(value)
});
regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
}
// utility
private static byte[] toCstr(String str) {
byte[] result = new byte[str.length() + 1];
for (int i = 0; i < str.length(); i++) {
result[i] = (byte) str.charAt(i);
}
result[str.length()] = 0;
return result;
}
}
```
Original Author: Apache.
Library Source: <https://github.com/apache/npanday/tree/trunk/components/dotnet-registry/src/main/java/npanday/registry> |
62,317 | <p>In PHP, how can I replicate the expand/contract feature for Tinyurls as on search.twitter.com?</p>
| [
{
"answer_id": 62367,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 4,
"selected": true,
"text": "<p>If you want to find out where a tinyurl is going, use fsockopen to get a connection to tinyurl.com on port 80, and send ... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In PHP, how can I replicate the expand/contract feature for Tinyurls as on search.twitter.com? | If you want to find out where a tinyurl is going, use fsockopen to get a connection to tinyurl.com on port 80, and send it an HTTP request like this
```
GET /dmsfm HTTP/1.0
Host: tinyurl.com
```
The response you get back will look like
```
HTTP/1.0 301 Moved Permanently
Connection: close
X-Powered-By: PHP/5.2.6
Location: http://en.wikipedia.org/wiki/TinyURL
Content-type: text/html
Content-Length: 0
Date: Mon, 15 Sep 2008 12:29:04 GMT
Server: TinyURL/1.6
```
example code...
```
<?php
$tinyurl="dmsfm";
$fp = fsockopen("tinyurl.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET /$tinyurl HTTP/1.0\r\n";
$out .= "Host: tinyurl.com\r\n";
$out .= "Connection: Close\r\n\r\n";
$response="";
fwrite($fp, $out);
while (!feof($fp)) {
$response.=fgets($fp, 128);
}
fclose($fp);
//now parse the Location: header out of the response
}
?>
``` |
62,340 | <pre><code>std::vector<int> ints;
// ... fill ints with random values
for(std::vector<int>::iterator it = ints.begin(); it != ints.end(); )
{
if(*it < 10)
{
*it = ints.back();
ints.pop_back();
continue;
}
it++;
}
</code></pre>
<p>This code is not working because when <code>pop_back()</code> is called, <code>it</code> is invalidated. But I don't find any doc talking about invalidation of iterators in <code>std::vector::pop_back()</code>.</p>
<p>Do you have some links about that?</p>
| [
{
"answer_id": 62368,
"author": "David Joyner",
"author_id": 1146,
"author_profile": "https://Stackoverflow.com/users/1146",
"pm_score": 1,
"selected": false,
"text": "<p>Iterators are only invalidated on reallocation of storage. Google is your friend: <a href=\"http://www.sgi.com/tech/... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6605/"
] | ```
std::vector<int> ints;
// ... fill ints with random values
for(std::vector<int>::iterator it = ints.begin(); it != ints.end(); )
{
if(*it < 10)
{
*it = ints.back();
ints.pop_back();
continue;
}
it++;
}
```
This code is not working because when `pop_back()` is called, `it` is invalidated. But I don't find any doc talking about invalidation of iterators in `std::vector::pop_back()`.
Do you have some links about that? | The call to [`pop_back()`](http://en.cppreference.com/w/cpp/container/vector/pop_back) removes the last element in the vector and so the iterator to that element is invalidated. The `pop_back()` call does *not* invalidate iterators to items before the last element, only reallocation will do that. From Josuttis' "C++ Standard Library Reference":
>
> Inserting or removing elements
> invalidates references, pointers, and
> iterators that refer to the following
> element. If an insertion causes
> reallocation, it invalidates all
> references, iterators, and pointers.
>
>
> |
62,353 | <p>I have a solution with multiple project. I am trying to optimize AssemblyInfo.cs files by linking one solution wide assembly info file. What are the best practices for doing this? Which attributes should be in solution wide file and which are project/assembly specific?</p>
<hr>
<p><em>Edit: If you are interested there is a follow up question <a href="https://stackoverflow.com/questions/64602/what-are-differences-between-assemblyversion-assemblyfileversion-and-assemblyin">What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?</a></em></p>
| [
{
"answer_id": 62631,
"author": "SaguiItay",
"author_id": 6980,
"author_profile": "https://Stackoverflow.com/users/6980",
"pm_score": 0,
"selected": false,
"text": "<p>Using a single AseemblyInfo.cs file for multiple projects is not recommended.\nThe AssemblyInfo file includes informatio... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361/"
] | I have a solution with multiple project. I am trying to optimize AssemblyInfo.cs files by linking one solution wide assembly info file. What are the best practices for doing this? Which attributes should be in solution wide file and which are project/assembly specific?
---
*Edit: If you are interested there is a follow up question [What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?](https://stackoverflow.com/questions/64602/what-are-differences-between-assemblyversion-assemblyfileversion-and-assemblyin)* | We're using a global file called GlobalAssemblyInfo.cs and a local one called AssemblyInfo.cs. The global file contains the following attributes:
```
[assembly: AssemblyProduct("Your Product Name")]
[assembly: AssemblyCompany("Your Company")]
[assembly: AssemblyCopyright("Copyright © 2008 ...")]
[assembly: AssemblyTrademark("Your Trademark - if applicable")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyVersion("This is set by build process")]
[assembly: AssemblyFileVersion("This is set by build process")]
```
The local AssemblyInfo.cs contains the following attributes:
```
[assembly: AssemblyTitle("Your assembly title")]
[assembly: AssemblyDescription("Your assembly description")]
[assembly: AssemblyCulture("The culture - if not neutral")]
[assembly: ComVisible(true/false)]
// unique id per assembly
[assembly: Guid("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")]
```
You can add the GlobalAssemblyInfo.cs using the following procedure:
* Select **Add/Existing Item...** in the context menu of the project
* Select GlobalAssemblyInfo.cs
* Expand the Add-Button by clicking on that little down-arrow on the right hand
* Select "Add As Link" in the buttons drop down list |
62,365 | <p>Say I have an ASMX web service, MyService. The service has a method, MyMethod. I could execute MyMethod on the server side as follows:</p>
<pre><code>MyService service = new MyService();
service.MyMethod();
</code></pre>
<p>I need to do similar, with service and method not known until runtime. </p>
<p>I'm assuming that reflection is the way to go about that. Unfortunately, I'm having a hard time making it work. When I execute this code:</p>
<pre><code>Type.GetType("MyService", true);
</code></pre>
<p>It throws this error:</p>
<blockquote>
<p>Could not load type 'MyService' from assembly 'App_Web__ktsp_r0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.</p>
</blockquote>
<p>Any guidance would be appreciated.</p>
| [
{
"answer_id": 62381,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 3,
"selected": true,
"text": "<p>I'm not sure if this would be the best way to go about it. The most obvious way to me, would be to make an HTTP Request, an... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60/"
] | Say I have an ASMX web service, MyService. The service has a method, MyMethod. I could execute MyMethod on the server side as follows:
```
MyService service = new MyService();
service.MyMethod();
```
I need to do similar, with service and method not known until runtime.
I'm assuming that reflection is the way to go about that. Unfortunately, I'm having a hard time making it work. When I execute this code:
```
Type.GetType("MyService", true);
```
It throws this error:
>
> Could not load type 'MyService' from assembly 'App\_Web\_\_ktsp\_r0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
>
>
>
Any guidance would be appreciated. | I'm not sure if this would be the best way to go about it. The most obvious way to me, would be to make an HTTP Request, and call the webservice using an actual HTTP GET or POST. Using your method, I'm not entirely sure how you'd set up the data you are sending to the web service. I've added some sample code in VB.Net
```
Dim HTTPRequest As HttpWebRequest
Dim HTTPResponse As HttpWebResponse
Dim ResponseReader As StreamReader
Dim URL AS String
Dim ResponseText As String
URL = "http://www.example.com/MyWebSerivce/MyMethod?arg1=A&arg2=B"
HTTPRequest = HttpWebRequest.Create(URL)
HTTPRequest.Method = "GET"
HTTPResponse = HTTPRequest.GetResponse()
ResponseReader = New StreamReader(HTTPResponse.GetResponseStream())
ResponseText = ResponseReader.ReadToEnd()
``` |
62,382 | <p>I might be missing something really obvious. I'm trying to write a custom Panel where the contents are laid out according to a couple of dependency properties (I'm assuming they <em>have</em> to be DPs because I want to be able to animate them.)</p>
<p>However, when I try to run a storyboard to animate both of these properties, Silverlight throws a Catastophic Error. But if I try to animate just one of them, it works fine. And if I try to animate one of my properties and a 'built-in' property (like Opacity) it also works. But if I try to animate both my custom properties I get the Catastrophic error.</p>
<p>Anyone else come across this?</p>
<p>edit:</p>
<p>The two DPs are ScaleX and ScaleY - both doubles. They scale the X and Y position of children in the panel. Here's how one of them is defined:</p>
<pre><code> public double ScaleX
{
get { return (double)GetValue(ScaleXProperty); }
set { SetValue(ScaleXProperty, value); }
}
/// <summary>
/// Identifies the ScaleX dependency property.
/// </summary>
public static readonly DependencyProperty ScaleXProperty =
DependencyProperty.Register(
"ScaleX",
typeof(double),
typeof(MyPanel),
new PropertyMetadata(OnScaleXPropertyChanged));
/// <summary>
/// ScaleXProperty property changed handler.
/// </summary>
/// <param name="d">MyPanel that changed its ScaleX.</param>
/// <param name="e">DependencyPropertyChangedEventArgs.</param>
private static void OnScaleXPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MyPanel _MyPanel = d as MyPanel;
if (_MyPanel != null)
{
_MyPanel.InvalidateArrange();
}
}
public static void SetScaleX(DependencyObject obj, double val)
{
obj.SetValue(ScaleXProperty, val);
}
public static double GetScaleX(DependencyObject obj)
{
return (double)obj.GetValue(ScaleXProperty);
}
</code></pre>
<p>Edit: I've tried it with and without the call to InvalidateArrange (which is absolutely necessary in any case) and the result is the same. The event handler doesn't even get called before the Catastrophic error kicks off.</p>
| [
{
"answer_id": 72058,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I would try commenting out the InvalidateArrange in the OnPropertyChanged and see what happens.</p>\n"
},
{
"answer_... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6483/"
] | I might be missing something really obvious. I'm trying to write a custom Panel where the contents are laid out according to a couple of dependency properties (I'm assuming they *have* to be DPs because I want to be able to animate them.)
However, when I try to run a storyboard to animate both of these properties, Silverlight throws a Catastophic Error. But if I try to animate just one of them, it works fine. And if I try to animate one of my properties and a 'built-in' property (like Opacity) it also works. But if I try to animate both my custom properties I get the Catastrophic error.
Anyone else come across this?
edit:
The two DPs are ScaleX and ScaleY - both doubles. They scale the X and Y position of children in the panel. Here's how one of them is defined:
```
public double ScaleX
{
get { return (double)GetValue(ScaleXProperty); }
set { SetValue(ScaleXProperty, value); }
}
/// <summary>
/// Identifies the ScaleX dependency property.
/// </summary>
public static readonly DependencyProperty ScaleXProperty =
DependencyProperty.Register(
"ScaleX",
typeof(double),
typeof(MyPanel),
new PropertyMetadata(OnScaleXPropertyChanged));
/// <summary>
/// ScaleXProperty property changed handler.
/// </summary>
/// <param name="d">MyPanel that changed its ScaleX.</param>
/// <param name="e">DependencyPropertyChangedEventArgs.</param>
private static void OnScaleXPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MyPanel _MyPanel = d as MyPanel;
if (_MyPanel != null)
{
_MyPanel.InvalidateArrange();
}
}
public static void SetScaleX(DependencyObject obj, double val)
{
obj.SetValue(ScaleXProperty, val);
}
public static double GetScaleX(DependencyObject obj)
{
return (double)obj.GetValue(ScaleXProperty);
}
```
Edit: I've tried it with and without the call to InvalidateArrange (which is absolutely necessary in any case) and the result is the same. The event handler doesn't even get called before the Catastrophic error kicks off. | It's a documented bug with Silverlight 2 Beta 2. You can't animate two custom dependancy properties on the same object. |
62,430 | <p>Is is possible to construct a regular expression that rejects all input strings?</p>
| [
{
"answer_id": 62438,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": -1,
"selected": false,
"text": "<p>EDIT:\n [^\\n\\r\\w\\s]</p>\n"
},
{
"answer_id": 62473,
"author": "Jan Hančič",
"author_id": 185527,
... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4984/"
] | Is is possible to construct a regular expression that rejects all input strings? | Probably this:
```
[^\w\W]
```
\w - word character (letter, digit, etc)
\W - opposite of \w
[^\w\W] - should always fail, because any character should belong to one of the character classes - \w or \W
Another snippets:
```
$.^
```
$ - assert position at the end of the string
^ - assert position at the start of the line
. - any char
```
(?#it's just a comment inside of empty regex)
```
Empty lookahead/behind should work:
```
(?<!)
``` |
62,436 | <p>I am having a problem with the speed of accessing an association property with a large number of records.</p>
<p>I have an XAF app with a parent class called <code>MyParent</code>.</p>
<p>There are 230 records in <code>MyParent</code>.</p>
<p><code>MyParent</code> has a child class called <code>MyChild</code>.</p>
<p>There are 49,000 records in <code>MyChild</code>.</p>
<p>I have an association defined between <code>MyParent</code> and <code>MyChild</code> in the standard way:</p>
<p>In <code>MyChild</code>:</p>
<pre><code>// MyChild (many) and MyParent (one)
[Association("MyChild-MyParent")]
public MyParent MyParent;
</code></pre>
<p>And in <code>MyParent</code>:</p>
<pre><code>[Association("MyChild-MyParent", typeof(MyChild))]
public XPCollection<MyCHild> MyCHildren
{
get { return GetCollection<MyCHild>("MyCHildren"); }
}
</code></pre>
<p>There's a specific <code>MyParent</code> record called <code>MyParent1</code>.</p>
<p>For <code>MyParent1</code>, there are 630 <code>MyChild</code> records.</p>
<p>I have a DetailView for a class called <code>MyUI</code>.</p>
<p>The user chooses an item in one drop-down in the <code>MyUI</code> DetailView, and my code has to fill another drop-down with <code>MyChild</code> objects.</p>
<p>The user chooses <code>MyParent1</code> in the first drop-down.</p>
<p>I created a property in <code>MyUI</code> to return the collection of <code>MyChild</code> objects for the selected value in the first drop-down.</p>
<p>Here is the code for the property:</p>
<pre><code>[NonPersistent]
public XPCollection<MyChild> DisplayedValues
{
get
{
Session theSession;
MyParent theParentValue;
XPCollection<MyCHild> theChildren;
theParentValue = this.DropDownOne;
// get the parent value
if theValue == null)
{
// if none
return null;
// return null
}
theChildren = theParentValue.MyChildren;
// get the child values for the parent
return theChildren;
// return it
}
</code></pre>
<p>I marked the <code>DisplayedValues</code> property as <code>NonPersistent</code> because it is only needed for the UI of the DetailVIew. I don't think that persisting it will speed up the creation of the collection the first time, and after it's used to fill the drop-down, I don't need it, so I don't want to spend time storing it.</p>
<p>The problem is that it takes 45 seconds to call <code>theParentValue = this.DropDownOne</code>.</p>
<p>Specs:</p>
<ul>
<li>Vista Business</li>
<li>8 GB of RAM</li>
<li>2.33 GHz E6550 processor</li>
<li>SQL Server Express 2005</li>
</ul>
<p>This is too long for users to wait for one of many drop-downs in the DetailView.</p>
<p>I took the time to sketch out the business case because I have two questions:</p>
<ol>
<li><p>How can I make the associated values load faster?</p></li>
<li><p>Is there another (simple) way to program the drop-downs and DetailView that runs much faster?</p></li>
</ol>
<p>Yes, you can say that 630 is too many items to display in a drop-down, but this code is taking so long I suspect that the speed is proportional to the 49,000 and not to the 630. 100 items in the drop-down would not be too many for my app.</p>
<p>I need quite a few of these drop-downs in my app, so it's not appropriate to force the user to enter more complicated filtering criteria for each one. The user needs to pick one value and see the related values.</p>
<p>I would understand if finding a large number of records was slow, but finding a few hundred shouldn't take that long.</p>
| [
{
"answer_id": 78123,
"author": "Tim Jarvis",
"author_id": 10387,
"author_profile": "https://Stackoverflow.com/users/10387",
"pm_score": 3,
"selected": true,
"text": "<p>Firstly you are right to be sceptical that this operation should take this long, XPO on read operations should add onl... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6783/"
] | I am having a problem with the speed of accessing an association property with a large number of records.
I have an XAF app with a parent class called `MyParent`.
There are 230 records in `MyParent`.
`MyParent` has a child class called `MyChild`.
There are 49,000 records in `MyChild`.
I have an association defined between `MyParent` and `MyChild` in the standard way:
In `MyChild`:
```
// MyChild (many) and MyParent (one)
[Association("MyChild-MyParent")]
public MyParent MyParent;
```
And in `MyParent`:
```
[Association("MyChild-MyParent", typeof(MyChild))]
public XPCollection<MyCHild> MyCHildren
{
get { return GetCollection<MyCHild>("MyCHildren"); }
}
```
There's a specific `MyParent` record called `MyParent1`.
For `MyParent1`, there are 630 `MyChild` records.
I have a DetailView for a class called `MyUI`.
The user chooses an item in one drop-down in the `MyUI` DetailView, and my code has to fill another drop-down with `MyChild` objects.
The user chooses `MyParent1` in the first drop-down.
I created a property in `MyUI` to return the collection of `MyChild` objects for the selected value in the first drop-down.
Here is the code for the property:
```
[NonPersistent]
public XPCollection<MyChild> DisplayedValues
{
get
{
Session theSession;
MyParent theParentValue;
XPCollection<MyCHild> theChildren;
theParentValue = this.DropDownOne;
// get the parent value
if theValue == null)
{
// if none
return null;
// return null
}
theChildren = theParentValue.MyChildren;
// get the child values for the parent
return theChildren;
// return it
}
```
I marked the `DisplayedValues` property as `NonPersistent` because it is only needed for the UI of the DetailVIew. I don't think that persisting it will speed up the creation of the collection the first time, and after it's used to fill the drop-down, I don't need it, so I don't want to spend time storing it.
The problem is that it takes 45 seconds to call `theParentValue = this.DropDownOne`.
Specs:
* Vista Business
* 8 GB of RAM
* 2.33 GHz E6550 processor
* SQL Server Express 2005
This is too long for users to wait for one of many drop-downs in the DetailView.
I took the time to sketch out the business case because I have two questions:
1. How can I make the associated values load faster?
2. Is there another (simple) way to program the drop-downs and DetailView that runs much faster?
Yes, you can say that 630 is too many items to display in a drop-down, but this code is taking so long I suspect that the speed is proportional to the 49,000 and not to the 630. 100 items in the drop-down would not be too many for my app.
I need quite a few of these drop-downs in my app, so it's not appropriate to force the user to enter more complicated filtering criteria for each one. The user needs to pick one value and see the related values.
I would understand if finding a large number of records was slow, but finding a few hundred shouldn't take that long. | Firstly you are right to be sceptical that this operation should take this long, XPO on read operations should add only between 30 - 70% overhead, and on this tiny amount of data we should be talking milli-seconds not seconds.
Some general perf tips are available in the DevExpress forums, and centre around object caching, lazy vs deep loads etc, but I think in your case the issue is something else, unfortunately its very hard to second guess whats going on from your question, only to say, its highly unlikely to be a problem with XPO much more likely to be something else, I would be inclined to look at your session creation (this also creates your object cache) and SQL connection code (the IDataStore stuff), Connections are often slow if hosts cannot not be resolved cleanly and if you are not pooling / re-using connections this problem can be exacerbated. |
62,437 | <p>I load some XML from a servlet from my Flex application like this:</p>
<pre><code>_loader = new URLLoader();
_loader.load(new URLRequest(_servletURL+"?do=load&id="+_id));
</code></pre>
<p>As you can imagine <code>_servletURL</code> is something like <a href="http://foo.bar/path/to/servlet" rel="nofollow noreferrer">http://foo.bar/path/to/servlet</a></p>
<p>In some cases, this URL contains accented characters (long story). I pass the <code>unescaped</code> string to <code>URLRequest</code>, but it seems that flash escapes it and calls the escaped URL, which is invalid. Ideas?</p>
| [
{
"answer_id": 62519,
"author": "grapefrukt",
"author_id": 914,
"author_profile": "https://Stackoverflow.com/users/914",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure if this will be any different, but this is a cleaner way of achieving the same URLRequest:</p>\n\n<pre><code... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199623/"
] | I load some XML from a servlet from my Flex application like this:
```
_loader = new URLLoader();
_loader.load(new URLRequest(_servletURL+"?do=load&id="+_id));
```
As you can imagine `_servletURL` is something like <http://foo.bar/path/to/servlet>
In some cases, this URL contains accented characters (long story). I pass the `unescaped` string to `URLRequest`, but it seems that flash escapes it and calls the escaped URL, which is invalid. Ideas? | My friend Luis figured it out:
You should use encodeURI does the UTF8URL encoding
<http://livedocs.adobe.com/flex/3/langref/package.html#encodeURI()>
but not unescape because it unescapes to ASCII see
<http://livedocs.adobe.com/flex/3/langref/package.html#unescape()>
I think that is where we are getting a %E9 in the URL instead of the expected %C3%A9.
<http://www.w3schools.com/TAGS/ref_urlencode.asp> |
62,447 | <p>Tomcat fails to start even if i remove all my applications from the WEBAPPS directory leaving everything just like after the OS installation.</p>
<p>The log (catalina.out) says:</p>
<pre><code>Using CATALINA_BASE: /usr/share/tomcat5
Using CATALINA_HOME: /usr/share/tomcat5
Using CATALINA_TMPDIR: /usr/share/tomcat5/temp
Using JRE_HOME:
Created MBeanServer with ID: -dpv07y:fl4s82vl.0:hydrogenium.timberlinecolorado.com:1
java.lang.NoClassDefFoundError: org.apache.catalina.core.StandardService
at java.lang.Class.initializeClass(libgcj.so.7rh)
at java.lang.Class.initializeClass(libgcj.so.7rh)
at java.lang.Class.initializeClass(libgcj.so.7rh)
at java.lang.Class.newInstance(libgcj.so.7rh)
at org.apache.catalina.startup.Bootstrap.init(bootstrap.jar.so)
at org.apache.catalina.startup.Bootstrap.main(bootstrap.jar.so)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.modeler.Registry not found in org.apache.catalina.loader.StandardClassLoader{urls=[file:/var/lib/tomcat5/server/classes/,file:/usr/share/java/tomcat5/catalina-cluster-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-storeconfig-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-optional-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-coyote-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-jkstatus-ant-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-ajp-5.5.23.jar,file:/usr/share/java/tomcat5/servlets-default-5.5.23.jar,file:/usr/share/java/tomcat5/servlets-invoker-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-ant-jmx-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-http-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-util-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-apr-5.5.23.jar,file:/usr/share/eclipse/plugins/org.eclipse.jdt.core_3.2.1.v_677_R32x.jar,file:/usr/share/java/tomcat5/servlets-webdav-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-5.5.23.jar], parent=org.apache.catalina.loader.StandardClassLoader{urls=[file:/var/lib/tomcat5/common/classes/,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-ja.jar,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-fr.jar,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-en.jar,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-es.jar,file:/usr/share/java/tomcat5/naming-resources-5.5.23.jar,file:/usr/share/eclipse/plugins/org.eclipse.jdt.core_3.2.1.v_677_R32x.jar,file:/usr/share/java/tomcat5/naming-factory-5.5.23.jar], parent=gnu.gcj.runtime.SystemClassLoader{urls=[file:/usr/lib/jvm/java/lib/tools.jar,file:/usr/share/tomcat5/bin/bootstrap.jar,file:/usr/share/tomcat5/bin/commons-logging-api.jar,file:/usr/share/java/mx4j/mx4j-impl.jar,file:/usr/share/java/mx4j/mx4j-jmx.jar], parent=gnu.gcj.runtime.ExtensionClassLoader{urls=[], parent=null}}}}
at java.net.URLClassLoader.findClass(libgcj.so.7rh)
at java.lang.ClassLoader.loadClass(libgcj.so.7rh)
at java.lang.ClassLoader.loadClass(libgcj.so.7rh)
at java.lang.Class.initializeClass(libgcj.so.7rh)
...5 more
</code></pre>
| [
{
"answer_id": 62488,
"author": "Stu Thompson",
"author_id": 2961,
"author_profile": "https://Stackoverflow.com/users/2961",
"pm_score": 0,
"selected": false,
"text": "<p>This screams class path issue, to me. Where exactly is your tomcat installed? (Give us command line printouts of wh... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Tomcat fails to start even if i remove all my applications from the WEBAPPS directory leaving everything just like after the OS installation.
The log (catalina.out) says:
```
Using CATALINA_BASE: /usr/share/tomcat5
Using CATALINA_HOME: /usr/share/tomcat5
Using CATALINA_TMPDIR: /usr/share/tomcat5/temp
Using JRE_HOME:
Created MBeanServer with ID: -dpv07y:fl4s82vl.0:hydrogenium.timberlinecolorado.com:1
java.lang.NoClassDefFoundError: org.apache.catalina.core.StandardService
at java.lang.Class.initializeClass(libgcj.so.7rh)
at java.lang.Class.initializeClass(libgcj.so.7rh)
at java.lang.Class.initializeClass(libgcj.so.7rh)
at java.lang.Class.newInstance(libgcj.so.7rh)
at org.apache.catalina.startup.Bootstrap.init(bootstrap.jar.so)
at org.apache.catalina.startup.Bootstrap.main(bootstrap.jar.so)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.modeler.Registry not found in org.apache.catalina.loader.StandardClassLoader{urls=[file:/var/lib/tomcat5/server/classes/,file:/usr/share/java/tomcat5/catalina-cluster-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-storeconfig-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-optional-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-coyote-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-jkstatus-ant-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-ajp-5.5.23.jar,file:/usr/share/java/tomcat5/servlets-default-5.5.23.jar,file:/usr/share/java/tomcat5/servlets-invoker-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-ant-jmx-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-http-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-util-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-apr-5.5.23.jar,file:/usr/share/eclipse/plugins/org.eclipse.jdt.core_3.2.1.v_677_R32x.jar,file:/usr/share/java/tomcat5/servlets-webdav-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-5.5.23.jar], parent=org.apache.catalina.loader.StandardClassLoader{urls=[file:/var/lib/tomcat5/common/classes/,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-ja.jar,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-fr.jar,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-en.jar,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-es.jar,file:/usr/share/java/tomcat5/naming-resources-5.5.23.jar,file:/usr/share/eclipse/plugins/org.eclipse.jdt.core_3.2.1.v_677_R32x.jar,file:/usr/share/java/tomcat5/naming-factory-5.5.23.jar], parent=gnu.gcj.runtime.SystemClassLoader{urls=[file:/usr/lib/jvm/java/lib/tools.jar,file:/usr/share/tomcat5/bin/bootstrap.jar,file:/usr/share/tomcat5/bin/commons-logging-api.jar,file:/usr/share/java/mx4j/mx4j-impl.jar,file:/usr/share/java/mx4j/mx4j-jmx.jar], parent=gnu.gcj.runtime.ExtensionClassLoader{urls=[], parent=null}}}}
at java.net.URLClassLoader.findClass(libgcj.so.7rh)
at java.lang.ClassLoader.loadClass(libgcj.so.7rh)
at java.lang.ClassLoader.loadClass(libgcj.so.7rh)
at java.lang.Class.initializeClass(libgcj.so.7rh)
...5 more
``` | Seems like you've implemented a JMX service and tried to install it on your server.xml file but forgot to add the apache commons modeler jar to the server/lib directory (therefore the `ClassNotFoundException` for `org.apache.commons.modeler.Registry`). Check your server.xml file for anything you might have added, and try to add the proper jar file to your server classpath. |
62,449 | <p>When using the Net.Sockets.TcpListener, what is the best way to handle incoming connections (.AcceptSocket) in seperate threads?</p>
<p>The idea is to start a new thread when a new incoming connection is accepted, while the tcplistener then stays available for further incoming connections (and for every new incoming connection a new thread is created). All communication and termination with the client that originated the connection will be handled in the thread.</p>
<p>Example C# of VB.NET code is appreciated.</p>
| [
{
"answer_id": 62481,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 0,
"selected": false,
"text": "<p>I would use a threadpool, this way you won't have to start a new thread every time (since this is kinda expen... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1271/"
] | When using the Net.Sockets.TcpListener, what is the best way to handle incoming connections (.AcceptSocket) in seperate threads?
The idea is to start a new thread when a new incoming connection is accepted, while the tcplistener then stays available for further incoming connections (and for every new incoming connection a new thread is created). All communication and termination with the client that originated the connection will be handled in the thread.
Example C# of VB.NET code is appreciated. | The code that I've been using looks like this:
```
class Server
{
private AutoResetEvent connectionWaitHandle = new AutoResetEvent(false);
public void Start()
{
TcpListener listener = new TcpListener(IPAddress.Any, 5555);
listener.Start();
while(true)
{
IAsyncResult result = listener.BeginAcceptTcpClient(HandleAsyncConnection, listener);
connectionWaitHandle.WaitOne(); // Wait until a client has begun handling an event
connectionWaitHandle.Reset(); // Reset wait handle or the loop goes as fast as it can (after first request)
}
}
private void HandleAsyncConnection(IAsyncResult result)
{
TcpListener listener = (TcpListener)result.AsyncState;
TcpClient client = listener.EndAcceptTcpClient(result);
connectionWaitHandle.Set(); //Inform the main thread this connection is now handled
//... Use your TcpClient here
client.Close();
}
}
``` |
62,490 | <p>I am receiving SOAP requests from a client that uses the Axis 1.4 libraries. The requests have the following form:</p>
<pre><code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<PlaceOrderRequest xmlns="http://example.com/schema/order/request">
<order>
<ns1:requestParameter xmlns:ns1="http://example.com/schema/common/request">
<ns1:orderingSystemWithDomain>
<ns1:orderingSystem>Internet</ns1:orderingSystem>
<ns1:domainSign>2</ns1:domainSign>
</ns1:orderingSystemWithDomain>
</ns1:requestParameter>
<ns2:directDeliveryAddress ns2:addressType="0" ns2:index="1"
xmlns:ns2="http://example.com/schema/order/request">
<ns3:address xmlns:ns3="http://example.com/schema/common/request">
<ns4:zipcode xmlns:ns4="http://example.com/schema/common">12345</ns4:zipcode>
<ns5:city xmlns:ns5="http://example.com/schema/common">City</ns5:city>
<ns6:street xmlns:ns6="http://example.com/schema/common">Street</ns6:street>
<ns7:houseNum xmlns:ns7="http://example.com/schema/common">1</ns7:houseNum>
<ns8:country xmlns:ns8="http://example.com/schema/common">XX</ns8:country>
</ns3:address>
[...]
</code></pre>
<p>As you can see, several prefixes are defined for the same namespace, e.g. the namespace <a href="http://example.com/schema/common" rel="noreferrer">http://example.com/schema/common</a> has the prefixes ns4, ns5, ns6, ns7 and ns8. Some long requests define several hundred prefixes for the same namespace.</p>
<p>This causes a problem with the <a href="http://saxon.sourceforge.net/" rel="noreferrer">Saxon</a> XSLT processor, that I use to transform the requests. Saxon limits the the number of different prefixes for the same namespace to 255 and throws an exception when you define more prefixes.</p>
<p>Can Axis 1.4 be configured to define smarter prefixes, so that there is only one prefix for each namespace?</p>
| [
{
"answer_id": 179495,
"author": "Ian McLaird",
"author_id": 18796,
"author_profile": "https://Stackoverflow.com/users/18796",
"pm_score": 2,
"selected": false,
"text": "<p>I have the same issue. For the moment, I've worked around it by writing a BasicHandler extension, and then walking... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5035/"
] | I am receiving SOAP requests from a client that uses the Axis 1.4 libraries. The requests have the following form:
```
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<PlaceOrderRequest xmlns="http://example.com/schema/order/request">
<order>
<ns1:requestParameter xmlns:ns1="http://example.com/schema/common/request">
<ns1:orderingSystemWithDomain>
<ns1:orderingSystem>Internet</ns1:orderingSystem>
<ns1:domainSign>2</ns1:domainSign>
</ns1:orderingSystemWithDomain>
</ns1:requestParameter>
<ns2:directDeliveryAddress ns2:addressType="0" ns2:index="1"
xmlns:ns2="http://example.com/schema/order/request">
<ns3:address xmlns:ns3="http://example.com/schema/common/request">
<ns4:zipcode xmlns:ns4="http://example.com/schema/common">12345</ns4:zipcode>
<ns5:city xmlns:ns5="http://example.com/schema/common">City</ns5:city>
<ns6:street xmlns:ns6="http://example.com/schema/common">Street</ns6:street>
<ns7:houseNum xmlns:ns7="http://example.com/schema/common">1</ns7:houseNum>
<ns8:country xmlns:ns8="http://example.com/schema/common">XX</ns8:country>
</ns3:address>
[...]
```
As you can see, several prefixes are defined for the same namespace, e.g. the namespace <http://example.com/schema/common> has the prefixes ns4, ns5, ns6, ns7 and ns8. Some long requests define several hundred prefixes for the same namespace.
This causes a problem with the [Saxon](http://saxon.sourceforge.net/) XSLT processor, that I use to transform the requests. Saxon limits the the number of different prefixes for the same namespace to 255 and throws an exception when you define more prefixes.
Can Axis 1.4 be configured to define smarter prefixes, so that there is only one prefix for each namespace? | I have the same issue. For the moment, I've worked around it by writing a BasicHandler extension, and then walking the SOAPPart myself and moving the namespace reference up to a parent node. I don't *like* this solution, but it does seem to work.
I really hope somebody comes along and tells us what we have to do.
***EDIT***
This is way too complicated, and like I said, I don't like it at all, but here we go. I actually broke the functionality into a few classes (This wasn't the only manipulation that we needed to do in that project, so there were other implementations) I really hope that somebody can fix this soon. This uses dom4j to process the XML passing through the SOAP process, so you'll need dom4j to make it work.
```
public class XMLManipulationHandler extends BasicHandler {
private static Log log = LogFactory.getLog(XMLManipulationHandler.class);
private static List processingHandlers;
public static void setProcessingHandlers(List handlers) {
processingHandlers = handlers;
}
protected Document process(Document doc) {
if (processingHandlers == null) {
processingHandlers = new ArrayList();
processingHandlers.add(new EmptyProcessingHandler());
}
log.trace(processingHandlers);
treeWalk(doc.getRootElement());
return doc;
}
protected void treeWalk(Element element) {
for (int i = 0, size = element.nodeCount(); i < size; i++) {
Node node = element.node(i);
for (int handlerIndex = 0; handlerIndex < processingHandlers.size(); handlerIndex++) {
ProcessingHandler handler = (ProcessingHandler) processingHandlers.get(handlerIndex);
handler.process(node);
}
if (node instanceof Element) {
treeWalk((Element) node);
}
}
}
public void invoke(MessageContext context) throws AxisFault {
if (!context.getPastPivot()) {
SOAPMessage message = context.getMessage();
SOAPPart soapPart = message.getSOAPPart();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
message.writeTo(baos);
baos.flush();
baos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
SAXReader saxReader = new SAXReader();
Document doc = saxReader.read(bais);
doc = process(doc);
DocumentSource ds = new DocumentSource(doc);
soapPart.setContent(ds);
message.saveChanges();
} catch (Exception e) {
throw new AxisFault("Error Caught processing document in XMLManipulationHandler", e);
}
}
}
}
```
```
public interface ProcessingHandler {
public Node process(Node node);
}
```
```
public class NamespaceRemovalHandler implements ProcessingHandler {
private static Log log = LogFactory.getLog(NamespaceRemovalHandler.class);
private Namespace namespace;
private String targetElement;
private Set ignoreElements;
public NamespaceRemovalHandler() {
ignoreElements = new HashSet();
}
public Node process(Node node) {
if (node instanceof Element) {
Element element = (Element) node;
if (element.isRootElement()) {
// Evidently, we never actually see the root node when we're called from
// SOAP...
} else {
if (element.getName().equals(targetElement)) {
log.trace("Found the target Element. Adding requested namespace");
Namespace already = element.getNamespaceForURI(namespace.getURI());
if (already == null) {
element.add(namespace);
}
} else if (!ignoreElements.contains(element.getName())) {
Namespace target = element.getNamespaceForURI(namespace.getURI());
if (target != null) {
element.remove(target);
element.setQName(new QName(element.getName(), namespace));
}
}
Attribute type = element.attribute("type");
if (type != null) {
log.trace("Replacing type information: " + type.getText());
String typeText = type.getText();
typeText = typeText.replaceAll("ns[0-9]+", namespace.getPrefix());
type.setText(typeText);
}
}
}
return node;
}
public Namespace getNamespace() {
return namespace;
}
public void setNamespace(Namespace namespace) {
this.namespace = namespace;
}
/**
* @return the targetElement
*/
public String getTargetElement() {
return targetElement;
}
/**
* @param targetElement the targetElement to set
*/
public void setTargetElement(String targetElement) {
this.targetElement = targetElement;
}
/**
* @return the ignoreElements
*/
public Set getIgnoreElements() {
return ignoreElements;
}
/**
* @param ignoreElements the ignoreElements to set
*/
public void setIgnoreElements(Set ignoreElements) {
this.ignoreElements = ignoreElements;
}
public void addIgnoreElement(String element) {
this.ignoreElements.add(element);
}
}
```
No warranty, etc, etc. |
62,501 | <p>I need to remotely install windows service on number of computers, so I use CreateService() and other service functions from winapi. I know admin password and user name for machines that I need access to. In order to gain access to remote machine I impersonate calling process with help of LogonUser like this: </p>
<pre><code>//all variables are initialized correctly
int status = 0;
status = LogonUser(lpwUsername,
lpwDomain,
lpwPassword,
LOGON32_LOGON_NEW_CREDENTIALS,
LOGON32_PROVIDER_DEFAULT,
&hToken);
if (status == 0)
{
//here comes a error
}
status = ImpersonateLoggedOnUser(hToken);
if (status == 0)
{
//once again a error
}
//ok, now we are impersonated, do all service work there
</code></pre>
<p>So, I gain access to machine in a domain, but some of computers are out of domain. On machines that are out of domain this code doesn't work. Is there any way to access service manager on machine out of domain?</p>
| [
{
"answer_id": 62560,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>You can do it , the account needs to exist on the remote machine and you need to use the machine name for the domain name in ... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6698/"
] | I need to remotely install windows service on number of computers, so I use CreateService() and other service functions from winapi. I know admin password and user name for machines that I need access to. In order to gain access to remote machine I impersonate calling process with help of LogonUser like this:
```
//all variables are initialized correctly
int status = 0;
status = LogonUser(lpwUsername,
lpwDomain,
lpwPassword,
LOGON32_LOGON_NEW_CREDENTIALS,
LOGON32_PROVIDER_DEFAULT,
&hToken);
if (status == 0)
{
//here comes a error
}
status = ImpersonateLoggedOnUser(hToken);
if (status == 0)
{
//once again a error
}
//ok, now we are impersonated, do all service work there
```
So, I gain access to machine in a domain, but some of computers are out of domain. On machines that are out of domain this code doesn't work. Is there any way to access service manager on machine out of domain? | You can do it , the account needs to exist on the remote machine and you need to use the machine name for the domain name in the LogonUser call. |
62,504 | <p>I am using MS Access 2003. I want to run a lot of insert SQL statements in what is called 'Query' in MS Access. Is there any easy(or indeed any way) to do it?</p>
| [
{
"answer_id": 62572,
"author": "Rikalous",
"author_id": 4271,
"author_profile": "https://Stackoverflow.com/users/4271",
"pm_score": 1,
"selected": false,
"text": "<p>No - a query in Access is a single SQL statement. There is no way of creating a batch of several statements within one qu... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6613/"
] | I am using MS Access 2003. I want to run a lot of insert SQL statements in what is called 'Query' in MS Access. Is there any easy(or indeed any way) to do it? | yes and no.
You can't do:
```
insert into foo (c1, c2, c3)
values ("v1a", "v2a", "v3a"),
("v1b", "v2b", "v3b"),
("v1c", "v2c", "v3c")
```
but you can do
```
insert into foo (c1, c2, c3)
select (v1, v2, v3) from bar
```
What does that get you if you don't already have the data in a table? Well, you could craft a Select statement composed of a lot of unions of Selects with hard coded results.
```
INSERT INTO foo (f1, f2, f3)
SELECT *
FROM (select top 1 "b1a" AS f1, "b2a" AS f2, "b3a" AS f3 from onerow
union all
select top 1 "b1b" AS f1, "b2b" AS f2, "b3b" AS f3 from onerow
union all
select top 1 "b1c" AS f1, "b2c" AS f2, "b3c" AS f3 from onerow)
```
Note: I also have to include a some form of a dummy table (e.g., onerow) to fool access into allowing the union (it must have at least one row in it), and you need the "top 1" to ensure you don't get repeats for a table with more than one row
But then again, it would probably be easier just to do three separate insert statements,
especially if you are already building things up in a loop (unless of course the cost of doing the inserts is greater than the cost of your time to code it). |
62,512 | <p>I would like to find out safe ways of implementing three dimensional arrays of integers in C++, using pointer arithmetic / dynamic memory allocation, or, alternatively using <code>STL</code> techniques such as vectors.</p>
<p>Essentially I want my integer array dimensions to look like:</p>
<pre><code>[ x ][ y ][ z ]
</code></pre>
<p>x and y are in the range 20-6000
z is known and equals 4.</p>
| [
{
"answer_id": 62532,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 5,
"selected": true,
"text": "<p>Have a look at the Boost <a href=\"http://www.boost.org/doc/libs/release/libs/multi_array\" rel=\"noreferrer\">multi-dimensi... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6795/"
] | I would like to find out safe ways of implementing three dimensional arrays of integers in C++, using pointer arithmetic / dynamic memory allocation, or, alternatively using `STL` techniques such as vectors.
Essentially I want my integer array dimensions to look like:
```
[ x ][ y ][ z ]
```
x and y are in the range 20-6000
z is known and equals 4. | Have a look at the Boost [multi-dimensional array](http://www.boost.org/doc/libs/release/libs/multi_array) library. Here's an example (adapted from the Boost documentation):
```
#include "boost/multi_array.hpp"
int main() {
// Create a 3D array that is 20 x 30 x 4
int x = 20;
int y = 30;
int z = 4;
typedef boost::multi_array<int, 3> array_type;
typedef array_type::index index;
array_type my_array(boost::extents[x][y][z]);
// Assign values to the elements
int values = 0;
for (index i = 0; i != x; ++i) {
for (index j = 0; j != y; ++j) {
for (index k = 0; k != z; ++k) {
my_array[i][j][k] = values++;
}
}
}
}
``` |
62,529 | <p>The RoR tutorials posit one model per table for the ORM to work.
My DB schema has some 70 tables divided conceptually into 5 groups of functionality
(eg, any given table lives in one and only one functional group, and relations between tables of different groups are minimised.)
So: should I design a model per conceptual group, or should I simply have 70 Rails models and leave the grouping 'conceptual'?
Thanks!</p>
| [
{
"answer_id": 62677,
"author": "Clinton Dreisbach",
"author_id": 6262,
"author_profile": "https://Stackoverflow.com/users/6262",
"pm_score": 3,
"selected": false,
"text": "<p>Most likely, you should have 70 models. You could namespace the models to have 5 namespaces, one for each group,... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6941/"
] | The RoR tutorials posit one model per table for the ORM to work.
My DB schema has some 70 tables divided conceptually into 5 groups of functionality
(eg, any given table lives in one and only one functional group, and relations between tables of different groups are minimised.)
So: should I design a model per conceptual group, or should I simply have 70 Rails models and leave the grouping 'conceptual'?
Thanks! | I cover this in one of my large apps by just making sure that the tables/models are conceptually grouped by name (with almost 1:1 table-model relationship). Example:
```
events
event_types
event_groups
event_attendees
etc...
```
That way when I'm using TextMate or whatever, the model files are nicely grouped together by the alpha sort. I have 80 models in this app, and it works well enough to keep things organised. |
62,567 | <p>What is the easiest way to compare strings in Python, ignoring case?</p>
<p>Of course one can do (str1.lower() <= str2.lower()), etc., but this created two additional temporary strings (with the obvious alloc/g-c overheads).</p>
<p>I guess I'm looking for an equivalent to C's stricmp().</p>
<p>[Some more context requested, so I'll demonstrate with a trivial example:]</p>
<p>Suppose you want to sort a looong list of strings. You simply do theList.sort().
This is O(n * log(n)) string comparisons and no memory management (since all
strings and list elements are some sort of smart pointers). You are happy.</p>
<p>Now, you want to do the same, but ignore the case (let's simplify and say
all strings are ascii, so locale issues can be ignored).
You can do theList.sort(key=lambda s: s.lower()), but then you cause two new
allocations per comparison, plus burden the garbage-collector with the duplicated
(lowered) strings.
Each such memory-management noise is orders-of-magnitude slower than simple string comparison.</p>
<p>Now, with an in-place stricmp()-like function, you do: theList.sort(cmp=stricmp)
and it is as fast and as memory-friendly as theList.sort(). You are happy again.</p>
<p>The problem is any Python-based case-insensitive comparison involves implicit string
duplications, so I was expecting to find a C-based comparisons (maybe in module string).</p>
<p>Could not find anything like that, hence the question here.
(Hope this clarifies the question).</p>
| [
{
"answer_id": 62592,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 0,
"selected": false,
"text": "<p>I'm pretty sure you either have to use .lower() or use a regular expression. I'm not aware of a built-in case-insensitive... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6984/"
] | What is the easiest way to compare strings in Python, ignoring case?
Of course one can do (str1.lower() <= str2.lower()), etc., but this created two additional temporary strings (with the obvious alloc/g-c overheads).
I guess I'm looking for an equivalent to C's stricmp().
[Some more context requested, so I'll demonstrate with a trivial example:]
Suppose you want to sort a looong list of strings. You simply do theList.sort().
This is O(n \* log(n)) string comparisons and no memory management (since all
strings and list elements are some sort of smart pointers). You are happy.
Now, you want to do the same, but ignore the case (let's simplify and say
all strings are ascii, so locale issues can be ignored).
You can do theList.sort(key=lambda s: s.lower()), but then you cause two new
allocations per comparison, plus burden the garbage-collector with the duplicated
(lowered) strings.
Each such memory-management noise is orders-of-magnitude slower than simple string comparison.
Now, with an in-place stricmp()-like function, you do: theList.sort(cmp=stricmp)
and it is as fast and as memory-friendly as theList.sort(). You are happy again.
The problem is any Python-based case-insensitive comparison involves implicit string
duplications, so I was expecting to find a C-based comparisons (maybe in module string).
Could not find anything like that, hence the question here.
(Hope this clarifies the question). | In response to your clarification...
You could use [ctypes](http://docs.python.org/lib/ctypes-ctypes-tutorial.html) to execute the c function "strcasecmp". Ctypes is included in Python 2.5. It provides the ability to call out to dll and shared libraries such as libc. Here is a quick example (Python on Linux; see link for Win32 help):
```
from ctypes import *
libc = CDLL("libc.so.6") // see link above for Win32 help
libc.strcasecmp("THIS", "this") // returns 0
libc.strcasecmp("THIS", "THAT") // returns 8
```
may also want to reference [strcasecmp documentation](http://linux.die.net/man/3/strcasecmp)
Not really sure this is any faster or slower (have not tested), but it's a way to use a C function to do case insensitive string comparisons.
~~~~~~~~~~~~~~
[ActiveState Code - Recipe 194371: Case Insensitive Strings](http://code.activestate.com/recipes/194371/ "ActiveState Code")
is a recipe for creating a case insensitive string class. It might be a bit over kill for something quick, but could provide you with a common way of handling case insensitive strings if you plan on using them often. |
62,588 | <p>I have some ASP.NET web services which all share a common helper class they only need to instantiate one instance of <em>per server</em>. It's used for simple translation of data, but does spend some time during start-up loading things from the web.config file, etc. <em>The helper class is 100% thread-safe. Think of it as a simple library of utility calls. I'd make all the methods shared on the class, but I want to load the initial configuration from web.config.</em> We've deployed the web services to IIS 6.0 and using an Application Pool, with a Web Garden of 15 workers.</p>
<p>I declared the helper class as a Private Shared variable in Global.asax, and added a lazy load Shared ReadOnly property like this:</p>
<pre><code>Private Shared _helper As MyHelperClass
Public Shared ReadOnly Property Helper() As MyHelperClass
Get
If _helper Is Nothing Then
_helper = New MyHelperClass()
End If
Return _helper
End Get
End Property
</code></pre>
<p>I have logging code in the constructor for <code>MyHelperClass()</code>, and it shows the constructor running for each request, even on the same thread. I'm sure I'm just missing some key detail of ASP.NET but MSDN hasn't been very helpful.</p>
<p>I've tried doing similar things using both <code>Application("Helper")</code> and <code>Cache("Helper")</code> and I still saw the constructor run with each request.</p>
| [
{
"answer_id": 62913,
"author": "Donny V.",
"author_id": 1231,
"author_profile": "https://Stackoverflow.com/users/1231",
"pm_score": 0,
"selected": false,
"text": "<p>I 'v done something like this in my own app in the past and it caused all kinds of weird errors.\nEvery user will have ac... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6897/"
] | I have some ASP.NET web services which all share a common helper class they only need to instantiate one instance of *per server*. It's used for simple translation of data, but does spend some time during start-up loading things from the web.config file, etc. *The helper class is 100% thread-safe. Think of it as a simple library of utility calls. I'd make all the methods shared on the class, but I want to load the initial configuration from web.config.* We've deployed the web services to IIS 6.0 and using an Application Pool, with a Web Garden of 15 workers.
I declared the helper class as a Private Shared variable in Global.asax, and added a lazy load Shared ReadOnly property like this:
```
Private Shared _helper As MyHelperClass
Public Shared ReadOnly Property Helper() As MyHelperClass
Get
If _helper Is Nothing Then
_helper = New MyHelperClass()
End If
Return _helper
End Get
End Property
```
I have logging code in the constructor for `MyHelperClass()`, and it shows the constructor running for each request, even on the same thread. I'm sure I'm just missing some key detail of ASP.NET but MSDN hasn't been very helpful.
I've tried doing similar things using both `Application("Helper")` and `Cache("Helper")` and I still saw the constructor run with each request. | It's not wise to use application state unless you absolutely require it, things are much simpler if you stick to using per-request objects. Any addition of state to the helper classes could cause all sorts of subtle errors. Use the HttpContext.Current items collection and intialise it per request. A VB module would do what you want, but you must be sure not to make it stateful. |
62,599 | <p>How do you define your UserControls as being in a namespace below the project namespace, ie. [RootNameSpace].[SubSectionOfProgram].Controls?</p>
<p><strong>Edit due to camainc's answer:</strong> I also have a constraint that I have to have all the code in a single project.</p>
<p><strong>Edit to finalise question:</strong> As I suspected it isn't possible to do what I required so camainc's answer is the nearest solution.</p>
| [
{
"answer_id": 62817,
"author": "camainc",
"author_id": 7232,
"author_profile": "https://Stackoverflow.com/users/7232",
"pm_score": 2,
"selected": true,
"text": "<p>I'm not sure if this is what you are asking, but this is how we do it.</p>\n\n<p>We namespace all of our projects in a cons... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6369/"
] | How do you define your UserControls as being in a namespace below the project namespace, ie. [RootNameSpace].[SubSectionOfProgram].Controls?
**Edit due to camainc's answer:** I also have a constraint that I have to have all the code in a single project.
**Edit to finalise question:** As I suspected it isn't possible to do what I required so camainc's answer is the nearest solution. | I'm not sure if this is what you are asking, but this is how we do it.
We namespace all of our projects in a consistent manner, user controls are no different. We also namespace using the project settings window, although you could do it through a combination of the project window and in code.
Each solution gets a namespace like this:
```
[CompanyName].[SolutionName].[ProjectName]
```
So, our user controls are normally in a project called "Controls," which would have a namespace of:
```
OurCompany.ThisSolution.Controls
```
If we have controls that might span several different solutions, we just namespace it like so:
```
OurCompany.Common.Controls
```
Then, in our code we will import the library, or add the project to the solution.
```
Imports OurCompany
Imports OurCompany.Common
Imports OurCompany.Common.Controls
```
We also name the folders where the projects live the same as the namespace, down to but not including the company name (all solutions are assumed to be in the company namespace):
\Projects
\Projects\MySolution
\Projects\MySolution\Controls
-- or --
\Projects\
\Projects\Common
\Projects\Common\Assemblies
\Projects\Common\Controls
etc.
Hope that helps... |
62,606 | <p>I'm using <code>int</code> as an example, but this applies to any value type in .Net</p>
<p>In .Net 1 the following would throw a compiler exception:</p>
<pre><code>int i = SomeFunctionThatReturnsInt();
if( i == null ) //compiler exception here
</code></pre>
<p>Now (in .Net 2 or 3.5) that exception has gone.</p>
<p>I know why this is:</p>
<pre><code>int? j = null; //nullable int
if( i == j ) //this shouldn't throw an exception
</code></pre>
<p>The problem is that because <code>int?</code> is nullable and <code>int</code> now has a implicit cast to <code>int?</code>. The syntax above is compiler magic. Really we're doing:</p>
<pre><code>Nullable<int> j = null; //nullable int
//compiler is smart enough to do this
if( (Nullable<int>) i == j)
//and not this
if( i == (int) j)
</code></pre>
<p>So now, when we do <code>i == null</code> we get:</p>
<pre><code>if( (Nullable<int>) i == null )
</code></pre>
<p>Given that C# is doing compiler logic to calculate this anyway why can't it be smart enough to not do it when dealing with absolute values like <code>null</code>?</p>
| [
{
"answer_id": 62724,
"author": "ima",
"author_id": 5733,
"author_profile": "https://Stackoverflow.com/users/5733",
"pm_score": 1,
"selected": false,
"text": "<p>Compiler still generates warning when you compare non-nullable type to null, which is just the way it should be. May be your w... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | I'm using `int` as an example, but this applies to any value type in .Net
In .Net 1 the following would throw a compiler exception:
```
int i = SomeFunctionThatReturnsInt();
if( i == null ) //compiler exception here
```
Now (in .Net 2 or 3.5) that exception has gone.
I know why this is:
```
int? j = null; //nullable int
if( i == j ) //this shouldn't throw an exception
```
The problem is that because `int?` is nullable and `int` now has a implicit cast to `int?`. The syntax above is compiler magic. Really we're doing:
```
Nullable<int> j = null; //nullable int
//compiler is smart enough to do this
if( (Nullable<int>) i == j)
//and not this
if( i == (int) j)
```
So now, when we do `i == null` we get:
```
if( (Nullable<int>) i == null )
```
Given that C# is doing compiler logic to calculate this anyway why can't it be smart enough to not do it when dealing with absolute values like `null`? | I don't think this is a compiler problem *per se*; an integer value is never null, but the idea of equating them isn't invalid; it's a valid function that always returns false. And the compiler knows; the code
```
bool oneIsNull = 1 == null;
```
compiles, but gives a compiler warning: `The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type '<null>'`.
So if you want the compiler error back, go to the project properties and turn on 'treat warnings as errors' for this error, and you'll start seeing them as build-breaking problems again. |
62,618 | <p>I've got many, many mp3 files that I would like to merge into a single file. I've used the command line method</p>
<pre><code>copy /b 1.mp3+2.mp3 3.mp3
</code></pre>
<p>but it's a pain when there's a lot of them and their namings are inconsistent. The time never seems to come out right either.</p>
| [
{
"answer_id": 62635,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 3,
"selected": false,
"text": "<p>The time problem has to do with the ID3 headers of the MP3 files, which is something your method isn't taking into acco... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4230/"
] | I've got many, many mp3 files that I would like to merge into a single file. I've used the command line method
```
copy /b 1.mp3+2.mp3 3.mp3
```
but it's a pain when there's a lot of them and their namings are inconsistent. The time never seems to come out right either. | As Thomas Owens pointed out, simply concatenating the files will leave multiple ID3 headers scattered throughout the resulting concatenated file - so the time/bitrate info will be wildly wrong.
You're going to need to use a tool which can combine the audio data for you.
[mp3wrap](http://mp3wrap.sourceforge.net/) would be ideal for this - it's designed to join together MP3 files, without needing to decode + re-encode the data (which would result in a loss of audio quality) and will also deal with the ID3 tags intelligently.
The resulting file can also be split back into its component parts using the mp3splt tool - mp3wrap adds information to the IDv3 comment to allow this. |
62,629 | <p>I need to determine when my Qt 4.4.1 application receives focus.</p>
<p>I have come up with 2 possible solutions, but they both don’t work exactly as I would like.</p>
<p>In the first possible solution, I connect the focusChanged() signal from qApp to a SLOT. In the slot I check the ‘old’ pointer. If it ‘0’, then I know we’ve switched to this application, and I do what I want. This seems to be the most reliable method of getting the application to detect focus in of the two solutions presented here, but suffers from the problem described below. </p>
<p>In the second possible solution, I overrode the ‘focusInEvent()’ routine, and do what I want if the reason is ‘ActiveWindowFocusReason’.</p>
<p>In both of these solutions, the code is executed at times when I don’t want it to be.</p>
<p>For example, I have this code that overrides the focusInEvent() routine:</p>
<pre><code>void
ApplicationWindow::focusInEvent( QFocusEvent* p_event )
{
Qt::FocusReason reason = p_event->reason();
if( reason == Qt::ActiveWindowFocusReason &&
hasNewUpstreamData() )
{
switch( QMessageBox::warning( this, "New Upstream Data Found!",
"New upstream data exists!\n"
"Do you want to refresh this simulation?",
"&Yes", "&No", 0, 0, 1 ) )
{
case 0: // Yes
refreshSimulation();
break;
case 1: // No
break;
}
}
}
</code></pre>
<p>When this gets executed, the QMessageBox dialog appears. However, when the dialog is dismissed by pressing either ‘yes’ or ‘no’, this function immediately gets called again because I suppose the focus changed back to the application window at that point with the ActiveWindowFocusReason. Obviously I don’t want this to happen.</p>
<p>Likewise, if the user is using the application opening & closing dialogs and windows etc, I don’t want this routine to activate. NOTE: I’m not sure of the circumstances when this routine is activated though since I’ve tried a bit, and it doesn’t happen for all windows & dialogs, though it does happen at least for the one shown in the sample code.</p>
<p>I only want it to activate if the application is focussed on from outside of this application, not when the main window is focussed in from other dialog windows.</p>
<p>Is this possible? How can this be done?</p>
<p>Thanks for any information, since this is very important for our application to do.</p>
<p>Raymond.</p>
| [
{
"answer_id": 62820,
"author": "David Dibben",
"author_id": 5022,
"author_profile": "https://Stackoverflow.com/users/5022",
"pm_score": 0,
"selected": false,
"text": "<p>Looking at the Qt docs it seems that focus events are created each time a widget gets the focus, so the sample code y... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/460958/"
] | I need to determine when my Qt 4.4.1 application receives focus.
I have come up with 2 possible solutions, but they both don’t work exactly as I would like.
In the first possible solution, I connect the focusChanged() signal from qApp to a SLOT. In the slot I check the ‘old’ pointer. If it ‘0’, then I know we’ve switched to this application, and I do what I want. This seems to be the most reliable method of getting the application to detect focus in of the two solutions presented here, but suffers from the problem described below.
In the second possible solution, I overrode the ‘focusInEvent()’ routine, and do what I want if the reason is ‘ActiveWindowFocusReason’.
In both of these solutions, the code is executed at times when I don’t want it to be.
For example, I have this code that overrides the focusInEvent() routine:
```
void
ApplicationWindow::focusInEvent( QFocusEvent* p_event )
{
Qt::FocusReason reason = p_event->reason();
if( reason == Qt::ActiveWindowFocusReason &&
hasNewUpstreamData() )
{
switch( QMessageBox::warning( this, "New Upstream Data Found!",
"New upstream data exists!\n"
"Do you want to refresh this simulation?",
"&Yes", "&No", 0, 0, 1 ) )
{
case 0: // Yes
refreshSimulation();
break;
case 1: // No
break;
}
}
}
```
When this gets executed, the QMessageBox dialog appears. However, when the dialog is dismissed by pressing either ‘yes’ or ‘no’, this function immediately gets called again because I suppose the focus changed back to the application window at that point with the ActiveWindowFocusReason. Obviously I don’t want this to happen.
Likewise, if the user is using the application opening & closing dialogs and windows etc, I don’t want this routine to activate. NOTE: I’m not sure of the circumstances when this routine is activated though since I’ve tried a bit, and it doesn’t happen for all windows & dialogs, though it does happen at least for the one shown in the sample code.
I only want it to activate if the application is focussed on from outside of this application, not when the main window is focussed in from other dialog windows.
Is this possible? How can this be done?
Thanks for any information, since this is very important for our application to do.
Raymond. | I think you need to track the [QEvent::ApplicationActivate](http://doc.qt.io/qt-4.8/qevent.html#Type-enum) event.
You can put an [event filter](http://doc.qt.io/qt-4.8/qobject.html#eventFilter) on your QApplication instance and then look for it.
```
bool
ApplicationWindow::eventFilter( QObject * watched, QEvent * event )
{
if ( watched != qApp )
goto finished;
if ( event->type() != QEvent::ApplicationActivate )
goto finished;
// Invariant: we are now looking at an application activate event for
// the application object
if ( !hasNewUpstreamData() )
goto finished;
QMessageBox::StandardButton response =
QMessageBox::warning( this, "New Upstream Data Found!",
"New upstream data exists!\n"
"Do you want to refresh this simulation?",
QMessageBox::Yes | QMessageBox::No) );
if ( response == QMessageBox::Yes )
refreshSimulation();
finished:
return <The-Superclass-here>::eventFilter( watched, event );
}
ApplicationWindow::ApplicationWindow(...)
{
if (qApp)
qApp->installEventFilter( this );
...
}
``` |
62,661 | <p>What Direct3D render states should be used to implement Java's Porter-Duff compositing rules (CLEAR, SRC, SRCOVER, etc.)?</p>
| [
{
"answer_id": 67873,
"author": "Corey Ross",
"author_id": 5927,
"author_profile": "https://Stackoverflow.com/users/5927",
"pm_score": 2,
"selected": false,
"text": "<p>I'm haven't used Java too much, but based on the <a href=\"http://keithp.com/~keithp/porterduff/p253-porter.pdf\" rel=\... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7071/"
] | What Direct3D render states should be used to implement Java's Porter-Duff compositing rules (CLEAR, SRC, SRCOVER, etc.)? | I'm haven't used Java too much, but based on the [white paper from 1984](http://keithp.com/~keithp/porterduff/p253-porter.pdf), it should be a fairly straightforward mapping of render state blend modes.
There are of course more that you can do than just these, like normal alpha blending (SourceAlpha, InvSourceAlpha) or additive (One, One) to name a few. *(I assume that you are asking about these specifically because you are porting some existing functionality? In that cause you may not care about other combinations...)*
Anyway, these assume a BlendOperation of Add and that AlphaBlendEnable is true.
Clear
```
SourceBlend = Zero
DestinationBlend = Zero
```
A
```
SourceBlend = One
DestinationBlend = Zero
```
B
```
SourceBlend = Zero
DestinationBlend = One
```
A over B
```
SourceBlend = One
DestinationBlend = InvSourceAlpha
```
B over A
```
SourceBlend = InvDestinationAlpha
DestinationBlend = One
```
A in B
```
SourceBlend = DestinationAlpha
DestinationBlend = One
```
B in A
```
SourceBlend = Zero
DestinationBlend = SourceAlpha
```
A out B
```
SourceBlend = InvDestinationAlpha
DestinationBlend = Zero
```
B out A
```
SourceBlend = Zero
DestinationBlend = InvSourceAlpha
```
A atop B
```
SourceBlend = DestinationAlpha
DestinationBlend = InvSourceAlpha
```
B atop A
```
SourceBlend = InvDestinationAlpha
DestinationBlend = SourceAlpha
```
A xor B
```
SourceBlend = InvDestinationAlpha
DestinationBlend = InvSourceAlpha
```
Chaining these is a little more complex and would require either multiple passes or multiple texture inputs to a shader. |
62,689 | <p>I'm trying to implement a data compression idea I've had, and since I'm imagining running it against a large corpus of test data, I had thought to code it in C (I mostly have experience in scripting languages like Ruby and Tcl.) </p>
<p>Looking through the O'Reilly 'cow' books on C, I realize that I can't simply index the bits of a simple 'char' or 'int' type variable as I'd like to to do bitwise comparisons and operators. </p>
<p>Am I correct in this perception? Is it reasonable for me to use an enumerated type for representing a bit (and make an array of these, and writing functions to convert to and from char)? If so, is such a type and functions defined in a standard library already somewhere? Are there other (better?) approaches? Is there some example code somewhere that someone could point me to?</p>
<p>Thanks - </p>
| [
{
"answer_id": 62723,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 3,
"selected": false,
"text": "<p>It is possible.</p>\n\n<p>To set the nth bit, use OR:</p>\n\n<pre><code>x |= (1 << 5); // sets the 5th-from right\... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm trying to implement a data compression idea I've had, and since I'm imagining running it against a large corpus of test data, I had thought to code it in C (I mostly have experience in scripting languages like Ruby and Tcl.)
Looking through the O'Reilly 'cow' books on C, I realize that I can't simply index the bits of a simple 'char' or 'int' type variable as I'd like to to do bitwise comparisons and operators.
Am I correct in this perception? Is it reasonable for me to use an enumerated type for representing a bit (and make an array of these, and writing functions to convert to and from char)? If so, is such a type and functions defined in a standard library already somewhere? Are there other (better?) approaches? Is there some example code somewhere that someone could point me to?
Thanks - | Following on from what Kyle has said, you can use a macro to do the hard work for you.
>
> It is possible.
>
>
> To set the nth bit, use OR:
>
>
> x |= (1 << 5); // sets the 6th-from
> right
>
>
> To clear a bit, use AND:
>
>
> x &= ~(1 << 5); // clears
> 6th-from-right
>
>
> To flip a bit, use XOR:
>
>
> x ^= (1 << 5); // flips 6th-from-right
>
>
>
**Or...**
```
#define GetBit(var, bit) ((var & (1 << bit)) != 0) // Returns true / false if bit is set
#define SetBit(var, bit) (var |= (1 << bit))
#define FlipBit(var, bit) (var ^= (1 << bit))
```
Then you can use it in code like:
```
int myVar = 0;
SetBit(myVar, 5);
if (GetBit(myVar, 5))
{
// Do something
}
``` |
62,776 | <p>How do I implement a Copy menu item in a Windows application written in C#/.NET 2.0?</p>
<p>I want to let the user to mark some text in a control and then select the Copy menu item from an Edit menu in the menubar of the application and then do a Paste in for example Excel. </p>
<p>What makes my head spin is how to first determine which child form is active and then how to find the control that contains the marked text that should be copied to the clipboard. </p>
<p>Help, please.</p>
| [
{
"answer_id": 62833,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": -1,
"selected": false,
"text": "<p>It seems to me that you might be better off breaking this into smaller tasks/questions.\nYou have a few issues you are st... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7174/"
] | How do I implement a Copy menu item in a Windows application written in C#/.NET 2.0?
I want to let the user to mark some text in a control and then select the Copy menu item from an Edit menu in the menubar of the application and then do a Paste in for example Excel.
What makes my head spin is how to first determine which child form is active and then how to find the control that contains the marked text that should be copied to the clipboard.
Help, please. | With the aid of some heavy pair programming a colleague of mine and I came up with this, feel free to refactor.
The code is placed in the main form. The copyToolStripMenuItem\_Click method handles the Click event on the Copy menu item in the Edit menu.
```
/// <summary>
/// Recursively traverse a tree of controls to find the control that has focus, if any
/// </summary>
/// <param name="c">The control to search, might be a control container</param>
/// <returns>The control that either has focus or contains the control that has focus</returns>
private Control FindFocus(Control c)
{
foreach (Control k in c.Controls)
{
if (k.Focused)
{
return k;
}
else if (k.ContainsFocus)
{
return FindFocus(k);
}
}
return null;
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
Form f = this.ActiveMdiChild;
// Find the control that has focus
Control focusedControl = FindFocus(f.ActiveControl);
// See if focusedControl is of a type that can select text/data
if (focusedControl is TextBox)
{
TextBox tb = focusedControl as TextBox;
Clipboard.SetDataObject(tb.SelectedText);
}
else if (focusedControl is DataGridView)
{
DataGridView dgv = focusedControl as DataGridView;
Clipboard.SetDataObject(dgv.GetClipboardContent());
}
else if (...more?...)
{
}
}
``` |
62,804 | <p>Is there a standard library method that converts a string that has duration in the standard ISO 8601 Duration (also used in XSD for its <code>duration</code> type) format into the .NET TimeSpan object?</p>
<p>For example, P0DT1H0M0S which represents a duration of one hour, is converted into New TimeSpan(0,1,0,0,0).</p>
<p>A Reverse converter does exist which works as follows:
Xml.XmlConvert.ToString(New TimeSpan(0,1,0,0,0))
The above expression will return P0DT1H0M0S.</p>
| [
{
"answer_id": 63219,
"author": "user7658",
"author_id": 7658,
"author_profile": "https://Stackoverflow.com/users/7658",
"pm_score": 6,
"selected": true,
"text": "<p>This will convert from xs:duration to TimeSpan:</p>\n\n<pre><code>System.Xml.XmlConvert.ToTimeSpan(\"P0DT1H0M0S\")\n</code... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7105/"
] | Is there a standard library method that converts a string that has duration in the standard ISO 8601 Duration (also used in XSD for its `duration` type) format into the .NET TimeSpan object?
For example, P0DT1H0M0S which represents a duration of one hour, is converted into New TimeSpan(0,1,0,0,0).
A Reverse converter does exist which works as follows:
Xml.XmlConvert.ToString(New TimeSpan(0,1,0,0,0))
The above expression will return P0DT1H0M0S. | This will convert from xs:duration to TimeSpan:
```
System.Xml.XmlConvert.ToTimeSpan("P0DT1H0M0S")
```
See <http://msdn.microsoft.com/en-us/library/system.xml.xmlconvert.totimespan.aspx> |
62,810 | <p>I use RCF with boost.serialization (why use RCF's copy when we already use the original?) It works OK, but when an exception is thrown in the server, it's not passed correctly to the client. Instead, I get an RCF::SerializationException quoting an <code>archive_exception</code> saying "class name too long". When I change the protocol to BsText, the exceptions is "unregistered class". When I change the protocol to SfBinary, it works.
I've registered RemoteException on both server and client like this:</p>
<pre><code>BOOST_CLASS_VERSION(RCF::RemoteException, 0)
BOOST_CLASS_EXPORT(RCF::RemoteException)
</code></pre>
<p>I even tried serializing and deserializing a <code>boost::shared_ptr<RCF::RemoteException></code> in the same test, and it works.</p>
<p>So how can I make RCF pass exceptions correctly without resorting to SF?</p>
| [
{
"answer_id": 85626,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 0,
"selected": false,
"text": "<p>According to Jarl it works, check <a href=\"http://www.codeproject.com/KB/threads/Rcf_Ipc_For_Cpp.aspx?fid=248794&d... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7224/"
] | I use RCF with boost.serialization (why use RCF's copy when we already use the original?) It works OK, but when an exception is thrown in the server, it's not passed correctly to the client. Instead, I get an RCF::SerializationException quoting an `archive_exception` saying "class name too long". When I change the protocol to BsText, the exceptions is "unregistered class". When I change the protocol to SfBinary, it works.
I've registered RemoteException on both server and client like this:
```
BOOST_CLASS_VERSION(RCF::RemoteException, 0)
BOOST_CLASS_EXPORT(RCF::RemoteException)
```
I even tried serializing and deserializing a `boost::shared_ptr<RCF::RemoteException>` in the same test, and it works.
So how can I make RCF pass exceptions correctly without resorting to SF? | Here's a patch given by Jarl at [CodeProject](http://www.codeproject.com/KB/threads/Rcf_Ipc_For_Cpp.aspx?msg=2739150#xx2730536xx):
In RcfServer.cpp, before the line where RcfServer::handleSession() is defined (around line 792), insert the following code:
```
void serialize(SerializationProtocolOut & out, const RemoteException & e)
{
serialize(out, std::auto_ptr<RemoteException>(new RemoteException(e)));
}
```
And in Marshal.cpp, around line 37, replace this line:
```
ar & boost::serialization::make_nvp("Dummy", apt.get());
```
, with
```
T *pt = apt.get();
ar & boost::serialization::make_nvp("Dummy", pt);
``` |
62,814 | <p>Is there any difference between a binary semaphore and mutex or are they essentially the same?</p>
| [
{
"answer_id": 62883,
"author": "Mladen Janković",
"author_id": 6300,
"author_profile": "https://Stackoverflow.com/users/6300",
"pm_score": 9,
"selected": false,
"text": "<ul>\n<li>A <strong>mutex</strong> can be released only by <strong>the thread that had acquired it</strong>. <br></li... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7086/"
] | Is there any difference between a binary semaphore and mutex or are they essentially the same? | They are **NOT** the same thing. They are used for different purposes!
While both types of semaphores have a full/empty state and use the same API, their usage is very different.
**Mutual Exclusion Semaphores**
Mutual Exclusion semaphores are used to protect shared resources (data structure, file, etc..).
A Mutex semaphore is "owned" by the task that takes it. If Task B attempts to semGive a mutex currently held by Task A, Task B's call will return an error and fail.
Mutexes always use the following sequence:
```
- SemTake
- Critical Section
- SemGive
```
Here is a simple example:
```
Thread A Thread B
Take Mutex
access data
... Take Mutex <== Will block
...
Give Mutex access data <== Unblocks
...
Give Mutex
```
**Binary Semaphore**
Binary Semaphore address a totally different question:
* Task B is pended waiting for something to happen (a sensor being tripped for example).
* Sensor Trips and an Interrupt Service Routine runs. It needs to notify a task of the trip.
* Task B should run and take appropriate actions for the sensor trip. Then go back to waiting.
```
Task A Task B
... Take BinSemaphore <== wait for something
Do Something Noteworthy
Give BinSemaphore do something <== unblocks
```
Note that with a binary semaphore, it is OK for B to take the semaphore and A to give it.
Again, a binary semaphore is NOT protecting a resource from access. The act of Giving and Taking a semaphore are fundamentally decoupled.
It typically makes little sense for the same task to so a give and a take on the same binary semaphore. |
62,916 | <p>I have installed and setup RubyCAS-Server and RubyCAS-Client on my machine. Login works perfectly but when I try to logout I get this error message from the RubyCAS-Server:</p>
<pre><code>Camping Problem!
CASServer::Controllers::Logout.GET
ActiveRecord::StatementInvalid Mysql::Error: Unknown column 'username' in 'where clause': SELECT * FROM `casserver_pgt` WHERE (username = 'lgs') :
</code></pre>
<p>I am using version 0.6 of the gem. Looking at the migrations in the RubyCAS-Server it looks like there shouldn't be a username column in that table at all.</p>
<p>Does anyone know why this is happening and what I can do about it?</p>
| [
{
"answer_id": 62914,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 0,
"selected": false,
"text": "<p>Are you unable to use the <a href=\"http://msdn.microsoft.com/en-us/library/aa335422(VS.71).aspx\" rel=\"nofollow noreferr... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3842/"
] | I have installed and setup RubyCAS-Server and RubyCAS-Client on my machine. Login works perfectly but when I try to logout I get this error message from the RubyCAS-Server:
```
Camping Problem!
CASServer::Controllers::Logout.GET
ActiveRecord::StatementInvalid Mysql::Error: Unknown column 'username' in 'where clause': SELECT * FROM `casserver_pgt` WHERE (username = 'lgs') :
```
I am using version 0.6 of the gem. Looking at the migrations in the RubyCAS-Server it looks like there shouldn't be a username column in that table at all.
Does anyone know why this is happening and what I can do about it? | Why not create your own template? I've done that with several types of forms, not just dialogs. It is a great way to give yourself a jump-start.
Create your basic dialog, keeping it as generic as possible, then save it as a template.
Here is an article that will help you:
<http://www.builderau.com.au/program/dotnet/soa/Save-time-with-Visual-Studio-2005-project-templates/0,339028399,339285540,00.htm>
And:
<http://msdn.microsoft.com/en-us/magazine/cc188697.aspx> |
62,929 | <p>I am getting the following error trying to read from a socket. I'm doing a <code>readInt()</code> on that <code>InputStream</code>, and I am getting this error. Perusing the documentation this suggests that the client part of the connection closed the connection. In this scenario, I am the server.</p>
<p>I have access to the client log files and it is not closing the connection, and in fact its log files suggest I am closing the connection. So does anybody have an idea why this is happening? What else to check for? Does this arise when there are local resources that are perhaps reaching thresholds?</p>
<hr>
<p>I do note that I have the following line:</p>
<pre><code>socket.setSoTimeout(10000);
</code></pre>
<p>just prior to the <code>readInt()</code>. There is a reason for this (long story), but just curious, are there circumstances under which this might lead to the indicated error? I have the server running in my IDE, and I happened to leave my IDE stuck on a breakpoint, and I then noticed the exact same errors begin appearing in my own logs in my IDE.</p>
<p>Anyway, just mentioning it, hopefully not a red herring. :-(</p>
| [
{
"answer_id": 62996,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 4,
"selected": false,
"text": "<p>Whenever I have had odd issues like this, I usually sit down with a tool like <a href=\"http://www.wireshark.org/\" rel=\"... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am getting the following error trying to read from a socket. I'm doing a `readInt()` on that `InputStream`, and I am getting this error. Perusing the documentation this suggests that the client part of the connection closed the connection. In this scenario, I am the server.
I have access to the client log files and it is not closing the connection, and in fact its log files suggest I am closing the connection. So does anybody have an idea why this is happening? What else to check for? Does this arise when there are local resources that are perhaps reaching thresholds?
---
I do note that I have the following line:
```
socket.setSoTimeout(10000);
```
just prior to the `readInt()`. There is a reason for this (long story), but just curious, are there circumstances under which this might lead to the indicated error? I have the server running in my IDE, and I happened to leave my IDE stuck on a breakpoint, and I then noticed the exact same errors begin appearing in my own logs in my IDE.
Anyway, just mentioning it, hopefully not a red herring. :-( | There are several possible causes.
1. The other end has deliberately reset the connection, in a way which I will not document here. It is rare, and generally incorrect, for application software to do this, but it is not unknown for commercial software.
2. More commonly, it is caused by writing to a connection that the other end has already closed normally. In other words an application protocol error.
3. It can also be caused by closing a socket when there is unread data in the socket receive buffer.
4. In Windows, 'software caused connection abort', which is not the same as 'connection reset', is caused by network problems sending from your end. There's a Microsoft knowledge base article about this. |
62,936 | <p>For example: <code>man(1)</code>, <code>find(3)</code>, <code>updatedb(2)</code>? </p>
<p>What do the numbers in parentheses (Brit. "brackets") mean?</p>
| [
{
"answer_id": 62943,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 7,
"selected": false,
"text": "<p>The section the command is documented in the manual. The list of sections is documented on man's manual. For examp... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7370/"
] | For example: `man(1)`, `find(3)`, `updatedb(2)`?
What do the numbers in parentheses (Brit. "brackets") mean? | It's the section that the man page for the command is assigned to.
These are split as
1. General commands
2. System calls
3. C library functions
4. Special files (usually devices, those found in /dev) and drivers
5. File formats and conventions
6. Games and screensavers
7. Miscellanea
8. System administration commands and daemons
Original descriptions of each section can be seen in the [Unix Programmer's Manual](https://web.archive.org/web/20170601064537/http://plan9.bell-labs.com/7thEdMan/v7vol1.pdf) (page ii).
In order to access a man page given as "foo(5)", run:
```sh
man 5 foo
``` |
62,940 | <p>Need to show a credits screen where I want to acknowledge the many contributors to my application. </p>
<p>Want it to be an automatically scrolling box, much like the credits roll at the end of the film.</p>
| [
{
"answer_id": 62978,
"author": "Phil Wright",
"author_id": 6276,
"author_profile": "https://Stackoverflow.com/users/6276",
"pm_score": 0,
"selected": false,
"text": "<p>A quick and dirty method would be to use a Panel with a long list of Label controls on it that list out the various pe... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Need to show a credits screen where I want to acknowledge the many contributors to my application.
Want it to be an automatically scrolling box, much like the credits roll at the end of the film. | A easy-to-use snippet would be to make a multiline textbox. With a timer you may insert line after line and scroll to the end after that:
```
textbox1.SelectionStart = textbox1.Text.Length;
textbox1.ScrollToCaret();
textbox1.Refresh();
```
Not the best method but it's simple and working. There are also some free controls available for exactly this auto-scrolling. |
62,963 | <p>Last year, Scott Guthrie <a href="http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx" rel="noreferrer">stated</a> “You can actually override the raw SQL that LINQ to SQL uses if you want absolute control over the SQL executed”, but I can’t find documentation describing an extensibility method.</p>
<p>I would like to modify the following LINQ to SQL query:</p>
<pre>using (NorthwindContext northwind = new NorthwindContext ()) {
var q = from row in northwind.Customers
let orderCount = row.Orders.Count ()
select new {
row.ContactName,
orderCount
};
}</pre>
<p>Which results in the following TSQL:</p>
<pre>SELECT [t0].[ContactName], (
SELECT COUNT(*)
FROM [dbo].[Orders] AS [t1]
WHERE [t1].[CustomerID] = [t0].[CustomerID]
) AS [orderCount]
FROM [dbo].[Customers] AS [t0]</pre>
<p>To:</p>
<pre>using (NorthwindContext northwind = new NorthwindContext ()) {
var q = from row in northwind.Customers.With (
TableHint.NoLock, TableHint.Index (0))
let orderCount = row.Orders.With (
TableHint.HoldLock).Count ()
select new {
row.ContactName,
orderCount
};
}</pre>
<p>Which <em>would</em> result in the following TSQL:</p>
<pre>SELECT [t0].[ContactName], (
SELECT COUNT(*)
FROM [dbo].[Orders] AS [t1] WITH (HOLDLOCK)
WHERE [t1].[CustomerID] = [t0].[CustomerID]
) AS [orderCount]
FROM [dbo].[Customers] AS [t0] WITH (NOLOCK, INDEX(0))</pre>
<p>Using:</p>
<pre>public static Table<TEntity> With<TEntity> (
this Table<TEntity> table,
params TableHint[] args) where TEntity : class {
//TODO: implement
return table;
}
public static EntitySet<TEntity> With<TEntity> (
this EntitySet<TEntity> entitySet,
params TableHint[] args) where TEntity : class {
//TODO: implement
return entitySet;
}</pre>
<p>And</p>
<pre>
public class TableHint {
//TODO: implement
public static TableHint NoLock;
public static TableHint HoldLock;
public static TableHint Index (int id) {
return null;
}
public static TableHint Index (string name) {
return null;
}
}</pre>
<p>Using some type of LINQ to SQL extensibility, other than <a href="http://blogs.msdn.com/mattwar/archive/2008/05/04/mocks-nix-an-extensible-linq-to-sql-datacontext.aspx" rel="noreferrer">this one</a>. Any ideas?</p>
| [
{
"answer_id": 64612,
"author": "user8456",
"author_id": 8456,
"author_profile": "https://Stackoverflow.com/users/8456",
"pm_score": -1,
"selected": false,
"text": "<p><code>DataContext x = new DataContext</code></p>\n\n<p>Something like this perhaps?</p>\n\n<p><code>var a = x.Where().wi... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5869/"
] | Last year, Scott Guthrie [stated](http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx) “You can actually override the raw SQL that LINQ to SQL uses if you want absolute control over the SQL executed”, but I can’t find documentation describing an extensibility method.
I would like to modify the following LINQ to SQL query:
```
using (NorthwindContext northwind = new NorthwindContext ()) {
var q = from row in northwind.Customers
let orderCount = row.Orders.Count ()
select new {
row.ContactName,
orderCount
};
}
```
Which results in the following TSQL:
```
SELECT [t0].[ContactName], (
SELECT COUNT(*)
FROM [dbo].[Orders] AS [t1]
WHERE [t1].[CustomerID] = [t0].[CustomerID]
) AS [orderCount]
FROM [dbo].[Customers] AS [t0]
```
To:
```
using (NorthwindContext northwind = new NorthwindContext ()) {
var q = from row in northwind.Customers.With (
TableHint.NoLock, TableHint.Index (0))
let orderCount = row.Orders.With (
TableHint.HoldLock).Count ()
select new {
row.ContactName,
orderCount
};
}
```
Which *would* result in the following TSQL:
```
SELECT [t0].[ContactName], (
SELECT COUNT(*)
FROM [dbo].[Orders] AS [t1] WITH (HOLDLOCK)
WHERE [t1].[CustomerID] = [t0].[CustomerID]
) AS [orderCount]
FROM [dbo].[Customers] AS [t0] WITH (NOLOCK, INDEX(0))
```
Using:
```
public static Table<TEntity> With<TEntity> (
this Table<TEntity> table,
params TableHint[] args) where TEntity : class {
//TODO: implement
return table;
}
public static EntitySet<TEntity> With<TEntity> (
this EntitySet<TEntity> entitySet,
params TableHint[] args) where TEntity : class {
//TODO: implement
return entitySet;
}
```
And
```
public class TableHint {
//TODO: implement
public static TableHint NoLock;
public static TableHint HoldLock;
public static TableHint Index (int id) {
return null;
}
public static TableHint Index (string name) {
return null;
}
}
```
Using some type of LINQ to SQL extensibility, other than [this one](http://blogs.msdn.com/mattwar/archive/2008/05/04/mocks-nix-an-extensible-linq-to-sql-datacontext.aspx). Any ideas? | The ability to change the underlying provider and thus modify the SQL did not make the final cut in LINQ to SQL. |
62,987 | <p>A project I'm working on at the moment involves refactoring a C# Com Object which serves as a database access layer to some Sql 2005 databases.</p>
<p>The author of the existent code has built all the sql queries manually using a string and many if-statements to construct the fairly complex sql statement (~10 joins, >10 sub selects, ~15-25 where conditions and GroupBy's). The base table is always the same one, but the structure of joins, conditions and groupings depend on a set of parameters that are passed into my class/method.</p>
<p>Constructing the sql query like this does work but it obviously isn't a very elegant solution (and rather hard to read/understand and maintain as well)... I could just write a simple "querybuilder" myself but I am pretty sure that I am not the first one with this kind of problem, hence my questions:</p>
<ul>
<li>How do <em>you</em> construct your database queries?</li>
<li>Does C# offer an easy way to dynamically build queries?</li>
</ul>
| [
{
"answer_id": 63009,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.google.com/search?q=dynamic+LINQ+tutorial\" rel=\"nofollow noreferrer\">LINQ</a> is the way t... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5005/"
] | A project I'm working on at the moment involves refactoring a C# Com Object which serves as a database access layer to some Sql 2005 databases.
The author of the existent code has built all the sql queries manually using a string and many if-statements to construct the fairly complex sql statement (~10 joins, >10 sub selects, ~15-25 where conditions and GroupBy's). The base table is always the same one, but the structure of joins, conditions and groupings depend on a set of parameters that are passed into my class/method.
Constructing the sql query like this does work but it obviously isn't a very elegant solution (and rather hard to read/understand and maintain as well)... I could just write a simple "querybuilder" myself but I am pretty sure that I am not the first one with this kind of problem, hence my questions:
* How do *you* construct your database queries?
* Does C# offer an easy way to dynamically build queries? | I used C# and Linq to do something similar to get log entries filtered on user input (see [Conditional Linq Queries](https://stackoverflow.com/questions/11194/conditional-linq-queries)):
```
IQueryable<Log> matches = m_Locator.Logs;
// Users filter
if (usersFilter)
matches = matches.Where(l => l.UserName == comboBoxUsers.Text);
// Severity filter
if (severityFilter)
matches = matches.Where(l => l.Severity == comboBoxSeverity.Text);
Logs = (from log in matches
orderby log.EventTime descending
select log).ToList();
```
Edit: The query isn't performed until .ToList() in the last statement. |
62,995 | <p>I am currently building in Version 3.5 of the .Net framework and I have a resource (.resx) file that I am trying to access in a web application. I have exposed the .resx properties as public access modifiers and am able to access these properties in the controller files or other .cs files in the web app. My question is this: Is it possible to access the name/value pairs within my view page? I'd like to do something like this...</p>
<pre><code>text="<%$ Resources: Namespace.ResourceFileName, NAME %>"
</code></pre>
<p>or some other similar method in the view page.</p>
| [
{
"answer_id": 63062,
"author": "Joel Martinez",
"author_id": 5416,
"author_profile": "https://Stackoverflow.com/users/5416",
"pm_score": 2,
"selected": false,
"text": "<p>Expose the resource property you want to consume in the page as a protected page property. Then you can just do use... | 2008/09/15 | [
"https://Stackoverflow.com/questions/62995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7215/"
] | I am currently building in Version 3.5 of the .Net framework and I have a resource (.resx) file that I am trying to access in a web application. I have exposed the .resx properties as public access modifiers and am able to access these properties in the controller files or other .cs files in the web app. My question is this: Is it possible to access the name/value pairs within my view page? I'd like to do something like this...
```
text="<%$ Resources: Namespace.ResourceFileName, NAME %>"
```
or some other similar method in the view page. | ```cs
<%= Resources.<ResourceName>.<Property> %>
``` |
63,008 | <p>I'm writing a C# application which downloads a compressed database backup via FTP. The application then needs to extract the backup and restore it to the default database location.</p>
<p>I will not know which version of SQL Server will be installed on the machine where the application runs. Therefore, I need to find the default location based on the instance name (which is in the config file).</p>
<p>The examples I found all had a registry key which they read, but this will not work, since this assumes that only one instance of SQL is installed.</p>
<p>Another example I found created a database, read that database's file properties, the deleting the database once it was done. That's just cumbersome.</p>
<p>I did find something in the .NET framework which should work, ie:</p>
<p><pre><code>Microsoft.SqlServer.Management.Smo.Server(ServerName).Settings.DefaultFile</code></pre></p>
<p>The problem is that this is returning empty strings, which does not help.</p>
<p>I also need to find out the NT account under which the SQL service is running, so that I can grant read access to that user on the backup file once I have the it extracted.</p>
| [
{
"answer_id": 63200,
"author": "Darrel Miller",
"author_id": 6819,
"author_profile": "https://Stackoverflow.com/users/6819",
"pm_score": 1,
"selected": false,
"text": "<p>One option, that may be a simpler solution, is to create a new database on your destination server and then RESTORE ... | 2008/09/15 | [
"https://Stackoverflow.com/questions/63008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6389/"
] | I'm writing a C# application which downloads a compressed database backup via FTP. The application then needs to extract the backup and restore it to the default database location.
I will not know which version of SQL Server will be installed on the machine where the application runs. Therefore, I need to find the default location based on the instance name (which is in the config file).
The examples I found all had a registry key which they read, but this will not work, since this assumes that only one instance of SQL is installed.
Another example I found created a database, read that database's file properties, the deleting the database once it was done. That's just cumbersome.
I did find something in the .NET framework which should work, ie:
```
Microsoft.SqlServer.Management.Smo.Server(ServerName).Settings.DefaultFile
```
The problem is that this is returning empty strings, which does not help.
I also need to find out the NT account under which the SQL service is running, so that I can grant read access to that user on the backup file once I have the it extracted. | What I discovered is that
```
Microsoft.SqlServer.Management.Smo.Server(ServerName).Settings.DefaultFile
```
only returns non-null when there is no path explicitly defined. As soon as you specify a path which is not the default, then this function returns that path correctly.
So, a simple workaround was to check whether this function returns a string, or null. If it returns a string, then use that, but if it's null, use
```
Microsoft.SqlServer.Management.Smo.Server(ServerName).Information.RootDirectory + "\\DATA\\"
``` |
63,011 | <p>I'm displaying a set of images as an overlay using Google Maps. Displaying these images should be in an endless loop but most most browsers detect this, and display a warning. </p>
<p>Is there a way to make a endless loop in JavaScript so that it isn't stopped or warned against by the browser?</p>
| [
{
"answer_id": 63039,
"author": "Erik",
"author_id": 6733,
"author_profile": "https://Stackoverflow.com/users/6733",
"pm_score": 4,
"selected": true,
"text": "<p>Try <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval\" rel=\"nofollow noreferr... | 2008/09/15 | [
"https://Stackoverflow.com/questions/63011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7417/"
] | I'm displaying a set of images as an overlay using Google Maps. Displaying these images should be in an endless loop but most most browsers detect this, and display a warning.
Is there a way to make a endless loop in JavaScript so that it isn't stopped or warned against by the browser? | Try [setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) or [setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/settimeout).
Here is an example:
```js
(show = (o) => setTimeout(() => {
console.log(o)
show(++o)
}, 1000))(1);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
``` |
63,043 | <p>Has anybody got this to actually work? Documentation is non existent on how to enable this feature and I get missing attribute exceptions despite having a 3.5 SP1 project. </p>
| [
{
"answer_id": 63554,
"author": "Doanair",
"author_id": 4774,
"author_profile": "https://Stackoverflow.com/users/4774",
"pm_score": 0,
"selected": false,
"text": "<p>There are several serialization options in WCF: Data contract, XML Serialization and and raw data payload. Which of these ... | 2008/09/15 | [
"https://Stackoverflow.com/questions/63043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7375/"
] | Has anybody got this to actually work? Documentation is non existent on how to enable this feature and I get missing attribute exceptions despite having a 3.5 SP1 project. | I found that it doesn't work with internal/private types, but making my type public it worked fine. This means no anonymous types either :(
Using reflector I found the method ClassDataContract.IsNonAttributedTypeValidForSerialization(Type) that seems to make the decision. It's the last line that seems to be the killer, the type must be visible, so no internal/private types allowed :(
```
internal static bool IsNonAttributedTypeValidForSerialization(Type type)
{
if (type.IsArray)
{
return false;
}
if (type.IsEnum)
{
return false;
}
if (type.IsGenericParameter)
{
return false;
}
if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type))
{
return false;
}
if (type.IsPointer)
{
return false;
}
if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))
{
return false;
}
foreach (Type type2 in type.GetInterfaces())
{
if (CollectionDataContract.IsCollectionInterface(type2))
{
return false;
}
}
if (type.IsSerializable)
{
return false;
}
if (Globals.TypeOfISerializable.IsAssignableFrom(type))
{
return false;
}
if (type.IsDefined(Globals.TypeOfDataContractAttribute, false))
{
return false;
}
if (type == Globals.TypeOfExtensionDataObject)
{
return false;
}
if (type.IsValueType)
{
return type.IsVisible;
}
return (type.IsVisible && (type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, Globals.EmptyTypeArray, null) != null));
```
} |
63,067 | <p>We have to connect to a third party SOAP service and we are using WCF to do so. The service was developed using Apache AXIS, and we have no control over it, and have no influence to change how it works.
The problem we are seeing is that it expects the requests to be formatted using Web Services Security, so we are doing all the correct signing, etc. The response from the 3rd party however, is not secured. If we sniff the wire, we see the response coming back fine (albeit without any timestamp, signature etc.).
The underlying .NET components throw this as an error because it sees it as a security issue, so we don't actually receive the soap response as such. Is there any way to configure the WCF framework for sending secure requests, but not to expect security fields in the response? Looking at the OASIS specs, it doesn't appear to mandate that the responses must be secure.</p>
<p>For information, here's the exception we see:</p>
<p>The exception we receive is:</p>
<pre><code>System.ServiceModel.Security.MessageSecurityException was caught
Message="Security processor was unable to find a security header in the message. This might be because the message is an unsecured fault or because there is a binding mismatch between the communicating parties. This can occur if the service is configured for security and the client is not using security."
Source="mscorlib"
StackTrace:
Server stack trace:
at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessageCore(Message& message, TimeSpan timeout)
at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout)
at System.ServiceModel.Security.SecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
</code></pre>
<p>Incidentally, I've seen plenty of posts stating that if you leave the timestamp out, then the security fields will not be expected. This is not an option - The service we are communicating with mandates timestamps. </p>
| [
{
"answer_id": 63651,
"author": "Doanair",
"author_id": 4774,
"author_profile": "https://Stackoverflow.com/users/4774",
"pm_score": 2,
"selected": false,
"text": "<p>Funny you should ask this question. I asked Microsoft how to do this about a year ago. At the time, using .NET 3.0, it was... | 2008/09/15 | [
"https://Stackoverflow.com/questions/63067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | We have to connect to a third party SOAP service and we are using WCF to do so. The service was developed using Apache AXIS, and we have no control over it, and have no influence to change how it works.
The problem we are seeing is that it expects the requests to be formatted using Web Services Security, so we are doing all the correct signing, etc. The response from the 3rd party however, is not secured. If we sniff the wire, we see the response coming back fine (albeit without any timestamp, signature etc.).
The underlying .NET components throw this as an error because it sees it as a security issue, so we don't actually receive the soap response as such. Is there any way to configure the WCF framework for sending secure requests, but not to expect security fields in the response? Looking at the OASIS specs, it doesn't appear to mandate that the responses must be secure.
For information, here's the exception we see:
The exception we receive is:
```
System.ServiceModel.Security.MessageSecurityException was caught
Message="Security processor was unable to find a security header in the message. This might be because the message is an unsecured fault or because there is a binding mismatch between the communicating parties. This can occur if the service is configured for security and the client is not using security."
Source="mscorlib"
StackTrace:
Server stack trace:
at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessageCore(Message& message, TimeSpan timeout)
at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout)
at System.ServiceModel.Security.SecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
```
Incidentally, I've seen plenty of posts stating that if you leave the timestamp out, then the security fields will not be expected. This is not an option - The service we are communicating with mandates timestamps. | Funny you should ask this question. I asked Microsoft how to do this about a year ago. At the time, using .NET 3.0, it was not possible. Not sure if that changed in the 3.5 world. But, no, there was no physical way of adding security to the request and leaving the response empty.
At my previous employer we used a model that required a WS-Security header using certificates on the request but the response was left unsecured.
You can do this with ASMX web services and WSE, but not with WCF v3.0. |
63,104 | <p>When a previous Vim session crashed, you are greeted with the "Swap file ... already exists!" for each and every file that was open in the previous session.</p>
<p>Can you make this Vim recovery prompt smarter? (Without switching off recovery!) Specifically, I'm thinking of:</p>
<ul>
<li>If the swapped version does not contain unsaved changes and the editing process is no longer running, can you make Vim automatically delete the swap file?</li>
<li>Can you automate the suggested process of saving the recovered file under a new name, merging it with file on disk and then deleting the old swap file, so that minimal interaction is required? Especially when the swap version and the disk version are the same, everything should be automatic.</li>
</ul>
<p>I discovered the <code>SwapExists</code> autocommand but I don't know if it can help with these tasks.</p>
| [
{
"answer_id": 63341,
"author": "Chouser",
"author_id": 7624,
"author_profile": "https://Stackoverflow.com/users/7624",
"pm_score": 6,
"selected": true,
"text": "<p>I have vim store my swap files in a single local directory, by having this in my .vimrc:</p>\n\n<pre><code>set directory=~/... | 2008/09/15 | [
"https://Stackoverflow.com/questions/63104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6918/"
] | When a previous Vim session crashed, you are greeted with the "Swap file ... already exists!" for each and every file that was open in the previous session.
Can you make this Vim recovery prompt smarter? (Without switching off recovery!) Specifically, I'm thinking of:
* If the swapped version does not contain unsaved changes and the editing process is no longer running, can you make Vim automatically delete the swap file?
* Can you automate the suggested process of saving the recovered file under a new name, merging it with file on disk and then deleting the old swap file, so that minimal interaction is required? Especially when the swap version and the disk version are the same, everything should be automatic.
I discovered the `SwapExists` autocommand but I don't know if it can help with these tasks. | I have vim store my swap files in a single local directory, by having this in my .vimrc:
```
set directory=~/.vim/swap,.
```
Among other benefits, this makes the swap files easy to find all at once.
Now when my laptop loses power or whatever and I start back up with a bunch of swap files laying around, I just run my `cleanswap` script:
```
TMPDIR=$(mktemp -d) || exit 1
RECTXT="$TMPDIR/vim.recovery.$USER.txt"
RECFN="$TMPDIR/vim.recovery.$USER.fn"
trap 'rm -f "$RECTXT" "$RECFN"; rmdir "$TMPDIR"' 0 1 2 3 15
for q in ~/.vim/swap/.*sw? ~/.vim/swap/*; do
[[ -f $q ]] || continue
rm -f "$RECTXT" "$RECFN"
vim -X -r "$q" \
-c "w! $RECTXT" \
-c "let fn=expand('%')" \
-c "new $RECFN" \
-c "exec setline( 1, fn )" \
-c w\! \
-c "qa"
if [[ ! -f $RECFN ]]; then
echo "nothing to recover from $q"
rm -f "$q"
continue
fi
CRNT="$(cat $RECFN)"
if diff --strip-trailing-cr --brief "$CRNT" "$RECTXT"; then
echo "removing redundant $q"
echo " for $CRNT"
rm -f "$q"
else
echo $q contains changes
vim -n -d "$CRNT" "$RECTXT"
rm -i "$q" || exit
fi
done
```
This will remove any swap files that are up-to-date with the real files. Any that don't match are brought up in a vimdiff window so I can merge in my unsaved changes.
--Chouser |
63,150 | <p>While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be in advance. The best I could come up with off the top of my head was something like this:</p>
<pre><code>public String appendWithDelimiter( String original, String addition, String delimiter ) {
if ( original.equals( "" ) ) {
return addition;
} else {
return original + delimiter + addition;
}
}
String parameterString = "";
if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," );
if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," );
</code></pre>
<p>I realize this isn't particularly efficient, since there are strings being created all over the place, but I was going for clarity more than optimization.</p>
<p>In Ruby, I can do something like this instead, which feels much more elegant:</p>
<pre><code>parameterArray = [];
parameterArray << "elementName" if condition;
parameterArray << "anotherElementName" if anotherCondition;
parameterString = parameterArray.join(",");
</code></pre>
<p>But since Java lacks a join command, I couldn't figure out anything equivalent.</p>
<p>So, what's the best way to do this in Java?</p>
| [
{
"answer_id": 63173,
"author": "Stu Thompson",
"author_id": 2961,
"author_profile": "https://Stackoverflow.com/users/2961",
"pm_score": 4,
"selected": false,
"text": "<p>Use an approach based on <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html\" rel=\"noref... | 2008/09/15 | [
"https://Stackoverflow.com/questions/63150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2041950/"
] | While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be in advance. The best I could come up with off the top of my head was something like this:
```
public String appendWithDelimiter( String original, String addition, String delimiter ) {
if ( original.equals( "" ) ) {
return addition;
} else {
return original + delimiter + addition;
}
}
String parameterString = "";
if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," );
if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," );
```
I realize this isn't particularly efficient, since there are strings being created all over the place, but I was going for clarity more than optimization.
In Ruby, I can do something like this instead, which feels much more elegant:
```
parameterArray = [];
parameterArray << "elementName" if condition;
parameterArray << "anotherElementName" if anotherCondition;
parameterString = parameterArray.join(",");
```
But since Java lacks a join command, I couldn't figure out anything equivalent.
So, what's the best way to do this in Java? | ### Pre Java 8:
Apache's commons lang is your friend here - it provides a join method very similar to the one you refer to in Ruby:
[`StringUtils.join(java.lang.Iterable,char)`](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#join(java.lang.Iterable,%20char))
---
### Java 8:
Java 8 provides joining out of the box via `StringJoiner` and `String.join()`. The snippets below show how you can use them:
[`StringJoiner`](https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html)
```
StringJoiner joiner = new StringJoiner(",");
joiner.add("01").add("02").add("03");
String joinedString = joiner.toString(); // "01,02,03"
```
---
[`String.join(CharSequence delimiter, CharSequence... elements))`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence...-)
```
String joinedString = String.join(" - ", "04", "05", "06"); // "04 - 05 - 06"
```
---
[`String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-)
```
List<String> strings = new LinkedList<>();
strings.add("Java");strings.add("is");
strings.add("cool");
String message = String.join(" ", strings);
//message returned is: "Java is cool"
``` |
63,166 | <p>I once had the task of determining the following performance parameters from inside a running application:</p>
<ul>
<li>Total virtual memory available</li>
<li>Virtual memory currently used</li>
<li>Virtual memory currently used by my process<hr></li>
<li>Total RAM available</li>
<li>RAM currently used</li>
<li>RAM currently used by my process<hr></li>
<li>% CPU currently used</li>
<li>% CPU currently used by my process</li>
</ul>
<p>The code had to run on Windows and Linux. Even though this seems to be a standard task, finding the necessary information in the manuals (WIN32 API, GNU docs) as well as on the Internet took me several days, because there's so much incomplete/incorrect/outdated information on this topic to be found out there.</p>
<p>In order to save others from going through the same trouble, I thought it would be a good idea to collect all the scattered information plus what I found by trial and error here in one place.</p>
| [
{
"answer_id": 64166,
"author": "Lanzelot",
"author_id": 7381,
"author_profile": "https://Stackoverflow.com/users/7381",
"pm_score": 10,
"selected": false,
"text": "<h2>Windows</h2>\n<p>Some of the above values are easily available from the appropriate Win32 API, I just list them here fo... | 2008/09/15 | [
"https://Stackoverflow.com/questions/63166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7381/"
] | I once had the task of determining the following performance parameters from inside a running application:
* Total virtual memory available
* Virtual memory currently used
* Virtual memory currently used by my process
---
* Total RAM available
* RAM currently used
* RAM currently used by my process
---
* % CPU currently used
* % CPU currently used by my process
The code had to run on Windows and Linux. Even though this seems to be a standard task, finding the necessary information in the manuals (WIN32 API, GNU docs) as well as on the Internet took me several days, because there's so much incomplete/incorrect/outdated information on this topic to be found out there.
In order to save others from going through the same trouble, I thought it would be a good idea to collect all the scattered information plus what I found by trial and error here in one place. | Windows
-------
Some of the above values are easily available from the appropriate Win32 API, I just list them here for completeness. Others, however, need to be obtained from the Performance Data Helper library (PDH), which is a bit "unintuitive" and takes a lot of painful trial and error to get to work. (At least it took me quite a while, perhaps I've been only a bit stupid...)
Note: for clarity all error checking has been omitted from the following code. Do check the return codes...!
* Total Virtual Memory:
```
#include "windows.h"
MEMORYSTATUSEX memInfo;
memInfo.dwLength = sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&memInfo);
DWORDLONG totalVirtualMem = memInfo.ullTotalPageFile;
```
Note: The name "TotalPageFile" is a bit misleading here. In reality this parameter gives the "Virtual Memory Size", which is size of swap file plus installed RAM.
* Virtual Memory currently used:
Same code as in "Total Virtual Memory" and then
```
DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile;
```
* Virtual Memory currently used by current process:
```
#include "windows.h"
#include "psapi.h"
PROCESS_MEMORY_COUNTERS_EX pmc;
GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc));
SIZE_T virtualMemUsedByMe = pmc.PrivateUsage;
```
* Total Physical Memory (RAM):
Same code as in "Total Virtual Memory" and then
```
DWORDLONG totalPhysMem = memInfo.ullTotalPhys;
```
* Physical Memory currently used:
Same code as in "Total Virtual Memory" and then
```
DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys;
```
* Physical Memory currently used by current process:
Same code as in "Virtual Memory currently used by current process" and then
```
SIZE_T physMemUsedByMe = pmc.WorkingSetSize;
```
* CPU currently used:
```
#include "TCHAR.h"
#include "pdh.h"
static PDH_HQUERY cpuQuery;
static PDH_HCOUNTER cpuTotal;
void init(){
PdhOpenQuery(NULL, NULL, &cpuQuery);
// You can also use L"\\Processor(*)\\% Processor Time" and get individual CPU values with PdhGetFormattedCounterArray()
PdhAddEnglishCounter(cpuQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal);
PdhCollectQueryData(cpuQuery);
}
double getCurrentValue(){
PDH_FMT_COUNTERVALUE counterVal;
PdhCollectQueryData(cpuQuery);
PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);
return counterVal.doubleValue;
}
```
* CPU currently used by current process:
```
#include "windows.h"
static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU;
static int numProcessors;
static HANDLE self;
void init(){
SYSTEM_INFO sysInfo;
FILETIME ftime, fsys, fuser;
GetSystemInfo(&sysInfo);
numProcessors = sysInfo.dwNumberOfProcessors;
GetSystemTimeAsFileTime(&ftime);
memcpy(&lastCPU, &ftime, sizeof(FILETIME));
self = GetCurrentProcess();
GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
memcpy(&lastSysCPU, &fsys, sizeof(FILETIME));
memcpy(&lastUserCPU, &fuser, sizeof(FILETIME));
}
double getCurrentValue(){
FILETIME ftime, fsys, fuser;
ULARGE_INTEGER now, sys, user;
double percent;
GetSystemTimeAsFileTime(&ftime);
memcpy(&now, &ftime, sizeof(FILETIME));
GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
memcpy(&sys, &fsys, sizeof(FILETIME));
memcpy(&user, &fuser, sizeof(FILETIME));
percent = (sys.QuadPart - lastSysCPU.QuadPart) +
(user.QuadPart - lastUserCPU.QuadPart);
percent /= (now.QuadPart - lastCPU.QuadPart);
percent /= numProcessors;
lastCPU = now;
lastUserCPU = user;
lastSysCPU = sys;
return percent * 100;
}
```
---
Linux
-----
On Linux the choice that seemed obvious at first was to use the POSIX APIs like `getrusage()` etc. I spent some time trying to get this to work, but never got meaningful values. When I finally checked the kernel sources themselves, I found out that apparently these APIs are not yet completely implemented as of Linux kernel 2.6!?
In the end I got all values via a combination of reading the pseudo-filesystem `/proc` and kernel calls.
* Total Virtual Memory:
```
#include "sys/types.h"
#include "sys/sysinfo.h"
struct sysinfo memInfo;
sysinfo (&memInfo);
long long totalVirtualMem = memInfo.totalram;
//Add other values in next statement to avoid int overflow on right hand side...
totalVirtualMem += memInfo.totalswap;
totalVirtualMem *= memInfo.mem_unit;
```
* Virtual Memory currently used:
Same code as in "Total Virtual Memory" and then
```
long long virtualMemUsed = memInfo.totalram - memInfo.freeram;
//Add other values in next statement to avoid int overflow on right hand side...
virtualMemUsed += memInfo.totalswap - memInfo.freeswap;
virtualMemUsed *= memInfo.mem_unit;
```
* Virtual Memory currently used by current process:
```
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
int parseLine(char* line){
// This assumes that a digit will be found and the line ends in " Kb".
int i = strlen(line);
const char* p = line;
while (*p <'0' || *p > '9') p++;
line[i-3] = '\0';
i = atoi(p);
return i;
}
int getValue(){ //Note: this value is in KB!
FILE* file = fopen("/proc/self/status", "r");
int result = -1;
char line[128];
while (fgets(line, 128, file) != NULL){
if (strncmp(line, "VmSize:", 7) == 0){
result = parseLine(line);
break;
}
}
fclose(file);
return result;
}
```
* Total Physical Memory (RAM):
Same code as in "Total Virtual Memory" and then
```
long long totalPhysMem = memInfo.totalram;
//Multiply in next statement to avoid int overflow on right hand side...
totalPhysMem *= memInfo.mem_unit;
```
* Physical Memory currently used:
Same code as in "Total Virtual Memory" and then
```
long long physMemUsed = memInfo.totalram - memInfo.freeram;
//Multiply in next statement to avoid int overflow on right hand side...
physMemUsed *= memInfo.mem_unit;
```
* Physical Memory currently used by current process:
Change getValue() in "Virtual Memory currently used by current process" as follows:
```
int getValue(){ //Note: this value is in KB!
FILE* file = fopen("/proc/self/status", "r");
int result = -1;
char line[128];
while (fgets(line, 128, file) != NULL){
if (strncmp(line, "VmRSS:", 6) == 0){
result = parseLine(line);
break;
}
}
fclose(file);
return result;
}
```
* CPU currently used:
```
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
static unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle;
void init(){
FILE* file = fopen("/proc/stat", "r");
fscanf(file, "cpu %llu %llu %llu %llu", &lastTotalUser, &lastTotalUserLow,
&lastTotalSys, &lastTotalIdle);
fclose(file);
}
double getCurrentValue(){
double percent;
FILE* file;
unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total;
file = fopen("/proc/stat", "r");
fscanf(file, "cpu %llu %llu %llu %llu", &totalUser, &totalUserLow,
&totalSys, &totalIdle);
fclose(file);
if (totalUser < lastTotalUser || totalUserLow < lastTotalUserLow ||
totalSys < lastTotalSys || totalIdle < lastTotalIdle){
//Overflow detection. Just skip this value.
percent = -1.0;
}
else{
total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) +
(totalSys - lastTotalSys);
percent = total;
total += (totalIdle - lastTotalIdle);
percent /= total;
percent *= 100;
}
lastTotalUser = totalUser;
lastTotalUserLow = totalUserLow;
lastTotalSys = totalSys;
lastTotalIdle = totalIdle;
return percent;
}
```
* CPU currently used by current process:
```
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "sys/times.h"
#include "sys/vtimes.h"
static clock_t lastCPU, lastSysCPU, lastUserCPU;
static int numProcessors;
void init(){
FILE* file;
struct tms timeSample;
char line[128];
lastCPU = times(&timeSample);
lastSysCPU = timeSample.tms_stime;
lastUserCPU = timeSample.tms_utime;
file = fopen("/proc/cpuinfo", "r");
numProcessors = 0;
while(fgets(line, 128, file) != NULL){
if (strncmp(line, "processor", 9) == 0) numProcessors++;
}
fclose(file);
}
double getCurrentValue(){
struct tms timeSample;
clock_t now;
double percent;
now = times(&timeSample);
if (now <= lastCPU || timeSample.tms_stime < lastSysCPU ||
timeSample.tms_utime < lastUserCPU){
//Overflow detection. Just skip this value.
percent = -1.0;
}
else{
percent = (timeSample.tms_stime - lastSysCPU) +
(timeSample.tms_utime - lastUserCPU);
percent /= (now - lastCPU);
percent /= numProcessors;
percent *= 100;
}
lastCPU = now;
lastSysCPU = timeSample.tms_stime;
lastUserCPU = timeSample.tms_utime;
return percent;
}
```
---
TODO: Other Platforms
---------------------
I would assume, that some of the Linux code also works for the Unixes, except for the parts that read the /proc pseudo-filesystem. Perhaps on Unix these parts can be replaced by `getrusage()` and similar functions? |
63,181 | <p>In Flex, I have an xml document such as the following:</p>
<pre><code>var xml:XML = <root><node>value1</node><node>value2</node><node>value3</node></root>
</code></pre>
<p>At runtime, I want to create a TextInput control for each node under root, and have the values bound to the values in the XML. As far as I can tell I can't use BindingUtils to bind to e4x nodes at runtime (please tell me if I'm wrong here!), so I'm trying to do this by hand:</p>
<pre><code>for each (var node:XML in xml.node)
{
var textInput:TextInput = new TextInput();
var handler:Function = function(event:Event):void
{
node.setChildren(event.target.text);
};
textInput.text = node.text();
textInput.addEventListener(Event.CHANGE, handler);
this.addChild(pileHeightEditor);
}
</code></pre>
<p>My problem is that when the user edits one of the TextInputs, the node getting assigned to is always the last one encountered in the for loop. I am used to this pattern from C#, where each time an anonymous function is created, a "snapshot" of the values of the used values is taken, so "node" would be different in each handler function.</p>
<p>How do I "take a snapshot" of the current value of node to use in the handler? Or should I be using a different pattern in Flex?</p>
| [
{
"answer_id": 64166,
"author": "Lanzelot",
"author_id": 7381,
"author_profile": "https://Stackoverflow.com/users/7381",
"pm_score": 10,
"selected": false,
"text": "<h2>Windows</h2>\n<p>Some of the above values are easily available from the appropriate Win32 API, I just list them here fo... | 2008/09/15 | [
"https://Stackoverflow.com/questions/63181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6448/"
] | In Flex, I have an xml document such as the following:
```
var xml:XML = <root><node>value1</node><node>value2</node><node>value3</node></root>
```
At runtime, I want to create a TextInput control for each node under root, and have the values bound to the values in the XML. As far as I can tell I can't use BindingUtils to bind to e4x nodes at runtime (please tell me if I'm wrong here!), so I'm trying to do this by hand:
```
for each (var node:XML in xml.node)
{
var textInput:TextInput = new TextInput();
var handler:Function = function(event:Event):void
{
node.setChildren(event.target.text);
};
textInput.text = node.text();
textInput.addEventListener(Event.CHANGE, handler);
this.addChild(pileHeightEditor);
}
```
My problem is that when the user edits one of the TextInputs, the node getting assigned to is always the last one encountered in the for loop. I am used to this pattern from C#, where each time an anonymous function is created, a "snapshot" of the values of the used values is taken, so "node" would be different in each handler function.
How do I "take a snapshot" of the current value of node to use in the handler? Or should I be using a different pattern in Flex? | Windows
-------
Some of the above values are easily available from the appropriate Win32 API, I just list them here for completeness. Others, however, need to be obtained from the Performance Data Helper library (PDH), which is a bit "unintuitive" and takes a lot of painful trial and error to get to work. (At least it took me quite a while, perhaps I've been only a bit stupid...)
Note: for clarity all error checking has been omitted from the following code. Do check the return codes...!
* Total Virtual Memory:
```
#include "windows.h"
MEMORYSTATUSEX memInfo;
memInfo.dwLength = sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&memInfo);
DWORDLONG totalVirtualMem = memInfo.ullTotalPageFile;
```
Note: The name "TotalPageFile" is a bit misleading here. In reality this parameter gives the "Virtual Memory Size", which is size of swap file plus installed RAM.
* Virtual Memory currently used:
Same code as in "Total Virtual Memory" and then
```
DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile;
```
* Virtual Memory currently used by current process:
```
#include "windows.h"
#include "psapi.h"
PROCESS_MEMORY_COUNTERS_EX pmc;
GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc));
SIZE_T virtualMemUsedByMe = pmc.PrivateUsage;
```
* Total Physical Memory (RAM):
Same code as in "Total Virtual Memory" and then
```
DWORDLONG totalPhysMem = memInfo.ullTotalPhys;
```
* Physical Memory currently used:
Same code as in "Total Virtual Memory" and then
```
DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys;
```
* Physical Memory currently used by current process:
Same code as in "Virtual Memory currently used by current process" and then
```
SIZE_T physMemUsedByMe = pmc.WorkingSetSize;
```
* CPU currently used:
```
#include "TCHAR.h"
#include "pdh.h"
static PDH_HQUERY cpuQuery;
static PDH_HCOUNTER cpuTotal;
void init(){
PdhOpenQuery(NULL, NULL, &cpuQuery);
// You can also use L"\\Processor(*)\\% Processor Time" and get individual CPU values with PdhGetFormattedCounterArray()
PdhAddEnglishCounter(cpuQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal);
PdhCollectQueryData(cpuQuery);
}
double getCurrentValue(){
PDH_FMT_COUNTERVALUE counterVal;
PdhCollectQueryData(cpuQuery);
PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);
return counterVal.doubleValue;
}
```
* CPU currently used by current process:
```
#include "windows.h"
static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU;
static int numProcessors;
static HANDLE self;
void init(){
SYSTEM_INFO sysInfo;
FILETIME ftime, fsys, fuser;
GetSystemInfo(&sysInfo);
numProcessors = sysInfo.dwNumberOfProcessors;
GetSystemTimeAsFileTime(&ftime);
memcpy(&lastCPU, &ftime, sizeof(FILETIME));
self = GetCurrentProcess();
GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
memcpy(&lastSysCPU, &fsys, sizeof(FILETIME));
memcpy(&lastUserCPU, &fuser, sizeof(FILETIME));
}
double getCurrentValue(){
FILETIME ftime, fsys, fuser;
ULARGE_INTEGER now, sys, user;
double percent;
GetSystemTimeAsFileTime(&ftime);
memcpy(&now, &ftime, sizeof(FILETIME));
GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
memcpy(&sys, &fsys, sizeof(FILETIME));
memcpy(&user, &fuser, sizeof(FILETIME));
percent = (sys.QuadPart - lastSysCPU.QuadPart) +
(user.QuadPart - lastUserCPU.QuadPart);
percent /= (now.QuadPart - lastCPU.QuadPart);
percent /= numProcessors;
lastCPU = now;
lastUserCPU = user;
lastSysCPU = sys;
return percent * 100;
}
```
---
Linux
-----
On Linux the choice that seemed obvious at first was to use the POSIX APIs like `getrusage()` etc. I spent some time trying to get this to work, but never got meaningful values. When I finally checked the kernel sources themselves, I found out that apparently these APIs are not yet completely implemented as of Linux kernel 2.6!?
In the end I got all values via a combination of reading the pseudo-filesystem `/proc` and kernel calls.
* Total Virtual Memory:
```
#include "sys/types.h"
#include "sys/sysinfo.h"
struct sysinfo memInfo;
sysinfo (&memInfo);
long long totalVirtualMem = memInfo.totalram;
//Add other values in next statement to avoid int overflow on right hand side...
totalVirtualMem += memInfo.totalswap;
totalVirtualMem *= memInfo.mem_unit;
```
* Virtual Memory currently used:
Same code as in "Total Virtual Memory" and then
```
long long virtualMemUsed = memInfo.totalram - memInfo.freeram;
//Add other values in next statement to avoid int overflow on right hand side...
virtualMemUsed += memInfo.totalswap - memInfo.freeswap;
virtualMemUsed *= memInfo.mem_unit;
```
* Virtual Memory currently used by current process:
```
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
int parseLine(char* line){
// This assumes that a digit will be found and the line ends in " Kb".
int i = strlen(line);
const char* p = line;
while (*p <'0' || *p > '9') p++;
line[i-3] = '\0';
i = atoi(p);
return i;
}
int getValue(){ //Note: this value is in KB!
FILE* file = fopen("/proc/self/status", "r");
int result = -1;
char line[128];
while (fgets(line, 128, file) != NULL){
if (strncmp(line, "VmSize:", 7) == 0){
result = parseLine(line);
break;
}
}
fclose(file);
return result;
}
```
* Total Physical Memory (RAM):
Same code as in "Total Virtual Memory" and then
```
long long totalPhysMem = memInfo.totalram;
//Multiply in next statement to avoid int overflow on right hand side...
totalPhysMem *= memInfo.mem_unit;
```
* Physical Memory currently used:
Same code as in "Total Virtual Memory" and then
```
long long physMemUsed = memInfo.totalram - memInfo.freeram;
//Multiply in next statement to avoid int overflow on right hand side...
physMemUsed *= memInfo.mem_unit;
```
* Physical Memory currently used by current process:
Change getValue() in "Virtual Memory currently used by current process" as follows:
```
int getValue(){ //Note: this value is in KB!
FILE* file = fopen("/proc/self/status", "r");
int result = -1;
char line[128];
while (fgets(line, 128, file) != NULL){
if (strncmp(line, "VmRSS:", 6) == 0){
result = parseLine(line);
break;
}
}
fclose(file);
return result;
}
```
* CPU currently used:
```
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
static unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle;
void init(){
FILE* file = fopen("/proc/stat", "r");
fscanf(file, "cpu %llu %llu %llu %llu", &lastTotalUser, &lastTotalUserLow,
&lastTotalSys, &lastTotalIdle);
fclose(file);
}
double getCurrentValue(){
double percent;
FILE* file;
unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total;
file = fopen("/proc/stat", "r");
fscanf(file, "cpu %llu %llu %llu %llu", &totalUser, &totalUserLow,
&totalSys, &totalIdle);
fclose(file);
if (totalUser < lastTotalUser || totalUserLow < lastTotalUserLow ||
totalSys < lastTotalSys || totalIdle < lastTotalIdle){
//Overflow detection. Just skip this value.
percent = -1.0;
}
else{
total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) +
(totalSys - lastTotalSys);
percent = total;
total += (totalIdle - lastTotalIdle);
percent /= total;
percent *= 100;
}
lastTotalUser = totalUser;
lastTotalUserLow = totalUserLow;
lastTotalSys = totalSys;
lastTotalIdle = totalIdle;
return percent;
}
```
* CPU currently used by current process:
```
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "sys/times.h"
#include "sys/vtimes.h"
static clock_t lastCPU, lastSysCPU, lastUserCPU;
static int numProcessors;
void init(){
FILE* file;
struct tms timeSample;
char line[128];
lastCPU = times(&timeSample);
lastSysCPU = timeSample.tms_stime;
lastUserCPU = timeSample.tms_utime;
file = fopen("/proc/cpuinfo", "r");
numProcessors = 0;
while(fgets(line, 128, file) != NULL){
if (strncmp(line, "processor", 9) == 0) numProcessors++;
}
fclose(file);
}
double getCurrentValue(){
struct tms timeSample;
clock_t now;
double percent;
now = times(&timeSample);
if (now <= lastCPU || timeSample.tms_stime < lastSysCPU ||
timeSample.tms_utime < lastUserCPU){
//Overflow detection. Just skip this value.
percent = -1.0;
}
else{
percent = (timeSample.tms_stime - lastSysCPU) +
(timeSample.tms_utime - lastUserCPU);
percent /= (now - lastCPU);
percent /= numProcessors;
percent *= 100;
}
lastCPU = now;
lastSysCPU = timeSample.tms_stime;
lastUserCPU = timeSample.tms_utime;
return percent;
}
```
---
TODO: Other Platforms
---------------------
I would assume, that some of the Linux code also works for the Unixes, except for the parts that read the /proc pseudo-filesystem. Perhaps on Unix these parts can be replaced by `getrusage()` and similar functions? |
63,206 | <p>If Java application requires certain JRE version then how can I check its availability on Mac OS X during installation?</p>
| [
{
"answer_id": 63227,
"author": "Stu Thompson",
"author_id": 2961,
"author_profile": "https://Stackoverflow.com/users/2961",
"pm_score": 2,
"selected": true,
"text": "<p>It should be as simple as looking at /System/Library/Frameworks/JavaVM.framework/Versions/</p>\n\n<p>E.g. from my mach... | 2008/09/15 | [
"https://Stackoverflow.com/questions/63206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7292/"
] | If Java application requires certain JRE version then how can I check its availability on Mac OS X during installation? | It should be as simple as looking at /System/Library/Frameworks/JavaVM.framework/Versions/
E.g. from my machine:
```
manoa:~ stu$ ll /System/Library/Frameworks/JavaVM.framework/Versions/
total 56
774077 lrwxr-xr-x 1 root wheel 5 Jul 23 15:31 1.3 -> 1.3.1
167151 drwxr-xr-x 3 root wheel 102 Jan 14 2008 1.3.1
167793 lrwxr-xr-x 1 root wheel 5 Feb 21 2008 1.4 -> 1.4.2
774079 lrwxr-xr-x 1 root wheel 3 Jul 23 15:31 1.4.1 -> 1.4
166913 drwxr-xr-x 8 root wheel 272 Feb 21 2008 1.4.2
168494 lrwxr-xr-x 1 root wheel 5 Feb 21 2008 1.5 -> 1.5.0
166930 drwxr-xr-x 8 root wheel 272 Feb 21 2008 1.5.0
774585 lrwxr-xr-x 1 root wheel 5 Jul 23 15:31 1.6 -> 1.6.0
747415 drwxr-xr-x 8 root wheel 272 Jul 23 10:24 1.6.0
167155 drwxr-xr-x 8 root wheel 272 Jul 23 15:31 A
776765 lrwxr-xr-x 1 root wheel 1 Jul 23 15:31 Current -> A
774125 lrwxr-xr-x 1 root wheel 3 Jul 23 15:31 CurrentJDK -> 1.5
manoa:~ stu$
``` |
63,291 | <p>How do I select all the columns in a table that only contain NULL values for all the rows? I'm using <strong>MS SQL Server 2005</strong>. I'm trying to find out which columns are not used in the table so I can delete them.</p>
| [
{
"answer_id": 63312,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<pre><code>SELECT cols\nFROM table\nWHERE cols IS NULL\n</code></pre>\n"
},
{
"answer_id": 63374,
"author": "Charle... | 2008/09/15 | [
"https://Stackoverflow.com/questions/63291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/299/"
] | How do I select all the columns in a table that only contain NULL values for all the rows? I'm using **MS SQL Server 2005**. I'm trying to find out which columns are not used in the table so I can delete them. | Here is the sql 2005 or later version: Replace ADDR\_Address with your tablename.
```
declare @col varchar(255), @cmd varchar(max)
DECLARE getinfo cursor for
SELECT c.name FROM sys.tables t JOIN sys.columns c ON t.Object_ID = c.Object_ID
WHERE t.Name = 'ADDR_Address'
OPEN getinfo
FETCH NEXT FROM getinfo into @col
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @cmd = 'IF NOT EXISTS (SELECT top 1 * FROM ADDR_Address WHERE [' + @col + '] IS NOT NULL) BEGIN print ''' + @col + ''' end'
EXEC(@cmd)
FETCH NEXT FROM getinfo into @col
END
CLOSE getinfo
DEALLOCATE getinfo
``` |
63,295 | <p>I have Sun webserver iws6 (iplanet 6) proxying my bea cluster.
My cluster is under /portal/yadda.
I want anyone who goes to </p>
<pre><code>http://the.domain.com/
</code></pre>
<p>to be quickly redirected to </p>
<pre><code>http://the.domain.com/portal/
</code></pre>
<p>I have and index.html that does a post and redirect, but the user sometimes sees it.
Does anyone have a better way?</p>
<p>Aaron</p>
<p>I have tried the 3 replies below. None of them worked for me. Back to the drawing board.
A</p>
| [
{
"answer_id": 63362,
"author": "wolak",
"author_id": 7717,
"author_profile": "https://Stackoverflow.com/users/7717",
"pm_score": 0,
"selected": false,
"text": "<p>Does this help?\n<a href=\"http://docs.sun.com/source/816-5691-10/essearch.htm#25618\" rel=\"nofollow noreferrer\">http://do... | 2008/09/15 | [
"https://Stackoverflow.com/questions/63295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7659/"
] | I have Sun webserver iws6 (iplanet 6) proxying my bea cluster.
My cluster is under /portal/yadda.
I want anyone who goes to
```
http://the.domain.com/
```
to be quickly redirected to
```
http://the.domain.com/portal/
```
I have and index.html that does a post and redirect, but the user sometimes sees it.
Does anyone have a better way?
Aaron
I have tried the 3 replies below. None of them worked for me. Back to the drawing board.
A | Does this help?
<http://docs.sun.com/source/816-5691-10/essearch.htm#25618>
---
To map a URL, perform the following steps:
Open the Class Manager and select the server instance from the drop-down list.
Choose the Content Mgmt tab.
Click the Additional Document Directories link.
The web server displays the Additional Document Directories page.
(Optional) Add another directory by entering one of the following.
URL prefix.
For example: plans.
Absolute physical path of the directory you want the URL mapped to.
For example:
C:/iPlanet/Servers/docs/marketing/plans
Click OK.
Click Apply.
Edit one of the current additional directories listed by selecting one of the following:
Edit
Remove
If editing, select edit next to the listed directory you wish to change.
Enter a new prefix using ASCII format.
(Optional) Select a style in the Apply Style drop-down list if you want to apply a style to the directory:
For more information about styles, see Applying Configuration Styles.
Click OK to add the new document directory.
Click Apply.
Choose Apply Changes to hard start /restart your server. |
63,303 | <p>I have a System.Diagnostics.Process object in a program targeted at the .Net framework 3.5</p>
<p>I have redirected both <code>StandardOutput</code> and <code>StandardError</code> pipes and I'm receiving data from them asynchronously. I've also set an event handler for the Exited event.</p>
<p>Once I call <code>Process.Start()</code> I want to go off and do other work whilst I wait for events to be raised.</p>
<p>Unfortunately it appears that, for a process which returns a large amount of information, the Exited event is fired before the last <code>OutputDataReceived</code> event.</p>
<p>How do I know when the last <code>OutputDataReceived</code> has been received? Ideally I would like the <code>Exited</code> event to be the last event I receive.</p>
<p>Here is an example program:</p>
<pre><code>using System;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string command = "output.exe";
string arguments = " whatever";
ProcessStartInfo info = new ProcessStartInfo(command, arguments);
// Redirect the standard output of the process.
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
// Set UseShellExecute to false for redirection
info.UseShellExecute = false;
Process proc = new Process();
proc.StartInfo = info;
proc.EnableRaisingEvents = true;
// Set our event handler to asynchronously read the sort output.
proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);
proc.ErrorDataReceived += new DataReceivedEventHandler(proc_ErrorDataReceived);
proc.Exited += new EventHandler(proc_Exited);
proc.Start();
// Start the asynchronous read of the sort output stream. Note this line!
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.WaitForExit();
Console.WriteLine("Exited (Main)");
}
static void proc_Exited(object sender, EventArgs e)
{
Console.WriteLine("Exited (Event)");
}
static void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Error: {0}", e.Data);
}
static void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Output data: {0}", e.Data);
}
}
}
</code></pre>
<p>When running this program you will notice that "Exited (Event)" appears in a completely variable location within the output. You may need to run it a few times and, obviously, you will need to replace "output.exe" with a program of your choice that produces a suitably large amount of output.</p>
<p>So, the question again: How do I know when the last <code>OutputDataReceived</code> has been received? Ideally I would like the <code>Exited</code> event to be the last event I receive.</p>
| [
{
"answer_id": 1423665,
"author": "csharptest.net",
"author_id": 164392,
"author_profile": "https://Stackoverflow.com/users/164392",
"pm_score": 5,
"selected": false,
"text": "<p>The answer to this is that <a href=\"https://msdn.microsoft.com/en-us/library/system.diagnostics.datareceived... | 2008/09/15 | [
"https://Stackoverflow.com/questions/63303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a System.Diagnostics.Process object in a program targeted at the .Net framework 3.5
I have redirected both `StandardOutput` and `StandardError` pipes and I'm receiving data from them asynchronously. I've also set an event handler for the Exited event.
Once I call `Process.Start()` I want to go off and do other work whilst I wait for events to be raised.
Unfortunately it appears that, for a process which returns a large amount of information, the Exited event is fired before the last `OutputDataReceived` event.
How do I know when the last `OutputDataReceived` has been received? Ideally I would like the `Exited` event to be the last event I receive.
Here is an example program:
```
using System;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string command = "output.exe";
string arguments = " whatever";
ProcessStartInfo info = new ProcessStartInfo(command, arguments);
// Redirect the standard output of the process.
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
// Set UseShellExecute to false for redirection
info.UseShellExecute = false;
Process proc = new Process();
proc.StartInfo = info;
proc.EnableRaisingEvents = true;
// Set our event handler to asynchronously read the sort output.
proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);
proc.ErrorDataReceived += new DataReceivedEventHandler(proc_ErrorDataReceived);
proc.Exited += new EventHandler(proc_Exited);
proc.Start();
// Start the asynchronous read of the sort output stream. Note this line!
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.WaitForExit();
Console.WriteLine("Exited (Main)");
}
static void proc_Exited(object sender, EventArgs e)
{
Console.WriteLine("Exited (Event)");
}
static void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Error: {0}", e.Data);
}
static void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Output data: {0}", e.Data);
}
}
}
```
When running this program you will notice that "Exited (Event)" appears in a completely variable location within the output. You may need to run it a few times and, obviously, you will need to replace "output.exe" with a program of your choice that produces a suitably large amount of output.
So, the question again: How do I know when the last `OutputDataReceived` has been received? Ideally I would like the `Exited` event to be the last event I receive. | The answer to this is that [`e.Data` will be set to `null`](https://msdn.microsoft.com/en-us/library/system.diagnostics.datareceivedeventhandler%28v=vs.110%29.aspx):
```
static void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
if( e.Data == null ) _exited.Set();
}
``` |
63,399 | <p>I need to do a dump of a table on a remote server, but I can't access the server directly. The only access I have is through PHP scripts.</p>
<p>Is there some way in which MySQL will return an </p>
<pre><code>INSERT INTO `table_name` (`field1`, `field2`) VALUES ('a', 'b'), ('c', 'd')
</code></pre>
<p>statement, like what <code>mysqldump</code> will return?</p>
<p>I don't have access to phpMyAdmin, and I preferably don't want to use <code>exec</code>, <code>system</code> or <code>passthru</code>.</p>
<p>See <a href="https://stackoverflow.com/questions/81934/easy-way-to-export-a-sql-table-without-access-to-the-server-or-phpmyadmin">this question</a> for another export method</p>
| [
{
"answer_id": 63405,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 4,
"selected": true,
"text": "<p>1) can you run mysqldump from exec or passthru<br />\n2) take a look at this: <a href=\"http://www.php-mysql-tutorial.com/p... | 2008/09/15 | [
"https://Stackoverflow.com/questions/63399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6681/"
] | I need to do a dump of a table on a remote server, but I can't access the server directly. The only access I have is through PHP scripts.
Is there some way in which MySQL will return an
```
INSERT INTO `table_name` (`field1`, `field2`) VALUES ('a', 'b'), ('c', 'd')
```
statement, like what `mysqldump` will return?
I don't have access to phpMyAdmin, and I preferably don't want to use `exec`, `system` or `passthru`.
See [this question](https://stackoverflow.com/questions/81934/easy-way-to-export-a-sql-table-without-access-to-the-server-or-phpmyadmin) for another export method | 1) can you run mysqldump from exec or passthru
2) take a look at this: <http://www.php-mysql-tutorial.com/perform-mysql-backup-php.php> |
63,447 | <p>How do I perform an <code>IF...THEN</code> in an <code>SQL SELECT</code> statement?</p>
<p>For example:</p>
<pre><code>SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product
</code></pre>
| [
{
"answer_id": 63474,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 6,
"selected": false,
"text": "<pre><code>SELECT \n(CASE \n WHEN (Obsolete = 'N' OR InStock = 'Y') THEN 'YES'\n ... | 2008/09/15 | [
"https://Stackoverflow.com/questions/63447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6522/"
] | How do I perform an `IF...THEN` in an `SQL SELECT` statement?
For example:
```
SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product
``` | The `CASE` statement is the closest to IF in SQL and is supported on all versions of SQL Server.
```
SELECT CAST(
CASE
WHEN Obsolete = 'N' or InStock = 'Y'
THEN 1
ELSE 0
END AS bit) as Saleable, *
FROM Product
```
You only need to use the `CAST` operator if you want the result as a Boolean value. If you are happy with an `int`, this works:
```
SELECT CASE
WHEN Obsolete = 'N' or InStock = 'Y'
THEN 1
ELSE 0
END as Saleable, *
FROM Product
```
`CASE` statements can be embedded in other `CASE` statements and even included in aggregates.
SQL Server Denali (SQL Server 2012) adds the [IIF](http://msdn.microsoft.com/en-us/library/hh213574%28v=sql.110%29.aspx) statement which is also available in [access](http://www.techonthenet.com/access/functions/advanced/iif.php) (pointed out by [Martin Smith](https://stackoverflow.com/questions/63447/how-do-you-perform-an-if-then-in-an-sql-select/6769805#6769805)):
```
SELECT IIF(Obsolete = 'N' or InStock = 'Y', 1, 0) as Saleable, * FROM Product
``` |
63,556 | <p>I have a class with a bunch of properties that look like this:</p>
<pre><code>public string Name
{
get { return _name; }
set { IsDirty = true; _name = value; }
}
</code></pre>
<p>It would be a lot easier if I could rely on C# 3.0 to generate the backing store for these, but is there any way to factor out the IsDirty=true; so that I can write my properties something like this and still get the same behaviour:</p>
<pre><code>[MakesDirty]
public string Name { get; set; }
</code></pre>
| [
{
"answer_id": 63564,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>You could try setting up a code snippet to make it easy to create those.</p>\n"
},
{
"answer_id": 63600,
... | 2008/09/15 | [
"https://Stackoverflow.com/questions/63556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1404/"
] | I have a class with a bunch of properties that look like this:
```
public string Name
{
get { return _name; }
set { IsDirty = true; _name = value; }
}
```
It would be a lot easier if I could rely on C# 3.0 to generate the backing store for these, but is there any way to factor out the IsDirty=true; so that I can write my properties something like this and still get the same behaviour:
```
[MakesDirty]
public string Name { get; set; }
``` | **No. Not without writing considerably more (arcane?) code than the original version** (You'd have to use reflection to check for the attribute on the property and what not.. did I mention it being 'slower').. This is the kind of duplication I can live with.
MS has the same need for [raising events when a property is changed](http://msdn.microsoft.com/en-us/library/ms229614.aspx). INotifyPropertyChanged that is a vital interface for change notifications. Every implementation I've seen yet
does
```
set
{
_name = value;
NotifyPropertyChanged("Name");
}
```
If it was possible, I'd figure those smart guys at MS would already have something like that in place.. |
63,581 | <p>I'm using <a href="http://www.c6software.com/Products/PopBox/" rel="nofollow noreferrer">PopBox</a> for magnifying thumbnails on my page.
But I want my website to work even for users which turned javascript off.</p>
<p>I tried to use the following HTML code:</p>
<pre><code><a href="image.jpg">
<img src="thumbnail.jpg" pbsrc="image.jpg" onclick="Pop(...);"/>
</a>
</code></pre>
<p>Now i need to disable the a-Tag using javascript, otherwise my PopBox won't work.</p>
<p>How do I do that?</p>
| [
{
"answer_id": 63612,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 2,
"selected": false,
"text": "<p>Put the onclick event onto the link itself, and return false from the handler if you don't want the default behavi... | 2008/09/15 | [
"https://Stackoverflow.com/questions/63581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4186/"
] | I'm using [PopBox](http://www.c6software.com/Products/PopBox/) for magnifying thumbnails on my page.
But I want my website to work even for users which turned javascript off.
I tried to use the following HTML code:
```
<a href="image.jpg">
<img src="thumbnail.jpg" pbsrc="image.jpg" onclick="Pop(...);"/>
</a>
```
Now i need to disable the a-Tag using javascript, otherwise my PopBox won't work.
How do I do that? | Just put the onclick on the a-tag:
```
<a href="image.jpg onclick="Pop()"; return false;"><img ...></a>
```
Make sure to return `false` either at the end of the function (here `Pop`) or inline like in the above example. This prevents the user from being redirected to the link by the `<a>`'s default behaviour. |
63,599 | <p>We have an issue using the <code>PEAR</code> libraries on <code>Windows</code> from <code>PHP</code>.</p>
<p>Pear contains many classes, we are making use of a fair few, one of which is the Mail class found in <code>Mail.php</code>. We use PEAR on the path, rather than providing the full explicit path to individual PEAR files:</p>
<pre><code>require_once('Mail.php');
</code></pre>
<p>Rather than:</p>
<pre><code>require_once('/path/to/pear/Mail.php');
</code></pre>
<p>This causes issues in the administration module of the site, where there is a <code>mail.php</code> file (used to send mails to users). If we are in an administrative screen that sends an email (such as the user administration screen that can generate and email new random passwords to users when they are approved from the moderation queue) and we attempt to include <code>Mail.php</code> we "accidentally" include mail.php.</p>
<p>Without changing to prepend the full path to the PEAR install explicitly requiring the PEAR modules (non-standard, typically you install PEAR to your path...) is there a way to enforce PHP on Windows to require files case-sensitively?</p>
<p>We are adding the PEAR path to the include path ourselves, so have control over the path order. We also recognize that we should avoid using filenames that clash with PEAR names regardless of case, and in the future will do so. This page however (which is not an include file, but a controller), has been in the repository for some years, and plugins specifically generate URLS to provide links/redirects to this page in their processing.</p>
<blockquote>
<p>(We support Apache, Microsoft IIS, LightHTTPD and Zeus, using PHP 4.3 or later (including PHP5))</p>
</blockquote>
| [
{
"answer_id": 63627,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 2,
"selected": false,
"text": "<p>As it's an OS level thing, I don't believe there's an easy way of doing this.</p>\n\n<p>You could try changing your... | 2008/09/15 | [
"https://Stackoverflow.com/questions/63599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7106/"
] | We have an issue using the `PEAR` libraries on `Windows` from `PHP`.
Pear contains many classes, we are making use of a fair few, one of which is the Mail class found in `Mail.php`. We use PEAR on the path, rather than providing the full explicit path to individual PEAR files:
```
require_once('Mail.php');
```
Rather than:
```
require_once('/path/to/pear/Mail.php');
```
This causes issues in the administration module of the site, where there is a `mail.php` file (used to send mails to users). If we are in an administrative screen that sends an email (such as the user administration screen that can generate and email new random passwords to users when they are approved from the moderation queue) and we attempt to include `Mail.php` we "accidentally" include mail.php.
Without changing to prepend the full path to the PEAR install explicitly requiring the PEAR modules (non-standard, typically you install PEAR to your path...) is there a way to enforce PHP on Windows to require files case-sensitively?
We are adding the PEAR path to the include path ourselves, so have control over the path order. We also recognize that we should avoid using filenames that clash with PEAR names regardless of case, and in the future will do so. This page however (which is not an include file, but a controller), has been in the repository for some years, and plugins specifically generate URLS to provide links/redirects to this page in their processing.
>
> (We support Apache, Microsoft IIS, LightHTTPD and Zeus, using PHP 4.3 or later (including PHP5))
>
>
> | having 2 files with the same name in the include path is not a good idea, rename your files so the files that you wrote have different names from third party libraries. anyway for your current situation I think by changing the order of paths in your include path, you can fix this.
PHP searches for the files in the include paths, one by one. when the required file is found in the include path, PHP will stop searching for the file. so in the administration section of your application, if you want to include the PEAR Mail file, instead of the mail.php that you wrote, change your include path so the PEAR path is before the current directory.
do something like this:
```
<?php
$path_to_pear = '/usr/share/php/pear';
set_include_path( $path_to_pear . PATH_SEPARATOR . get_include_path() );
?>
``` |