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 |
|---|---|---|---|---|---|---|
134,127 | <p>I've created a VB 2008 program to track work requests. It all works perfectly on a VISTA box, but I am having an issue with the program on an XP environment with adding new records.</p>
<p>Basically I've got 2 tabs: TAB 1 holds a datagridview with limited info and a calendar. Selecting dates on the calendar change the info in the datagridview. TAB 2 holds all the available info for that record in text/combo boxes. Both the datagridview and text boxes use the same Binding Source, so they are always in sync whenever the user selects a row from the datagridview. When you select the NEW button, TAB 2 appears with all the text boxes empty so the user can add data. If you look back on TAB 1, you see an empty, new row added to the datagridview (user can not directly add a row in the datagridview as AllowUserToAdd is set to false). If you let the app stay in the AddNew record state on VISTA, you remain on that new record until you select SAVE or CANCEL. On XP, however, after 1 minute time lapse, all the empty fields will eventually fill in with an existing record for that particular calendar day. When you look back on TAB 1, you no longer see the new empty row, you only see existing records previously saved.</p>
<p>Any ideas on how to resolve?? Thanks for any assistance.</p>
<p>Here is the code for adding new records:</p>
<pre><code>Private Sub cmdNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNew.Click
'Focus on Work tab
TabControl1.SelectedTab = tabWork
'Change the files from read-only
bEditMode = True
ChangeEditMode()
'Clear the current information stored in the fields
Try
Me.BindingContext(WorkRequestBindingSource).AddNew()
Catch ex As Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
'Hidden text boxes populate with current selected calendar
'Used to populate TimeIn and DateNeed because if never clicked on, will populate as NULL on save
dtpDateNeed.Text = txtDate.Text
dtpTimeIn.Text = txtTime.Text
End Sub
</code></pre>
| [
{
"answer_id": 146849,
"author": "alexmac",
"author_id": 23066,
"author_profile": "https://Stackoverflow.com/users/23066",
"pm_score": 0,
"selected": false,
"text": "<p>If the code is exactly the same I wonder if it is an environment issue e.g. something like different international opti... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I've created a VB 2008 program to track work requests. It all works perfectly on a VISTA box, but I am having an issue with the program on an XP environment with adding new records.
Basically I've got 2 tabs: TAB 1 holds a datagridview with limited info and a calendar. Selecting dates on the calendar change the info in the datagridview. TAB 2 holds all the available info for that record in text/combo boxes. Both the datagridview and text boxes use the same Binding Source, so they are always in sync whenever the user selects a row from the datagridview. When you select the NEW button, TAB 2 appears with all the text boxes empty so the user can add data. If you look back on TAB 1, you see an empty, new row added to the datagridview (user can not directly add a row in the datagridview as AllowUserToAdd is set to false). If you let the app stay in the AddNew record state on VISTA, you remain on that new record until you select SAVE or CANCEL. On XP, however, after 1 minute time lapse, all the empty fields will eventually fill in with an existing record for that particular calendar day. When you look back on TAB 1, you no longer see the new empty row, you only see existing records previously saved.
Any ideas on how to resolve?? Thanks for any assistance.
Here is the code for adding new records:
```
Private Sub cmdNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNew.Click
'Focus on Work tab
TabControl1.SelectedTab = tabWork
'Change the files from read-only
bEditMode = True
ChangeEditMode()
'Clear the current information stored in the fields
Try
Me.BindingContext(WorkRequestBindingSource).AddNew()
Catch ex As Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
'Hidden text boxes populate with current selected calendar
'Used to populate TimeIn and DateNeed because if never clicked on, will populate as NULL on save
dtpDateNeed.Text = txtDate.Text
dtpTimeIn.Text = txtTime.Text
End Sub
``` | This is definitely an environmental issue. To solve the problem I would need to know which browsers you are using on each machine and some of the settings on each.
It **sounds** like the XP machine is refreshing the page after a timeout period and therefore munging the new record. I have seen that happen before and it stinks.
You might need to consider saving some more state information in the viewstate to catch that kind of thing. |
134,131 | <p>I've recently installed the MVC CTP5 and VS is now crashing on me when I try to open an aspx, I get the following error in event viewer:</p>
<pre><code>.NET Runtime version 2.0.50727.3053 - Fatal Execution Engine Error (7A035E00) (80131506)
</code></pre>
<p>I was able to find <a href="http://forums.asp.net/t/1313452.aspx" rel="nofollow noreferrer">This</a> post on the asp.net forums relating to the same issue but nobody has had a working solution yet (at least not for me).</p>
<p>Just wondering if anyone else has run into this issue and what they have done to resolve it?</p>
<p>EDIT: Wanted to add that I have tried all the tips in the article and can open the markup with a code editor but was wondering an actual solution had been found to resolve this issue.. Thanks!</p>
<p>EDIT: I don't have this issue on my Vista box, seems to only occur on my XP VM.</p>
| [
{
"answer_id": 134143,
"author": "alex",
"author_id": 19268,
"author_profile": "https://Stackoverflow.com/users/19268",
"pm_score": 2,
"selected": false,
"text": "<p>Here are a steps to work around from <strong>the post</strong> that work for me:</p>\n\n<p>1.Open project based on CTP5</p... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12707/"
] | I've recently installed the MVC CTP5 and VS is now crashing on me when I try to open an aspx, I get the following error in event viewer:
```
.NET Runtime version 2.0.50727.3053 - Fatal Execution Engine Error (7A035E00) (80131506)
```
I was able to find [This](http://forums.asp.net/t/1313452.aspx) post on the asp.net forums relating to the same issue but nobody has had a working solution yet (at least not for me).
Just wondering if anyone else has run into this issue and what they have done to resolve it?
EDIT: Wanted to add that I have tried all the tips in the article and can open the markup with a code editor but was wondering an actual solution had been found to resolve this issue.. Thanks!
EDIT: I don't have this issue on my Vista box, seems to only occur on my XP VM. | I had a problem with Power Commands and Preview 5. If you have Power Commands installed, try updating or uninstalling it to fix the issue. |
134,161 | <p>I want to create a class which implements IEnumerable<T> but, using reflection, generates T's and returns them via IEnumerable<T>, where T' is a entirely constructed subclass of T with some properties hidden and others read-only. </p>
<p>Okay., that might not be very clear. Let me explain this via the medium of code - I'd like to have a class CollectionView<T> as follows:-</p>
<pre><code>public class CollectionView<T> : IEnumerable<T> {
public CollectionView(IEnumerable<T> inputCollection,
List<string> hiddenProperties, List<string> readonlyProperties) {
// ...
}
// IEnumerable<T> implementation which returns a collection of T' where T':T.
}
...
public class SomeObject {
public A { get; set; }
public B { get; set; }
public C { get; set; }
}
...
var hiddenProperties = new List<string>(new[] { "A" });
var readOnlyProperties = new List<string>(new[] { "C" });
IEnumerable<SomeObject> someObjects = CollectionView<SomeObject>(hiddenProperties,
readOnlyProperties);
...
dataGridView1.DataSource = someObjects;
</code></pre>
<p>(When displayed in dataGridView1 shows columns B and C and C has an underlying store which is read-only)</p>
<p>Is this possible/desirable or have I completely lost my mind/does this question demonstrate my deep inadequacy as a programmer?</p>
<p>I want to do this so I can manipulate a collection that is to be passed into a DataGridView, <em>without having to directly manipulate the DataGridView to hide columns/make columns read-only</em>. So no 'oh just use dataGridView1.Columns.Remove(blah) / dataGridView1.Columns[blah].ReadOnly = true' answers please!!</p>
<p>Help!</p>
| [
{
"answer_id": 134318,
"author": "Gilligan",
"author_id": 12356,
"author_profile": "https://Stackoverflow.com/users/12356",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.castleproject.org/dynamicproxy/index.html\" rel=\"nofollow noreferrer\">Castle.DynamicProxy</a> w... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] | I want to create a class which implements IEnumerable<T> but, using reflection, generates T's and returns them via IEnumerable<T>, where T' is a entirely constructed subclass of T with some properties hidden and others read-only.
Okay., that might not be very clear. Let me explain this via the medium of code - I'd like to have a class CollectionView<T> as follows:-
```
public class CollectionView<T> : IEnumerable<T> {
public CollectionView(IEnumerable<T> inputCollection,
List<string> hiddenProperties, List<string> readonlyProperties) {
// ...
}
// IEnumerable<T> implementation which returns a collection of T' where T':T.
}
...
public class SomeObject {
public A { get; set; }
public B { get; set; }
public C { get; set; }
}
...
var hiddenProperties = new List<string>(new[] { "A" });
var readOnlyProperties = new List<string>(new[] { "C" });
IEnumerable<SomeObject> someObjects = CollectionView<SomeObject>(hiddenProperties,
readOnlyProperties);
...
dataGridView1.DataSource = someObjects;
```
(When displayed in dataGridView1 shows columns B and C and C has an underlying store which is read-only)
Is this possible/desirable or have I completely lost my mind/does this question demonstrate my deep inadequacy as a programmer?
I want to do this so I can manipulate a collection that is to be passed into a DataGridView, *without having to directly manipulate the DataGridView to hide columns/make columns read-only*. So no 'oh just use dataGridView1.Columns.Remove(blah) / dataGridView1.Columns[blah].ReadOnly = true' answers please!!
Help! | [Castle.DynamicProxy](http://www.castleproject.org/dynamicproxy/index.html) will help you accomplish this.
What you would do is create an interceptor that inherits T. You would store the collection of hidden and read-only properties. When a getter or setter is called, the interceptor would check to see if the property exists in either collection and then take appropriate action.
However, I know not how you would hide a property. You cannot change the access modifier of a base class in a derived class. You MAY be able to use the `new` keyword, but I know not how to do that with Castle.DynamicProxy. |
134,182 | <p>Here's the code that I'm attempting to do:</p>
<pre><code>public IList<IOperator> GetAll()
{
using (var c = new MyDataContext())
{
return c.Operators.ToList();
}
}
</code></pre>
<p>Operator implements IOperator, but I'm getting the following compilation error:</p>
<pre><code>Cannot implicitly convert type 'System.Collections.Generic.List<MyProject.Core.Operator>' to 'System.Collections.Generic.IList<MyProject.Core.Model.IOperator>'. An explicit conversion exists (are you missing a cast?)
</code></pre>
<p>How do I cast this to get what I need?</p>
| [
{
"answer_id": 134268,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 3,
"selected": false,
"text": "<p>Try the <code>Cast<>()</code> method:</p>\n\n<pre><code>return c.Operators.Cast<IOperator>().ToList();\n</code>... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11097/"
] | Here's the code that I'm attempting to do:
```
public IList<IOperator> GetAll()
{
using (var c = new MyDataContext())
{
return c.Operators.ToList();
}
}
```
Operator implements IOperator, but I'm getting the following compilation error:
```
Cannot implicitly convert type 'System.Collections.Generic.List<MyProject.Core.Operator>' to 'System.Collections.Generic.IList<MyProject.Core.Model.IOperator>'. An explicit conversion exists (are you missing a cast?)
```
How do I cast this to get what I need? | Try the `Cast<>()` method:
```
return c.Operators.Cast<IOperator>().ToList();
``` |
134,214 | <p>Right now, I have code that looks something like this:</p>
<pre><code>Private Sub ShowReport(ByVal reportName As String)
Select Case reportName
Case "Security"
Me.ShowSecurityReport()
Case "Configuration"
Me.ShowConfigurationReport()
Case "RoleUsers"
Me.ShowRoleUsersReport()
Case Else
pnlMessage.Visible = True
litMessage.Text = "The report name """ + reportName + """ is invalid."
End Select
End Sub
</code></pre>
<p>Is there any way to create code that would use my method naming conventions to simplify things? Here's some pseudocode that describes what I'm looking for:</p>
<pre><code>Private Sub ShowReport(ByVal reportName As String)
Try
Call("Show" + reportName + "Report")
Catch ex As Exception
'method not found
End Try
End Sub
</code></pre>
| [
{
"answer_id": 134225,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 2,
"selected": false,
"text": "<p>You could use reflection to do this but to be honest I think it's overcomplicating things for your particular scenario i.e. cod... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/681/"
] | Right now, I have code that looks something like this:
```
Private Sub ShowReport(ByVal reportName As String)
Select Case reportName
Case "Security"
Me.ShowSecurityReport()
Case "Configuration"
Me.ShowConfigurationReport()
Case "RoleUsers"
Me.ShowRoleUsersReport()
Case Else
pnlMessage.Visible = True
litMessage.Text = "The report name """ + reportName + """ is invalid."
End Select
End Sub
```
Is there any way to create code that would use my method naming conventions to simplify things? Here's some pseudocode that describes what I'm looking for:
```
Private Sub ShowReport(ByVal reportName As String)
Try
Call("Show" + reportName + "Report")
Catch ex As Exception
'method not found
End Try
End Sub
``` | ```
Type type = GetType();
MethodInfo method = type.GetMethod("Show"+reportName+"Report");
if (method != null)
{
method.Invoke(this, null);
}
```
This is C#, should be easy enough to turn it into VB. If you need to pass parameter into the method, they can be added in the 2nd argument to Invoke. |
134,224 | <p>This code produces a FileNotFoundException, but ultimately runs without issue:</p>
<pre><code>void ReadXml()
{
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
//...
}
</code></pre>
<p>Here is the exception:</p>
<hr>
<p>A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll</p>
<p>Additional information: Could not load file or assembly 'MyAssembly.XmlSerializers, Version=1.4.3190.15950, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.</p>
<hr>
<p><strong>It appears that the framework automatically generates the serialization assembly if it isn't found.</strong> I can generate it manually using sgen.exe, which alleviates the exception. </p>
<p><strong>How do I get visual studio to generate the XML Serialization assembly automatically?</strong></p>
<hr>
<p><strong>Update: The Generate Serialization Assembly: On setting doesn't appear to do anything.</strong></p>
| [
{
"answer_id": 134273,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 1,
"selected": false,
"text": "<p>Look in the properties on the solution. On the build tab at the bottom there is a dropdown called \"Generate Serializatio... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4066/"
] | This code produces a FileNotFoundException, but ultimately runs without issue:
```
void ReadXml()
{
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
//...
}
```
Here is the exception:
---
A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
Additional information: Could not load file or assembly 'MyAssembly.XmlSerializers, Version=1.4.3190.15950, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
---
**It appears that the framework automatically generates the serialization assembly if it isn't found.** I can generate it manually using sgen.exe, which alleviates the exception.
**How do I get visual studio to generate the XML Serialization assembly automatically?**
---
**Update: The Generate Serialization Assembly: On setting doesn't appear to do anything.** | This is how I managed to do it by modifying the MSBUILD script in my .CSPROJ file:
First, open your .CSPROJ file as a file rather than as a project. Scroll to the bottom of the file until you find this commented out code, just before the close of the Project tag:
```
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
```
Now we just insert our own AfterBuild target to delete any existing XmlSerializer and SGen our own, like so:
```
<Target Name="AfterBuild" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)" Outputs="$(OutputPath)$(_SGenDllName)">
<!-- Delete the file because I can't figure out how to force the SGen task. -->
<Delete
Files="$(TargetDir)$(TargetName).XmlSerializers.dll"
ContinueOnError="true" />
<SGen
BuildAssemblyName="$(TargetFileName)"
BuildAssemblyPath="$(OutputPath)"
References="@(ReferencePath)"
ShouldGenerateSerializer="true"
UseProxyTypes="false"
KeyContainer="$(KeyContainerName)"
KeyFile="$(KeyOriginatorFile)"
DelaySign="$(DelaySign)"
ToolPath="$(TargetFrameworkSDKToolsDirectory)"
Platform="$(Platform)">
<Output
TaskParameter="SerializationAssembly"
ItemName="SerializationAssembly" />
</SGen>
</Target>
```
That works for me. |
134,251 | <p>I have a basic C# console application that reads a text file (CSV format) line by line and puts the data into a HashTable. The first CSV item in the line is the key (id num) and the rest of the line is the value. However I've discovered that my import file has a few duplicate keys that it shouldn't have. When I try to import the file the application errors out because you can't have duplicate keys in a HashTable. I want my program to be able to handle this error though. When I run into a duplicate key I would like to put that key into a arraylist and continue importing the rest of the data into the hashtable. How can I do this in C#</p>
<p>Here is my code:</p>
<hr>
<p>private static Hashtable importFile(Hashtable myHashtable, String myFileName)
{</p>
<pre><code> StreamReader sr = new StreamReader(myFileName);
CSVReader csvReader = new CSVReader();
ArrayList tempArray = new ArrayList();
int count = 0;
while (!sr.EndOfStream)
{
String temp = sr.ReadLine();
if (temp.StartsWith(" "))
{
ServMissing.Add(temp);
}
else
{
tempArray = csvReader.CSVParser(temp);
Boolean first = true;
String key = "";
String value = "";
foreach (String x in tempArray)
{
if (first)
{
key = x;
first = false;
}
else
{
value += x + ",";
}
}
myHashtable.Add(key, value);
}
count++;
}
Console.WriteLine("Import Count: " + count);
return myHashtable;
}
</code></pre>
| [
{
"answer_id": 134283,
"author": "Dror Helper",
"author_id": 11361,
"author_profile": "https://Stackoverflow.com/users/11361",
"pm_score": 2,
"selected": false,
"text": "<p>A better solution is to call ContainsKey to check if the key exist before adding it to the hash table instead. Thro... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8664/"
] | I have a basic C# console application that reads a text file (CSV format) line by line and puts the data into a HashTable. The first CSV item in the line is the key (id num) and the rest of the line is the value. However I've discovered that my import file has a few duplicate keys that it shouldn't have. When I try to import the file the application errors out because you can't have duplicate keys in a HashTable. I want my program to be able to handle this error though. When I run into a duplicate key I would like to put that key into a arraylist and continue importing the rest of the data into the hashtable. How can I do this in C#
Here is my code:
---
private static Hashtable importFile(Hashtable myHashtable, String myFileName)
{
```
StreamReader sr = new StreamReader(myFileName);
CSVReader csvReader = new CSVReader();
ArrayList tempArray = new ArrayList();
int count = 0;
while (!sr.EndOfStream)
{
String temp = sr.ReadLine();
if (temp.StartsWith(" "))
{
ServMissing.Add(temp);
}
else
{
tempArray = csvReader.CSVParser(temp);
Boolean first = true;
String key = "";
String value = "";
foreach (String x in tempArray)
{
if (first)
{
key = x;
first = false;
}
else
{
value += x + ",";
}
}
myHashtable.Add(key, value);
}
count++;
}
Console.WriteLine("Import Count: " + count);
return myHashtable;
}
``` | ```
if (myHashtable.ContainsKey(key))
duplicates.Add(key);
else
myHashtable.Add(key, value);
``` |
134,344 | <p>Is there a way to retrieve the time zone choices in Windows Mobile in order to display them in a GUI? It would be much better not to have to show every 15 minutes just to be
able to display GMT+5:45 for Kathmandu.</p>
| [
{
"answer_id": 135540,
"author": "ctacke",
"author_id": 13154,
"author_profile": "https://Stackoverflow.com/users/13154",
"pm_score": 0,
"selected": false,
"text": "<p>Windows Mobile stores timezone info in a <a href=\"http://msdn.microsoft.com/en-us/library/aa458853.aspx\" rel=\"nofollo... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Is there a way to retrieve the time zone choices in Windows Mobile in order to display them in a GUI? It would be much better not to have to show every 15 minutes just to be
able to display GMT+5:45 for Kathmandu. | As per [MSDN:City List and Time Zone Data Files](http://msdn.microsoft.com/en-us/library/aa458853.aspx),
>
> You can add or remove content to these
> files. You can redistribute these
> files as is or repackage this data by
> including it in source code, a
> database, or another format. You are
> permitted to use excerpts of this data
> rather than the entire data set.
>
>
>
```
Note Microsoft bears no responsibility for the content or
usage of these files. Certain locales have specific legal requirements with
regard to providing data of this type; ensure you are in compliance with such
regulations.
```
>
> If you use the city data
> provided or if you use any type of
> geographical information from any
> source, you are encouraged to provide
> a way for users to edit, add, and
> delete information.
>
>
> |
134,374 | <p>I would like to listen to method calls.</p>
<p>For example, when an element is appended by anything to the document, I would like to be passed that element to act on it, like:</p>
<p>//somewhere</p>
<pre><code>aParent.appendChild(aChild);
</code></pre>
<p>//when the former, a function I defined as listener is called with the <code>aChild</code> as argument</p>
<p>Does anybody know how to do that?</p>
| [
{
"answer_id": 134420,
"author": "Filini",
"author_id": 21162,
"author_profile": "https://Stackoverflow.com/users/21162",
"pm_score": 1,
"selected": false,
"text": "<p>don't know if that's possible with the core functions, but you could always create your own functions, for the actions y... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I would like to listen to method calls.
For example, when an element is appended by anything to the document, I would like to be passed that element to act on it, like:
//somewhere
```
aParent.appendChild(aChild);
```
//when the former, a function I defined as listener is called with the `aChild` as argument
Does anybody know how to do that? | don't know if that's possible with the core functions, but you could always create your own functions, for the actions you want to monitor:
```
function AppendChild(oParent, oChild) {
// your stuff on oParent
// append oChild
oParent.appendChild(oChild)
}
```
or, maybe, modify the actual appendChild(), but that would be tricky... |
134,379 | <p>Is it possible to do a <code>SELECT</code> statement with a predetermined order, ie. selecting IDs 7,2,5,9 and 8 <strong>and returning them in that order</strong>, based on nothing more than the ID field?</p>
<p>Both these statements return them in the same order: </p>
<pre><code>SELECT id FROM table WHERE id in (7,2,5,9,8)
</code></pre>
<pre><code>SELECT id FROM table WHERE id in (8,2,5,9,7)
</code></pre>
| [
{
"answer_id": 134391,
"author": "Teifion",
"author_id": 1384652,
"author_profile": "https://Stackoverflow.com/users/1384652",
"pm_score": 0,
"selected": false,
"text": "<p>All ordering is done by the ORDER BY keywords, you can only however sort ascending and descending. If you are using... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21716/"
] | Is it possible to do a `SELECT` statement with a predetermined order, ie. selecting IDs 7,2,5,9 and 8 **and returning them in that order**, based on nothing more than the ID field?
Both these statements return them in the same order:
```
SELECT id FROM table WHERE id in (7,2,5,9,8)
```
```
SELECT id FROM table WHERE id in (8,2,5,9,7)
``` | I didn't think this was possible, but found a [blog entry here](http://www.handgestrickt.biz/item/21/) that seems to do the type of thing you're after:
```
SELECT id FROM table WHERE id in (7,2,5,9,8)
ORDER BY FIND_IN_SET(id,"7,2,5,9,8");
```
will give different results to
```
SELECT id FROM table WHERE id in (7,2,5,9,8)
ORDER BY FIND_IN_SET(id,"8,2,5,9,7");
```
`[FIND\_IN\_SET](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set)` returns the position of `id` in the second argument given to it, so for the first case above, `id` of 7 is at position 1 in the set, 2 at 2 and so on - mysql internally works out something like
```
id | FIND_IN_SET
---|-----------
7 | 1
2 | 2
5 | 3
```
then orders by the results of `FIND_IN_SET`. |
134,387 | <p>I have a Pylons app where I would like to move some of the logic to a separate batch process. I've been running it under the main app for testing, but it is going to be doing a lot of work in the database, and I'd like it to be a separate process that will be running in the background constantly. The main pylons app will submit jobs into the database, and the new process will do the work requested in each job.</p>
<p>How can I launch a controller as a stand alone script?</p>
<p>I currently have:</p>
<pre><code>from warehouse2.controllers import importServer
importServer.runServer(60)
</code></pre>
<p>and in the controller file, but not part of the controller class:</p>
<pre><code>def runServer(sleep_secs):
try:
imp = ImportserverController()
while(True):
imp.runImport()
sleepFor(sleep_secs)
except Exception, e:
log.info("Unexpected error: %s" % sys.exc_info()[0])
log.info(e)
</code></pre>
<p>But starting ImportServer.py on the command line results in:</p>
<pre><code>2008-09-25 12:31:12.687000 Could not locate a bind configured on mapper Mapper|I
mportJob|n_imports, SQL expression or this Session
</code></pre>
| [
{
"answer_id": 135290,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 2,
"selected": true,
"text": "<p>I'm redacting my response and upvoting the other answer by Ben Bangert, as it's the correct one. I answered and hav... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1566663/"
] | I have a Pylons app where I would like to move some of the logic to a separate batch process. I've been running it under the main app for testing, but it is going to be doing a lot of work in the database, and I'd like it to be a separate process that will be running in the background constantly. The main pylons app will submit jobs into the database, and the new process will do the work requested in each job.
How can I launch a controller as a stand alone script?
I currently have:
```
from warehouse2.controllers import importServer
importServer.runServer(60)
```
and in the controller file, but not part of the controller class:
```
def runServer(sleep_secs):
try:
imp = ImportserverController()
while(True):
imp.runImport()
sleepFor(sleep_secs)
except Exception, e:
log.info("Unexpected error: %s" % sys.exc_info()[0])
log.info(e)
```
But starting ImportServer.py on the command line results in:
```
2008-09-25 12:31:12.687000 Could not locate a bind configured on mapper Mapper|I
mportJob|n_imports, SQL expression or this Session
``` | I'm redacting my response and upvoting the other answer by Ben Bangert, as it's the correct one. I answered and have since learned the correct way (mentioned below). If you really want to, check out the history of this answer to see the wrong (but working) solution I originally proposed. |
134,392 | <p>I have a form in which people will be entering dollar values.</p>
<p>Possible inputs:<br>
$999,999,999.99<br>
999,999,999.99<br>
999999999<br>
99,999<br>
$99,999<br></p>
<p>The user can enter a dollar value however they wish. I want to read the inputs as doubles so I can total them.</p>
<p>I tried just typecasting the strings to doubles but that didn't work. Total just equals 50 when it is output:</p>
<pre><code>$string1 = "$50,000";
$string2 = "$50000";
$string3 = "50,000";
$total = (double)$string1 + (double)$string2 + (double)$string3;
echo $total;
</code></pre>
| [
{
"answer_id": 134402,
"author": "tim_yates",
"author_id": 6509,
"author_profile": "https://Stackoverflow.com/users/6509",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://p2p.wrox.com/topic.asp?TOPIC_ID=3099\" rel=\"nofollow noreferrer\">http://p2p.wrox.com/topic.asp?TOPIC... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16292/"
] | I have a form in which people will be entering dollar values.
Possible inputs:
$999,999,999.99
999,999,999.99
999999999
99,999
$99,999
The user can enter a dollar value however they wish. I want to read the inputs as doubles so I can total them.
I tried just typecasting the strings to doubles but that didn't work. Total just equals 50 when it is output:
```
$string1 = "$50,000";
$string2 = "$50000";
$string3 = "50,000";
$total = (double)$string1 + (double)$string2 + (double)$string3;
echo $total;
``` | A regex won't convert your string into a number. I would suggest that you use a regex to validate the field (confirm that it fits one of your allowed formats), and then just loop over the string, discarding all non-digit and non-period characters. If you don't care about validation, you could skip the first step. The second step will still strip it down to digits and periods only.
By the way, you cannot safely use floats when calculating currency values. You will lose precision, and very possibly end up with totals that do not exactly match the inputs.
Update: Here are two functions you could use to verify your input and to convert it into a decimal-point representation.
```
function validateCurrency($string)
{
return preg_match('/^\$?(\d{1,3})(,\d{3})*(.\d{2})?$/', $string) ||
preg_match('/^\$?\d+(.\d{2})?$/', $string);
}
function makeCurrency($string)
{
$newstring = "";
$array = str_split($string);
foreach($array as $char)
{
if (($char >= '0' && $char <= '9') || $char == '.')
{
$newstring .= $char;
}
}
return $newstring;
}
```
The first function will match the bulk of currency formats you can expect "$99", "99,999.00", etc. It will not match ".00" or "99.", nor will it match most European-style numbers (99.999,00). Use this on your original string to verify that it is a valid currency string.
The second function will just strip out everything except digits and decimal points. Note that by itself it may still return invalid strings (e.g. "", "....", and "abc" come out as "", "....", and ""). Use this to eliminate extraneous commas once the string is validated, or possibly use this by itself if you want to skip validation. |
134,453 | <p>Are there any tools available to log the page load time for a php site?</p>
<p>Mainly looking for something that I can see trends of load times over time, I was considering dumping them into a file using error_log(), but I don't know what I could use to parse it and display graphs</p>
| [
{
"answer_id": 134491,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 2,
"selected": false,
"text": "<p>Use the Firebug extension for Firefox, it has a Net panel that shows you load times. </p>\n\n<p>If you want t... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Are there any tools available to log the page load time for a php site?
Mainly looking for something that I can see trends of load times over time, I was considering dumping them into a file using error\_log(), but I don't know what I could use to parse it and display graphs | You can record the microtime at the start of execution, hold that variable until the end, check the time, subtract them, and there you have your execution time. Output buffering will be required to make this work in most cases, unless it's a situation in which a particular thing always runs last (like `footer()`).
```
$time_start = microtime_float();
function microtime_float() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
//at the start.
//at the end:
$time_end = microtime_float();
$time = round($time_end - $time_start, 4);
echo "Last uncached content render took $time seconds";
``` |
134,456 | <p>This</p>
<pre><code>SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE '%some_value%';
</code></pre>
<p>is slower than this</p>
<pre><code>SELECT * FROM SOME_TABLE WHERE SOME_FIELD = 'some_value';
</code></pre>
<p>but what about this?</p>
<pre><code>SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE 'some_value';
</code></pre>
<p>My testing indicates the second and third examples are exactly the same. If that's true, my question is, why ever use "=" ?</p>
| [
{
"answer_id": 134472,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 3,
"selected": false,
"text": "<p>Check out the <a href=\"http://www.adp-gmbh.ch/ora/explainplan.html\" rel=\"nofollow noreferrer\">EXPLAIN PLAN</a> for both... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] | This
```
SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE '%some_value%';
```
is slower than this
```
SELECT * FROM SOME_TABLE WHERE SOME_FIELD = 'some_value';
```
but what about this?
```
SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE 'some_value';
```
My testing indicates the second and third examples are exactly the same. If that's true, my question is, why ever use "=" ? | There is a clear difference when you use bind variables, which you should be using in Oracle for anything other than data warehousing or other bulk data operations.
Take the case of:
```
SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE :b1
```
Oracle cannot know that the value of :b1 is '%some\_value%', or 'some\_value' etc. until execution time, so it will make an estimation of the cardinality of the result based on heuristics and come up with an appropriate plan that either may or may not be suitable for various values of :b, such as '%A','%', 'A' etc.
Similar issues can apply with an equality predicate but the range of cardinalities that might result is much more easily estimated based on column statistics or the presence of a unique constraint, for example.
So, personally I wouldn't start using LIKE as a replacement for =. The optimizer is pretty easy to fool sometimes. |
134,463 | <p>I am using a popup menu in Delphi. I want to use it in a "radio group" fashion where if the user selects an item it is checked and the other items are not checked. I tried using the AutoCheck property, but this allows multiple items to be checked. Is there a way to set the popup menu so that only one item can be checked?</p>
| [
{
"answer_id": 134583,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 4,
"selected": true,
"text": "<p>Zartog is right, but if you want to keep the checkbox, assign this event to every item in the popup menu.</p>\n\n<p>Not... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12833/"
] | I am using a popup menu in Delphi. I want to use it in a "radio group" fashion where if the user selects an item it is checked and the other items are not checked. I tried using the AutoCheck property, but this allows multiple items to be checked. Is there a way to set the popup menu so that only one item can be checked? | Zartog is right, but if you want to keep the checkbox, assign this event to every item in the popup menu.
Note that this code is a little hairy looking because it does not depend on knowing the name of your popup menu (hence, looking it up with "GetParentComponent").
```
procedure TForm2.OnPopupItemClick(Sender: TObject);
var
i : integer;
begin
with (Sender as TMenuItem) do begin
//if they just checked something...
if Checked then begin
//go through the list and *un* check everything *else*
for i := 0 to (GetParentComponent as TPopupMenu).Items.Count - 1 do begin
if i <> MenuIndex then begin //don't uncheck the one they just clicked!
(GetParentComponent as TPopupMenu).Items[i].Checked := False;
end; //if not the one they just clicked
end; //for each item in the popup
end; //if we checked something
end; //with
end;
```
You can assign the event at runtime to every popup box on your form like this (if you want to do that):
```
procedure TForm2.FormCreate(Sender: TObject);
var
i,j: integer;
begin
inherited;
//look for any popup menus, and assign our custom checkbox handler to them
if Sender is TForm then begin
with (Sender as TForm) do begin
for i := 0 to ComponentCount - 1 do begin
if (Components[i] is TPopupMenu) then begin
for j := 0 to (Components[i] as TPopupMenu).Items.Count - 1 do begin
(Components[i] as TPopupMenu).Items[j].OnClick := OnPopupItemClick;
end; //for every item in the popup list we found
end; //if we found a popup list
end; //for every component on the form
end; //with the form
end; //if we are looking at a form
end;
```
In response to a comment below this answer: If you want to require at least one item to be checked, then use this instead of the first code block. You may want to set a default checked item in the oncreate event.
```
procedure TForm2.OnPopupItemClick(Sender: TObject);
var
i : integer;
begin
with (Sender as TMenuItem) do begin
//go through the list and make sure *only* the clicked item is checked
for i := 0 to (GetParentComponent as TPopupMenu).Items.Count - 1 do begin
(GetParentComponent as TPopupMenu).Items[i].Checked := (i = MenuIndex);
end; //for each item in the popup
end; //with
end;
``` |
134,470 | <p>I have two controllers which share most of their code (but must be, nonetheless, different controllers). The obvious solution (to me, at least) is to create a class, and make the two controllers inherit from it. The thing is... where to put it? Now I have it in app_controller.php, but it's kind of messy there.</p>
| [
{
"answer_id": 134504,
"author": "tyshock",
"author_id": 16448,
"author_profile": "https://Stackoverflow.com/users/16448",
"pm_score": 4,
"selected": true,
"text": "<p>In cake, components are used to store logic that can be used by multiple controllers. The directory is /app/controllers... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18396/"
] | I have two controllers which share most of their code (but must be, nonetheless, different controllers). The obvious solution (to me, at least) is to create a class, and make the two controllers inherit from it. The thing is... where to put it? Now I have it in app\_controller.php, but it's kind of messy there. | In cake, components are used to store logic that can be used by multiple controllers. The directory is /app/controllers/components. For instance, if you had some sharable utility logic, you would have an object called UtilComponent and a file in /app/controlers/components called UtilComponent.php.
```
<?php
class UtilComponent extends Object {
function yourMethod($param) {
// logic here.......
return $param;
}
}
?>
```
Then, in your controller classes, you would add:
```
var $components = array('Util');
```
Then you call the methods like:
```
$this->Util->yourMethod($yourparam);
```
More Info:
[Documentation](http://book.cakephp.org/view/315/Components) |
134,481 | <p>What I have now (which successfully loads the plug-in) is this:</p>
<pre><code>Assembly myDLL = Assembly.LoadFrom("my.dll");
IMyClass myPluginObject = myDLL.CreateInstance("MyCorp.IMyClass") as IMyClass;
</code></pre>
<p>This only works for a class that has a constructor with no arguments. How do I pass in an argument to a constructor?</p>
| [
{
"answer_id": 134484,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "<p>You can with <a href=\"http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx\" rel=\"nofollow noreferrer\">Activator.Crea... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22252/"
] | What I have now (which successfully loads the plug-in) is this:
```
Assembly myDLL = Assembly.LoadFrom("my.dll");
IMyClass myPluginObject = myDLL.CreateInstance("MyCorp.IMyClass") as IMyClass;
```
This only works for a class that has a constructor with no arguments. How do I pass in an argument to a constructor? | You cannot. Instead use [Activator.CreateInstance](http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx) as shown in the example below (note that the Client namespace is in one DLL and the Host in another. Both must be found in the same directory for code to work.)
However, if you want to create a truly pluggable interface, I suggest you use an Initialize method that take the given parameters in your interface, instead of relying on constructors. That way you can just demand that the plugin class implement your interface, instead of "hoping" that it accepts the accepted parameters in the constructor.
```
using System;
using Host;
namespace Client
{
public class MyClass : IMyInterface
{
public int _id;
public string _name;
public MyClass(int id,
string name)
{
_id = id;
_name = name;
}
public string GetOutput()
{
return String.Format("{0} - {1}", _id, _name);
}
}
}
namespace Host
{
public interface IMyInterface
{
string GetOutput();
}
}
using System;
using System.Reflection;
namespace Host
{
internal class Program
{
private static void Main()
{
//These two would be read in some configuration
const string dllName = "Client.dll";
const string className = "Client.MyClass";
try
{
Assembly pluginAssembly = Assembly.LoadFrom(dllName);
Type classType = pluginAssembly.GetType(className);
var plugin = (IMyInterface) Activator.CreateInstance(classType,
42, "Adams");
if (plugin == null)
throw new ApplicationException("Plugin not correctly configured");
Console.WriteLine(plugin.GetOutput());
}
catch (Exception e)
{
Console.Error.WriteLine(e.ToString());
}
}
}
}
``` |
134,492 | <p>I am able to serialize an object into a file and then restore it again as is shown in the next code snippet. I would like to serialize the object into a string and store into a database instead. Can anyone help me?</p>
<pre><code>LinkedList<Diff_match_patch.Patch> patches = // whatever...
FileOutputStream fileStream = new FileOutputStream("foo.ser");
ObjectOutputStream os = new ObjectOutputStream(fileStream);
os.writeObject(patches1);
os.close();
FileInputStream fileInputStream = new FileInputStream("foo.ser");
ObjectInputStream oInputStream = new ObjectInputStream(fileInputStream);
Object one = oInputStream.readObject();
LinkedList<Diff_match_patch.Patch> patches3 = (LinkedList<Diff_match_patch.Patch>) one;
os.close();
</code></pre>
| [
{
"answer_id": 134525,
"author": "Tim Frey",
"author_id": 1471,
"author_profile": "https://Stackoverflow.com/users/1471",
"pm_score": 4,
"selected": false,
"text": "<p>How about writing the data to a ByteArrayOutputStream instead of a FileOutputStream?</p>\n\n<p>Otherwise, you could seri... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] | I am able to serialize an object into a file and then restore it again as is shown in the next code snippet. I would like to serialize the object into a string and store into a database instead. Can anyone help me?
```
LinkedList<Diff_match_patch.Patch> patches = // whatever...
FileOutputStream fileStream = new FileOutputStream("foo.ser");
ObjectOutputStream os = new ObjectOutputStream(fileStream);
os.writeObject(patches1);
os.close();
FileInputStream fileInputStream = new FileInputStream("foo.ser");
ObjectInputStream oInputStream = new ObjectInputStream(fileInputStream);
Object one = oInputStream.readObject();
LinkedList<Diff_match_patch.Patch> patches3 = (LinkedList<Diff_match_patch.Patch>) one;
os.close();
``` | Sergio:
You should use [BLOB](http://docs.oracle.com/javase/6/docs/api/java/sql/Blob.html). It is pretty straighforward with JDBC.
The problem with the second code you posted is the encoding. You should additionally encode the bytes to make sure none of them fails.
If you still want to write it down into a String you can encode the bytes using [java.util.Base64](https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html).
Still you should use CLOB as data type because you don't know how long the serialized data is going to be.
Here is a sample of how to use it.
```
import java.util.*;
import java.io.*;
/**
* Usage sample serializing SomeClass instance
*/
public class ToStringSample {
public static void main( String [] args ) throws IOException,
ClassNotFoundException {
String string = toString( new SomeClass() );
System.out.println(" Encoded serialized version " );
System.out.println( string );
SomeClass some = ( SomeClass ) fromString( string );
System.out.println( "\n\nReconstituted object");
System.out.println( some );
}
/** Read the object from Base64 string. */
private static Object fromString( String s ) throws IOException ,
ClassNotFoundException {
byte [] data = Base64.getDecoder().decode( s );
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream( data ) );
Object o = ois.readObject();
ois.close();
return o;
}
/** Write the object to a Base64 string. */
private static String toString( Serializable o ) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream( baos );
oos.writeObject( o );
oos.close();
return Base64.getEncoder().encodeToString(baos.toByteArray());
}
}
/** Test subject. A very simple class. */
class SomeClass implements Serializable {
private final static long serialVersionUID = 1; // See Nick's comment below
int i = Integer.MAX_VALUE;
String s = "ABCDEFGHIJKLMNOP";
Double d = new Double( -1.0 );
public String toString(){
return "SomeClass instance says: Don't worry, "
+ "I'm healthy. Look, my data is i = " + i
+ ", s = " + s + ", d = " + d;
}
}
```
Output:
```
C:\samples>javac *.java
C:\samples>java ToStringSample
Encoded serialized version
rO0ABXNyAAlTb21lQ2xhc3MAAAAAAAAAAQIAA0kAAWlMAAFkdAASTGphdmEvbGFuZy9Eb3VibGU7T
AABc3QAEkxqYXZhL2xhbmcvU3RyaW5nO3hwf////3NyABBqYXZhLmxhbmcuRG91YmxlgLPCSilr+w
QCAAFEAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQuU4IsCAAB4cL/wAAAAAAAAdAAQQUJ
DREVGR0hJSktMTU5PUA==
Reconstituted object
SomeClass instance says: Don't worry, I'm healthy. Look, my data is i = 2147483647, s = ABCDEFGHIJKLMNOP, d = -1.0
```
**NOTE**: for Java 7 and earlier you can see the original [answer here](https://stackoverflow.com/revisions/134918/9) |
134,501 | <p>Usually when I need to fork in C, I do something like this:</p>
<pre><code>pid_t p = fork();
if(p == 0) { /* do child stuff */ }
else { /* do parent stuff and pray there wasn't an error */ }
</code></pre>
<p>It occured to me that I could ditch the extra variable and use:</p>
<pre><code>if(fork() == 0) { /* child */ }
else { /* parent/pray */ }
</code></pre>
<p>Improper error handling aside, (why) does this work/not work?</p>
| [
{
"answer_id": 134528,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 2,
"selected": false,
"text": "<p>You lose the child process ID in the parent, which is what is returned to the parent. I think you could recover that informat... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12926/"
] | Usually when I need to fork in C, I do something like this:
```
pid_t p = fork();
if(p == 0) { /* do child stuff */ }
else { /* do parent stuff and pray there wasn't an error */ }
```
It occured to me that I could ditch the extra variable and use:
```
if(fork() == 0) { /* child */ }
else { /* parent/pray */ }
```
Improper error handling aside, (why) does this work/not work? | What you are suggesting will certainly work. However, error handling is not optional in any well-behaved application. The following implementation pattern is similarly succinct and also handles errors. Furthermore, it saves the fork() return value in the pid variable, in case you want to use it later in the parent to, say, wait for the child.
```
switch (pid = fork()) {
case -1: /* Failure */
/* ... */
case 0: /* Child */
/* ... */
default: /* Parent */
/* ... */
}
``` |
134,505 | <p>I've found mention of a data application block existing for ODBC, but can't seem to find it anywhere. If i didn't have a copy of the Access DB application block I wouldn't believe it ever existed either.</p>
<p>Anyone know where to download either the DLL or the code-base from?</p>
<p>--UPDATE: It is NOT included in either the v1, v2, or Enterprise Library versions of the Data ApplicationBlocks</p>
<p>Thanks,
Brian Swanson</p>
| [
{
"answer_id": 134521,
"author": "ScaleOvenStove",
"author_id": 12268,
"author_profile": "https://Stackoverflow.com/users/12268",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=F63D1F0A-9877-4A7B-88EC-0426B48DF275&disp... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1795/"
] | I've found mention of a data application block existing for ODBC, but can't seem to find it anywhere. If i didn't have a copy of the Access DB application block I wouldn't believe it ever existed either.
Anyone know where to download either the DLL or the code-base from?
--UPDATE: It is NOT included in either the v1, v2, or Enterprise Library versions of the Data ApplicationBlocks
Thanks,
Brian Swanson | Which version of .net are you interested in using the ODBC block on?
The Enterprise library has a Data Access component. It is useful on SQL, Oracle, and ODBC. Just set a different provider name in the .config file
EX:
<add name="MyConnection" connectionString="Dsn=Datasource;uid=UserID;pwd=Password"
providerName=**"System.Data.Odbc"** />
At that point, the data access code is "standardized" and looks identical for SQL, Oracle, and ODBC
EX:
```
Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling
Public Class MyClass
Private dbMyDatabase As Database
dbMyDatabase = DatabaseFactory.CreateDatabase("MyConnection")
Public Function GetMyData(ByVal FacilityCode As String) As Data.DataSet
Try
Dim SQL As String
SQL = "SELECT * from MyDataTable"
Dim cmd As Data.Common.DbCommand = dbMyDatabase.GetSqlStringCommand(SQL)
Return dbMyDatabase.ExecuteDataSet(cmd)
Catch ex As Exception
ExceptionPolicy.HandleException(ex, "All")
Throw
End Try
End Function
End Class
```
The address for the latest Enterprise Library is:
<http://msdn.microsoft.com/en-us/library/cc467894.aspx>
This is assuming you are using .net 3x.
Also note that we are using the Exception Handling block in the above code. |
134,520 | <p>Okay, this is just a crazy idea I have. Stack Overflow looks very structured and integrable into development applications. So would it be possible, even useful, to have a Stack Overflow plugin for, say, Eclipse? </p>
<p>Which features of Stack Overflow would you like to have directly integrated into your IDE so you can use it "natively" without changing to a browser?</p>
<p>EDIT: I'm thinking about ways of deeper integration than just using the web page inside the IDE. Like when you use a certain Java class and have a problem, answers from SO might flare up. There would probably be cases where something like this is annoying, but others may be very helpful.</p>
| [
{
"answer_id": 134534,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 0,
"selected": false,
"text": "<p>You could just set it as your Start Page in Visual Studio.</p>\n\n<p>Not sure what benefit this would provide... but to e... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19734/"
] | Okay, this is just a crazy idea I have. Stack Overflow looks very structured and integrable into development applications. So would it be possible, even useful, to have a Stack Overflow plugin for, say, Eclipse?
Which features of Stack Overflow would you like to have directly integrated into your IDE so you can use it "natively" without changing to a browser?
EDIT: I'm thinking about ways of deeper integration than just using the web page inside the IDE. Like when you use a certain Java class and have a problem, answers from SO might flare up. There would probably be cases where something like this is annoying, but others may be very helpful. | Following up on Josh's answer. This VS Macro will search StackOverflow for highlighted text in the Visual Studio IDE. Just highlight and press Alt+F1
```
Public Sub SearchStackOverflowForSelectedText()
Dim s As String = ActiveWindowSelection().Trim()
If s.Length > 0 Then
DTE.ItemOperations.Navigate("http://www.stackoverflow.com/search?q=" & _
Web.HttpUtility.UrlEncode(s))
End If
End Sub
Private Function ActiveWindowSelection() As String
If DTE.ActiveWindow.ObjectKind = EnvDTE.Constants.vsWindowKindOutput Then
Return OutputWindowSelection()
End If
If DTE.ActiveWindow.ObjectKind = "{57312C73-6202-49E9-B1E1-40EA1A6DC1F6}" Then
Return HTMLEditorSelection()
End If
Return SelectionText(DTE.ActiveWindow.Selection)
End Function
Private Function HTMLEditorSelection() As String
Dim hw As HTMLWindow = ActiveDocument.ActiveWindow.Object
Dim tw As TextWindow = hw.CurrentTabObject
Return SelectionText(tw.Selection)
End Function
Private Function OutputWindowSelection() As String
Dim w As Window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)
Dim ow As OutputWindow = w.Object
Dim owp As OutputWindowPane = ow.OutputWindowPanes.Item(ow.ActivePane.Name)
Return SelectionText(owp.TextDocument.Selection)
End Function
Private Function SelectionText(ByVal sel As EnvDTE.TextSelection) As String
If sel Is Nothing Then
Return ""
End If
If sel.Text.Length = 0 Then
SelectWord(sel)
End If
If sel.Text.Length <= 2 Then
Return ""
End If
Return sel.Text
End Function
Private Sub SelectWord(ByVal sel As EnvDTE.TextSelection)
Dim leftPos As Integer
Dim line As Integer
Dim pt As EnvDTE.EditPoint = sel.ActivePoint.CreateEditPoint()
sel.WordLeft(True, 1)
line = sel.TextRanges.Item(1).StartPoint.Line
leftPos = sel.TextRanges.Item(1).StartPoint.LineCharOffset
pt.MoveToLineAndOffset(line, leftPos)
sel.MoveToPoint(pt)
sel.WordRight(True, 1)
End Sub
```
To install:
1. go to Tools - Macros - IDE
2. create a new Module with a name of your choice under "MyMacros". Or use an existing module.
3. paste the above code into the module
4. add a reference to the System.Web namespace (for HttpUtility) to the module
5. close the macro IDE window
6. go to Tools - Options - Environment - Keyboard
7. type "google" in the Show Commands Containing textbox. The SearchGoogleForSelectedText macro should show up
8. click in the Press Shortcut Keys textbox, then press ALT+F1
9. click the Assign button
10. click OK
This is all taken from Jeff Atwood's [Google Search VS Macro](https://blog.codinghorror.com/google-search-vsnet-macro/) post, just modified to search StackOverflow instead. |
134,569 | <p>I would like to throw an exception when my C++ methods encounter something weird and can't recover. Is it OK to throw a <code>std::string</code> pointer?</p>
<p>Here's what I was looking forward to doing:</p>
<pre><code>void Foo::Bar() {
if(!QueryPerformanceTimer(&m_baz)) {
throw new std::string("it's the end of the world!");
}
}
void Foo::Caller() {
try {
this->Bar(); // should throw
}
catch(std::string *caught) { // not quite sure the syntax is OK here...
std::cout << "Got " << caught << std::endl;
}
}
</code></pre>
| [
{
"answer_id": 134596,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 3,
"selected": false,
"text": "<p>It works, but I wouldn't do it if I were you. You don't seem to be deleting that heap data when you're done, whic... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22187/"
] | I would like to throw an exception when my C++ methods encounter something weird and can't recover. Is it OK to throw a `std::string` pointer?
Here's what I was looking forward to doing:
```
void Foo::Bar() {
if(!QueryPerformanceTimer(&m_baz)) {
throw new std::string("it's the end of the world!");
}
}
void Foo::Caller() {
try {
this->Bar(); // should throw
}
catch(std::string *caught) { // not quite sure the syntax is OK here...
std::cout << "Got " << caught << std::endl;
}
}
``` | Yes. [`std::exception`](http://en.cppreference.com/w/cpp/error/exception) is the base exception class in the C++ standard library. You may want to avoid using strings as exception classes because they themselves can throw an exception during use. If that happens, then where will you be?
boost has an excellent [document](http://www.boost.org/community/error_handling.html) on good style for exceptions and error handling. It's worth a read. |
134,572 | <p>I am using the jQuery AutoComplete plugin in an html page where I also have an accordion menu which uses prototype.</p>
<p>They both work perfectly separately but when I tried to implement both components in a single page I get an error that I have not been able to understand.</p>
<blockquote>
<p>uncaught exception: [Exception... "Component returned failure code:
0x80004005 (NS_ERROR_FAILURE) [nsIDOMViewCSS.getComputedStyle]"
nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame ::
file:///C:/Documents and
Settings/Administrator/Desktop/website/js/jquery-1.2.6.pack.js ::
anonymous :: line 11" data: no]</p>
</blockquote>
<p>I found out the file conflicting with jQuery is 'effects.js' which is used by the accordion menu. I tried replacing this file with a newer version but newer seems to break the accordion behavior. </p>
<p>My guess is that the 'effects.js' file used in the accordion was modified to obtain the accordion demo output. I also tried using the overriding methods jQuery needs to avoid conflict with other libraries and that did not work.</p>
<p>I obtained the accordion demo from <a href="http://www.stickmanlabs.com/accordion/" rel="nofollow noreferrer">stickmanlabs.com</a>.</p>
<p>And the jQuery AutoComplete can be obtained from <a href="http://docs.jquery.com/Plugins/Autocomplete#Setup" rel="nofollow noreferrer">jQuery site</a>.</p>
<p>Has any one else experienced this issue?</p>
| [
{
"answer_id": 134635,
"author": "Tahir Akhtar",
"author_id": 18027,
"author_profile": "https://Stackoverflow.com/users/18027",
"pm_score": 3,
"selected": false,
"text": "<p>jQuery lets you rename the jQuery function from <code>$</code> to something else to avoid namespace conflicts with... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am using the jQuery AutoComplete plugin in an html page where I also have an accordion menu which uses prototype.
They both work perfectly separately but when I tried to implement both components in a single page I get an error that I have not been able to understand.
>
> uncaught exception: [Exception... "Component returned failure code:
> 0x80004005 (NS\_ERROR\_FAILURE) [nsIDOMViewCSS.getComputedStyle]"
> nsresult: "0x80004005 (NS\_ERROR\_FAILURE)" location: "JS frame ::
> file:///C:/Documents and
> Settings/Administrator/Desktop/website/js/jquery-1.2.6.pack.js ::
> anonymous :: line 11" data: no]
>
>
>
I found out the file conflicting with jQuery is 'effects.js' which is used by the accordion menu. I tried replacing this file with a newer version but newer seems to break the accordion behavior.
My guess is that the 'effects.js' file used in the accordion was modified to obtain the accordion demo output. I also tried using the overriding methods jQuery needs to avoid conflict with other libraries and that did not work.
I obtained the accordion demo from [stickmanlabs.com](http://www.stickmanlabs.com/accordion/).
And the jQuery AutoComplete can be obtained from [jQuery site](http://docs.jquery.com/Plugins/Autocomplete#Setup).
Has any one else experienced this issue? | There are two possible solutions: There was a conflict with an older version of Scriptaculous and jQuery (Scriptaculous was attempting to extend the native Array prototype incorrectly) - first try upgrading your copy of Scriptaculous.
If that does not work you will need to use `noConflict()` (as alluded to above). However, there's a catch. Since you're including a plugin you'll need to do the includes in a specific order, for example:
```
<script src="jquery.js"></script>
<script src="jquery.autocomplete.js"></script>
<script>
jQuery.noConflict();
jQuery(document).ready(function($){
$("#example").autocomplete(options);
});
</script>
<script src="prototype.js"></script>
<script src="effects.js"></script>
<script src="accordion.js"></script>
```
Hope this helps to clarify the situation. |
134,581 | <p>This is a follow-up to <a href="https://stackoverflow.com/questions/43778/sqlite3-ruby-gem-failed-to-build-gem-native-extension">this question</a>.</p>
<p>When I issue the <strong><code>gem update</code></strong> command on Windows, whenever it gets to a
gem whose latest version DOESN'T have Windows binaries, it'll attempt to
build the native extension which will, of course, fail. For example:</p>
<pre><code>Updating sqlite3-ruby
Building native extensions. This could take a while...
ERROR: While executing gem ... (Gem::Installer::ExtensionBuildError)
ERROR: Failed to build gem native extension.
c:/ruby/bin/ruby.exe extconf.rb update
checking for fdatasync() in rt.lib... no
checking for sqlite3.h... no
nmake
'nmake' is not recognized as an internal or external command,
operable program or batch file.
</code></pre>
<p>The old pre-1.x behavior of asking for the required platform at least
made updating possible. Now I can't update at all unless I uninstall the
troublesome gems (currently sqlite3-ruby and hpricot), run the update,
then re-install the gems using the --version switch.</p>
<p>Does anyone have a solution to this conundrum or are we stuck with it?</p>
<hr>
<p><strong>Note:</strong></p>
<pre><code>$ gem -v
1.2.0
$ ruby -v
ruby 1.8.6 (2007-09-24 patchlevel 111) [i386-mswin32]
</code></pre>
<hr>
<p><strong>Note (26 September 2008):</strong> I just updated to gems 1.3.0 and this problem persists.</p>
<p><strong>Note (18 November 2008):</strong> Just updated to gems 1.3.1 and the problem persists.</p>
<p><strong>Note (28 April 2009):</strong> The latest version of Gems (<a href="http://blog.segment7.net/articles/2009/04/15/rubygems-1-3-2" rel="nofollow noreferrer">1.3.2</a>) now skips any gems where building of native extensions fails during update; in other words, the problem is fixed. Hooray!</p>
| [
{
"answer_id": 136226,
"author": "hectorsq",
"author_id": 14755,
"author_profile": "https://Stackoverflow.com/users/14755",
"pm_score": 2,
"selected": false,
"text": "<p>It seems that we are stuck. I have found <a href=\"http://rubyforge.org/frs/?group_id=254\" rel=\"nofollow noreferrer\... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1944/"
] | This is a follow-up to [this question](https://stackoverflow.com/questions/43778/sqlite3-ruby-gem-failed-to-build-gem-native-extension).
When I issue the **`gem update`** command on Windows, whenever it gets to a
gem whose latest version DOESN'T have Windows binaries, it'll attempt to
build the native extension which will, of course, fail. For example:
```
Updating sqlite3-ruby
Building native extensions. This could take a while...
ERROR: While executing gem ... (Gem::Installer::ExtensionBuildError)
ERROR: Failed to build gem native extension.
c:/ruby/bin/ruby.exe extconf.rb update
checking for fdatasync() in rt.lib... no
checking for sqlite3.h... no
nmake
'nmake' is not recognized as an internal or external command,
operable program or batch file.
```
The old pre-1.x behavior of asking for the required platform at least
made updating possible. Now I can't update at all unless I uninstall the
troublesome gems (currently sqlite3-ruby and hpricot), run the update,
then re-install the gems using the --version switch.
Does anyone have a solution to this conundrum or are we stuck with it?
---
**Note:**
```
$ gem -v
1.2.0
$ ruby -v
ruby 1.8.6 (2007-09-24 patchlevel 111) [i386-mswin32]
```
---
**Note (26 September 2008):** I just updated to gems 1.3.0 and this problem persists.
**Note (18 November 2008):** Just updated to gems 1.3.1 and the problem persists.
**Note (28 April 2009):** The latest version of Gems ([1.3.2](http://blog.segment7.net/articles/2009/04/15/rubygems-1-3-2)) now skips any gems where building of native extensions fails during update; in other words, the problem is fixed. Hooray! | Gems, as of [version 1.3.2](http://blog.segment7.net/articles/2009/04/15/rubygems-1-3-2), will now skip gems that fail to build, so update Rubygems to the latest version and the problem discussed here should be solved.
```
gem update --system
```
***The following solution is now deprecated, but I leave it here for the record.***
I [started a thread on this issue](http://www.ruby-forum.com/topic/166693) on the Ruby Forum (it's a front end to the mailing list). There's some interesting discussion; it's worth a read. There's even a very hacky solution to this problem on there:
```
`gem.bat outdated`.split(/\n/).map{|z|z.scan(/^[^[:space:]]+/)}.flatten.each{|z| `gem.bat update #{z}`}
```
It calls the `gem outdated` command and builds a list of all of the outdated gems. It then iterates over the list and calls `gem update` for each individual outdated gem. If one fails, it just moves onto the next. |
134,626 | <p>I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior.</p>
<p>Here are some trivial examples where they functionally do the same thing if either were found within another function:</p>
<p><strong>Lambda function</strong></p>
<pre><code>>>> a = lambda x : 1 + x
>>> a(5)
6
</code></pre>
<p><strong>Nested function</strong></p>
<pre><code>>>> def b(x): return 1 + x
>>> b(5)
6
</code></pre>
<p>Are there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.)</p>
<p>Does it even matter? If it doesn't then does that violate the Pythonic principle:</p>
<blockquote>
<p><a href="https://www.python.org/dev/peps/pep-0020/" rel="noreferrer">There should be one-- and preferably only one --obvious way to do it.</a>.</p>
</blockquote>
| [
{
"answer_id": 134638,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 8,
"selected": true,
"text": "<p>If you need to assign the <code>lambda</code> to a name, use a <code>def</code> instead. <code>def</code>s are just synta... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] | I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior.
Here are some trivial examples where they functionally do the same thing if either were found within another function:
**Lambda function**
```
>>> a = lambda x : 1 + x
>>> a(5)
6
```
**Nested function**
```
>>> def b(x): return 1 + x
>>> b(5)
6
```
Are there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.)
Does it even matter? If it doesn't then does that violate the Pythonic principle:
>
> [There should be one-- and preferably only one --obvious way to do it.](https://www.python.org/dev/peps/pep-0020/).
>
>
> | If you need to assign the `lambda` to a name, use a `def` instead. `def`s are just syntactic sugar for an assignment, so the result is the same, and they are a lot more flexible and readable.
`lambda`s can be used for *use once, throw away* functions which won't have a name.
However, this use case is very rare. You rarely need to pass around unnamed function objects.
The builtins `map()` and `filter()` need function objects, but **list comprehensions** and **generator expressions** are generally more readable than those functions and can cover all use cases, without the need of lambdas.
For the cases you really need a small function object, you should use the `operator` module functions, like `operator.add` instead of `lambda x, y: x + y`
If you still need some `lambda` not covered, you might consider writing a `def`, just to be more readable. If the function is more complex than the ones at `operator` module, a `def` is probably better.
So, real world good `lambda` use cases are very rare. |
134,629 | <p>In my <code>urls.py</code> file, I have:</p>
<pre><code>from myapp import views
...
(r'^categories/$', views.categories)
</code></pre>
<p>Where <code>categories</code> is a view function inside <code>myapp/views.py</code>. No other URLconf lines reference <code>views.categories</code>.</p>
<p>In a unit test file, I’m trying to grab this URL using <code>django.core.urlresolvers.reverse()</code>, instead of just copying '/categories/' (DRY and all that). So, I have:</p>
<pre><code>from django.core.urlresolvers import reverse
from myapp import views
...
url = reverse(views.categories)
</code></pre>
<p>When I run my tests, I get a <code>NoReverseMatch</code> error:</p>
<pre><code>NoReverseMatch: Reverse for '<function categories at 0x1082f30>' with arguments '()' and keyword arguments '{}' not found.
</code></pre>
<p>It matches just fine if I make the URL pattern a named pattern, like this:</p>
<pre><code>url(r'^categories/$', views.categories, 'myapp-categories')
</code></pre>
<p>And use the pattern name to match it:</p>
<pre><code>url = reverse('myapp-categories')
</code></pre>
<p>But as far as I can tell from <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse" rel="noreferrer">the <code>reverse</code> documentation</a>, I shouldn’t need to make it a named URL pattern just to use <code>reverse</code>.</p>
<p>Any ideas what I’m doing wrong?</p>
| [
{
"answer_id": 134651,
"author": "Jack M.",
"author_id": 3421,
"author_profile": "https://Stackoverflow.com/users/3421",
"pm_score": -1,
"selected": false,
"text": "<p>The reverse function actually uses the \"name\" of the URL. This is defined like so:</p>\n\n<pre><code>urlpatterns = pa... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20578/"
] | In my `urls.py` file, I have:
```
from myapp import views
...
(r'^categories/$', views.categories)
```
Where `categories` is a view function inside `myapp/views.py`. No other URLconf lines reference `views.categories`.
In a unit test file, I’m trying to grab this URL using `django.core.urlresolvers.reverse()`, instead of just copying '/categories/' (DRY and all that). So, I have:
```
from django.core.urlresolvers import reverse
from myapp import views
...
url = reverse(views.categories)
```
When I run my tests, I get a `NoReverseMatch` error:
```
NoReverseMatch: Reverse for '<function categories at 0x1082f30>' with arguments '()' and keyword arguments '{}' not found.
```
It matches just fine if I make the URL pattern a named pattern, like this:
```
url(r'^categories/$', views.categories, 'myapp-categories')
```
And use the pattern name to match it:
```
url = reverse('myapp-categories')
```
But as far as I can tell from [the `reverse` documentation](http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse), I shouldn’t need to make it a named URL pattern just to use `reverse`.
Any ideas what I’m doing wrong? | After futher investigation, turns out it was an issue with how I was importing the views module:
[How do I successfully pass a function reference to Django’s reverse() function?](https://stackoverflow.com/questions/146522/how-do-i-successfully-pass-a-function-reference-to-djangos-reverse-function)
Thanks for the help though, guys: you inspired me to look at it properly. |
134,644 | <p>Suppose you have a collection of <code>Foo</code> classes:</p>
<pre><code>class Foo
{
public string Bar;
public string Baz;
}
List<Foo> foolist;
</code></pre>
<p>And you want to check this collection to see if another entry has a matching <code>Bar</code>.</p>
<pre><code>bool isDuplicate = false;
foreach (Foo f in foolist)
{
if (f.Bar == SomeBar)
{
isDuplicate = true;
break;
}
}
</code></pre>
<p><code>Contains()</code> doesn't work because it compares the classes as whole.</p>
<p>Does anyone have a better way to do this that works for .NET 2.0?</p>
| [
{
"answer_id": 134662,
"author": "Karg",
"author_id": 12685,
"author_profile": "https://Stackoverflow.com/users/12685",
"pm_score": 0,
"selected": false,
"text": "<p>fooList.Exists(item => item.Bar == SomeBar)</p>\n\n<p>or with anonymous delegate</p>\n\n<p>fooList.Exists(delegate(Foo ite... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | Suppose you have a collection of `Foo` classes:
```
class Foo
{
public string Bar;
public string Baz;
}
List<Foo> foolist;
```
And you want to check this collection to see if another entry has a matching `Bar`.
```
bool isDuplicate = false;
foreach (Foo f in foolist)
{
if (f.Bar == SomeBar)
{
isDuplicate = true;
break;
}
}
```
`Contains()` doesn't work because it compares the classes as whole.
Does anyone have a better way to do this that works for .NET 2.0? | ```
fooList.Exists(item => item.Bar == SomeBar)
```
That's not LINQ, but a Lambda expression, but nevertheless, it uses a v3.5 feature. No problem:
```
fooList.Exists(delegate(Foo Item) { return item.Bar == SomeBar});
```
That should work in 2.0. |
134,653 | <p><b>Summary:</b> C#/.NET is supposed to be garbage collected. C# has a destructor, used to clean resources. What happen when an object A is garbage collected the same line I try to clone one of its variable members? Apparently, on multiprocessors, sometimes, the garbage collector wins...</p>
<p><b>The problem</b></p>
<p>Today, on a training session on C#, the teacher showed us some code which contained a bug only when run on multiprocessors.</p>
<p>I'll summarize to say that sometimes, the compiler or the JIT screws up by calling the finalizer of a C# class object before returning from its called method.</p>
<p>The full code, given in Visual C++ 2005 documentation, will be posted as an "answer" to avoid making a very very large questions, but the essential are below:</p>
<p>The following class has a "Hash" property which will return a cloned copy of an internal array. At is construction, the first item of the array has a value of 2. In the destructor, its value is set to zero.</p>
<p>The point is: If you try to get the "Hash" property of "Example", you'll get a clean copy of the array, whose first item is still 2, as the object is being used (and as such, not being garbage collected/finalized):</p>
<pre><code>public class Example
{
private int nValue;
public int N { get { return nValue; } }
// The Hash property is slower because it clones an array. When
// KeepAlive is not used, the finalizer sometimes runs before
// the Hash property value is read.
private byte[] hashValue;
public byte[] Hash { get { return (byte[])hashValue.Clone(); } }
public Example()
{
nValue = 2;
hashValue = new byte[20];
hashValue[0] = 2;
}
~Example()
{
nValue = 0;
if (hashValue != null)
{
Array.Clear(hashValue, 0, hashValue.Length);
}
}
}
</code></pre>
<p>But nothing is so simple...
The code using this class is wokring inside a thread, and of course, for the test, the app is heavily multithreaded:</p>
<pre><code>public static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(ThreadProc));
t.Start();
t.Join();
}
private static void ThreadProc()
{
// running is a boolean which is always true until
// the user press ENTER
while (running) DoWork();
}
</code></pre>
<p>The DoWork static method is the code where the problem happens:</p>
<pre><code>private static void DoWork()
{
Example ex = new Example();
byte[] res = ex.Hash; // [1]
// If the finalizer runs before the call to the Hash
// property completes, the hashValue array might be
// cleared before the property value is read. The
// following test detects that.
if (res[0] != 2)
{
// Oops... The finalizer of ex was launched before
// the Hash method/property completed
}
}
</code></pre>
<p>Once every 1,000,000 excutions of DoWork, apparently, the Garbage Collector does its magic, and tries to reclaim "ex", as it is not anymore referenced in the remaning code of the function, and this time, it is faster than the "Hash" get method. So what we have in the end is a clone of a zero-ed byte array, instead of having the right one (with the 1st item at 2).</p>
<p>My guess is that there is inlining of the code, which essentially replaces the line marked [1] in the DoWork function by something like:</p>
<pre><code> // Supposed inlined processing
byte[] res2 = ex.Hash2;
// note that after this line, "ex" could be garbage collected,
// but not res2
byte[] res = (byte[])res2.Clone();
</code></pre>
<p>If we supposed Hash2 is a simple accessor coded like:</p>
<pre><code>// Hash2 code:
public byte[] Hash2 { get { return (byte[])hashValue; } }
</code></pre>
<p>So, the question is: <b>Is this supposed to work that way in C#/.NET, or could this be considered as a bug of either the compiler of the JIT?</b></p>
<h1>edit</h1>
<p>See Chris Brumme's and Chris Lyons' blogs for an explanation.</p>
<p><a href="http://blogs.msdn.com/cbrumme/archive/2003/04/19/51365.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/cbrumme/archive/2003/04/19/51365.aspx</a><br>
<a href="http://blogs.msdn.com/clyon/archive/2004/09/21/232445.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/clyon/archive/2004/09/21/232445.aspx</a></p>
<p>Everyone's answer was interesting, but I couldn't choose one better than the other. So I gave you all a +1...</p>
<p>Sorry</p>
<p>:-)</p>
<h1>Edit 2</h1>
<p>I was unable to reproduce the problem on Linux/Ubuntu/Mono, despite using the same code on the same conditions (multiple same executable running simultaneously, release mode, etc.)</p>
| [
{
"answer_id": 134687,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 0,
"selected": false,
"text": "<h2>The Full Code</h2>\n<p>You'll find below the full code, copy/pasted from a Visual C++ 2008 .cs file. As I'm now on L... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14089/"
] | **Summary:** C#/.NET is supposed to be garbage collected. C# has a destructor, used to clean resources. What happen when an object A is garbage collected the same line I try to clone one of its variable members? Apparently, on multiprocessors, sometimes, the garbage collector wins...
**The problem**
Today, on a training session on C#, the teacher showed us some code which contained a bug only when run on multiprocessors.
I'll summarize to say that sometimes, the compiler or the JIT screws up by calling the finalizer of a C# class object before returning from its called method.
The full code, given in Visual C++ 2005 documentation, will be posted as an "answer" to avoid making a very very large questions, but the essential are below:
The following class has a "Hash" property which will return a cloned copy of an internal array. At is construction, the first item of the array has a value of 2. In the destructor, its value is set to zero.
The point is: If you try to get the "Hash" property of "Example", you'll get a clean copy of the array, whose first item is still 2, as the object is being used (and as such, not being garbage collected/finalized):
```
public class Example
{
private int nValue;
public int N { get { return nValue; } }
// The Hash property is slower because it clones an array. When
// KeepAlive is not used, the finalizer sometimes runs before
// the Hash property value is read.
private byte[] hashValue;
public byte[] Hash { get { return (byte[])hashValue.Clone(); } }
public Example()
{
nValue = 2;
hashValue = new byte[20];
hashValue[0] = 2;
}
~Example()
{
nValue = 0;
if (hashValue != null)
{
Array.Clear(hashValue, 0, hashValue.Length);
}
}
}
```
But nothing is so simple...
The code using this class is wokring inside a thread, and of course, for the test, the app is heavily multithreaded:
```
public static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(ThreadProc));
t.Start();
t.Join();
}
private static void ThreadProc()
{
// running is a boolean which is always true until
// the user press ENTER
while (running) DoWork();
}
```
The DoWork static method is the code where the problem happens:
```
private static void DoWork()
{
Example ex = new Example();
byte[] res = ex.Hash; // [1]
// If the finalizer runs before the call to the Hash
// property completes, the hashValue array might be
// cleared before the property value is read. The
// following test detects that.
if (res[0] != 2)
{
// Oops... The finalizer of ex was launched before
// the Hash method/property completed
}
}
```
Once every 1,000,000 excutions of DoWork, apparently, the Garbage Collector does its magic, and tries to reclaim "ex", as it is not anymore referenced in the remaning code of the function, and this time, it is faster than the "Hash" get method. So what we have in the end is a clone of a zero-ed byte array, instead of having the right one (with the 1st item at 2).
My guess is that there is inlining of the code, which essentially replaces the line marked [1] in the DoWork function by something like:
```
// Supposed inlined processing
byte[] res2 = ex.Hash2;
// note that after this line, "ex" could be garbage collected,
// but not res2
byte[] res = (byte[])res2.Clone();
```
If we supposed Hash2 is a simple accessor coded like:
```
// Hash2 code:
public byte[] Hash2 { get { return (byte[])hashValue; } }
```
So, the question is: **Is this supposed to work that way in C#/.NET, or could this be considered as a bug of either the compiler of the JIT?**
edit
====
See Chris Brumme's and Chris Lyons' blogs for an explanation.
<http://blogs.msdn.com/cbrumme/archive/2003/04/19/51365.aspx>
<http://blogs.msdn.com/clyon/archive/2004/09/21/232445.aspx>
Everyone's answer was interesting, but I couldn't choose one better than the other. So I gave you all a +1...
Sorry
:-)
Edit 2
======
I was unable to reproduce the problem on Linux/Ubuntu/Mono, despite using the same code on the same conditions (multiple same executable running simultaneously, release mode, etc.) | It's simply a bug in your code: finalizers should not be accessing managed objects.
The only reason to implement a finalizer is to release unmanaged resources. And in this case, you should carefully implement [the standard IDisposable pattern](http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx).
With this pattern, you implement a protected method "protected Dispose(bool disposing)". When this method is called from the finalizer, it cleans up unmanaged resources, but does not attempt to clean up managed resources.
In your example, you don't have any unmanaged resources, so should not be implementing a finalizer. |
134,656 | <p>Where can I find a Perl module for converting a Perl data structure into a JavaScript one?</p>
<p>e.g. this is my code (Mason):</p>
<pre><code>% # convert our @cti data structure into a javascript one
var cti = [
% foreach my $cti_category (@cti) {
{
label: "<% $cti_category->{'label'} %>",
value: "<% $cti_category->{'value'} %>",
children: [
% foreach my $cti_type (@{$cti_category->{'children'}}) {
{
label: "<% $cti_type->{'label'} %>",
value: "<% $cti_type->{'value'} %>",
},
% }
]
},
% }
];
</code></pre>
<p>is there a module for this?</p>
| [
{
"answer_id": 134672,
"author": "moritz",
"author_id": 14132,
"author_profile": "https://Stackoverflow.com/users/14132",
"pm_score": 3,
"selected": false,
"text": "<p>Check out <a href=\"http://search.cpan.org/perldoc?JSON\" rel=\"noreferrer\">JSON</a> or <a href=\"http://search.cpan.or... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8913/"
] | Where can I find a Perl module for converting a Perl data structure into a JavaScript one?
e.g. this is my code (Mason):
```
% # convert our @cti data structure into a javascript one
var cti = [
% foreach my $cti_category (@cti) {
{
label: "<% $cti_category->{'label'} %>",
value: "<% $cti_category->{'value'} %>",
children: [
% foreach my $cti_type (@{$cti_category->{'children'}}) {
{
label: "<% $cti_type->{'label'} %>",
value: "<% $cti_type->{'value'} %>",
},
% }
]
},
% }
];
```
is there a module for this? | JSON stands for JavaScript Object Notation, which is the format you're looking for.
Unfortunately, none of the modules you're looking for are in the Perl core, but they are available on CPAN, as a quick [search](http://search.cpan.org/search?query=JSON&mode=all) will reveal.
I'd actually recommend installing [JSON::Any](http://search.cpan.org/author/RBERJON/JSON-Any-1.17/lib/JSON/Any.pm) as a wrapper, as well as [JSON::XS](http://search.cpan.org/author/MLEHMANN/JSON-XS-2.2222/XS.pm) (if you have a C compiler) or one of [JSON](http://search.cpan.org/author/MAKAMAKA/JSON-2.12/lib/JSON.pm) and [JSON::Syck](http://search.cpan.org/~audreyt/YAML-Syck-1.05/lib/JSON/Syck.pm) if you don't. JSON::Any provides an [interface class](http://en.wikipedia.org/wiki/Interface_pattern) on top of several other JSON modules (you can choose, or let it pick from what's installed) that's independent of which module you wind up using. That way, if your code should need to be ported elsewhere, and (say) the target machine can install JSON::XS when you can't, you get a performance boost without any extra code.
```
use JSON::Any;
my $j = JSON::Any->new;
$json = $j->objToJson($perl_data);
```
Like so. |
134,658 | <p>I am trying to encrypt the "system.web.membership" element within the Web.Config of our .Net application to secure username and password to Active Directory. I am using the aspnet_regiis command to encrypt, and have tried several different strings for the value of the "pe" option with no success. I have successfully encrypted the "connectstrings" element on my web.config.</p>
<p>Cmd</p>
<pre>C:\Windows\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -pe "connectionStrings" -site MySite -app /MyApp
Encrypting configuration section...
Succeeded!
C:\Windows\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -pe "membership" -site MySite -app /MyApp
Encrypting configuration section...
The configuration section 'membership' was not found.
Failed!
C:\Windows\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -pe "system.web.membership" -site MySite -app /MyApp
Encrypting configuration section...
The configuration section 'system.web.membership' was not found.
Failed!</pre>
<p>Web.Config</p>
<pre><code><configuration>
...
<system.web>
...
<authentication mode="Forms">
<forms name=".ADAuthCookie"
timeout="30"/>
</authentication>
<authorization>
<deny users="?"/>
<allow users="*"/>
</authorization>
<membership defaultProvider="MyADMembershipProvider">
<providers>
<add name="MyADMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ADConnectionString"
connectionUsername="MyUserName"
connectionPassword="MyPassowrd"/>
</providers>
</membership>
...
</system.web>
...
</configuration>
</code></pre>
<p>So what gives? What am I missing?</p>
| [
{
"answer_id": 134733,
"author": "Paul Lalonde",
"author_id": 5782,
"author_profile": "https://Stackoverflow.com/users/5782",
"pm_score": 4,
"selected": true,
"text": "<p>The configuration section is identified by \"<code>system.web/membership</code>\", not \"<code>membership</code>\" no... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/576/"
] | I am trying to encrypt the "system.web.membership" element within the Web.Config of our .Net application to secure username and password to Active Directory. I am using the aspnet\_regiis command to encrypt, and have tried several different strings for the value of the "pe" option with no success. I have successfully encrypted the "connectstrings" element on my web.config.
Cmd
```
C:\Windows\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -pe "connectionStrings" -site MySite -app /MyApp
Encrypting configuration section...
Succeeded!
C:\Windows\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -pe "membership" -site MySite -app /MyApp
Encrypting configuration section...
The configuration section 'membership' was not found.
Failed!
C:\Windows\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -pe "system.web.membership" -site MySite -app /MyApp
Encrypting configuration section...
The configuration section 'system.web.membership' was not found.
Failed!
```
Web.Config
```
<configuration>
...
<system.web>
...
<authentication mode="Forms">
<forms name=".ADAuthCookie"
timeout="30"/>
</authentication>
<authorization>
<deny users="?"/>
<allow users="*"/>
</authorization>
<membership defaultProvider="MyADMembershipProvider">
<providers>
<add name="MyADMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ADConnectionString"
connectionUsername="MyUserName"
connectionPassword="MyPassowrd"/>
</providers>
</membership>
...
</system.web>
...
</configuration>
```
So what gives? What am I missing? | The configuration section is identified by "`system.web/membership`", not "`membership`" nor "`system.web.membership`". |
134,673 | <p>I've got a VS2008 deployment project that builds an installer for a couple of Windows services.</p>
<p>Each service references several different projects:</p>
<pre>
CustomerName.MailSendingService
-> CustomerName.Network
-> CustomerName.Data
-> CustomerName.Security
CustomerName.ProductIntegrationService
-> CustomerName.Core
-> CustomerName.Security
</pre>
<p>The Windows service projects, the projects they reference, and the deployment project are all in the same VS2008 solution.</p>
<p>I've added the primary output from the Windows service projects in the deployment project's file system editor. </p>
<p>My expectation is that the primary output for the Windows service projects would include the DLLs from the referenced projects. However, when the deployment project is built, the DLL from one of the referenced projects is missing. (<code>CustomerName.ProductIntegrationService</code> is missing <code>CustomerName.Security</code>) </p>
<p>Maddeningly, the DLLs for the other projects referenced by the Windows service are present; just one project's output is missing.</p>
<p>(Edit) I've verified that the reference is set to Copy Local in the reference properties window. The DLL for the referenced project is placed in the windows service project's <code>bin\Release</code> folder, but isn't packaged in the MSI file built for the deployment project.</p>
<p>(Edit 2) Following Joseph Daigle's suggestion, I checked that the dependency is in the dependencies list for the primary output, and it's not marked "excluded," so that doesn't appear to be the cause of this issue.</p>
<p>Why would just one project's output be missing?</p>
| [
{
"answer_id": 134759,
"author": "hectorsq",
"author_id": 14755,
"author_profile": "https://Stackoverflow.com/users/14755",
"pm_score": 0,
"selected": false,
"text": "<p>I have not used Visual Studio 2008 yet, however in 2005 you have to verify that the missing reference on the project h... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18102/"
] | I've got a VS2008 deployment project that builds an installer for a couple of Windows services.
Each service references several different projects:
```
CustomerName.MailSendingService
-> CustomerName.Network
-> CustomerName.Data
-> CustomerName.Security
CustomerName.ProductIntegrationService
-> CustomerName.Core
-> CustomerName.Security
```
The Windows service projects, the projects they reference, and the deployment project are all in the same VS2008 solution.
I've added the primary output from the Windows service projects in the deployment project's file system editor.
My expectation is that the primary output for the Windows service projects would include the DLLs from the referenced projects. However, when the deployment project is built, the DLL from one of the referenced projects is missing. (`CustomerName.ProductIntegrationService` is missing `CustomerName.Security`)
Maddeningly, the DLLs for the other projects referenced by the Windows service are present; just one project's output is missing.
(Edit) I've verified that the reference is set to Copy Local in the reference properties window. The DLL for the referenced project is placed in the windows service project's `bin\Release` folder, but isn't packaged in the MSI file built for the deployment project.
(Edit 2) Following Joseph Daigle's suggestion, I checked that the dependency is in the dependencies list for the primary output, and it's not marked "excluded," so that doesn't appear to be the cause of this issue.
Why would just one project's output be missing? | I have a couple more things to add after reproducing the same suspected msi defect.
1) When I added the second project output sharing the same detected dependency to the installer it did not automatically add the dependency. I removed both project output's and added them back in reverse order. The second project output added never added the detected dependency. This excludes any configuration or code issue with the projects and how the references were added. It's always the second one that fails.
2) My team actually hit a second problem after using the 'Manually add detected assembly' workaround. Initially we added the dependency from the location in '\Program Files\xxx' but ran into build problems on 64 bit machines where that same dependency was in the '\Program Files (x86)\xxx' folder even though VS is smart enough to handle this problem when picking up references.
* The proper way to manually add the assembly is by navigating to the bin folder and adding the assembly that is copied local. This ensures that the right assembly will be present on x86 or x64 machines. |
134,683 | <p>This might be a stupid question but if there's a better or proper way to do this, I'd love to learn it.</p>
<p>I have run across this a few times, including recently, where small spaces show up in the rendered version of my HTML page. Intuitively I think these should not be there because outside of text or entities the formatting of a page's HTML shouldn't matter but apparently it does.</p>
<p>What I'm referring to is this - I have some Photoshop file from the client on how they want their site to look. They want it to look basically pixel perfect to the image in this file. </p>
<p>One of the places in the page calls for a menu bar, where each one does the changing bit on hovering, acts like a hyperlink, etc. In the Photoshop file this is one long bar, so a cheap and easy way to do this is to just split that segment into multiple images and then place them next to each other in the file. </p>
<p>So instinctively I lay it out like so (there's more to it but this is the gist)</p>
<pre><code><a href="page1.html">
<img src="image1.png" />
</a>
<a href="page2.html">
<img src="image2.png" />
</a>
<a href="page3.html">
<img src="image3.png" />
</a>
</code></pre>
<p>and so forth. </p>
<p>The problem is the images have this tiny space between them which is unacceptable since the client wants this thing pixel-perfect (and it just plain looks bad).</p>
<p>One way to get it to render properly is to remove the carriage returns between the images</p>
<pre><code><a href="page1.html">
<img src="image1.png" />
</a>
<a href="page2.html">
<img src="image2.png" />
</a>
<a href="page3.html">
<img src="image3.png" />
</a>
</code></pre>
<p>Which makes the images go right up against each other (the desired effect) but it makes the line incredibly long and the code more difficult to maintain (it wraps here in SO and this is a simplified version - the real one has longer filenames and JavaScript sprinkled in to do the hovering).</p>
<p>It seems to me that this shouldn't happen but it looks like the carriage return in the HTML is being rendered as a small empty space. And this happens in all browsers, looks like.</p>
<p>Am I right or wrong for thinking the two snippets above should render the same? And is there something I'm doing wrong? Maybe saving the file with the wrong encoding? Should I make every one of these links a perfectly positioned CSS element instead?</p>
| [
{
"answer_id": 134701,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 5,
"selected": true,
"text": "<p>The whitespace (carriage return included) is usually rendered as space in all browsers.</p>\n\n<p>You need to put the ele... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2577/"
] | This might be a stupid question but if there's a better or proper way to do this, I'd love to learn it.
I have run across this a few times, including recently, where small spaces show up in the rendered version of my HTML page. Intuitively I think these should not be there because outside of text or entities the formatting of a page's HTML shouldn't matter but apparently it does.
What I'm referring to is this - I have some Photoshop file from the client on how they want their site to look. They want it to look basically pixel perfect to the image in this file.
One of the places in the page calls for a menu bar, where each one does the changing bit on hovering, acts like a hyperlink, etc. In the Photoshop file this is one long bar, so a cheap and easy way to do this is to just split that segment into multiple images and then place them next to each other in the file.
So instinctively I lay it out like so (there's more to it but this is the gist)
```
<a href="page1.html">
<img src="image1.png" />
</a>
<a href="page2.html">
<img src="image2.png" />
</a>
<a href="page3.html">
<img src="image3.png" />
</a>
```
and so forth.
The problem is the images have this tiny space between them which is unacceptable since the client wants this thing pixel-perfect (and it just plain looks bad).
One way to get it to render properly is to remove the carriage returns between the images
```
<a href="page1.html">
<img src="image1.png" />
</a>
<a href="page2.html">
<img src="image2.png" />
</a>
<a href="page3.html">
<img src="image3.png" />
</a>
```
Which makes the images go right up against each other (the desired effect) but it makes the line incredibly long and the code more difficult to maintain (it wraps here in SO and this is a simplified version - the real one has longer filenames and JavaScript sprinkled in to do the hovering).
It seems to me that this shouldn't happen but it looks like the carriage return in the HTML is being rendered as a small empty space. And this happens in all browsers, looks like.
Am I right or wrong for thinking the two snippets above should render the same? And is there something I'm doing wrong? Maybe saving the file with the wrong encoding? Should I make every one of these links a perfectly positioned CSS element instead? | The whitespace (carriage return included) is usually rendered as space in all browsers.
You need to put the elements one after another, but you can use a trick:
```
<a href="page1.html"><img src="image1.png"
/></a><a href="page2.html"><img src="image2.png"
/></a><a href="page3.html"><img src="image3.png"
/></a>
```
This also looks a little ugly, but it's still better than one single line. You might change the formatting, but the idea is to add carriage returns inside the elements and not between them. |
134,691 | <p>I am trying to create a jar file which includes some class and java files needed, but I also would like to include some extra xml, xsl, html, txt (README) files.</p>
<p>I am using Eclipse on Windows XP.</p>
<p>Is there an easy way for me to set up a directory structure and package all my files into a jar?</p>
| [
{
"answer_id": 134716,
"author": "Roman Plášil",
"author_id": 16590,
"author_profile": "https://Stackoverflow.com/users/16590",
"pm_score": 1,
"selected": false,
"text": "<p>A .jar is nothing but a ZIP archive, so you can use any program capable of creating ZIPs. Just make sure that you ... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am trying to create a jar file which includes some class and java files needed, but I also would like to include some extra xml, xsl, html, txt (README) files.
I am using Eclipse on Windows XP.
Is there an easy way for me to set up a directory structure and package all my files into a jar? | Add the files to a source folder and they can be included in the jar.
One common way is to have, at the root of your project, a src folder. Within that, folders for java files, and others. something like:
```
src/
css/
java/
html/
images/
```
Then you can make each of those subfolders a source folder (Right click, Use as Source Folder) and they should be available to add to the jar. |
134,712 | <p>I would like to sort a matrix according to a particular column. There is a <code>sort</code> function, but it sorts all columns independently.</p>
<p>For example, if my matrix <code>data</code> is:</p>
<pre><code> 1 3
5 7
-1 4
</code></pre>
<p>Then the desired output (sorting by the first column) would be:</p>
<pre><code>-1 4
1 3
5 7
</code></pre>
<p>But the output of <code>sort(data)</code> is:</p>
<pre><code>-1 3
1 4
5 7
</code></pre>
<p>How can I sort this matrix by the first column?</p>
| [
{
"answer_id": 135115,
"author": "Kena",
"author_id": 8027,
"author_profile": "https://Stackoverflow.com/users/8027",
"pm_score": 7,
"selected": true,
"text": "<p>I think the <a href=\"http://www.mathworks.com/help/matlab/ref/sortrows.html\" rel=\"noreferrer\">sortrows</a> function is wh... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9425/"
] | I would like to sort a matrix according to a particular column. There is a `sort` function, but it sorts all columns independently.
For example, if my matrix `data` is:
```
1 3
5 7
-1 4
```
Then the desired output (sorting by the first column) would be:
```
-1 4
1 3
5 7
```
But the output of `sort(data)` is:
```
-1 3
1 4
5 7
```
How can I sort this matrix by the first column? | I think the [sortrows](http://www.mathworks.com/help/matlab/ref/sortrows.html) function is what you're looking for.
```
>> sortrows(data,1)
ans =
-1 4
1 3
5 7
``` |
134,728 | <p>I have a class declared as follows:</p>
<pre><code>Public MustInherit Container(Of T As {New, BaseClass}) Inherits ArrayList(Of T)
</code></pre>
<p>I have classes that inherit this class.</p>
<p>I have another class that I must pass instances in this method:</p>
<pre><code>Public Sub LoadCollection(Of T As {BaseClass, New})(ByRef Collection As Container(Of T))
</code></pre>
<p>I need to store the passed in object in a global variable, but i can't simply declare it:</p>
<pre><code>Private _Container as Collection(Of BaseClass)
</code></pre>
<p>What is the syntax to declare this object?</p>
| [
{
"answer_id": 134811,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<p>It cannot be a global variable. Container is an idea, not a thing.</p>\n\n<p>As you have it designed, that idea i... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4770/"
] | I have a class declared as follows:
```
Public MustInherit Container(Of T As {New, BaseClass}) Inherits ArrayList(Of T)
```
I have classes that inherit this class.
I have another class that I must pass instances in this method:
```
Public Sub LoadCollection(Of T As {BaseClass, New})(ByRef Collection As Container(Of T))
```
I need to store the passed in object in a global variable, but i can't simply declare it:
```
Private _Container as Collection(Of BaseClass)
```
What is the syntax to declare this object? | Sorry haven't got time to expand on this right now, but I think [this link](http://rasor.wordpress.com/2008/08/19/cast-a-generic-list-c/) describes your underlying problem and a solution.
(You might also find [this](http://blogs.msdn.com/lucian/archive/2008/10/02/co-and-contra-variance-how-do-i-convert-a-list-of-apple-into-a-list-of-fruit.aspx) interesting.) |
134,731 | <p>Whilst refactoring some code I came across some getter methods that returns a std::string. Something like this for example:</p>
<pre><code>class foo
{
private:
std::string name_;
public:
std::string name()
{
return name_;
}
};
</code></pre>
<p>Surely the getter would be better returning a <code>const std::string&</code>? The current method is returning a copy which isn't as efficient. Would returning a const reference instead cause any problems?</p>
| [
{
"answer_id": 134743,
"author": "Kristopher Johnson",
"author_id": 1175,
"author_profile": "https://Stackoverflow.com/users/1175",
"pm_score": 2,
"selected": false,
"text": "<p>I'd change it to return const std::string&. The caller will probably make a copy of the result anyway if ... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] | Whilst refactoring some code I came across some getter methods that returns a std::string. Something like this for example:
```
class foo
{
private:
std::string name_;
public:
std::string name()
{
return name_;
}
};
```
Surely the getter would be better returning a `const std::string&`? The current method is returning a copy which isn't as efficient. Would returning a const reference instead cause any problems? | The only way this can cause a problem is if the caller stores the reference, rather than copy the string, and tries to use it after the object is destroyed. Like this:
```
foo *pFoo = new foo;
const std::string &myName = pFoo->getName();
delete pFoo;
cout << myName; // error! dangling reference
```
However, since your existing function returns a copy, then you would
not break any of the existing code.
**Edit:** Modern C++ (i. e. C++11 and up) supports [Return Value Optimization](https://en.wikipedia.org/wiki/Copy_elision), so returning things by value is no longer frowned upon. One should still be mindful of returning extremely large objects by value, but in most cases it should be ok. |
134,742 | <p>I have a data table with a variable number of columns and a data scroller. How can I enable server side sorting? I prefer that it be fired by the user clicking the column header.</p>
<pre><code><rich:datascroller for="instanceList" actionListener="#{pageDataModel.pageChange}"/>
<rich:dataTable id="instanceList" rows="10" value="#{pageDataModel}"
var="fieldValues" rowKeyVar="rowKey">
<rich:columns value="#{pageDataModel.columnNames}" var="column" index="idx">
<f:facet name="header">
<h:outputText value="#{column}"/>
</f:facet>
<h:outputText value="#{classFieldValues[idx]}" />
</rich:columns>
</rich:dataTable>
</code></pre>
<p>I already have a method on the bean for executing the sort.</p>
<pre><code>public void sort(int column)
</code></pre>
| [
{
"answer_id": 135958,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 4,
"selected": true,
"text": "<p>I ended up doing it manually. I adding a support tag to the header text tag, like so.</p>\n\n<pre><code><h:outputText v... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] | I have a data table with a variable number of columns and a data scroller. How can I enable server side sorting? I prefer that it be fired by the user clicking the column header.
```
<rich:datascroller for="instanceList" actionListener="#{pageDataModel.pageChange}"/>
<rich:dataTable id="instanceList" rows="10" value="#{pageDataModel}"
var="fieldValues" rowKeyVar="rowKey">
<rich:columns value="#{pageDataModel.columnNames}" var="column" index="idx">
<f:facet name="header">
<h:outputText value="#{column}"/>
</f:facet>
<h:outputText value="#{classFieldValues[idx]}" />
</rich:columns>
</rich:dataTable>
```
I already have a method on the bean for executing the sort.
```
public void sort(int column)
``` | I ended up doing it manually. I adding a support tag to the header text tag, like so.
```
<h:outputText value="#{column}">
<a4j:support event="onclick" action="#{pageDataModel.sort(idx)}"
eventsQueue="instancesQueue"
reRender="instanceList,instanceListScroller"/>
</h:outputText>
```
To get the ascending/descending arrows, I added a css class.
```
<h:outputText value="#{column}" styleClass="#{pageDataModel.getOrderClass(idx)}" >
<a4j:support event="onclick" action="#{pageDataModel.sort(idx)}"
eventsQueue="instancesQueue"
reRender="instanceList,instanceListScroller"/>
</h:outputText>
``` |
134,796 | <p>I know I can compile individual source files, but sometimes -- say, when editing a header file used by many <code>.cpp</code> files -- multiple source files need to be recompiled. That's what Build is for.</p>
<p>Default behavior of the "Build" command in VC9 (Visual C++ 2008) is to attempt to compile all files that need it. Sometimes this just results in many failed compiles. I usually just watch for errors and hit ctrl-break to stop the build manually.</p>
<p>Is there a way to configure it such the build stops at the <strong>very first compile error</strong> (not the first failed project build) automatically?</p>
| [
{
"answer_id": 134929,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 1,
"selected": false,
"text": "<p>There is <a href=\"http://old.stevenharman.net/blog/archive/2008/01/17/visual-studio-tip-kill-that-build.aspx\" ... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10559/"
] | I know I can compile individual source files, but sometimes -- say, when editing a header file used by many `.cpp` files -- multiple source files need to be recompiled. That's what Build is for.
Default behavior of the "Build" command in VC9 (Visual C++ 2008) is to attempt to compile all files that need it. Sometimes this just results in many failed compiles. I usually just watch for errors and hit ctrl-break to stop the build manually.
Is there a way to configure it such the build stops at the **very first compile error** (not the first failed project build) automatically? | I came up with a better macro guys. It stops immediately after the first error/s (soon as build window is updated).
Visual Studio -> Tools -> Macros -> Macro IDE... (or ALT+F11)
```
Private Sub OutputWindowEvents_OnPaneUpdated(ByVal pPane As OutputWindowPane) Handles OutputWindowEvents.PaneUpdated
If Not (pPane.Name = "Build") Then Exit Sub
pPane.TextDocument.Selection.SelectAll()
Dim Context As String = pPane.TextDocument.Selection.Text
pPane.TextDocument.Selection.EndOfDocument()
Dim found As Integer = Context.IndexOf(": error ")
If found > 0 Then
DTE.ExecuteCommand("Build.Cancel")
End If
End Sub
```
Hope it works out for you guys. |
134,815 | <p>Is there a way to listen for a javascript function to exit? A trigger that could be setup when a function has completed?</p>
<p>I am attempting to use a user interface obfuscation technique (BlockUI) while an AJAX object is retrieving data from the DB, but the function doesn't necessarily execute last, even if you put it at the end of the function call. </p>
<p>Example:</p>
<pre><code>function doStuff() {
blockUI();
ajaxCall();
unblockUI();
};
</code></pre>
<p>Is there a way for doStuff to listen for ajaxCall to complete, before firing the unBlockUI? As it is, it processes the function linearly, calling each object in order, then a separate thread is spawned to complete each one. So, though my AJAX call might take 10-15 seconds to complete, I am only blocking the user for just a split-second, due to the linear execution of the function.</p>
<p>There are less elegant ways around this...putting a loop to end only when a return value set by the AJAX function is set to true, or something of that nature. But that seems unnecessarily complicated and inefficient.</p>
| [
{
"answer_id": 134828,
"author": "jgreep",
"author_id": 16345,
"author_profile": "https://Stackoverflow.com/users/16345",
"pm_score": 1,
"selected": false,
"text": "<p>Your AJAX call should specify a callback function. You can call the unblockUI from within the callback.</p>\n\n<p><a hr... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5405/"
] | Is there a way to listen for a javascript function to exit? A trigger that could be setup when a function has completed?
I am attempting to use a user interface obfuscation technique (BlockUI) while an AJAX object is retrieving data from the DB, but the function doesn't necessarily execute last, even if you put it at the end of the function call.
Example:
```
function doStuff() {
blockUI();
ajaxCall();
unblockUI();
};
```
Is there a way for doStuff to listen for ajaxCall to complete, before firing the unBlockUI? As it is, it processes the function linearly, calling each object in order, then a separate thread is spawned to complete each one. So, though my AJAX call might take 10-15 seconds to complete, I am only blocking the user for just a split-second, due to the linear execution of the function.
There are less elegant ways around this...putting a loop to end only when a return value set by the AJAX function is set to true, or something of that nature. But that seems unnecessarily complicated and inefficient. | However you're accomplishing your Ajax routines, what you need is a "callback" function that will run once it's complete:
```
function ajaxCall(callback){
//do ajax stuff...
callback();
}
```
Then:
```
function doStuff(){
blockUI();
ajaxCall(unblockUI);
}
``` |
134,833 | <p>I have an <em>index.php</em> file which has to process many different file types. How do I guess the filetype based on the <code>REQUEST_URI</code>?</p>
<p>If I request <code>http://site/image.jpg</code>, and all requests redirect through <em>index.php</em>, which looks like this</p>
<pre><code><?php
include('/www/site'.$_SERVER['REQUEST_URI']);
?>
</code></pre>
<p>How would I make that work correctly?</p>
<p>Should I test based on the extension of the file requested, or is there a way to get the filetype?</p>
| [
{
"answer_id": 134893,
"author": "leek",
"author_id": 3765,
"author_profile": "https://Stackoverflow.com/users/3765",
"pm_score": 7,
"selected": true,
"text": "<p>If you are sure you're only ever working with images, you can check out the <a href=\"http://us3.php.net/manual/en/function.e... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/144/"
] | I have an *index.php* file which has to process many different file types. How do I guess the filetype based on the `REQUEST_URI`?
If I request `http://site/image.jpg`, and all requests redirect through *index.php*, which looks like this
```
<?php
include('/www/site'.$_SERVER['REQUEST_URI']);
?>
```
How would I make that work correctly?
Should I test based on the extension of the file requested, or is there a way to get the filetype? | If you are sure you're only ever working with images, you can check out the [exif\_imagetype()](http://us3.php.net/manual/en/function.exif-imagetype.php) PHP function, which attempts to return the image MIME type.
If you don't mind external dependencies, you can also check out the excellent [getID3](http://getid3.sourceforge.net) library which can determine the MIME type of many different file types.
Lastly, you can check out the [mime\_content\_type()](http://us3.php.net/manual/en/function.mime-content-type.php) function - but it has been deprecated for the [Fileinfo](http://us3.php.net/manual/en/ref.fileinfo.php) PECL extension. |
134,834 | <p>This is really the first thing that I have written in python. I come from Java background. I don't want to just learn how to program java code with Python syntax. I want to learn how to program in a pythonic paradigm.</p>
<p>Could you guys please comment on how I can make the following code more pythonic?</p>
<pre><code>from math import sqrt
# recursively computes the factors of a number
def factors(num):
factorList = []
numroot = int(sqrt(num)) + 1
numleft = num
# brute force divide the number until you find a factor
for i in range(2, numroot):
if num % i == 0:
# if we found a factor, add it to the list and compute the remainder
factorList.append(i)
numleft = num / i
break
# if we didn't find a factor, get out of here!
if numleft == num:
factorList.append(num)
return factorList
# now recursively find the rest of the factors
restFactors = factors(numleft)
factorList.extend(restFactors)
return factorList
# grabs all of the twos in the list and puts them into 2 ^ x form
def transformFactorList(factorList):
num2s = 0
# remove all twos, counting them as we go
while 2 in factorList:
factorList.remove(2)
num2s += 1
# simply return the list with the 2's back in the right spot
if num2s == 0: return factorList
if num2s == 1:
factorList.insert(0, 2)
return factorList
factorList.insert(0, '2 ^ ' + str(num2s))
return factorList
print transformFactorList(factors(#some number))
</code></pre>
| [
{
"answer_id": 134946,
"author": "mbac32768",
"author_id": 18446,
"author_profile": "https://Stackoverflow.com/users/18446",
"pm_score": 2,
"selected": false,
"text": "<p>Here's what jumps out at me:</p>\n\n<pre><code>def transformFactorList(factorList):\n oldsize = len(factorList)\n ... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
] | This is really the first thing that I have written in python. I come from Java background. I don't want to just learn how to program java code with Python syntax. I want to learn how to program in a pythonic paradigm.
Could you guys please comment on how I can make the following code more pythonic?
```
from math import sqrt
# recursively computes the factors of a number
def factors(num):
factorList = []
numroot = int(sqrt(num)) + 1
numleft = num
# brute force divide the number until you find a factor
for i in range(2, numroot):
if num % i == 0:
# if we found a factor, add it to the list and compute the remainder
factorList.append(i)
numleft = num / i
break
# if we didn't find a factor, get out of here!
if numleft == num:
factorList.append(num)
return factorList
# now recursively find the rest of the factors
restFactors = factors(numleft)
factorList.extend(restFactors)
return factorList
# grabs all of the twos in the list and puts them into 2 ^ x form
def transformFactorList(factorList):
num2s = 0
# remove all twos, counting them as we go
while 2 in factorList:
factorList.remove(2)
num2s += 1
# simply return the list with the 2's back in the right spot
if num2s == 0: return factorList
if num2s == 1:
factorList.insert(0, 2)
return factorList
factorList.insert(0, '2 ^ ' + str(num2s))
return factorList
print transformFactorList(factors(#some number))
``` | There is an excellent primer by David Goodger called "Code Like a Pythonista" [here](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html). A couple of things from that text re naming (quoting):
* `joined_lower` for functions, methods,
attributes
* `joined_lower` or ALL\_CAPS for
constants
* `StudlyCaps` for classes
* `camelCase` only to conform to
pre-existing conventions |
134,845 | <p>The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function myJsFunc() {
alert("myJsFunc");
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><a href="#" onclick="myJsFunc();">Run JavaScript Code</a></code></pre>
</div>
</div>
</p>
<p>or</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function myJsFunc() {
alert("myJsFunc");
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 134853,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 8,
"selected": false,
"text": "<p><code>'#'</code> will take the user back to the top of the page, so I usually go with <code>void(0)</code>.</p>\n\n<p><... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8018/"
] | The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.?
```js
function myJsFunc() {
alert("myJsFunc");
}
```
```html
<a href="#" onclick="myJsFunc();">Run JavaScript Code</a>
```
or
```js
function myJsFunc() {
alert("myJsFunc");
}
```
```html
<a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>
``` | I use `javascript:void(0)`.
Three reasons. Encouraging the use of `#` amongst a team of developers inevitably leads to some using the return value of the function called like this:
```
function doSomething() {
//Some code
return false;
}
```
But then they forget to use `return doSomething()` in the onclick and just use `doSomething()`.
A second reason for avoiding `#` is that the final `return false;` will not execute if the called function throws an error. Hence the developers have to also remember to handle any error appropriately in the called function.
A third reason is that there are cases where the `onclick` event property is assigned dynamically. I prefer to be able to call a function or assign it dynamically without having to code the function specifically for one method of attachment or another. Hence my `onclick` (or on anything) in HTML markup look like this:
```
onclick="someFunc.call(this)"
```
OR
```
onclick="someFunc.apply(this, arguments)"
```
Using `javascript:void(0)` avoids all of the above headaches, and I haven't found any examples of a downside.
So if you're a lone developer then you can clearly make your own choice, but if you work as a team you have to either state:
Use `href="#"`, make sure `onclick` always contains `return false;` at the end, that any called function does not throw an error and if you attach a function dynamically to the `onclick` property make sure that as well as not throwing an error it returns `false`.
OR
Use `href="javascript:void(0)"`
The second is clearly much easier to communicate. |
134,858 | <p>I have some code I've written in PHP for consuming our simple webservice, which I'd also like to provide in Perl for users who may prefer that language. What's the simplest method of making a HTTP request to do that? In PHP I can do it in one line with <code>file_get_contents()</code>.</p>
<p>Here's the entire code I want to port to Perl:</p>
<pre class="lang-php prettyprint-override"><code>/**
* Makes a remote call to the our API, and returns the response
* @param cmd {string} - command string ID
* @param argsArray {array} - associative array of argument names and argument values
* @return {array} - array of responses
*/
function callAPI( $cmd, $argsArray=array() )
{
$apikey="MY_API_KEY";
$secret="MY_SECRET";
$apiurl="https://foobar.com/api";
// timestamp this API was submitted (for security reasons)
$epoch_time=time();
//--- assemble argument array into string
$query = "cmd=" .$cmd;
foreach ($argsArray as $argName => $argValue) {
$query .= "&" . $argName . "=" . urlencode($argValue);
}
$query .= "&key=". $apikey . "&time=" . $epoch_time;
//--- make md5 hash of the query + secret string
$md5 = md5($query . $secret);
$url = $apiurl . "?" . $query . "&md5=" . $md5;
//--- make simple HTTP GET request, put the server response into $response
$response = file_get_contents($url);
//--- convert "|" (pipe) delimited string to array
$responseArray = explode("|", $response);
return $responseArray;
}
</code></pre>
| [
{
"answer_id": 134884,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at <a href=\"http://search.cpan.org/perldoc?LWP::Simple\" rel=\"noreferrer\">LWP::Simple</a>.\nFor more in... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14569/"
] | I have some code I've written in PHP for consuming our simple webservice, which I'd also like to provide in Perl for users who may prefer that language. What's the simplest method of making a HTTP request to do that? In PHP I can do it in one line with `file_get_contents()`.
Here's the entire code I want to port to Perl:
```php
/**
* Makes a remote call to the our API, and returns the response
* @param cmd {string} - command string ID
* @param argsArray {array} - associative array of argument names and argument values
* @return {array} - array of responses
*/
function callAPI( $cmd, $argsArray=array() )
{
$apikey="MY_API_KEY";
$secret="MY_SECRET";
$apiurl="https://foobar.com/api";
// timestamp this API was submitted (for security reasons)
$epoch_time=time();
//--- assemble argument array into string
$query = "cmd=" .$cmd;
foreach ($argsArray as $argName => $argValue) {
$query .= "&" . $argName . "=" . urlencode($argValue);
}
$query .= "&key=". $apikey . "&time=" . $epoch_time;
//--- make md5 hash of the query + secret string
$md5 = md5($query . $secret);
$url = $apiurl . "?" . $query . "&md5=" . $md5;
//--- make simple HTTP GET request, put the server response into $response
$response = file_get_contents($url);
//--- convert "|" (pipe) delimited string to array
$responseArray = explode("|", $response);
return $responseArray;
}
``` | LWP::Simple:
```
use LWP::Simple;
$contents = get("http://YOUR_URL_HERE");
``` |
134,866 | <p>I have a mindmp file from a target's application crash. Is it possible for me to rebuild the dll/pdb files for a version of software and have windbg load symbols correctly? </p>
<p>My problem is that our pdb files are only kept for major releases (unfortunately). This is a daily build, which I can rebuild myself, but I'm getting tripped up on errors.</p>
<p>With !sym noisy on:
"image header does not match memory image header."</p>
<pre><code>DBGENG: C:\...\XXX.dll image header does not match memory image header.
DBGENG: XXX.dll - Partial symbol image load missing image info
DBGHELP: Module is not fully loaded into memory.
DBGHELP: Searching for symbols using debugger-provided data.
DBGHELP: C:\...\XXX.pdb - mismatched pdb
</code></pre>
<p>Note I've build the pdb with the dll, they are from the same RELEASE directory (should I be building debug?)</p>
<p>Theses are release builds (as release builds are installed on the target and crashing) should I be somehow using the debug build dlls to get more symbol information?</p>
| [
{
"answer_id": 134928,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 4,
"selected": true,
"text": "<p>In my experience probably not.</p>\n\n<p>If you have the exact build directory and build with the <strong>exact same</s... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123/"
] | I have a mindmp file from a target's application crash. Is it possible for me to rebuild the dll/pdb files for a version of software and have windbg load symbols correctly?
My problem is that our pdb files are only kept for major releases (unfortunately). This is a daily build, which I can rebuild myself, but I'm getting tripped up on errors.
With !sym noisy on:
"image header does not match memory image header."
```
DBGENG: C:\...\XXX.dll image header does not match memory image header.
DBGENG: XXX.dll - Partial symbol image load missing image info
DBGHELP: Module is not fully loaded into memory.
DBGHELP: Searching for symbols using debugger-provided data.
DBGHELP: C:\...\XXX.pdb - mismatched pdb
```
Note I've build the pdb with the dll, they are from the same RELEASE directory (should I be building debug?)
Theses are release builds (as release builds are installed on the target and crashing) should I be somehow using the debug build dlls to get more symbol information? | In my experience probably not.
If you have the exact build directory and build with the **exact same** compiler settings then this might work. You definitely will not be able to load symbols from a debug build against a release crash dump.
You will need to turn on the 'load anything' options: .symopt+0x40 to get windbg to ignore the timestamp differences. |
134,882 | <p>How do I easily undo a git rebase? A lengthy manual method is:</p>
<ol>
<li>checkout the commit parent to both of the branches</li>
<li>create and checkout a temporary branch</li>
<li>cherry-pick all commits by hand</li>
<li>reset the faulty rebased branch to point to the temporary branch</li>
</ol>
<p>In my current situation, this works because I can easily spot commits from both branches (one was my stuff, the other was my colleague's stuff). However, my approach strikes me as suboptimal and error-prone (let's say I had just rebased with two of my own branches).</p>
<p>Clarification: I am talking about a rebase during which <em>multiple</em> commits were replayed, not only one.</p>
| [
{
"answer_id": 135614,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 13,
"selected": true,
"text": "<p>The easiest way would be to find the head commit of the branch as it was immediately before the rebase started in the... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6349/"
] | How do I easily undo a git rebase? A lengthy manual method is:
1. checkout the commit parent to both of the branches
2. create and checkout a temporary branch
3. cherry-pick all commits by hand
4. reset the faulty rebased branch to point to the temporary branch
In my current situation, this works because I can easily spot commits from both branches (one was my stuff, the other was my colleague's stuff). However, my approach strikes me as suboptimal and error-prone (let's say I had just rebased with two of my own branches).
Clarification: I am talking about a rebase during which *multiple* commits were replayed, not only one. | The easiest way would be to find the head commit of the branch as it was immediately before the rebase started in the [reflog](https://git-scm.com/docs/git-reflog)...
```
git reflog
```
and to reset the current branch to it (with the usual caveats about being absolutely sure before reseting with the `--hard` option).
Suppose the old commit was `HEAD@{2}` in the ref log:
```
git reset --hard HEAD@{2}
```
*In Windows, you may need to quote the reference:*
```
git reset --hard "HEAD@{2}"
```
You can check the history of the candidate old head by just doing a `git log HEAD@{2}` (*Windows:* `git log "HEAD@{2}"`).
If you've not disabled per branch reflogs you should be able to simply do `git reflog branchname@{1}` as a rebase detaches the branch head before reattaching to the final head. I would double check this, though as I haven't verified this recently.
Per default, all reflogs are activated for non-bare repositories:
```
[core]
logAllRefUpdates = true
``` |
134,885 | <p>I'm looking to use a VBScript variable within a reference to a DOM element for a web-app I'm building. Here's a brief excerpt of the affected area of code:</p>
<pre><code>dim num
num = CInt(document.myform.i.value)
dim x
x = 0
dim orders(num)
For x = 0 To num
orders(x) = document.getElementById("order" & x).value
objFile.writeLine(orders(x))
Next
</code></pre>
<p>This is my first venture into VBScript, and I've not been able to find any methods of performing this type of action online. As you can see in the above code, I'm trying to create an array (orders). This array can have any number of values, but that number will be specified in <code>document.myform.i.value</code>. So the For loop cycles through all text inputs with an ID of order+x (ie, order0, order1, order2, order3, order4, etc. up to num)</p>
<p>It seems to be a problem with my orders(x) line, I don't think it recognizes what I mean by <code>getElementById("order" & x)</code>, and I'm not sure exactly how to do such a thing. Anyone have any suggestions? It would be much appreciated!</p>
| [
{
"answer_id": 134927,
"author": "Dan Williams",
"author_id": 4230,
"author_profile": "https://Stackoverflow.com/users/4230",
"pm_score": 0,
"selected": false,
"text": "<p>I can only assume that this is client side VBScript as document.getElementById() isn't accessible from the server.</... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm looking to use a VBScript variable within a reference to a DOM element for a web-app I'm building. Here's a brief excerpt of the affected area of code:
```
dim num
num = CInt(document.myform.i.value)
dim x
x = 0
dim orders(num)
For x = 0 To num
orders(x) = document.getElementById("order" & x).value
objFile.writeLine(orders(x))
Next
```
This is my first venture into VBScript, and I've not been able to find any methods of performing this type of action online. As you can see in the above code, I'm trying to create an array (orders). This array can have any number of values, but that number will be specified in `document.myform.i.value`. So the For loop cycles through all text inputs with an ID of order+x (ie, order0, order1, order2, order3, order4, etc. up to num)
It seems to be a problem with my orders(x) line, I don't think it recognizes what I mean by `getElementById("order" & x)`, and I'm not sure exactly how to do such a thing. Anyone have any suggestions? It would be much appreciated! | I was able to get this working. Thanks to both of you for your time and input. Here is what solved it for me:
Rather than using
```
document.getElementById("order" & x).value
```
I set the entire ID as a variable:
```
temp = "order" & x
document.getElementById(temp).value
```
It seems to be working as expected. Again, many thanks for the time and effort on this! |
134,887 | <p>After making it through the major parts of an introductory Lisp book, I still couldn't understand what the special operator <code>(quote)</code> (or equivalent <code>'</code>) function does, yet this has been all over Lisp code that I've seen. </p>
<p>What does it do?</p>
| [
{
"answer_id": 134908,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 6,
"selected": false,
"text": "<p>It says \"don't evaluate me\". For example, if you wanted to use a list as data, and not as code, you'd put a qu... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1256/"
] | After making it through the major parts of an introductory Lisp book, I still couldn't understand what the special operator `(quote)` (or equivalent `'`) function does, yet this has been all over Lisp code that I've seen.
What does it do? | **Short answer**
Bypass the default evaluation rules and do *not* evaluate the expression (symbol or s-exp), passing it along to the function exactly as typed.
**Long Answer: The Default Evaluation Rule**
When a regular (I'll come to that later) function is invoked, all arguments passed to it are evaluated. This means you can write this:
```
(* (+ a 2)
3)
```
Which in turn evaluates `(+ a 2)`, by evaluating `a` and 2. The value of the symbol `a` is looked up in the current variable binding set, and then replaced. Say `a` is currently bound to the value 3:
```
(let ((a 3))
(* (+ a 2)
3))
```
We'd get `(+ 3 2)`, + is then invoked on 3 and 2 yielding 5. Our original form is now `(* 5 3)` yielding 15.
**Explain `quote` Already!**
Alright. As seen above, all arguments to a function are evaluated, so if you would like to pass the *symbol* `a` and not its value, you don't want to evaluate it. Lisp symbols can double both as their values, and markers where you in other languages would have used strings, such as keys to hash tables.
This is where `quote` comes in. Say you want to plot resource allocations from a Python application, but rather do the plotting in Lisp. Have your Python app do something like this:
```py
print("'(")
while allocating:
if random.random() > 0.5:
print(f"(allocate {random.randint(0, 20)})")
else:
print(f"(free {random.randint(0, 20)})")
...
print(")")
```
Giving you output looking like this (slightly prettyfied):
```
'((allocate 3)
(allocate 7)
(free 14)
(allocate 19)
...)
```
Remember what I said about `quote` ("tick") causing the default rule not to apply? Good. What would otherwise happen is that the values of `allocate` and `free` are looked up, and we don't want that. In our Lisp, we wish to do:
```
(dolist (entry allocation-log)
(case (first entry)
(allocate (plot-allocation (second entry)))
(free (plot-free (second entry)))))
```
For the data given above, the following sequence of function calls would have been made:
```
(plot-allocation 3)
(plot-allocation 7)
(plot-free 14)
(plot-allocation 19)
```
**But What About `list`?**
Well, sometimes you *do* want to evaluate the arguments. Say you have a nifty function manipulating a number and a string and returning a list of the resulting ... things. Let's make a false start:
```
(defun mess-with (number string)
'(value-of-number (1+ number) something-with-string (length string)))
Lisp> (mess-with 20 "foo")
(VALUE-OF-NUMBER (1+ NUMBER) SOMETHING-WITH-STRING (LENGTH STRING))
```
Hey! That's not what we wanted. We want to *selectively* evaluate some arguments, and leave the others as symbols. Try #2!
```
(defun mess-with (number string)
(list 'value-of-number (1+ number) 'something-with-string (length string)))
Lisp> (mess-with 20 "foo")
(VALUE-OF-NUMBER 21 SOMETHING-WITH-STRING 3)
```
**Not Just `quote`, But `backquote`**
Much better! Incidently, this pattern is so common in (mostly) macros, that there is special syntax for doing just that. The backquote:
```
(defun mess-with (number string)
`(value-of-number ,(1+ number) something-with-string ,(length string)))
```
It's like using `quote`, but with the option to explicitly evaluate some arguments by prefixing them with comma. The result is equivalent to using `list`, but if you're generating code from a macro you often only want to evaluate small parts of the code returned, so the backquote is more suited. For shorter lists, `list` can be more readable.
**Hey, You Forgot About `quote`!**
So, where does this leave us? Oh right, what does `quote` actually do? It simply returns its argument(s) unevaluated! Remember what I said in the beginning about regular functions? Turns out that some operators/functions need to *not* evaluate their arguments. Such as IF -- you wouldn't want the else branch to be evaluated if it wasn't taken, right? So-called *special operators*, together with macros, work like that. Special operators are also the "axiom" of the language -- minimal set of rules -- upon which you can implement the rest of Lisp by combining them together in different ways.
Back to `quote`, though:
```
Lisp> (quote spiffy-symbol)
SPIFFY-SYMBOL
Lisp> 'spiffy-symbol ; ' is just a shorthand ("reader macro"), as shown above
SPIFFY-SYMBOL
```
Compare to (on Steel-Bank Common Lisp):
```
Lisp> spiffy-symbol
debugger invoked on a UNBOUND-VARIABLE in thread #<THREAD "initial thread" RUNNING {A69F6A9}>:
The variable SPIFFY-SYMBOL is unbound.
Type HELP for debugger help, or (SB-EXT:QUIT) to exit from SBCL.
restarts (invokable by number or by possibly-abbreviated name):
0: [ABORT] Exit debugger, returning to top level.
(SB-INT:SIMPLE-EVAL-IN-LEXENV SPIFFY-SYMBOL #<NULL-LEXENV>)
0]
```
Because there is no `spiffy-symbol` in the current scope!
**Summing Up**
`quote`, `backquote` (with comma), and `list` are some of the tools you use to create lists, that are not only lists of values, but as you seen can be used as lightweight (no need to define a `struct`) data structures!
If you wish to learn more, I recommend Peter Seibel's book [Practical Common Lisp](http://gigamonkeys.com/book) for a practical approach to learning Lisp, if you're already into programming at large. Eventually on your Lisp journey, you'll start using packages too. Ron Garret's [The Idiot's Guide to Common Lisp Packages](http://www.flownet.com/ron/packages.pdf) will give you good explanation of those.
Happy hacking! |
134,905 | <p>What is the best way to return XML from a controller's action in ASP.NET MVC? There is a nice way to return JSON, but not for XML. Do I really need to route the XML through a View, or should I do the not-best-practice way of Response.Write-ing it?</p>
| [
{
"answer_id": 134982,
"author": "Luke Smith",
"author_id": 5556,
"author_profile": "https://Stackoverflow.com/users/5556",
"pm_score": 8,
"selected": true,
"text": "<p>Use <a href=\"http://www.codeplex.com/MVCContrib\" rel=\"noreferrer\">MVCContrib</a>'s XmlResult Action.</p>\n\n<p>For ... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22299/"
] | What is the best way to return XML from a controller's action in ASP.NET MVC? There is a nice way to return JSON, but not for XML. Do I really need to route the XML through a View, or should I do the not-best-practice way of Response.Write-ing it? | Use [MVCContrib](http://www.codeplex.com/MVCContrib)'s XmlResult Action.
For reference here is their code:
>
>
> ```
> public class XmlResult : ActionResult
> {
> private object objectToSerialize;
>
> /// <summary>
> /// Initializes a new instance of the <see cref="XmlResult"/> class.
> /// </summary>
> /// <param name="objectToSerialize">The object to serialize to XML.</param>
> public XmlResult(object objectToSerialize)
> {
> this.objectToSerialize = objectToSerialize;
> }
>
> /// <summary>
> /// Gets the object to be serialized to XML.
> /// </summary>
> public object ObjectToSerialize
> {
> get { return this.objectToSerialize; }
> }
>
> /// <summary>
> /// Serialises the object that was passed into the constructor to XML and writes the corresponding XML to the result stream.
> /// </summary>
> /// <param name="context">The controller context for the current request.</param>
> public override void ExecuteResult(ControllerContext context)
> {
> if (this.objectToSerialize != null)
> {
> context.HttpContext.Response.Clear();
> var xs = new System.Xml.Serialization.XmlSerializer(this.objectToSerialize.GetType());
> context.HttpContext.Response.ContentType = "text/xml";
> xs.Serialize(context.HttpContext.Response.Output, this.objectToSerialize);
> }
> }
> }
>
> ```
>
> |
134,906 | <p>Is there a command or an existing script that will let me view all of a *NIX system's scheduled cron jobs at once? I'd like it to include all of the user crontabs, as well as <code>/etc/crontab</code>, and whatever's in <code>/etc/cron.d</code>. It would also be nice to see the specific commands run by <code>run-parts</code> in <code>/etc/crontab</code>.</p>
<p>Ideally, I'd like the output in a nice column form and ordered in some meaningful way.</p>
<p>I could then merge these listings from multiple servers to view the overall "schedule of events."</p>
<p>I was about to write such a script myself, but if someone's already gone to the trouble...</p>
| [
{
"answer_id": 134944,
"author": "Kyle Burton",
"author_id": 19784,
"author_profile": "https://Stackoverflow.com/users/19784",
"pm_score": 10,
"selected": false,
"text": "<p>You would have to run this as root, but:</p>\n\n<pre><code>for user in $(cut -f1 -d: /etc/passwd); do crontab -u $... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726/"
] | Is there a command or an existing script that will let me view all of a \*NIX system's scheduled cron jobs at once? I'd like it to include all of the user crontabs, as well as `/etc/crontab`, and whatever's in `/etc/cron.d`. It would also be nice to see the specific commands run by `run-parts` in `/etc/crontab`.
Ideally, I'd like the output in a nice column form and ordered in some meaningful way.
I could then merge these listings from multiple servers to view the overall "schedule of events."
I was about to write such a script myself, but if someone's already gone to the trouble... | I ended up writing a script (I'm trying to teach myself the finer points of bash scripting, so that's why you don't see something like Perl here). It's not exactly a simple affair, but it does most of what I need. It uses Kyle's suggestion for looking up individual users' crontabs, but also deals with `/etc/crontab` (including the scripts launched by `run-parts` in `/etc/cron.hourly`, `/etc/cron.daily`, etc.) and the jobs in the `/etc/cron.d` directory. It takes all of those and merges them into a display something like the following:
```
mi h d m w user command
09,39 * * * * root [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -r -0 rm
47 */8 * * * root rsync -axE --delete --ignore-errors / /mirror/ >/dev/null
17 1 * * * root /etc/cron.daily/apt
17 1 * * * root /etc/cron.daily/aptitude
17 1 * * * root /etc/cron.daily/find
17 1 * * * root /etc/cron.daily/logrotate
17 1 * * * root /etc/cron.daily/man-db
17 1 * * * root /etc/cron.daily/ntp
17 1 * * * root /etc/cron.daily/standard
17 1 * * * root /etc/cron.daily/sysklogd
27 2 * * 7 root /etc/cron.weekly/man-db
27 2 * * 7 root /etc/cron.weekly/sysklogd
13 3 * * * archiver /usr/local/bin/offsite-backup 2>&1
32 3 1 * * root /etc/cron.monthly/standard
36 4 * * * yukon /home/yukon/bin/do-daily-stuff
5 5 * * * archiver /usr/local/bin/update-logs >/dev/null
```
Note that it shows the user, and more-or-less sorts by hour and minute so that I can see the daily schedule.
So far, I've tested it on Ubuntu, Debian, and Red Hat AS.
```sh
#!/bin/bash
# System-wide crontab file and cron job directory. Change these for your system.
CRONTAB='/etc/crontab'
CRONDIR='/etc/cron.d'
# Single tab character. Annoyingly necessary.
tab=$(echo -en "\t")
# Given a stream of crontab lines, exclude non-cron job lines, replace
# whitespace characters with a single space, and remove any spaces from the
# beginning of each line.
function clean_cron_lines() {
while read line ; do
echo "${line}" |
egrep --invert-match '^($|\s*#|\s*[[:alnum:]_]+=)' |
sed --regexp-extended "s/\s+/ /g" |
sed --regexp-extended "s/^ //"
done;
}
# Given a stream of cleaned crontab lines, echo any that don't include the
# run-parts command, and for those that do, show each job file in the run-parts
# directory as if it were scheduled explicitly.
function lookup_run_parts() {
while read line ; do
match=$(echo "${line}" | egrep -o 'run-parts (-{1,2}\S+ )*\S+')
if [[ -z "${match}" ]] ; then
echo "${line}"
else
cron_fields=$(echo "${line}" | cut -f1-6 -d' ')
cron_job_dir=$(echo "${match}" | awk '{print $NF}')
if [[ -d "${cron_job_dir}" ]] ; then
for cron_job_file in "${cron_job_dir}"/* ; do # */ <not a comment>
[[ -f "${cron_job_file}" ]] && echo "${cron_fields} ${cron_job_file}"
done
fi
fi
done;
}
# Temporary file for crontab lines.
temp=$(mktemp) || exit 1
# Add all of the jobs from the system-wide crontab file.
cat "${CRONTAB}" | clean_cron_lines | lookup_run_parts >"${temp}"
# Add all of the jobs from the system-wide cron directory.
cat "${CRONDIR}"/* | clean_cron_lines >>"${temp}" # */ <not a comment>
# Add each user's crontab (if it exists). Insert the user's name between the
# five time fields and the command.
while read user ; do
crontab -l -u "${user}" 2>/dev/null |
clean_cron_lines |
sed --regexp-extended "s/^((\S+ +){5})(.+)$/\1${user} \3/" >>"${temp}"
done < <(cut --fields=1 --delimiter=: /etc/passwd)
# Output the collected crontab lines. Replace the single spaces between the
# fields with tab characters, sort the lines by hour and minute, insert the
# header line, and format the results as a table.
cat "${temp}" |
sed --regexp-extended "s/^(\S+) +(\S+) +(\S+) +(\S+) +(\S+) +(\S+) +(.*)$/\1\t\2\t\3\t\4\t\5\t\6\t\7/" |
sort --numeric-sort --field-separator="${tab}" --key=2,1 |
sed "1i\mi\th\td\tm\tw\tuser\tcommand" |
column -s"${tab}" -t
rm --force "${temp}"
``` |
134,917 | <p>We will need to call out to a 3rd party to retrieve a value using REST, however if we do not receive a response within 10ms, I want to use a default value and continue processing.</p>
<p>I'm leaning towards using an asynchronous WebRequest do to this, but I was wondering if there was a trick to doing it using a synchronous request.</p>
<p>Any advice?</p>
| [
{
"answer_id": 135004,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 2,
"selected": false,
"text": "<p>If you are doing a request and waiting on it to return I'd say stay synchronous - there's no reason to do an async... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | We will need to call out to a 3rd party to retrieve a value using REST, however if we do not receive a response within 10ms, I want to use a default value and continue processing.
I'm leaning towards using an asynchronous WebRequest do to this, but I was wondering if there was a trick to doing it using a synchronous request.
Any advice? | If you are doing a request and waiting on it to return I'd say stay synchronous - there's no reason to do an async request if you're not going to do anything or stay responsive while waiting.
For a sync call:
```
WebRequest request = WebRequest.Create("http://something.somewhere/url");
WebResponse response = null;
request.Timeout = 10000; // 10 second timeout
try
{
response = request.GetResponse();
}
catch(WebException e)
{
if( e.Status == WebExceptionStatus.Timeout)
{
//something
}
}
```
If doing async:
You will have to call Abort() on the request object - you'll need to check the timeout yourself, there's no built-in way to enforce a hard timeout. |
134,934 | <p>How do I display a leading zero for all numbers with less than two digits?</p>
<pre class="lang-none prettyprint-override"><code>1 → 01
10 → 10
100 → 100
</code></pre>
| [
{
"answer_id": 134942,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 6,
"selected": false,
"text": "<pre><code>x = [1, 10, 100]\nfor i in x:\n print '%02d' % i\n</code></pre>\n<p>results in:</p>\n<pre class=\"lang-none p... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22306/"
] | How do I display a leading zero for all numbers with less than two digits?
```none
1 → 01
10 → 10
100 → 100
``` | In Python 2 (and Python 3) you can do:
```
number = 1
print("%02d" % (number,))
```
Basically **%** is like `printf` or `sprintf` (see [docs](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting)).
---
For Python 3.+, the same behavior can also be achieved with [`format`](https://docs.python.org/3/library/stdtypes.html#str.format):
```
number = 1
print("{:02d}".format(number))
```
---
For Python 3.6+ the same behavior can be achieved with [f-strings](https://docs.python.org/3/reference/lexical_analysis.html#f-strings):
```
number = 1
print(f"{number:02d}")
``` |
134,958 | <p>How would I be able to get N results for several groups in
an oracle query.</p>
<p>For example, given the following table:</p>
<pre><code>|--------+------------+------------|
| emp_id | name | occupation |
|--------+------------+------------|
| 1 | John Smith | Accountant |
| 2 | Jane Doe | Engineer |
| 3 | Jack Black | Funnyman |
|--------+------------+------------|
</code></pre>
<p>There are many more rows with more occupations. I would like to get
three employees (lets say) from each occupation.</p>
<p>Is there a way to do this without using a subquery?</p>
| [
{
"answer_id": 135046,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure this is very efficient, but maybe a starting place?</p>\n\n<pre><code>select *\nfrom people p1\n j... | 2008/09/25 | [
"https://Stackoverflow.com/questions/134958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9435/"
] | How would I be able to get N results for several groups in
an oracle query.
For example, given the following table:
```
|--------+------------+------------|
| emp_id | name | occupation |
|--------+------------+------------|
| 1 | John Smith | Accountant |
| 2 | Jane Doe | Engineer |
| 3 | Jack Black | Funnyman |
|--------+------------+------------|
```
There are many more rows with more occupations. I would like to get
three employees (lets say) from each occupation.
Is there a way to do this without using a subquery? | This produces what you want, and it uses no vendor-specific SQL features like TOP N or RANK().
```
SELECT MAX(e.name) AS name, MAX(e.occupation) AS occupation
FROM emp e
LEFT OUTER JOIN emp e2
ON (e.occupation = e2.occupation AND e.emp_id <= e2.emp_id)
GROUP BY e.emp_id
HAVING COUNT(*) <= 3
ORDER BY occupation;
```
In this example it gives the three employees with the lowest emp\_id values per occupation. You can change the attribute used in the inequality comparison, to make it give the top employees by name, or whatever. |
135,000 | <p>When generating XML from XmlDocument in .NET, a blank <code>xmlns</code> attribute appears the first time an element <em>without</em> an associated namespace is inserted; how can this be prevented?</p>
<p>Example:</p>
<pre><code>XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateElement("root",
"whatever:name-space-1.0"));
xml.DocumentElement.AppendChild(xml.CreateElement("loner"));
Console.WriteLine(xml.OuterXml);
</code></pre>
<p>Output:</p>
<pre><code><root xmlns="whatever:name-space-1.0"><loner xmlns="" /></root>
</code></pre>
<p><em>Desired</em> Output:</p>
<pre><code><root xmlns="whatever:name-space-1.0"><loner /></root>
</code></pre>
<p>Is there a solution applicable to the <code>XmlDocument</code> code, not something that occurs <em>after</em> converting the document to a string with <code>OuterXml</code>?</p>
<p>My reasoning for doing this is to see if I can match the standard XML of a particular protocol using XmlDocument-generated XML. The blank <code>xmlns</code> attribute <em>may</em> not break or confuse a parser, but it's also not present in any usage that I've seen of this protocol.</p>
| [
{
"answer_id": 135027,
"author": "JeniT",
"author_id": 6739,
"author_profile": "https://Stackoverflow.com/users/6739",
"pm_score": 4,
"selected": false,
"text": "<p>If the <code><loner></code> element in your sample XML didn't have the <code>xmlns</code> default namespace declarati... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9642/"
] | When generating XML from XmlDocument in .NET, a blank `xmlns` attribute appears the first time an element *without* an associated namespace is inserted; how can this be prevented?
Example:
```
XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateElement("root",
"whatever:name-space-1.0"));
xml.DocumentElement.AppendChild(xml.CreateElement("loner"));
Console.WriteLine(xml.OuterXml);
```
Output:
```
<root xmlns="whatever:name-space-1.0"><loner xmlns="" /></root>
```
*Desired* Output:
```
<root xmlns="whatever:name-space-1.0"><loner /></root>
```
Is there a solution applicable to the `XmlDocument` code, not something that occurs *after* converting the document to a string with `OuterXml`?
My reasoning for doing this is to see if I can match the standard XML of a particular protocol using XmlDocument-generated XML. The blank `xmlns` attribute *may* not break or confuse a parser, but it's also not present in any usage that I've seen of this protocol. | Thanks to Jeremy Lew's answer and a bit more playing around, I figured out how to remove blank `xmlns` attributes: pass in the root node's namespace when creating any child node you want *not* to have a prefix on. Using a namespace without a prefix at the root means that you need to use that same namespace on child elements for them to *also* not have prefixes.
Fixed Code:
```
XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateElement("root", "whatever:name-space-1.0"));
xml.DocumentElement.AppendChild(xml.CreateElement("loner", "whatever:name-space-1.0"));
Console.WriteLine(xml.OuterXml);
```
Thanks everyone to all your answers which led me in the right direction! |
135,010 | <p>I have a problem with stopping a service and starting it again and want to be notified when the process runs and let me know what the result is. </p>
<p>Here's the scenario,
I have a text file output of an "sc" command. I want to send that file but not as an attachment. Also, I want to see the initial status quickly in the subject of the email.</p>
<p>Here's the 'servstop.txt' file contents:</p>
<blockquote>
<p>[SC] StartService FAILED 1058:</p>
<p>The service cannot be started, either
because it is disabled or because it
has no enabled devices associated with
it.</p>
</blockquote>
<p>I want the subject of the email to be "Alert Service Start: [SC] StartService FAILED 1058"
and the body to contain the entire error message above.</p>
<p>I will put my current method in an answer below using a program called blat to send me the result.</p>
| [
{
"answer_id": 135027,
"author": "JeniT",
"author_id": 6739,
"author_profile": "https://Stackoverflow.com/users/6739",
"pm_score": 4,
"selected": false,
"text": "<p>If the <code><loner></code> element in your sample XML didn't have the <code>xmlns</code> default namespace declarati... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
] | I have a problem with stopping a service and starting it again and want to be notified when the process runs and let me know what the result is.
Here's the scenario,
I have a text file output of an "sc" command. I want to send that file but not as an attachment. Also, I want to see the initial status quickly in the subject of the email.
Here's the 'servstop.txt' file contents:
>
> [SC] StartService FAILED 1058:
>
>
> The service cannot be started, either
> because it is disabled or because it
> has no enabled devices associated with
> it.
>
>
>
I want the subject of the email to be "Alert Service Start: [SC] StartService FAILED 1058"
and the body to contain the entire error message above.
I will put my current method in an answer below using a program called blat to send me the result. | Thanks to Jeremy Lew's answer and a bit more playing around, I figured out how to remove blank `xmlns` attributes: pass in the root node's namespace when creating any child node you want *not* to have a prefix on. Using a namespace without a prefix at the root means that you need to use that same namespace on child elements for them to *also* not have prefixes.
Fixed Code:
```
XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateElement("root", "whatever:name-space-1.0"));
xml.DocumentElement.AppendChild(xml.CreateElement("loner", "whatever:name-space-1.0"));
Console.WriteLine(xml.OuterXml);
```
Thanks everyone to all your answers which led me in the right direction! |
135,020 | <p>When creating a class that has internal private methods, usually to reduce code duplication, that don't require the use of any instance fields, are there performance or memory advantages to declaring the method as static?</p>
<p>Example:</p>
<pre><code>foreach (XmlElement element in xmlDoc.DocumentElement.SelectNodes("sample"))
{
string first = GetInnerXml(element, ".//first");
string second = GetInnerXml(element, ".//second");
string third = GetInnerXml(element, ".//third");
}
</code></pre>
<p>...</p>
<pre><code>private static string GetInnerXml(XmlElement element, string nodeName)
{
return GetInnerXml(element, nodeName, null);
}
private static string GetInnerXml(XmlElement element, string nodeName, string defaultValue)
{
XmlNode node = element.SelectSingleNode(nodeName);
return node == null ? defaultValue : node.InnerXml;
}
</code></pre>
<p>Is there any advantage to declaring the GetInnerXml() methods as static? No opinion responses please, I have an opinion.</p>
| [
{
"answer_id": 135023,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 4,
"selected": false,
"text": "<p>Yes, the compiler does not need to pass the implicit <code>this</code> pointer to <code>static</code> methods. Even... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6146/"
] | When creating a class that has internal private methods, usually to reduce code duplication, that don't require the use of any instance fields, are there performance or memory advantages to declaring the method as static?
Example:
```
foreach (XmlElement element in xmlDoc.DocumentElement.SelectNodes("sample"))
{
string first = GetInnerXml(element, ".//first");
string second = GetInnerXml(element, ".//second");
string third = GetInnerXml(element, ".//third");
}
```
...
```
private static string GetInnerXml(XmlElement element, string nodeName)
{
return GetInnerXml(element, nodeName, null);
}
private static string GetInnerXml(XmlElement element, string nodeName, string defaultValue)
{
XmlNode node = element.SelectSingleNode(nodeName);
return node == null ? defaultValue : node.InnerXml;
}
```
Is there any advantage to declaring the GetInnerXml() methods as static? No opinion responses please, I have an opinion. | From the [FxCop rule page](http://msdn.microsoft.com/en-us/library/ms245046.aspx) on this:
>
> After you mark the methods as static, the compiler will emit non-virtual call sites to these members. Emitting non-virtual call sites will prevent a check at runtime for each call that ensures that the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.
>
>
> |
135,035 | <p>In ruby the library path is provided in <code>$:</code>, in perl it's in <code>@INC</code> - how do you get the list of paths that Python searches for modules when you do an import?</p>
| [
{
"answer_id": 135050,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<pre><code>import sys\nsys.path\n</code></pre>\n"
},
{
"answer_id": 135051,
"author": "Jack M.",
"auth... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19784/"
] | In ruby the library path is provided in `$:`, in perl it's in `@INC` - how do you get the list of paths that Python searches for modules when you do an import? | I think you're looking for [sys.path](https://docs.python.org/3/library/sys.html#sys.path)
```
import sys
print (sys.path)
``` |
135,041 | <p>Why or why not?</p>
| [
{
"answer_id": 135070,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 4,
"selected": false,
"text": "<p><code>xrange()</code> is more efficient because instead of generating a list of objects, it just generates one object ... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18446/"
] | Why or why not? | For performance, especially when you're iterating over a large range, `xrange()` is usually better. However, there are still a few cases why you might prefer `range()`:
* In python 3, `range()` does what `xrange()` used to do and `xrange()` does not exist. If you want to write code that will run on both Python 2 and Python 3, you can't use `xrange()`.
* `range()` can actually be faster in some cases - eg. if iterating over the same sequence multiple times. `xrange()` has to reconstruct the integer object every time, but `range()` will have real integer objects. (It will always perform worse in terms of memory however)
* `xrange()` isn't usable in all cases where a real list is needed. For instance, it doesn't support slices, or any list methods.
[Edit] There are a couple of posts mentioning how `range()` will be upgraded by the 2to3 tool. For the record, here's the output of running the tool on some sample usages of `range()` and `xrange()`
```
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: ws_comma
--- range_test.py (original)
+++ range_test.py (refactored)
@@ -1,7 +1,7 @@
for x in range(20):
- a=range(20)
+ a=list(range(20))
b=list(range(20))
c=[x for x in range(20)]
d=(x for x in range(20))
- e=xrange(20)
+ e=range(20)
```
As you can see, when used in a for loop or comprehension, or where already wrapped with list(), range is left unchanged. |
135,069 | <p>This may be a matter of style, but there's a bit of a divide in our dev team and I wondered if anyone else had any ideas on the matter...</p>
<p>Basically, we have some debug print statements which we turn off during normal development. Personally I prefer to do the following:</p>
<pre><code>//---- SomeSourceFile.cpp ----
#define DEBUG_ENABLED (0)
...
SomeFunction()
{
int someVariable = 5;
#if(DEBUG_ENABLED)
printf("Debugging: someVariable == %d", someVariable);
#endif
}
</code></pre>
<p>Some of the team prefer the following though:</p>
<pre><code>// #define DEBUG_ENABLED
...
SomeFunction()
{
int someVariable = 5;
#ifdef DEBUG_ENABLED
printf("Debugging: someVariable == %d", someVariable);
#endif
}
</code></pre>
<p>...which of those methods sounds better to you and why? My feeling is that the first is safer because there is always something defined and there's no danger it could destroy other defines elsewhere.</p>
| [
{
"answer_id": 135077,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 3,
"selected": false,
"text": "<p><code>#if</code> gives you the option of setting it to 0 to turn off the functionality, while still detecting th... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15369/"
] | This may be a matter of style, but there's a bit of a divide in our dev team and I wondered if anyone else had any ideas on the matter...
Basically, we have some debug print statements which we turn off during normal development. Personally I prefer to do the following:
```
//---- SomeSourceFile.cpp ----
#define DEBUG_ENABLED (0)
...
SomeFunction()
{
int someVariable = 5;
#if(DEBUG_ENABLED)
printf("Debugging: someVariable == %d", someVariable);
#endif
}
```
Some of the team prefer the following though:
```
// #define DEBUG_ENABLED
...
SomeFunction()
{
int someVariable = 5;
#ifdef DEBUG_ENABLED
printf("Debugging: someVariable == %d", someVariable);
#endif
}
```
...which of those methods sounds better to you and why? My feeling is that the first is safer because there is always something defined and there's no danger it could destroy other defines elsewhere. | My initial reaction was *`#ifdef`, of course*, but I think `#if` actually has some significant advantages for this - here's why:
First, you can use `DEBUG_ENABLED` in preprocessor *and* compiled tests. Example - Often, I want longer timeouts when debug is enabled, so using `#if`, I can write this
```
DoSomethingSlowWithTimeout(DEBUG_ENABLED? 5000 : 1000);
```
... instead of ...
```
#ifdef DEBUG_MODE
DoSomethingSlowWithTimeout(5000);
#else
DoSomethingSlowWithTimeout(1000);
#endif
```
Second, you're in a better position if you want to migrate from a `#define` to a global constant. `#define`s are usually frowned on by most C++ programmers.
And, Third, you say you've a divide in your team. My guess is this means different members have already adopted different approaches, and you need to standardise. Ruling that `#if` is the preferred choice means that code using `#ifdef` will compile -and run- even when `DEBUG_ENABLED` is false. And it's *much* easier to track down and remove debug output that is produced when it shouldn't be than vice-versa.
Oh, and a minor readability point. You should be able to use true/false rather than 0/1 in your `#define`, and because the value is a single lexical token, it's the one time you don't need parentheses around it.
```
#define DEBUG_ENABLED true
```
instead of
```
#define DEBUG_ENABLED (1)
``` |
135,076 | <p>I am <strong>losing hair</strong> on this one ... it seems that when I fix width an HTML SELECT control it renders its width differently depending on the browser. </p>
<p>Any idea how to to standardize this without having to turn to multiple style sheets?</p>
<p>Here is what I am working with:</p>
<pre><code>.combo
{
padding: 2px;
width: 200px;
}
.text
{
padding: 2px;
width: 200px;
}
</code></pre>
<p>This is my document type for the page:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
</code></pre>
| [
{
"answer_id": 135083,
"author": "Steve Paulo",
"author_id": 9414,
"author_profile": "https://Stackoverflow.com/users/9414",
"pm_score": 1,
"selected": false,
"text": "<p>Make sure you remove all default margins and padding, and define them explicitly. Make sure you're using a proper DOC... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768/"
] | I am **losing hair** on this one ... it seems that when I fix width an HTML SELECT control it renders its width differently depending on the browser.
Any idea how to to standardize this without having to turn to multiple style sheets?
Here is what I am working with:
```
.combo
{
padding: 2px;
width: 200px;
}
.text
{
padding: 2px;
width: 200px;
}
```
This is my document type for the page:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
``` | Form controls will always be less obedient to styling attempts,in particular selects and file inputs, so the only way to reliably style them cross-browser and with future-proofing in mind, is to replace them with JavaScript or Flash and mimic their functionality |
135,105 | <p>We'd like to override DataGridView's default behavior when using a mouse wheel with this control. By default, the DataGridView scrolls a number of rows equal the SystemInformation.MouseWheelScrollLines setting. What we'd like to do is scroll just one item at a time. </p>
<p>(We display images in the DataGridView, which are somewhat large. Because of this scroll three rows (a typical system setting) is too much, often causing the user to scroll to items they can't even see.)</p>
<p>I've tried a couple things already and haven't had much success so far. Here are some issues I've run into:</p>
<ol>
<li><p>You can subscribe to MouseWheel events but there's no way to mark the event as handled and do my own thing.</p></li>
<li><p>You can override OnMouseWheel but this never appears to be called.</p></li>
<li><p>You might be able to correct this in the base scrolling code but it sounds like a messy job since other types of scrolling (e.g. using the keyboard) come through the same pipeline.</p></li>
</ol>
<p>Anyone have a good suggestion?</p>
<p>Here's the final code, using the wonderful answer given:</p>
<pre><code> /// <summary>
/// Handle the mouse wheel manually due to the fact that we display
/// images, which don't work well when you scroll by more than one
/// item at a time.
/// </summary>
///
/// <param name="sender">
/// sender
/// </param>
/// <param name="e">
/// the mouse event
/// </param>
private void mImageDataGrid_MouseWheel(object sender, MouseEventArgs e)
{
// Hack alert! Through reflection, we know that the passed
// in event argument is actually a handled mouse event argument,
// allowing us to handle this event ourselves.
// See http://tinyurl.com/54o7lc for more info.
HandledMouseEventArgs handledE = (HandledMouseEventArgs) e;
handledE.Handled = true;
// Do the scrolling manually. Move just one row at a time.
int rowIndex = mImageDataGrid.FirstDisplayedScrollingRowIndex;
mImageDataGrid.FirstDisplayedScrollingRowIndex =
e.Delta < 0 ?
Math.Min(rowIndex + 1, mImageDataGrid.RowCount - 1):
Math.Max(rowIndex - 1, 0);
}
</code></pre>
| [
{
"answer_id": 135516,
"author": "ZeroBugBounce",
"author_id": 11314,
"author_profile": "https://Stackoverflow.com/users/11314",
"pm_score": 1,
"selected": false,
"text": "<p>I would subclass the DataGridView into my own custom control (you know, add a new Windows Forms --> Custom Contro... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7357/"
] | We'd like to override DataGridView's default behavior when using a mouse wheel with this control. By default, the DataGridView scrolls a number of rows equal the SystemInformation.MouseWheelScrollLines setting. What we'd like to do is scroll just one item at a time.
(We display images in the DataGridView, which are somewhat large. Because of this scroll three rows (a typical system setting) is too much, often causing the user to scroll to items they can't even see.)
I've tried a couple things already and haven't had much success so far. Here are some issues I've run into:
1. You can subscribe to MouseWheel events but there's no way to mark the event as handled and do my own thing.
2. You can override OnMouseWheel but this never appears to be called.
3. You might be able to correct this in the base scrolling code but it sounds like a messy job since other types of scrolling (e.g. using the keyboard) come through the same pipeline.
Anyone have a good suggestion?
Here's the final code, using the wonderful answer given:
```
/// <summary>
/// Handle the mouse wheel manually due to the fact that we display
/// images, which don't work well when you scroll by more than one
/// item at a time.
/// </summary>
///
/// <param name="sender">
/// sender
/// </param>
/// <param name="e">
/// the mouse event
/// </param>
private void mImageDataGrid_MouseWheel(object sender, MouseEventArgs e)
{
// Hack alert! Through reflection, we know that the passed
// in event argument is actually a handled mouse event argument,
// allowing us to handle this event ourselves.
// See http://tinyurl.com/54o7lc for more info.
HandledMouseEventArgs handledE = (HandledMouseEventArgs) e;
handledE.Handled = true;
// Do the scrolling manually. Move just one row at a time.
int rowIndex = mImageDataGrid.FirstDisplayedScrollingRowIndex;
mImageDataGrid.FirstDisplayedScrollingRowIndex =
e.Delta < 0 ?
Math.Min(rowIndex + 1, mImageDataGrid.RowCount - 1):
Math.Max(rowIndex - 1, 0);
}
``` | I just did a little scrounging and testing of my own. I used [Reflector](http://www.red-gate.com/products/reflector/) to investigate and discovered a couple things. The `MouseWheel` event provides a `MouseEventArgs` parameter, but the `OnMouseWheel()` override in `DataGridView` casts it to **`Handled`**`MouseEventArgs`. This also works when handling the `MouseWheel` event. `OnMouseWheel()` does indeed get called, and it is in `DataGridView`'s override that it uses `SystemInformation.MouseWheelScrollLines`.
So:
1. You could indeed handle the `MouseWheel` event, casting `MouseEventArgs` to `HandledMouseEventArgs` and set `Handled = true`, then do what you want.
2. Subclass `DataGridView`, override `OnMouseWheel()` yourself, and try to recreate all the code I read here in [Reflector](http://www.red-gate.com/products/reflector/) except for replacing `SystemInformation.MouseWheelScrollLines` with `1`.
The latter would be a huge pain because it uses a number of private variables (including references to the `ScrollBar`s) and you'd have replace some with your own and get/set others using Reflection. |
135,121 | <p>So in my documentation it says:</p>
<blockquote>
<p>public event TreeViewPlusNodeCheckedEventHandler NodeChecked()</p>
<p>You can use this event to run cause a method to run whenever the
check-box for a node is checked on the tree.</p>
</blockquote>
<p>So how do I add a method to my code behind file that will run when a node is checked? The method I want to run is:</p>
<pre><code>protected void TOCNodeCheckedServer(object sender, TreeViewPlusNodeEventArgs args)
{
TreeViewPlusNode aNode = args.Node;
if (!aNode.Checked)
return;
List<string> BaseLayers = new List<string>();
_arcTOCConfig.BaseDataLayers.CopyTo(BaseLayers);
List<MapResourceItem> mapResources = new List<MapResourceItem>();
if (BaseLayers.Contains(aNode.Text))
{
foreach (BaseDataLayerElement anEl in _arcTOCConfig.BaseDataLayers)
{
if (!aNode.Text.Equals(anEl.Name))
{
if (aNode.TreeViewPlus.Nodes.FindByValue(anEl.Name).Checked)
{
aNode.TreeViewPlus.Nodes.FindByValue(anEl.Name).Checked = false;
aNode.TreeViewPlus.Nodes.FindByValue(anEl.Name).Refresh();
MapResourceItem aMapResource = this.Map1.MapResourceManagerInstance.ResourceItems.Find(anEl.Name);
aMapResource.DisplaySettings.Visible = false;
this.Map1.RefreshResource(anEl.Name);
mapResources.Add(aMapResource);
this.Map1.MapResourceManagerInstance.ResourceItems.Remove(aMapResource);
}
else
{
MapResourceItem aMapResource = this.Map1.MapResourceManagerInstance.ResourceItems.Find(anEl.Name);
mapResources.Add(aMapResource);
this.Map1.MapResourceManagerInstance.ResourceItems.Remove(aMapResource);
}
}
}
foreach (MapResourceItem aMapResource in mapResources)
{
int count = this.Map1.MapResourceManagerInstance.ResourceItems.Count - 1;
this.Map1.MapResourceManagerInstance.ResourceItems.Insert(count, aMapResource);
this.Map1.MapResourceManagerInstance.CreateResource(aMapResource);
}
this.Map1.InitializeFunctionalities();
this.Map1.Refresh();
}
}
</code></pre>
<p>vs 2008
c#
.net 3.5</p>
| [
{
"answer_id": 135137,
"author": "DaveK",
"author_id": 4244,
"author_profile": "https://Stackoverflow.com/users/4244",
"pm_score": 4,
"selected": true,
"text": "<p>You need to assign a delegate to the event and have it run the method you want. Something like :</p>\n\n<p>TreeViewControl.N... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5234/"
] | So in my documentation it says:
>
> public event TreeViewPlusNodeCheckedEventHandler NodeChecked()
>
>
> You can use this event to run cause a method to run whenever the
> check-box for a node is checked on the tree.
>
>
>
So how do I add a method to my code behind file that will run when a node is checked? The method I want to run is:
```
protected void TOCNodeCheckedServer(object sender, TreeViewPlusNodeEventArgs args)
{
TreeViewPlusNode aNode = args.Node;
if (!aNode.Checked)
return;
List<string> BaseLayers = new List<string>();
_arcTOCConfig.BaseDataLayers.CopyTo(BaseLayers);
List<MapResourceItem> mapResources = new List<MapResourceItem>();
if (BaseLayers.Contains(aNode.Text))
{
foreach (BaseDataLayerElement anEl in _arcTOCConfig.BaseDataLayers)
{
if (!aNode.Text.Equals(anEl.Name))
{
if (aNode.TreeViewPlus.Nodes.FindByValue(anEl.Name).Checked)
{
aNode.TreeViewPlus.Nodes.FindByValue(anEl.Name).Checked = false;
aNode.TreeViewPlus.Nodes.FindByValue(anEl.Name).Refresh();
MapResourceItem aMapResource = this.Map1.MapResourceManagerInstance.ResourceItems.Find(anEl.Name);
aMapResource.DisplaySettings.Visible = false;
this.Map1.RefreshResource(anEl.Name);
mapResources.Add(aMapResource);
this.Map1.MapResourceManagerInstance.ResourceItems.Remove(aMapResource);
}
else
{
MapResourceItem aMapResource = this.Map1.MapResourceManagerInstance.ResourceItems.Find(anEl.Name);
mapResources.Add(aMapResource);
this.Map1.MapResourceManagerInstance.ResourceItems.Remove(aMapResource);
}
}
}
foreach (MapResourceItem aMapResource in mapResources)
{
int count = this.Map1.MapResourceManagerInstance.ResourceItems.Count - 1;
this.Map1.MapResourceManagerInstance.ResourceItems.Insert(count, aMapResource);
this.Map1.MapResourceManagerInstance.CreateResource(aMapResource);
}
this.Map1.InitializeFunctionalities();
this.Map1.Refresh();
}
}
```
vs 2008
c#
.net 3.5 | You need to assign a delegate to the event and have it run the method you want. Something like :
TreeViewControl.NodeChecked += new TreeViewPlusNodeCheckedEventHandler(TOCNodeCheckedServer) |
135,132 | <p>I'm really baffled by this - I know how to do this in VB, unmanaged C++ and C# but for some reason I can't accept a ref variable of a managed type in C++. I'm sure there's a simple answer, really - but here's the C# equivalent:</p>
<pre><code>myClass.myFunction(ref variableChangedByfunction);
</code></pre>
<p>I've tried C++ pointers - no dice. I've tried ref keywords. No dice. I tried the <code>[out]</code> keyword. Didn't work.</p>
<p>I can't find any documentation that clearly explains my problem, either.</p>
| [
{
"answer_id": 135135,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>Use a ^ instead of a *</p>\n"
},
{
"answer_id": 135404,
"author": "Community",
"author_id": -1,
... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm really baffled by this - I know how to do this in VB, unmanaged C++ and C# but for some reason I can't accept a ref variable of a managed type in C++. I'm sure there's a simple answer, really - but here's the C# equivalent:
```
myClass.myFunction(ref variableChangedByfunction);
```
I've tried C++ pointers - no dice. I've tried ref keywords. No dice. I tried the `[out]` keyword. Didn't work.
I can't find any documentation that clearly explains my problem, either. | Turns out in the function declaration you need to use a % after the parameter name:
bool Importer::GetBodyChunk(String^% BodyText, String^% ChunkText)
And then you pass in the variable per usual. |
135,151 | <p>The .NET web system I'm working on allows the end user to input HTML formatted text in some situations. In some of those places, we want to leave all the tags, but strip off any trailing break tags (but leave any breaks inside the body of the text.)</p>
<p>What's the best way to do this? (I can think of ways to do this, but I'm sure they're not the best.)</p>
| [
{
"answer_id": 135161,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 2,
"selected": false,
"text": "<p>You can use a regex to find and remove the text with the regex match set to anchor at the end of the string.</p... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
] | The .NET web system I'm working on allows the end user to input HTML formatted text in some situations. In some of those places, we want to leave all the tags, but strip off any trailing break tags (but leave any breaks inside the body of the text.)
What's the best way to do this? (I can think of ways to do this, but I'm sure they're not the best.) | As @[Mitch](https://stackoverflow.com/questions/135151#135161) said,
```
// using System.Text.RegularExpressions;
/// <summary>
/// Regular expression built for C# on: Thu, Sep 25, 2008, 02:01:36 PM
/// Using Expresso Version: 2.1.2150, http://www.ultrapico.com
///
/// A description of the regular expression:
///
/// Match expression but don't capture it. [\<br\s*/?\>], any number of repetitions
/// \<br\s*/?\>
/// <
/// br
/// Whitespace, any number of repetitions
/// /, zero or one repetitions
/// >
/// End of line or string
///
///
/// </summary>
public static Regex regex = new Regex(
@"(?:\<br\s*/?\>)*$",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
regex.Replace(text, string.Empty);
``` |
135,173 | <p>I have a table that holds only two columns - a ListID and PersonID. When a person is merged with another in the system, I was to update all references from the "source" person to be references to the "destination" person.</p>
<p>Ideally, I would like to call something simple like</p>
<pre><code>UPDATE MailingListSubscription
SET PersonID = @DestPerson
WHERE PersonID = @SourcePerson
</code></pre>
<p>However, if the destination person already exists in this table with the same ListID as the source person, a duplicate entry will be made. How can I perform this action without creating duplicated entries? (ListID, PersonID is the primary key)</p>
<p>EDIT: Multiple ListIDs are used. If SourcePerson is assigned to ListIDs 1, 2, and 3, and DestinationPerson is assigned to ListIDs 3 and 4, then the end result needs to have four rows - DestinationPerson assigned to ListID 1, 2, 3, and 4.</p>
| [
{
"answer_id": 135252,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": true,
"text": "<pre><code>--out with the bad\nDELETE\nFROM MailingListSubscription\nWHERE PersonId = @SourcePerson\n and ListID in (SELECT Li... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3259/"
] | I have a table that holds only two columns - a ListID and PersonID. When a person is merged with another in the system, I was to update all references from the "source" person to be references to the "destination" person.
Ideally, I would like to call something simple like
```
UPDATE MailingListSubscription
SET PersonID = @DestPerson
WHERE PersonID = @SourcePerson
```
However, if the destination person already exists in this table with the same ListID as the source person, a duplicate entry will be made. How can I perform this action without creating duplicated entries? (ListID, PersonID is the primary key)
EDIT: Multiple ListIDs are used. If SourcePerson is assigned to ListIDs 1, 2, and 3, and DestinationPerson is assigned to ListIDs 3 and 4, then the end result needs to have four rows - DestinationPerson assigned to ListID 1, 2, 3, and 4. | ```
--out with the bad
DELETE
FROM MailingListSubscription
WHERE PersonId = @SourcePerson
and ListID in (SELECT ListID FROM MailingListSubscription WHERE PersonID = @DestPerson)
--update the rest (good)
UPDATE MailingListSubscription
SET PersonId = @DestPerson
WHERE PersonId = @SourcePerson
``` |
135,186 | <p>I have a project at work the requires me to be able to enter information into a web page, read the next page I get redirected to and then take further action. A simplified real-world example would be something like going to google.com, entering "Coding tricks" as search criteria, and reading the resulting page.</p>
<p>Small coding examples like the ones linked to at <a href="http://www.csharp-station.com/HowTo/HttpWebFetch.aspx" rel="nofollow noreferrer">http://www.csharp-station.com/HowTo/HttpWebFetch.aspx</a> tell how to read a web page, but not how to interact with it by submitting information into a form and continuing on to the next page.</p>
<p>For the record, I'm not building a malicious and/or spam related product.</p>
<p>So how do I go read web pages that require a few steps of normal browsing to reach first?</p>
| [
{
"answer_id": 135231,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>What you need to do is keep retrieving and analyzing the html source for each page in the chain. For each page, yo... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a project at work the requires me to be able to enter information into a web page, read the next page I get redirected to and then take further action. A simplified real-world example would be something like going to google.com, entering "Coding tricks" as search criteria, and reading the resulting page.
Small coding examples like the ones linked to at <http://www.csharp-station.com/HowTo/HttpWebFetch.aspx> tell how to read a web page, but not how to interact with it by submitting information into a form and continuing on to the next page.
For the record, I'm not building a malicious and/or spam related product.
So how do I go read web pages that require a few steps of normal browsing to reach first? | You can programmatically create an Http request and retrieve the response:
```
string uri = "http://www.google.com/search";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// encode the data to POST:
string postData = "q=searchterm&hl=en";
byte[] encodedData = new ASCIIEncoding().GetBytes(postData);
request.ContentLength = encodedData.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(encodedData, 0, encodedData.Length);
// send the request and get the response
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// Do something with the response stream. As an example, we'll
// stream the response to the console via a 256 character buffer
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Char[] buffer = new Char[256];
int count = reader.Read(buffer, 0, 256);
while (count > 0)
{
Console.WriteLine(new String(buffer, 0, count));
count = reader.Read(buffer, 0, 256);
}
} // reader is disposed here
} // response is disposed here
```
Of course, this code will return an error since Google uses GET, not POST, for search queries.
This method will work if you are dealing with specific web pages, as the URLs and POST data are all basically hard-coded. If you needed something that was a little more dynamic, you'd have to:
1. Capture the page
2. Strip out the form
3. Create a POST string based on the form fields
FWIW, I think something like Perl or Python might be better suited to that sort of task.
edit: x-www-form-urlencoded |
135,234 | <p>What is the difference between <code>ref</code> and <code>out</code> parameters in .NET? What are the situations where one can be more useful than the other? What would be a code snippet where one can be used and another can't?</p>
| [
{
"answer_id": 135241,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>ref will probably choke on null since it presumably expects to be modifying an existing object. out expects null, ... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1909/"
] | What is the difference between `ref` and `out` parameters in .NET? What are the situations where one can be more useful than the other? What would be a code snippet where one can be used and another can't? | They're pretty much the same - the only difference is that a variable you pass as an `out` parameter doesn't need to be initialized but passing it as a `ref` parameter it has to be set to something.
```
int x;
Foo(out x); // OK
int y;
Foo(ref y); // Error: y should be initialized before calling the method
```
`Ref` parameters are for data that might be modified, `out` parameters are for data that's an additional output for the function (eg `int.TryParse`) that are already using the return value for something. |
135,246 | <p>I'm attempting to write a Python C extension that reads packed binary data (it is stored as structs of structs) and then parses it out into Python objects. Everything works as expected on a 32 bit machine (the binary files are always written on 32bit architecture), but not on a 64 bit box. Is there a "preferred" way of doing this?</p>
<hr>
<p>It would be a lot of code to post but as an example:</p>
<pre><code>struct
{
WORD version;
BOOL upgrade;
time_t time1;
time_t time2;
} apparms;
File *fp;
fp = fopen(filePath, "r+b");
fread(&apparms, sizeof(apparms), 1, fp);
return Py_BuildValue("{s:i,s:l,s:l}",
"sysVersion",apparms.version,
"powerFailTime", apparms.time1,
"normKitExpDate", apparms.time2
);
</code></pre>
<p>Now on a 32 bit system this works great, but on a 64 bit my time_t sizes are different (32bit vs 64 bit longs).</p>
<hr>
<p>Damn, you people are fast. </p>
<p>Patrick, I originally started using the struct package but found it just way to slow for my needs. Plus I was looking for an excuse to write a Python Extension.</p>
<p>I know this is a stupid question but what types do I need to watch out for?</p>
<p>Thanks.</p>
| [
{
"answer_id": 135267,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 1,
"selected": false,
"text": "<p>What's your code for reading the binary data? Make sure you're copying the data into properly-sized types like <cod... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16363/"
] | I'm attempting to write a Python C extension that reads packed binary data (it is stored as structs of structs) and then parses it out into Python objects. Everything works as expected on a 32 bit machine (the binary files are always written on 32bit architecture), but not on a 64 bit box. Is there a "preferred" way of doing this?
---
It would be a lot of code to post but as an example:
```
struct
{
WORD version;
BOOL upgrade;
time_t time1;
time_t time2;
} apparms;
File *fp;
fp = fopen(filePath, "r+b");
fread(&apparms, sizeof(apparms), 1, fp);
return Py_BuildValue("{s:i,s:l,s:l}",
"sysVersion",apparms.version,
"powerFailTime", apparms.time1,
"normKitExpDate", apparms.time2
);
```
Now on a 32 bit system this works great, but on a 64 bit my time\_t sizes are different (32bit vs 64 bit longs).
---
Damn, you people are fast.
Patrick, I originally started using the struct package but found it just way to slow for my needs. Plus I was looking for an excuse to write a Python Extension.
I know this is a stupid question but what types do I need to watch out for?
Thanks. | Explicitly specify that your data types (e.g. integers) are 32-bit. Otherwise if you have two integers next to each other when you read them they will be read as one 64-bit integer.
When you are dealing with cross-platform issues, the two main things to watch out for are:
1. Bitness. If your packed data is written with 32-bit ints, then all of your code must explicitly specify 32-bit ints when reading *and* writing.
2. Byte order. If you move your code from Intel chips to PPC or SPARC, your byte order will be wrong. You will have to import your data and then byte-flip it so that it matches up with the current architecture. Otherwise 12 (`0x0000000C`) will be read as 201326592 (`0x0C000000`).
Hopefully this helps. |
135,254 | <p>I have a number of panels in a single window in C# application and I created 2 scrollbars, one for horizontal and one vertical. This is what I currently have:</p>
<p><a href="http://www.simnet.is/elinnils52/scrollbar.jpg" rel="nofollow noreferrer">picture with 2 scroolbars http://www.simnet.is/elinnils52/scrollbar.jpg</a></p>
<p>I have 1 variable and that is the total height all the items take & need.
Here is my code on scroll change:</p>
<pre><code>for (int i = 0; i < this._splitMainView.Panel2.Controls.Count; i++)
{
this._splitMainView.Panel2.Controls[i].Location = new Point(
3 - _scrollBarX.Value,
3 + (132 + 6) * (i - 2) - _scrollBarY.Value);
this._splitMainView.Panel2.Controls[i].Refresh();
}
</code></pre>
<p>The scrollbar maximum is the total amount of all the containers height, the space in between and a few pixels extra.</p>
<p>As you can see from the picture, it doesn't look good. Even if the maximum in this case is a little around 50 - 100 pixels it still looks like it's a thousand pages long. When I change the SmallChange and LargeChange, the scrollbar bar itself lengthens but then it wont reach the maximum pixels. It will be able to get almost at the end (depening on the SmallChange and LargeChange value) and leave around 5 - 29 px left. And as everyone knows, seeing half is not good.</p>
<p>Does anyone know how to overcome this obstacle or a better way to implement it?</p>
| [
{
"answer_id": 193350,
"author": "Robert C. Barth",
"author_id": 9209,
"author_profile": "https://Stackoverflow.com/users/9209",
"pm_score": 1,
"selected": false,
"text": "<p>Why not just make the maximum value of the scrollbar the overflow (visible area height - panel height)? Then just... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a number of panels in a single window in C# application and I created 2 scrollbars, one for horizontal and one vertical. This is what I currently have:
[picture with 2 scroolbars http://www.simnet.is/elinnils52/scrollbar.jpg](http://www.simnet.is/elinnils52/scrollbar.jpg)
I have 1 variable and that is the total height all the items take & need.
Here is my code on scroll change:
```
for (int i = 0; i < this._splitMainView.Panel2.Controls.Count; i++)
{
this._splitMainView.Panel2.Controls[i].Location = new Point(
3 - _scrollBarX.Value,
3 + (132 + 6) * (i - 2) - _scrollBarY.Value);
this._splitMainView.Panel2.Controls[i].Refresh();
}
```
The scrollbar maximum is the total amount of all the containers height, the space in between and a few pixels extra.
As you can see from the picture, it doesn't look good. Even if the maximum in this case is a little around 50 - 100 pixels it still looks like it's a thousand pages long. When I change the SmallChange and LargeChange, the scrollbar bar itself lengthens but then it wont reach the maximum pixels. It will be able to get almost at the end (depening on the SmallChange and LargeChange value) and leave around 5 - 29 px left. And as everyone knows, seeing half is not good.
Does anyone know how to overcome this obstacle or a better way to implement it? | Why not just make the maximum value of the scrollbar the overflow (visible area height - panel height)? Then just set the top of the panel to the value of the scrollbar \* -1. |
135,303 | <p>In C# I could easily write the following:</p>
<pre><code>string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;
</code></pre>
<p>Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement?</p>
| [
{
"answer_id": 135318,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 6,
"selected": true,
"text": "<p>In Python 2.5, there is</p>\n\n<pre><code>A if C else B\n</code></pre>\n\n<p>which behaves a lot like ?: in C. Ho... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20133/"
] | In C# I could easily write the following:
```
string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;
```
Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement? | In Python 2.5, there is
```
A if C else B
```
which behaves a lot like ?: in C. However, it's frowned upon for two reasons: readability, and the fact that there's usually a simpler way to approach the problem. For instance, in your case:
```
stringValue = otherString or defaultString
``` |
135,317 | <p>When running a CherryPy app it will send server name tag something like CherryPy/version.
Is it possible to rename/overwrite that from the app without modifying CherryPy so it will show something else? </p>
<p>Maybe something like MyAppName/version (CherryPy/version) </p>
| [
{
"answer_id": 135644,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 2,
"selected": false,
"text": "<p>This string appears to be being set in the CherrPy <a href=\"http://www.cherrypy.org/browser/trunk/cherrypy/_cprequest.py\"... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9789/"
] | When running a CherryPy app it will send server name tag something like CherryPy/version.
Is it possible to rename/overwrite that from the app without modifying CherryPy so it will show something else?
Maybe something like MyAppName/version (CherryPy/version) | Actually asking on IRC on their official channel fumanchu gived me a more clean way to do this (using latest svn):
```
import cherrypy
from cherrypy import _cpwsgi_server
class HelloWorld(object):
def index(self):
return "Hello World!"
index.exposed = True
serverTag = "MyApp/%s (CherryPy/%s)" % ("1.2.3", cherrypy.__version__)
_cpwsgi_server.CPWSGIServer.environ['SERVER_SOFTWARE'] = serverTag
cherrypy.config.update({'tools.response_headers.on': True,
'tools.response_headers.headers': [('Server', serverTag)]})
cherrypy.quickstart(HelloWorld())
``` |
135,330 | <p>Does anybody know if there is a built-in function in Mathematica for getting the lhs of downvalue rules (without any holding)? I know how to write the code to do it, but it seems basic enough for a built-in</p>
<p>For example:</p>
<pre><code>a[1]=2;
a[2]=3;
</code></pre>
<p><code>BuiltInIDoNotKnowOf[a]</code> returns <code>{1,2}</code></p>
| [
{
"answer_id": 138033,
"author": "Will Robertson",
"author_id": 4161,
"author_profile": "https://Stackoverflow.com/users/4161",
"pm_score": 4,
"selected": true,
"text": "<p>This seems to work; not sure how useful it is, though:</p>\n\n<pre><code>a[1] = 2\na[2] = 3\na[3] = 5\na[6] = 8\nPa... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/279/"
] | Does anybody know if there is a built-in function in Mathematica for getting the lhs of downvalue rules (without any holding)? I know how to write the code to do it, but it seems basic enough for a built-in
For example:
```
a[1]=2;
a[2]=3;
```
`BuiltInIDoNotKnowOf[a]` returns `{1,2}` | This seems to work; not sure how useful it is, though:
```
a[1] = 2
a[2] = 3
a[3] = 5
a[6] = 8
Part[DownValues[a], All, 1, 1, 1]
``` |
135,339 | <p>Within an n-tier app that makes use of a WCF service to interact with the database, what is the best practice way of making use of LinqToSql classes throughout the app?</p>
<p>I've seen it done a couple of different ways but they seemed like they burned a lot of hours creating extra interfaces, message classes, and the like which reduces the benefit you get from not having to write your data access code.</p>
<p>Is there a good way to do it currently? Are we stuck waiting for the Entity Framework?</p>
| [
{
"answer_id": 138033,
"author": "Will Robertson",
"author_id": 4161,
"author_profile": "https://Stackoverflow.com/users/4161",
"pm_score": 4,
"selected": true,
"text": "<p>This seems to work; not sure how useful it is, though:</p>\n\n<pre><code>a[1] = 2\na[2] = 3\na[3] = 5\na[6] = 8\nPa... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1860358/"
] | Within an n-tier app that makes use of a WCF service to interact with the database, what is the best practice way of making use of LinqToSql classes throughout the app?
I've seen it done a couple of different ways but they seemed like they burned a lot of hours creating extra interfaces, message classes, and the like which reduces the benefit you get from not having to write your data access code.
Is there a good way to do it currently? Are we stuck waiting for the Entity Framework? | This seems to work; not sure how useful it is, though:
```
a[1] = 2
a[2] = 3
a[3] = 5
a[6] = 8
Part[DownValues[a], All, 1, 1, 1]
``` |
135,375 | <p>I have a <code>ListBox</code> <code>DataTemplate</code> in WPF. I want one item to be tight against the left side of the <code>ListBox</code> and another item to be tight against the right side, but I can't figure out how to do this.</p>
<p>So far I have a <code>Grid</code> with three columns, the left and right ones have content and the center is a placeholder with it's width set to "*". Where am I going wrong?</p>
<p>Here is the code:</p>
<pre><code><DataTemplate x:Key="SmallCustomerListItem">
<Grid HorizontalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="*"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<WrapPanel HorizontalAlignment="Stretch" Margin="0">
<!--Some content here-->
<TextBlock Text="{Binding Path=LastName}" TextWrapping="Wrap" FontSize="24"/>
<TextBlock Text=", " TextWrapping="Wrap" FontSize="24"/>
<TextBlock Text="{Binding Path=FirstName}" TextWrapping="Wrap" FontSize="24"/>
</WrapPanel>
<ListBox ItemsSource="{Binding Path=PhoneNumbers}" Grid.Column="2" d:DesignWidth="100" d:DesignHeight="50"
Margin="8,0" Background="Transparent" BorderBrush="Transparent" IsHitTestVisible="False" HorizontalAlignment="Stretch"/>
</Grid>
</DataTemplate>
</code></pre>
| [
{
"answer_id": 135741,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>Grid</code> should by default take up the whole width of the <code>ListBox</code> because the default <co... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/100/"
] | I have a `ListBox` `DataTemplate` in WPF. I want one item to be tight against the left side of the `ListBox` and another item to be tight against the right side, but I can't figure out how to do this.
So far I have a `Grid` with three columns, the left and right ones have content and the center is a placeholder with it's width set to "\*". Where am I going wrong?
Here is the code:
```
<DataTemplate x:Key="SmallCustomerListItem">
<Grid HorizontalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="*"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<WrapPanel HorizontalAlignment="Stretch" Margin="0">
<!--Some content here-->
<TextBlock Text="{Binding Path=LastName}" TextWrapping="Wrap" FontSize="24"/>
<TextBlock Text=", " TextWrapping="Wrap" FontSize="24"/>
<TextBlock Text="{Binding Path=FirstName}" TextWrapping="Wrap" FontSize="24"/>
</WrapPanel>
<ListBox ItemsSource="{Binding Path=PhoneNumbers}" Grid.Column="2" d:DesignWidth="100" d:DesignHeight="50"
Margin="8,0" Background="Transparent" BorderBrush="Transparent" IsHitTestVisible="False" HorizontalAlignment="Stretch"/>
</Grid>
</DataTemplate>
``` | I also had to set:
```
HorizontalContentAlignment="Stretch"
```
on the containing `ListBox`. |
135,443 | <p>There are a group of private methods in my class, and I need to call one dynamically based on an input value. Both the invoking code and the target methods are in the same instance. The code looks like this:</p>
<pre><code>MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType);
dynMethod.Invoke(this, new object[] { methodParams });
</code></pre>
<p>In this case, <code>GetMethod()</code> will not return private methods. What <code>BindingFlags</code> do I need to supply to <code>GetMethod()</code> so that it can locate private methods?</p>
| [
{
"answer_id": 135455,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 2,
"selected": false,
"text": "<p>I think you can pass it <code>BindingFlags.NonPublic</code> where <em>it</em> is the <code>GetMethod</code> meth... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8223/"
] | There are a group of private methods in my class, and I need to call one dynamically based on an input value. Both the invoking code and the target methods are in the same instance. The code looks like this:
```
MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType);
dynMethod.Invoke(this, new object[] { methodParams });
```
In this case, `GetMethod()` will not return private methods. What `BindingFlags` do I need to supply to `GetMethod()` so that it can locate private methods? | Simply change your code to use the overloaded [version of `GetMethod`](http://msdn.microsoft.com/en-us/library/system.type.getmethod.aspx) that accepts BindingFlags:
```
MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType,
BindingFlags.NonPublic | BindingFlags.Instance);
dynMethod.Invoke(this, new object[] { methodParams });
```
Here's the [BindingFlags enumeration documentation](http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx). |
135,445 | <p>I tried to use DriveInfo.IsReady, but it returns false if an unformatted floppy is in the drive.</p>
| [
{
"answer_id": 135479,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 1,
"selected": false,
"text": "<p>Simply speaking: you can't. Floppy drives don't support that.</p>\n"
},
{
"answer_id": 135597,
"aut... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I tried to use DriveInfo.IsReady, but it returns false if an unformatted floppy is in the drive. | You can always try to read a sector from the floppy and see if it succeeds or not.
I have no clue how to do it in .NET, but here is the C/C++ equivalent.
```
SetLastError(0);
HANDLE h = CreateFile("\\\\.\\A:", ...);
if (!ReadFile(h, buf, 512, &bytes_read, 0))
{
DWORD err = GetLastError();
}
```
[CreateFile](http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx), [ReadFile](http://msdn.microsoft.com/en-us/library/aa365467(VS.85).aspx) |
135,448 | <p>How do I check if an object has a specific property in JavaScript?</p>
<p>Consider:</p>
<pre><code>x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
</code></pre>
<p>Is that the best way to do it?</p>
| [
{
"answer_id": 135466,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 4,
"selected": false,
"text": "<p>Yes it is :) I think you can also do <code>Object.prototype.hasOwnProperty.call(x, 'key')</code> which should a... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4915/"
] | How do I check if an object has a specific property in JavaScript?
Consider:
```
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
```
Is that the best way to do it? | 2022 UPDATE
-----------
[`Object.hasOwn()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn)
-------------------------------------------------------------------------------------------------------------------
>
> `Object.hasOwn()` is recommended over `Object.hasOwnProperty()` because it works for objects created using `Object.create(null)` and with objects that have overridden the inherited `hasOwnProperty()` method. While it is possible to workaround these problems by calling `Object.prototype.hasOwnProperty()` on an external object, `Object.hasOwn()` is more intuitive.
>
>
>
#### Example
```js
const object1 = {
prop: 'exists'
};
console.log(Object.hasOwn(object1, 'prop'));
// expected output: true
```
---
Original answer
---------------
I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to `typeof this[property]` or, even worse, `x.key` will give you completely misleading results.
It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then `object.hasOwnProperty` is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.)
If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: `prop in object` will give you your desired effect.
Since using `hasOwnProperty` is probably what you want, and considering that you may want a fallback method, I present to you the following solution:
```
var obj = {
a: undefined,
b: null,
c: false
};
// a, b, c all found
for ( var prop in obj ) {
document.writeln( "Object1: " + prop );
}
function Class(){
this.a = undefined;
this.b = null;
this.c = false;
}
Class.prototype = {
a: undefined,
b: true,
c: true,
d: true,
e: true
};
var obj2 = new Class();
// a, b, c, d, e found
for ( var prop in obj2 ) {
document.writeln( "Object2: " + prop );
}
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
if ( Object.prototype.hasOwnProperty ) {
var hasOwnProperty = function(obj, prop) {
return obj.hasOwnProperty(prop);
}
}
// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
if ( hasOwnProperty(obj2, prop) ) {
document.writeln( "Object2 w/ hasOwn: " + prop );
}
}
```
The above is a working, cross-browser, solution to `hasOwnProperty()`, with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful. |
135,451 | <p>I want to create a list of methods to execute. Each method has the same signature.
I thought about putting delegates in a generic collection, but I keep getting this error:</p>
<blockquote>
<p>'method' is a 'variable' but is used like a 'method'</p>
</blockquote>
<p>In theory, here is what I would like to do:</p>
<pre><code>List<object> methodsToExecute;
int Add(int x, int y)
{ return x+y; }
int Subtract(int x, int y)
{ return x-y; }
delegate int BinaryOp(int x, int y);
methodsToExecute.add(new BinaryOp(add));
methodsToExecute.add(new BinaryOp(subtract));
foreach(object method in methodsToExecute)
{
method(1,2);
}
</code></pre>
<p>Any ideas on how to accomplish this?
Thanks!</p>
| [
{
"answer_id": 135453,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>Have them all implement of common interface, say IExecuteable, and then have a List<IExecutable></p>\n\n<p>Also,... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8797/"
] | I want to create a list of methods to execute. Each method has the same signature.
I thought about putting delegates in a generic collection, but I keep getting this error:
>
> 'method' is a 'variable' but is used like a 'method'
>
>
>
In theory, here is what I would like to do:
```
List<object> methodsToExecute;
int Add(int x, int y)
{ return x+y; }
int Subtract(int x, int y)
{ return x-y; }
delegate int BinaryOp(int x, int y);
methodsToExecute.add(new BinaryOp(add));
methodsToExecute.add(new BinaryOp(subtract));
foreach(object method in methodsToExecute)
{
method(1,2);
}
```
Any ideas on how to accomplish this?
Thanks! | You need to cast the `object` in the list to a `BinaryOp`, or, better, use a more specific type parameter for the list:
```
delegate int BinaryOp(int x, int y);
List<BinaryOp> methodsToExecute = new List<BinaryOp>();
methodsToExecute.add(Add);
methodsToExecute.add(Subtract);
foreach(BinaryOp method in methodsToExecute)
{
method(1,2);
}
``` |
135,458 | <p>Suppose I have the following code:</p>
<pre><code>while(TRUE) {
pthread_t *thread = (pthread_t *) malloc(sizeof(pthread_t));
pthread_create(thread, NULL, someFunction, someArgument);
pthread_detach(*thread);
sleep(10);
}
</code></pre>
<p>Will the detached thread free the memory allocated by malloc, or is that something I now have to do?</p>
| [
{
"answer_id": 135922,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 4,
"selected": true,
"text": "<p>No. <strong>pthread_create()</strong> has no way of knowing that the <strong>thread</strong> pointer passed to it... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/542226/"
] | Suppose I have the following code:
```
while(TRUE) {
pthread_t *thread = (pthread_t *) malloc(sizeof(pthread_t));
pthread_create(thread, NULL, someFunction, someArgument);
pthread_detach(*thread);
sleep(10);
}
```
Will the detached thread free the memory allocated by malloc, or is that something I now have to do? | No. **pthread\_create()** has no way of knowing that the **thread** pointer passed to it was dynamically allocated. pthreads doesn't use this value internally; it simply returns the new thread id to the caller. You don't need to dynamically allocate that value; you can pass the address of a local variable instead:
```
pthread_t thread;
pthread_create(&thread, NULL, someFunction, someArgument);
``` |
135,474 | <p>For example:</p>
<pre><code>char * myString = malloc(sizeof(char)*STRING_BUFFER_SIZE);
free(myString);
free(myString);
</code></pre>
<p>Are there any adverse side effects of doing this? </p>
| [
{
"answer_id": 135483,
"author": "jbleners",
"author_id": 542226,
"author_profile": "https://Stackoverflow.com/users/542226",
"pm_score": 4,
"selected": false,
"text": "<p>Yes, you can get a double free error that causes your program to crash. It has to do with malloc's internal data str... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064/"
] | For example:
```
char * myString = malloc(sizeof(char)*STRING_BUFFER_SIZE);
free(myString);
free(myString);
```
Are there any adverse side effects of doing this? | Here's the chapter and verse.
>
> If the argument [to the `free` function] does not match a pointer earlier returned by the `calloc`, `malloc`, or
> `realloc` function, or if the space has been deallocated by a call to `free` or `realloc`,
> the behavior is undefined. ([ISO 9899:1999 - *Programming languages — C*](http://www.open-std.org/jtc1/sc22/wg14/www/standards), Section 7.20.3.2)
>
>
> |
135,518 | <p>In WPF, we are creating custom controls that inherit from button with completely drawn-from-scratch xaml graphics. We have a border around the entire button xaml and we'd like to use that as the location for updating the background when MouseOver=True in a trigger. What we need to know is how do we update the background of the border in this button with a gradient when the mouse hovers over it?</p>
| [
{
"answer_id": 135638,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 3,
"selected": true,
"text": "<p>In your <code>ControlTemplate</code>, give the <code>Border</code> a <code>Name</code> and you can then reference th... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21096/"
] | In WPF, we are creating custom controls that inherit from button with completely drawn-from-scratch xaml graphics. We have a border around the entire button xaml and we'd like to use that as the location for updating the background when MouseOver=True in a trigger. What we need to know is how do we update the background of the border in this button with a gradient when the mouse hovers over it? | In your `ControlTemplate`, give the `Border` a `Name` and you can then reference that part of its visual tree in the triggers. Here's a very brief example of restyling a normal `Button`:
```
<Style
TargetType="{x:Type Button}">
<Setter
Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Name="customBorder"
CornerRadius="5"
BorderThickness="1"
BorderBrush="Black"
Background="{StaticResource normalButtonBG}">
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger
Property="IsMouseOver"
Value="True">
<Setter
TargetName="customBorder"
Property="Background"
Value="{StaticResource hoverButtonBG}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
If that doesn't help, we'll need to know more, probably seeing your own XAML. Your description doesn't make it very clear to me what your actual visual tree is. |
135,534 | <p>I need to validate this simple pick list:</p>
<pre><code><select name="<%= key %>">
<option value="ETC" SELECTED>Select an option...</option>
<option value="ONE">Lorem ipsum</option>
<option value="TWO">dolor sit amet</option>
</select>
</code></pre>
<p>So the user would never submit the form with the, excuse the repetition, "Select an option..." option selected. In principle I'm allowed to use JavaScript but It'd be interesting to learn how to solve it within JSP too.</p>
| [
{
"answer_id": 135795,
"author": "Peter",
"author_id": 17123,
"author_profile": "https://Stackoverflow.com/users/17123",
"pm_score": 3,
"selected": true,
"text": "<p>You can never really satisfy the condition 'never submit a given value' because you don't have control over the client sid... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6992/"
] | I need to validate this simple pick list:
```
<select name="<%= key %>">
<option value="ETC" SELECTED>Select an option...</option>
<option value="ONE">Lorem ipsum</option>
<option value="TWO">dolor sit amet</option>
</select>
```
So the user would never submit the form with the, excuse the repetition, "Select an option..." option selected. In principle I'm allowed to use JavaScript but It'd be interesting to learn how to solve it within JSP too. | You can never really satisfy the condition 'never submit a given value' because you don't have control over the client side. The user can always manipulate HTML to submit whatever they want.
It is a good approach is to use JavaScript to do client-side validation and give the user quick feedback and catch 99%+ of the cases, then do a server-side validation of the submitted parameters to catch the minority that don't have JS enabled or who manipulate the HTML to submit non-expected values.
Just remember that the client-side validation is optional, and is good for those 'common mistakes' input validation, but the server-side validation is mandatory for all input whether or not any client-side checks have been done on the given input. |
135,591 | <p>I've seen several products that will track the sales rank of an item on Amazon. Does Amazon have any web-services published that I can use to get the sales rank of a particular item? </p>
<p>I've looked through the AWS and didn't see anything of that nature.</p>
| [
{
"answer_id": 135627,
"author": "Adam Hughes",
"author_id": 3863,
"author_profile": "https://Stackoverflow.com/users/3863",
"pm_score": 4,
"selected": true,
"text": "<p>You should be able to determine the Sales Rank by querying for the SalesRank response group when doing an ItemLookup w... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4244/"
] | I've seen several products that will track the sales rank of an item on Amazon. Does Amazon have any web-services published that I can use to get the sales rank of a particular item?
I've looked through the AWS and didn't see anything of that nature. | You should be able to determine the Sales Rank by querying for the SalesRank response group when doing an ItemLookup with the Amazon Associates Web Service.
Example query:
```
http://ecs.amazonaws.com/onca/xml?
Service=AWSECommerceService&
AWSAccessKeyId=[AWS Access Key ID]&
Operation=ItemLookup&
ItemId=0976925524&
ResponseGroup=SalesRank&
Version=2008-08-19
```
Response:
```
<Item>
<ASIN>0976925524</ASIN>
<SalesRank>68</SalesRank>
</Item>
```
See the documentation here: <http://docs.amazonwebservices.com/AWSECommerceService/2008-08-19/DG/index.html?RG_SalesRank.html> |
135,600 | <p>When I download my program from my website to my windows 2003 machine, it has a block on it and you have to right click on the exe, then properties, then select the button "Unblock".</p>
<p>I would like to add detection in my installer for when the file is blocked and hence doesn't have enough permissions. </p>
<p>But I can't eaisly reproduce getting my exe in this state where it needs to be unblocked.</p>
<p>How can I get the unblock to appear on my exe so I can test this functionality?</p>
| [
{
"answer_id": 135924,
"author": "HitScan",
"author_id": 9490,
"author_profile": "https://Stackoverflow.com/users/9490",
"pm_score": 5,
"selected": true,
"text": "<p>This is done using NTFS File Streams. There is a stream named \"Zone.Identifier\" added to downloaded files. When IE7 down... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] | When I download my program from my website to my windows 2003 machine, it has a block on it and you have to right click on the exe, then properties, then select the button "Unblock".
I would like to add detection in my installer for when the file is blocked and hence doesn't have enough permissions.
But I can't eaisly reproduce getting my exe in this state where it needs to be unblocked.
How can I get the unblock to appear on my exe so I can test this functionality? | This is done using NTFS File Streams. There is a stream named "Zone.Identifier" added to downloaded files. When IE7 downloads certain types of file that stream contains:
```
[ZoneTransfer]
ZoneId=3
```
The simplest way to set it is to create a text file with those contents in it, and use more to add it to the alternate stream.
Zone.Identifier.txt:
```
[ZoneTransfer]
ZoneId=3
```
Command:
```
more Zone.Identifier.txt > file.exe:Zone.Identifier
```
Then, the way for you to check it would be to try to open the Zone.Identifier stream and look for ZoneId=3, or simply assume that if the stream exists at all that your user will receive that warning.
It's also important to note that this has nothing to do with permissions. Administrators see the same warning; it's to do entirely with the source and type of file. The entire stream goes away when users uncheck the "Always ask before opening this file" box and then click Run. |
135,664 | <p>For example, how much memory is required to store a list of one million (32-bit) integers?</p>
<pre><code>alist = range(1000000) # or list(range(1000000)) in Python 3.0
</code></pre>
| [
{
"answer_id": 135718,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 5,
"selected": false,
"text": "<p>\"It depends.\" Python allocates space for lists in such a way as to achieve <a href=\"http://effbot.org/zone/pytho... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4279/"
] | For example, how much memory is required to store a list of one million (32-bit) integers?
```
alist = range(1000000) # or list(range(1000000)) in Python 3.0
``` | Useful links:
[How to get memory size/usage of python object](http://bytes.com/forum/thread757255.html)
[Memory sizes of python objects?](http://mail.python.org/pipermail/python-list/2002-March/135223.html)
[if you put data into dictionary, how do we calculate the data size?](http://groups.google.com/group/comp.lang.python/msg/b9afcfc2e1de5b05)
However they don't give a definitive answer. The way to go:
1. Measure memory consumed by Python interpreter with/without the list (use OS tools).
2. Use a third-party extension module which defines some sort of sizeof(PyObject).
**Update**:
[Recipe 546530: Size of Python objects (revised)](http://code.activestate.com/recipes/546530/)
```
import asizeof
N = 1000000
print asizeof.asizeof(range(N)) / N
# -> 20 (python 2.5, WinXP, 32-bit Linux)
# -> 33 (64-bit Linux)
``` |
135,670 | <p>This post is similar to <a href="https://stackoverflow.com/questions/16829/structure-of-projects-in-version-control">this previously asked question.</a> I really want to set up my SVN repository in TTB format, but when creating a project in Visual Studio 2008 (ASP.NET/VB.NET), the structure created tends to be incompatible when considering the solution file, project files, folders for projects, multiple projects within solutions, etc. Does anyone have a script or procedure to take a newly created ASP.NET project and move it to a TTB format as painlessly as possible?</p>
<hr>
<p>Let me be more specific. Suppose I have a project that I'm creating called StackOverflowIsAwesome. I can put that into my local folder structure (let's say that it's c:\working). When I create it, VS creates c:\working\StackOverflowIsAwesome and a whole bunch of subfolders (bin, app_data, etc.). But I want my repository structure to look like...</p>
<pre>
StackOverflowIsAwesome
/trunk
/bin
/app_data
/tags
/branches
</pre>
<p>So, is there a clean way to do this consistently or do I need to resort to constantly moving/modifying files and folders to make this work?</p>
| [
{
"answer_id": 135719,
"author": "Lev",
"author_id": 7224,
"author_profile": "https://Stackoverflow.com/users/7224",
"pm_score": 0,
"selected": false,
"text": "<p>If your TTB are common rather than per project, there is no problem with it. Or am I missing something?</p>\n"
},
{
"... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18009/"
] | This post is similar to [this previously asked question.](https://stackoverflow.com/questions/16829/structure-of-projects-in-version-control) I really want to set up my SVN repository in TTB format, but when creating a project in Visual Studio 2008 (ASP.NET/VB.NET), the structure created tends to be incompatible when considering the solution file, project files, folders for projects, multiple projects within solutions, etc. Does anyone have a script or procedure to take a newly created ASP.NET project and move it to a TTB format as painlessly as possible?
---
Let me be more specific. Suppose I have a project that I'm creating called StackOverflowIsAwesome. I can put that into my local folder structure (let's say that it's c:\working). When I create it, VS creates c:\working\StackOverflowIsAwesome and a whole bunch of subfolders (bin, app\_data, etc.). But I want my repository structure to look like...
```
StackOverflowIsAwesome
/trunk
/bin
/app_data
/tags
/branches
```
So, is there a clean way to do this consistently or do I need to resort to constantly moving/modifying files and folders to make this work? | We went with a very simplistic approach:
**File Structure:**
* Solution Folder (contains solution file, build scripts, maybe more?)
+ Project Folder
+ Project Folder 2
+ References (contains shared assemblies for the solution).
Then we just check the entire solution folder's contents into our repository. We use one repository for each solution. I'm not sure if this is the optimal way to organize the solution, but it works for us.
Also, we branch at the highest level, not per project. |
135,688 | <p>What is the proper way to modify environment variables like PATH in OS X?</p>
<p>I've looked on Google a little bit and found three different files to edit:</p>
<ul>
<li>/etc/paths</li>
<li>~/.profile</li>
<li>~/.tcshrc</li>
</ul>
<p>I don't even have some of these files, and I'm pretty sure that <em>.tcshrc</em> is wrong, since OS X uses bash now. Where are these variables, especially PATH, defined?</p>
<p>I'm running <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="noreferrer">OS X v10.5</a> (Leopard).</p>
| [
{
"answer_id": 135697,
"author": "tim_yates",
"author_id": 6509,
"author_profile": "https://Stackoverflow.com/users/6509",
"pm_score": 7,
"selected": false,
"text": "<p><strong><em>Up to and including <a href=\"http://en.wikipedia.org/wiki/Mac_OS_X_Lion\" rel=\"noreferrer\">OS X&nbs... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] | What is the proper way to modify environment variables like PATH in OS X?
I've looked on Google a little bit and found three different files to edit:
* /etc/paths
* ~/.profile
* ~/.tcshrc
I don't even have some of these files, and I'm pretty sure that *.tcshrc* is wrong, since OS X uses bash now. Where are these variables, especially PATH, defined?
I'm running [OS X v10.5](http://en.wikipedia.org/wiki/Mac_OS_X_Leopard) (Leopard). | Bruno is right on track. I've done extensive research and if you want to set variables that are available in all GUI applications, your only option is `/etc/launchd.conf`.
Please note that [environment.plist does not work for applications launched via Spotlight. This is documented by Steve Sexton here](https://web.archive.org/web/20100212232552/https://www.digitaledgesw.com/node/31).
1. Open a terminal prompt
2. Type `sudo vi /etc/launchd.conf` (note: this file might not yet exist)
3. Put contents like the following into the file
```none
# Set environment variables here so they are available globally to all apps
# (and Terminal), including those launched via Spotlight.
#
# After editing this file run the following command from the terminal to update
# environment variables globally without needing to reboot.
# NOTE: You will still need to restart the relevant application (including
# Terminal) to pick up the changes!
# grep -E "^setenv" /etc/launchd.conf | xargs -t -L 1 launchctl
#
# See http://www.digitaledgesw.com/node/31
# and http://stackoverflow.com/questions/135688/setting-environment-variables-in-os-x/
#
# Note that you must hardcode the paths below, don't use environment variables.
# You also need to surround multiple values in quotes, see MAVEN_OPTS example below.
#
setenv JAVA_VERSION 1.6
setenv JAVA_HOME /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home
setenv GROOVY_HOME /Applications/Dev/groovy
setenv GRAILS_HOME /Applications/Dev/grails
setenv NEXUS_HOME /Applications/Dev/nexus/nexus-webapp
setenv JRUBY_HOME /Applications/Dev/jruby
setenv ANT_HOME /Applications/Dev/apache-ant
setenv ANT_OPTS -Xmx512M
setenv MAVEN_OPTS "-Xmx1024M -XX:MaxPermSize=512m"
setenv M2_HOME /Applications/Dev/apache-maven
setenv JMETER_HOME /Applications/Dev/jakarta-jmeter
```
4. Save your changes in vi and reboot your Mac. Or use the [`grep`](http://linux.die.net/man/1/grep)/[`xargs`](https://linux.die.net/man/1/xargs) command which is shown in the code comment above.
5. Prove that your variables are working by opening a Terminal window and typing `export` and you should see your new variables. These will also be available in IntelliJ IDEA and other GUI applications you launch via Spotlight. |
135,734 | <p>I am trying to learn Emacs and trying to find best keyboard layout for me. One thing is really annoying me. I have added following lines to .emacs</p>
<pre class="lang-lisp prettyprint-override"><code>(global-set-key "\C-y" 'scroll-up)
(global-set-key "\M-y" 'scroll-down)
</code></pre>
<p>When I hold <kbd>Control</kbd> and press <kbd>y</kbd> a few times, it will page down on every press of <kbd>y</kbd>.</p>
<p><strong>However</strong>, when I hold the <kbd>Windows</kbd> key (mapped as <kbd>Meta</kbd>) and press <kbd>y</kbd> a few times it will only page up on the <strong>first</strong> press of <kbd>y</kbd> and all subsequent presses of <kbd>y</kbd> I get the ‘y’ character inserted in the buffer.</p>
<p>Can the page up behave like page down? I want to hold <kbd>Meta</kbd> and keep pressing <kbd>y</kbd> to scroll multiple pages up.</p>
<p>I am using GNU Emacs 23.0.60.1 (i386-mingw-nt5.1.2600) of 2008-05-12 on LENNART-69DE564 (patched). It is Emacs with EmacsW32 patch. Is this problem with this Emacs? Problem with Meta key?</p>
<p>I tried original GNU Emacs (not patched) and it works OK with <kbd>Alt</kbd>. But my problem is not that I want to scroll without releasing any key. I release key <kbd>y</kbd> and press it multiple times but don't want to have to release <kbd>Meta</kbd> key. Same problem is described here:</p>
<p><a href="http://groups.google.com/group/gnu.emacs.help/browse_thread/thread/f30f4b75a8b75b10" rel="nofollow noreferrer">http://groups.google.com/group/gnu.emacs.help/browse_thread/thread/f30f4b75a8b75b10</a></p>
<p>Problem is not in that I have changed key mapping. It looks like it is a bug in EmacsW32 version. Here is another description of the problem:
<a href="http://www.nabble.com/23.0.60--Unreleased-Meta-Win-modifier-td19213327.html" rel="nofollow noreferrer">Unreleased Meta/Win modifier</a></p>
| [
{
"answer_id": 136427,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 3,
"selected": true,
"text": "<p>Could this be a side affect of using the Windows key as Meta? I'm thinking this because in a non-Emacs situation if you press... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438025/"
] | I am trying to learn Emacs and trying to find best keyboard layout for me. One thing is really annoying me. I have added following lines to .emacs
```lisp
(global-set-key "\C-y" 'scroll-up)
(global-set-key "\M-y" 'scroll-down)
```
When I hold `Control` and press `y` a few times, it will page down on every press of `y`.
**However**, when I hold the `Windows` key (mapped as `Meta`) and press `y` a few times it will only page up on the **first** press of `y` and all subsequent presses of `y` I get the ‘y’ character inserted in the buffer.
Can the page up behave like page down? I want to hold `Meta` and keep pressing `y` to scroll multiple pages up.
I am using GNU Emacs 23.0.60.1 (i386-mingw-nt5.1.2600) of 2008-05-12 on LENNART-69DE564 (patched). It is Emacs with EmacsW32 patch. Is this problem with this Emacs? Problem with Meta key?
I tried original GNU Emacs (not patched) and it works OK with `Alt`. But my problem is not that I want to scroll without releasing any key. I release key `y` and press it multiple times but don't want to have to release `Meta` key. Same problem is described here:
<http://groups.google.com/group/gnu.emacs.help/browse_thread/thread/f30f4b75a8b75b10>
Problem is not in that I have changed key mapping. It looks like it is a bug in EmacsW32 version. Here is another description of the problem:
[Unreleased Meta/Win modifier](http://www.nabble.com/23.0.60--Unreleased-Meta-Win-modifier-td19213327.html) | Could this be a side affect of using the Windows key as Meta? I'm thinking this because in a non-Emacs situation if you press and hold the Windows key and another key for a short cut (Win+E for Explorer, Win+R for Run dialog, etc.) the desired action only triggers once, not multiple times if you keep holding it down.
I'd try reassigning Meta to Alt and see if the problem persists. If it doesn't, then I'm not sure what other option you have, since likely it's the OS only sending the Windows key press once to the app in focus. |
135,745 | <p>I have a simple web service, it takes 2 parameters one is a simple xml security token, the other is usually a long xml string. It works with short strings but longer strings give a 400 error message. maxMessageLength did nothing to allow for longer strings.</p>
| [
{
"answer_id": 135809,
"author": "Yuval Peled",
"author_id": 20257,
"author_profile": "https://Stackoverflow.com/users/20257",
"pm_score": 2,
"selected": false,
"text": "<p>You should remove the quotas limitations as well.\nHere is how you can do it in code with Tcp binding. \nI have add... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22367/"
] | I have a simple web service, it takes 2 parameters one is a simple xml security token, the other is usually a long xml string. It works with short strings but longer strings give a 400 error message. maxMessageLength did nothing to allow for longer strings. | You should remove the quotas limitations as well.
Here is how you can do it in code with Tcp binding.
I have added some code that shows removal of timeout problems because usually sending very big arguments causes timeout issues. So use the code wisely...
Of course, you can set these parameters in the config file as well.
```
NetTcpBinding binding = new NetTcpBinding(SecurityMode.None, true);
// Allow big arguments on messages. Allow ~500 MB message.
binding.MaxReceivedMessageSize = 500 * 1024 * 1024;
// Allow unlimited time to send/receive a message.
// It also prevents closing idle sessions.
// From MSDN: To prevent the service from aborting idle sessions prematurely increase the Receive timeout on the service endpoint's binding.’
binding.ReceiveTimeout = TimeSpan.MaxValue;
binding.SendTimeout = TimeSpan.MaxValue;
XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas();
// Remove quotas limitations
quotas.MaxArrayLength = int.MaxValue;
quotas.MaxBytesPerRead = int.MaxValue;
quotas.MaxDepth = int.MaxValue;
quotas.MaxNameTableCharCount = int.MaxValue;
quotas.MaxStringContentLength = int.MaxValue;
binding.ReaderQuotas = quotas;
``` |
135,754 | <p>It is typical to have something like this in your cshrc file for setting the path:</p>
<pre><code>set path = ( . $otherpath $path )
</code></pre>
<p>but, the path gets duplicated when you source your cshrc file multiple times, how do you prevent the duplication?</p>
<p>EDIT: This is one unclean way of doing it:</p>
<pre><code>set localpaths = ( . $otherpaths )
echo ${path} | egrep -i "$localpaths" >& /dev/null
if ($status != 0) then
set path = ( . $otherpaths $path )
endif
</code></pre>
| [
{
"answer_id": 135783,
"author": "Andrew Stein",
"author_id": 13029,
"author_profile": "https://Stackoverflow.com/users/13029",
"pm_score": 0,
"selected": false,
"text": "<p>I always set my path from scratch in .cshrc.\nThat is I start off with a basic path, something like:</p>\n\n<pre><... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18415/"
] | It is typical to have something like this in your cshrc file for setting the path:
```
set path = ( . $otherpath $path )
```
but, the path gets duplicated when you source your cshrc file multiple times, how do you prevent the duplication?
EDIT: This is one unclean way of doing it:
```
set localpaths = ( . $otherpaths )
echo ${path} | egrep -i "$localpaths" >& /dev/null
if ($status != 0) then
set path = ( . $otherpaths $path )
endif
``` | you can use the following Perl script to prune paths of duplicates.
---
```
#!/usr/bin/perl
#
# ^^ ensure this is pointing to the correct location.
#
# Title: SLimPath
# Author: David "Shoe Lace" Pyke <eselle@users.sourceforge.net >
# : Tim Nelson
# Purpose: To create a slim version of my envirnoment path so as to eliminate
# duplicate entries and ensure that the "." path was last.
# Date Created: April 1st 1999
# Revision History:
# 01/04/99: initial tests.. didn't wok verywell at all
# : retreived path throught '$ENV' call
# 07/04/99: After an email from Tim Nelson <wayland@ne.com.au> got it to
# work.
# : used 'push' to add to array
# : used 'join' to create a delimited string from a list/array.
# 16/02/00: fixed cmd-line options to look/work better
# 25/02/00: made verbosity level-oriented
#
#
use Getopt::Std;
sub printlevel;
$initial_str = "";
$debug_mode = "";
$delim_chr = ":";
$opt_v = 1;
getopts("v:hd:l:e:s:");
OPTS: {
$opt_h && do {
print "\n$0 [-v level] [-d level] [-l delim] ( -e varname | -s strname | -h )";
print "\nWhere:";
print "\n -h This help";
print "\n -d Debug level";
print "\n -l Delimiter (between path vars)";
print "\n -e Specify environment variable (NB: don't include \$ sign)";
print "\n -s String (ie. $0 -s \$PATH:/looser/bin/)";
print "\n -v Verbosity (0 = quiet, 1 = normal, 2 = verbose)";
print "\n";
exit;
};
$opt_d && do {
printlevel 1, "You selected debug level $opt_d\n";
$debug_mode = $opt_d;
};
$opt_l && do {
printlevel 1, "You are going to delimit the string with \"$opt_l\"\n";
$delim_chr = $opt_l;
};
$opt_e && do {
if($opt_s) { die "Cannot specify BOTH env var and string\n"; }
printlevel 1, "Using Environment variable \"$opt_e\"\n";
$initial_str = $ENV{$opt_e};
};
$opt_s && do {
printlevel 1, "Using String \"$opt_s\"\n";
$initial_str = $opt_s;
};
}
if( ($#ARGV != 1) and !$opt_e and !$opt_s){
die "Nothing to work with -- try $0 -h\n";
}
$what = shift @ARGV;
# Split path using the delimiter
@dirs = split(/$delim_chr/, $initial_str);
$dest;
@newpath = ();
LOOP: foreach (@dirs){
# Ensure the directory exists and is a directory
if(! -e ) { printlevel 1, "$_ does not exist\n"; next; }
# If the directory is ., set $dot and go around again
if($_ eq '.') { $dot = 1; next; }
# if ($_ ne `realpath $_`){
# printlevel 2, "$_ becomes ".`realpath $_`."\n";
# }
undef $dest;
#$_=Stdlib::realpath($_,$dest);
# Check for duplicates and dot path
foreach $adir (@newpath) { if($_ eq $adir) {
printlevel 2, "Duplicate: $_\n";
next LOOP;
}}
push @newpath, $_;
}
# Join creates a string from a list/array delimited by the first expression
print join($delim_chr, @newpath) . ($dot ? $delim_chr.".\n" : "\n");
printlevel 1, "Thank you for using $0\n";
exit;
sub printlevel {
my($level, $string) = @_;
if($opt_v >= $level) {
print STDERR $string;
}
}
```
---
i hope thats useful. |
135,755 | <p>How do you find the version of an installed Perl module?</p>
<p>This is in an answer down at the bottom, but I figure it important enough to live up here. With these suggestions, I create a function in my <code>.bashrc</code></p>
<pre><code>function perlmodver {
perl -M$1 -e 'print "Version " . $ARGV[0]->VERSION . " of " . $ARGV[0] . \
" is installed.\n"' $1
}
</code></pre>
| [
{
"answer_id": 135760,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 6,
"selected": false,
"text": "<p>Most modules (especially ones from The CPAN) have a $VERSION variable:</p>\n\n<pre><code>perl -MSome::Module -le 'print $S... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17339/"
] | How do you find the version of an installed Perl module?
This is in an answer down at the bottom, but I figure it important enough to live up here. With these suggestions, I create a function in my `.bashrc`
```
function perlmodver {
perl -M$1 -e 'print "Version " . $ARGV[0]->VERSION . " of " . $ARGV[0] . \
" is installed.\n"' $1
}
``` | Why are you trying to get the version of the module? Do you need this from within a program, do you just need the number to pass to another operation, or are you just trying to find out what you have?
I have this built into the `cpan` (which comes with perl) with the `-D` switch so you can see the version that you have installed and the current version on CPAN:
```
$ cpan -D Text::CSV_XS
Text::CSV_XS
-------------------------------------------------------------------------
Fast 8bit clean version of Text::CSV
H/HM/HMBRAND/Text-CSV_XS-0.54.tgz
/usr/local/lib/perl5/site_perl/5.8.8/darwin-2level/Text/CSV_XS.pm
Installed: 0.32
CPAN: 0.54 Not up to date
H.Merijn Brand (HMBRAND)
h.m.brand@xs4all.nl
```
If you want to see all of the out-of-date modules, use the `-O` (capital O) switch:
```
$ cpan -O
Module Name Local CPAN
-------------------------------------------------------------------------
Apache::DB 0.1300 0.1400
Apache::SOAP 0.0000 0.7100
Apache::Session 1.8300 1.8700
Apache::SizeLimit 0.0300 0.9100
Apache::XMLRPC::Lite 0.0000 0.7100
... and so on
```
If you want to see this for all modules you have installed, try the `-a` switch to create an autobundle. |
135,759 | <p>Why can't I create a <code>class</code> in <code>VB.NET</code> that <code>inherits</code> <code>System.IO.Directory</code>? According to Lutz Roeder, it is <em>not</em> declared as <code>NotInheritable</code>!</p>
<p>I want to create a <code>utility class</code> that adds functionality to the <code>Directory class</code>. For instance, I want to add a <code>Directory.Move</code> function.</p>
<p>Please advise and I will send you a six pack. OK nevermind I'm not sending you anything but if you come to the bar tonight I will hook you up and then beat you in pool.</p>
| [
{
"answer_id": 135766,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 3,
"selected": false,
"text": "<p>Are you using <s>C# 3.0</s> VB.NET 2008 -- then you could add an <a href=\"http://msdn.microsoft.com/en-us/library/bb3... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54420/"
] | Why can't I create a `class` in `VB.NET` that `inherits` `System.IO.Directory`? According to Lutz Roeder, it is *not* declared as `NotInheritable`!
I want to create a `utility class` that adds functionality to the `Directory class`. For instance, I want to add a `Directory.Move` function.
Please advise and I will send you a six pack. OK nevermind I'm not sending you anything but if you come to the bar tonight I will hook you up and then beat you in pool. | From the Meta Data of .NET
```
namespace System.IO
{
// Summary:
// Exposes static methods for creating, moving, and enumerating through directories
// and subdirectories. This class cannot be inherited.
[ComVisible(true)]
public static class Directory
```
You cannot inherit from a Static Class. |
135,775 | <p>Any ideas on how i get MVP working with Silverlight? How Do I get around the fact there is no load event raised?</p>
<p>This the view I have:</p>
<pre><code> public partial class Person: IPersonView
{
public event RoutedEventHandler Loaded;
public Person()
{
new PersonPresenter(this);
InitializeComponent();
}
public Person Person
{
set { Person.ItemsSource = value; }
}
}
</code></pre>
<p>And my presenter:</p>
<pre><code> public class PersonPresenter
{
private readonly IPersonView _view;
private readonly ServiceContractClient _client;
public PersonPresenter(IPersonView view)
{
_client = new ServiceContractClient();
_view = view;
WireUpEvents();
}
private void WireUpEvents()
{
_view.Loaded += Load;
}
private void Load(object sender, EventArgs e)
{
_client.GetPersonCompleted += Client_GetPerson;
_client.GetPersonAsync();
}
private void Client_GetPerson(object sender, GetPersonCompletedEventArgs e)
{
_view.Person= e.Result;
}
}
</code></pre>
<p>Nothing happened for me as the Loaded event dont seem to get called, how do i get around this?</p>
| [
{
"answer_id": 135964,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 1,
"selected": false,
"text": "<p>I believe the loaded event gets called when the control has been initialized, loaded, rendered and ready for... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] | Any ideas on how i get MVP working with Silverlight? How Do I get around the fact there is no load event raised?
This the view I have:
```
public partial class Person: IPersonView
{
public event RoutedEventHandler Loaded;
public Person()
{
new PersonPresenter(this);
InitializeComponent();
}
public Person Person
{
set { Person.ItemsSource = value; }
}
}
```
And my presenter:
```
public class PersonPresenter
{
private readonly IPersonView _view;
private readonly ServiceContractClient _client;
public PersonPresenter(IPersonView view)
{
_client = new ServiceContractClient();
_view = view;
WireUpEvents();
}
private void WireUpEvents()
{
_view.Loaded += Load;
}
private void Load(object sender, EventArgs e)
{
_client.GetPersonCompleted += Client_GetPerson;
_client.GetPersonAsync();
}
private void Client_GetPerson(object sender, GetPersonCompletedEventArgs e)
{
_view.Person= e.Result;
}
}
```
Nothing happened for me as the Loaded event dont seem to get called, how do i get around this? | [Tim Ross](http://timross.wordpress.com/2008/03/16/implementing-the-mvp-pattern-in-silverlight/) has a good introduction to Silverlight MVP implementation, with source code. |
135,777 | <h2>Seeking a method to:</h2>
<h2>Take whitespace separated tokens in a String; return a suggested Word</h2>
<p><br>
<strong>ie:</strong><br>
Google Search can take <em>"fonetic wrd nterpreterr"</em>,<br>
and atop of the result page it shows <em>"Did you mean: phonetic word interpreter"</em></p>
<p><em>A solution in any of the C* languages or Java would be preferred.</em></p>
<p><br>
<strong>Are there any existing Open Libraries which perform such functionality?</strong></p>
<p><strong>Or is there a way to Utilise a Google API to request a suggested word?</strong></p>
| [
{
"answer_id": 135791,
"author": "jeannicolas",
"author_id": 14981,
"author_profile": "https://Stackoverflow.com/users/14981",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the yahoo web service here:\n<a href=\"http://developer.yahoo.com/search/web/V1/spellingSuggestion.html... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
] | Seeking a method to:
--------------------
Take whitespace separated tokens in a String; return a suggested Word
---------------------------------------------------------------------
**ie:**
Google Search can take *"fonetic wrd nterpreterr"*,
and atop of the result page it shows *"Did you mean: phonetic word interpreter"*
*A solution in any of the C\* languages or Java would be preferred.*
**Are there any existing Open Libraries which perform such functionality?**
**Or is there a way to Utilise a Google API to request a suggested word?** | In his article [How to Write a Spelling Corrector](http://norvig.com/spell-correct.html), Peter Norvig discusses how a Google-like spellchecker could be implemented. The article contains a 20-line implementation in Python, as well as links to several reimplementations in C, C++, C# and Java. Here is an excerpt:
>
> The full details of an
> industrial-strength spell corrector
> like Google's would be more confusing
> than enlightening, but I figured that
> on the plane flight home, in less than
> a page of code, I could write a toy
> spelling corrector that achieves 80 or
> 90% accuracy at a processing speed of
> at least 10 words per second.
>
>
>
Using Norvig's code and [this text](http://www.phon.ucl.ac.uk/home/johnm/ptlc2005/pdf/ptlcp56.pdf) as training set, i get the following results:
```
>>> import spellch
>>> [spellch.correct(w) for w in 'fonetic wrd nterpreterr'.split()]
['phonetic', 'word', 'interpreters']
``` |
135,782 | <p>A lot of my C# code follows this pattern:</p>
<pre><code>void foo(string param1, string param2, string param3)
{
try
{
// do something...
}
catch(Exception ex)
{
LogError(String.Format("Error in foo(param1={0}, param2={1}, param3={2}), exception={3}", param1, param2, param3, ex.Message));
}
}
</code></pre>
<p>Is there a way in .NET to get a Key/Value list of the parameters to a function so that I can call another function to construct my error logging string?
OR
Do you have a more generic / better way of doing this?</p>
| [
{
"answer_id": 135813,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 1,
"selected": false,
"text": "<p>When I have done this I just created a generic dictionary for the logging.</p>\n\n<p>I have this LogArgs class. An... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] | A lot of my C# code follows this pattern:
```
void foo(string param1, string param2, string param3)
{
try
{
// do something...
}
catch(Exception ex)
{
LogError(String.Format("Error in foo(param1={0}, param2={1}, param3={2}), exception={3}", param1, param2, param3, ex.Message));
}
}
```
Is there a way in .NET to get a Key/Value list of the parameters to a function so that I can call another function to construct my error logging string?
OR
Do you have a more generic / better way of doing this? | You could use Reflection and the convention that you must pass the parameters to the LogError with the right order:
```
private static void MyMethod(string s, int x, int y)
{
try
{
throw new NotImplementedException();
}
catch (Exception ex)
{
LogError(MethodBase.GetCurrentMethod(), ex, s, x, y);
}
}
private static void LogError(MethodBase method, Exception ex, params object[] values)
{
ParameterInfo[] parms = method.GetParameters();
object[] namevalues = new object[2 * parms.Length];
string msg = "Error in " + method.Name + "(";
for (int i = 0, j = 0; i < parms.Length; i++, j += 2)
{
msg += "{" + j + "}={" + (j + 1) + "}, ";
namevalues[j] = parms[i].Name;
if (i < values.Length) namevalues[j + 1] = values[i];
}
msg += "exception=" + ex.Message + ")";
Console.WriteLine(string.Format(msg, namevalues));
}
``` |
135,801 | <p>I am using prototype and I can't find any built in extensions to set or retrieve cookies. After googling for a little bit, I see a few different ways to go about it. I was wondering what you think is the best approach for getting a cookie in JavaScript?</p>
| [
{
"answer_id": 135855,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": -1,
"selected": false,
"text": "<p>I use this. It has been dependable:</p>\n\n<pre><code>function getCookie(c_name) {\nif (document.co... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6350/"
] | I am using prototype and I can't find any built in extensions to set or retrieve cookies. After googling for a little bit, I see a few different ways to go about it. I was wondering what you think is the best approach for getting a cookie in JavaScript? | I use this routine:
```
function ReadCookie(name)
{
name += '=';
var parts = document.cookie.split(/;\s*/);
for (var i = 0; i < parts.length; i++)
{
var part = parts[i];
if (part.indexOf(name) == 0)
return part.substring(name.length)
}
return null;
}
```
Works quite well. |
135,802 | <p>I'm looking for the concept to <strong>spawn a process</strong> such that:</p>
<ul>
<li>it has only access to certain libraries/APIs</li>
<li>it cannot acess the file system or only specific parts</li>
<li>it can <strong>do least harm should malicious code run in it</strong></li>
</ul>
<p>This concept is known as sandbox or jail.</p>
<p>It is required to do this <strong>for each major Operating system (Windows, MacOSX and Linux)</strong> and the question is conceptual (as in what to do, <strong>which APIs to use and and what to observe</strong>) rather then language specific.</p>
<h2>answer requirements</h2>
<p>I <strong>really</strong> want to accept an answer and give you 20 points for that. I cannot accept my own answer, and I don't have it yet anyway. So if you <strong>really</strong> want your answer to be accepted, please observe:</p>
<ul>
<li>The answer has to be specific and complete</li>
<li>With specific I mean that it is more then a pointer to some resource on the internet. It has to summarize what the resource says about the topic at least.</li>
<li>It may or may not contain example code, but if it does please write it in C</li>
<li>I cannot accept an answer that is 2/3 complete even if the 2/3 that are there are perfect.</li>
</ul>
<h2>this question FAQ</h2>
<ul>
<li>Is this homework? No.</li>
<li>Why do you ask this like a homework question? If you ask a specific question and you want to get a specific answer, and you know how that answer should look like, even though you don't know <em>the</em> answer, that's the style of question you get.</li>
<li>If you know how it should look like, why do you ask? 1) because I don't know all the answer 2) because on the internet there's no single place that contains all the details to this question in one place. Please also read the stackoverflow FAQ</li>
<li>Why is the main part of your question how to answer this question? Because nobody reads the FAQ.</li>
</ul>
| [
{
"answer_id": 135836,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 2,
"selected": false,
"text": "<p>FreeBSD has specific concepts of <a href=\"http://en.wikipedia.org/wiki/FreeBSD_jail\" rel=\"nofollow noreferrer\">jai... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19435/"
] | I'm looking for the concept to **spawn a process** such that:
* it has only access to certain libraries/APIs
* it cannot acess the file system or only specific parts
* it can **do least harm should malicious code run in it**
This concept is known as sandbox or jail.
It is required to do this **for each major Operating system (Windows, MacOSX and Linux)** and the question is conceptual (as in what to do, **which APIs to use and and what to observe**) rather then language specific.
answer requirements
-------------------
I **really** want to accept an answer and give you 20 points for that. I cannot accept my own answer, and I don't have it yet anyway. So if you **really** want your answer to be accepted, please observe:
* The answer has to be specific and complete
* With specific I mean that it is more then a pointer to some resource on the internet. It has to summarize what the resource says about the topic at least.
* It may or may not contain example code, but if it does please write it in C
* I cannot accept an answer that is 2/3 complete even if the 2/3 that are there are perfect.
this question FAQ
-----------------
* Is this homework? No.
* Why do you ask this like a homework question? If you ask a specific question and you want to get a specific answer, and you know how that answer should look like, even though you don't know *the* answer, that's the style of question you get.
* If you know how it should look like, why do you ask? 1) because I don't know all the answer 2) because on the internet there's no single place that contains all the details to this question in one place. Please also read the stackoverflow FAQ
* Why is the main part of your question how to answer this question? Because nobody reads the FAQ. | Mac OS X has a sandbox facility code-named Seatbelt. The public API for it is documented in the sandbox(7), sandbox\_init(3), and related manual pages. The public API is somewhat limited, but the facility itself is very powerful. While the public API only lets you choose from some pre-defined sandboxes (e.g. “All sockets-based networking is prohibited”), you can also use the more powerful underlying implementation which allows you to specify exactly what operating system resources are available via a Scheme-like language. For example, here is an excerpt of the sandbox used for portmap:
```
(allow process-exec (regex #"^/usr/sbin/portmap$"))
(allow file-read-data file-read-metadata (regex
#"^/etc"
#"^/usr/lib/.*\.dylib$"
#"^/var"
#"^/private/var/db/dyld/"
#"^/dev/urandom$"))
(allow file-write-data (regex
#"^/dev/dtracehelper$"))
```
You can see many sandboxes used by the system in /usr/share/sandbox. It is easy to experiment with sandboxes by using the sandbox-exec(1) command.
For Windows, you may want to have a look at [David LeBlanc’s “Practical Sandboxing” talk given at Black Hat USA 2007](http://media.blackhat.com/bh-usa-07/video/2007_BlackHat_Vegas-V11-LeBlanc-Practical_Sandboxing.mp4). Windows has no built-in sandboxing technology per se, so the techniques described leverage an incomplete mechanism introduced with Windows 2000 called SAFER. By using restricted tokens, one can create a process that has limited access to operating system resources.
For Linux, you might investigate the complicated SELinux mechanism:
[SELinux home](http://www.nsa.gov/selinux/),
[a HOWTO](http://www.lurking-grue.org/gettingstarted_newselinuxHOWTO.html). It is used by Red Hat, for example, to harden some system services in some of their products. |
135,803 | <blockquote>
<p>System.InvalidOperationException: DragDrop registration did not
succeed. ---> System.Threading.ThreadStateException:</p>
</blockquote>
<p>What does this exception mean? I get it at this line trying to add a panel to a panel at runtime...</p>
<pre><code>splitReport.Panel1.Controls.Add(ChartPanel);
</code></pre>
<p>Working in VS2008 C#</p>
| [
{
"answer_id": 160867,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 5,
"selected": false,
"text": "<p>This exception means that the thread that owns the Panel (the Panel being added) has been initialized using the MTA thr... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | >
> System.InvalidOperationException: DragDrop registration did not
> succeed. ---> System.Threading.ThreadStateException:
>
>
>
What does this exception mean? I get it at this line trying to add a panel to a panel at runtime...
```
splitReport.Panel1.Controls.Add(ChartPanel);
```
Working in VS2008 C# | This exception means that the thread that owns the Panel (the Panel being added) has been initialized using the MTA threading model. The drag/drop system requires that the calling thread use the STA thread model (particularly it requires that COM be initialized via OleInitialize). Threading models are an unfortunate vestige of COM, a predecessor of the .NET platform.
If you have the `[STAThread]` attribute on your Main function, then the main program thread should already be STA. The most likely explanation, then, is that this exception is happening on a different thread. Look at the Threads window in Visual Studio (Debug | Windows | Threads) when the exception occurs and see if you are on a thread other than the main thread. If you are, the solution is probably as simple as setting the thread model for that new thread, which you can do as follows (add this code to the thread where the control is being created):
`Thread.CurrentThread.SetApartmentState( ApartmentState.STA )`
(`Thread` and `ApartmentState` are members of `System.Threading`)
That code will need to happen before you actually start the new thread. As noted by @Tomer, you can also specify this declaratively using the `[STAThread]` attribute.
If you find that the exception is happening on the main thread, post back and let us know, and maybe we can help more. A stack trace at the time of the exception may help track down the problem. |
135,835 | <p>I am trying to load a small sample of records from a large database into a test database.</p>
<p>How do you tell mysqldump to only give you n records out of 8 million?</p>
<p>Thanks</p>
| [
{
"answer_id": 135843,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 3,
"selected": false,
"text": "<p>mysqldump can be given a SQL query to execute, from which it will take the data for the dump. You can then use the \"l... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am trying to load a small sample of records from a large database into a test database.
How do you tell mysqldump to only give you n records out of 8 million?
Thanks | As skaffman says, use the **--where** option:
```
mysqldump --opt --where="1 limit 1000000" database
```
Of course, that would give you the first million rows from every table. |
135,845 | <p>A colleague of mine states that <strong>booleans as method arguments are not acceptable</strong>. They shall be replaced by enumerations. At first I did not see any benefit, but he gave me an example.</p>
<p>What's easier to understand?</p>
<pre><code>file.writeData( data, true );
</code></pre>
<p>Or</p>
<pre><code>enum WriteMode {
Append,
Overwrite
};
file.writeData( data, Append );
</code></pre>
<p>Now I got it! ;-)<br>
This is definitely an example where an enumeration as second parameter makes the code much more readable.</p>
<p>So, what's your opinion on this topic?</p>
| [
{
"answer_id": 135865,
"author": "simon",
"author_id": 6040,
"author_profile": "https://Stackoverflow.com/users/6040",
"pm_score": 6,
"selected": false,
"text": "<p>Enums also allow for future modifications, where you now want a third choice (or more).</p>\n"
},
{
"answer_id": 13... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2012356/"
] | A colleague of mine states that **booleans as method arguments are not acceptable**. They shall be replaced by enumerations. At first I did not see any benefit, but he gave me an example.
What's easier to understand?
```
file.writeData( data, true );
```
Or
```
enum WriteMode {
Append,
Overwrite
};
file.writeData( data, Append );
```
Now I got it! ;-)
This is definitely an example where an enumeration as second parameter makes the code much more readable.
So, what's your opinion on this topic? | Boolean's represent "yes/no" choices. If you want to represent a "yes/no", then use a boolean, it should be self-explanatory.
But if it's a choice between two options, neither of which is clearly yes or no, then an enum can sometimes be more readable. |
135,849 | <p>I'm trying to host a python script using an apache web server, but the server tries to run the script instead of just offering it for download.</p>
<p>I do not have direct access to server, and adding the line</p>
<pre><code>AddType text/plain .py
</code></pre>
<p>to .htaccess in the root folder does not appear to work, though I could be doing something wrong.</p>
<p>How do I get the server to just send the file as text instead of trying to run it?</p>
<p>-Edit</p>
<p>Changing the name does not work. Script.py.safe still give a 500 Server error when you click it. </p>
<p>I should also mention that the .htaccess file does work, but for some reason that one addType line is not working. Either because it's not overriding something, or the line is wrong.</p>
| [
{
"answer_id": 135869,
"author": "Jeremy Bourque",
"author_id": 2192597,
"author_profile": "https://Stackoverflow.com/users/2192597",
"pm_score": 2,
"selected": false,
"text": "<p>If you can't change the Apache config and you can't override it with an htaccess file, then it seems to me t... | 2008/09/25 | [
"https://Stackoverflow.com/questions/135849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30/"
] | I'm trying to host a python script using an apache web server, but the server tries to run the script instead of just offering it for download.
I do not have direct access to server, and adding the line
```
AddType text/plain .py
```
to .htaccess in the root folder does not appear to work, though I could be doing something wrong.
How do I get the server to just send the file as text instead of trying to run it?
-Edit
Changing the name does not work. Script.py.safe still give a 500 Server error when you click it.
I should also mention that the .htaccess file does work, but for some reason that one addType line is not working. Either because it's not overriding something, or the line is wrong. | In your .htaccess:
>
> RemoveHandler .py
>
>
> |