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 |
|---|---|---|---|---|---|---|
123,159 | <p>Has anyone done this? Basically, I want to use the html by keeping basic tags such as h1, h2, em, etc; clean all non http addresses in the img and a tags; and HTMLEncode every other tag. </p>
<p>I'm stuck at the HTML Encoding part. I know to remove a node you do a "node.ParentNode.RemoveChild(node);" where node is the object of the class HtmlNode. Instead of removing the node though, I want to HTMLEncode it. </p>
| [
{
"answer_id": 123522,
"author": "Derek Slager",
"author_id": 18636,
"author_profile": "https://Stackoverflow.com/users/18636",
"pm_score": 1,
"selected": false,
"text": "<p>You would need to remove the node representing the element you don't want. The encoded HTML would then need to be ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10352/"
] | Has anyone done this? Basically, I want to use the html by keeping basic tags such as h1, h2, em, etc; clean all non http addresses in the img and a tags; and HTMLEncode every other tag.
I'm stuck at the HTML Encoding part. I know to remove a node you do a "node.ParentNode.RemoveChild(node);" where node is the object of the class HtmlNode. Instead of removing the node though, I want to HTMLEncode it. | You would need to remove the node representing the element you don't want. The encoded HTML would then need to be re-added as a text node.
If you don't want to process the children of the elements that you want to throw away, you should be able to just use OuterHtml ... something like this might work:
```
node.AppendChild(new HtmlTextNode { Text = HttpUtility.HtmlEncode(nodeToDelete.OuterHtml) });
``` |
123,181 | <p>Is there a way to test if an object is a dictionary?</p>
<p>In a method I'm trying to get a value from a selected item in a list box. In some circumstances, the list box might be bound to a dictionary, but this isn't known at compile time.</p>
<p>I would like to do something similar to this:</p>
<pre><code>if (listBox.ItemsSource is Dictionary<??>)
{
KeyValuePair<??> pair = (KeyValuePair<??>)listBox.SelectedItem;
object value = pair.Value;
}
</code></pre>
<p>Is there a way to do this dynamically at runtime using reflection? I know it's possible to use reflection with generic types and determine the key/value parameters, but I'm not sure if there's a way to do the rest after those values are retrieved.</p>
| [
{
"answer_id": 123191,
"author": "Guvante",
"author_id": 16800,
"author_profile": "https://Stackoverflow.com/users/16800",
"pm_score": 4,
"selected": false,
"text": "<p>Check to see if it implements IDictionary.</p>\n\n<p>See the definition of System.Collections.IDictionary to see what t... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12999/"
] | Is there a way to test if an object is a dictionary?
In a method I'm trying to get a value from a selected item in a list box. In some circumstances, the list box might be bound to a dictionary, but this isn't known at compile time.
I would like to do something similar to this:
```
if (listBox.ItemsSource is Dictionary<??>)
{
KeyValuePair<??> pair = (KeyValuePair<??>)listBox.SelectedItem;
object value = pair.Value;
}
```
Is there a way to do this dynamically at runtime using reflection? I know it's possible to use reflection with generic types and determine the key/value parameters, but I'm not sure if there's a way to do the rest after those values are retrieved. | It should be something like the following. I wrote this in the answer box so the syntax may not be exactly right, but I've made it Wiki editable so anybody can fix up.
```
if (listBox.ItemsSource.IsGenericType &&
typeof(IDictionary<,>).IsAssignableFrom(listBox.ItemsSource.GetGenericTypeDefinition()))
{
var method = typeof(KeyValuePair<,>).GetProperty("Value").GetGetMethod();
var item = method.Invoke(listBox.SelectedItem, null);
}
``` |
123,188 | <p>In C# when I am done entering the fields of a snippet, I can hit Enter to get to the next line. What is the equivalent Key in VB?</p>
<p>Edit: I prefer not to use the mouse.</p>
| [
{
"answer_id": 123195,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 1,
"selected": false,
"text": "<p>Don't know the key, but I use <em>right-click -> Hide Snippet Highlighting</em>.</p>\n"
},
{
"answer_id": 123243... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14484/"
] | In C# when I am done entering the fields of a snippet, I can hit Enter to get to the next line. What is the equivalent Key in VB?
Edit: I prefer not to use the mouse. | Wow... I sure hope they improve this soon.
Meanwhile, in case anyone cares, I created an additional replacement field ($Enter$) at the end of my custom snippet. This allows me to [tab] through the fields and then type [DownArrow] [Enter] when I reach the end of the list.
Something like....
```
private _$PropertyName$ As $PropertyType$
Public WriteOnly Property $PropertyName$() As $PropertyType$
Set(ByVal value as $PropertyType$)
_$PropertyName$ = value
End Set
End Property $Enter$
``` |
123,198 | <p>How do I copy a file in Python?</p>
| [
{
"answer_id": 123212,
"author": "Swati",
"author_id": 12682,
"author_profile": "https://Stackoverflow.com/users/12682",
"pm_score": 13,
"selected": true,
"text": "<p><a href=\"http://docs.python.org/3/library/shutil.html\" rel=\"noreferrer\"><code>shutil</code></a> has many methods you ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17693/"
] | How do I copy a file in Python? | [`shutil`](http://docs.python.org/3/library/shutil.html) has many methods you can use. One of which is:
```
import shutil
shutil.copyfile(src, dst)
# 2nd option
shutil.copy(src, dst) # dst can be a folder; use shutil.copy2() to preserve timestamp
```
* Copy the contents of the file named `src` to a file named `dst`. Both `src` and `dst` need to be the entire filename of the files, including path.
* The destination location must be writable; otherwise, an `IOError` exception will be raised.
* If `dst` already exists, it will be replaced.
* Special files such as character or block devices and pipes cannot be copied with this function.
* With `copy`, `src` and `dst` are path names given as `str`s.
Another `shutil` method to look at is [`shutil.copy2()`](https://docs.python.org/3/library/shutil.html#shutil.copy2). It's similar but preserves more metadata (e.g. time stamps).
If you use `os.path` operations, use `copy` rather than `copyfile`. `copyfile` will only accept strings. |
123,216 | <p>I can't make td "Date" to have fixed height. If there is less in Body section td Date element is bigger than it should be - even if I set Date height to 10% and Body height to 90%. Any suggestions?</p>
<pre><code><tr>
<td class="Author" rowspan="2">
<a href="#">Claude</a><br />
<a href="#"><img src="Users/4/Avatar.jpeg" style="border-width:0px;" /></a>
</td>
<td class="Date">
Sent:
<span>18.08.2008 20:49:28</span>
</td>
</tr>
<tr>
<td class="Body">
<span>Id lacinia lacus arcu non quis mollis sit. Ligula elit. Ultricies elit cursus. Quis ipsum nec rutrum id tellus aliquam. Tortor arcu fermentum nibh justo leo ante vitae fringilla. Pulvinar aliquam. Fringilla mollis facilisis.</span>
</td>
</tr>
</code></pre>
<p>And my css for now is: </p>
<pre><code>table.ForumThreadViewer td.Date {
text-align: left;
vertical-align: top;
font-size: xx-small;
border-bottom: solid 1 black;
height: 20px;
}
table.ForumThreadViewer td.Body {
text-align: left;
vertical-align: top;
border-top: solid 1 black;
}
table.ForumThreadViewer td.Author {
vertical-align: top;
text-align: left;
}
</code></pre>
<p>It's working for FF but not for IE. :(</p>
| [
{
"answer_id": 123245,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 0,
"selected": false,
"text": "<p>CSS</p>\n\n<pre><code>.Date {\n height: 50px;\n}\n</code></pre>\n"
},
{
"answer_id": 123248,
"autho... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3182/"
] | I can't make td "Date" to have fixed height. If there is less in Body section td Date element is bigger than it should be - even if I set Date height to 10% and Body height to 90%. Any suggestions?
```
<tr>
<td class="Author" rowspan="2">
<a href="#">Claude</a><br />
<a href="#"><img src="Users/4/Avatar.jpeg" style="border-width:0px;" /></a>
</td>
<td class="Date">
Sent:
<span>18.08.2008 20:49:28</span>
</td>
</tr>
<tr>
<td class="Body">
<span>Id lacinia lacus arcu non quis mollis sit. Ligula elit. Ultricies elit cursus. Quis ipsum nec rutrum id tellus aliquam. Tortor arcu fermentum nibh justo leo ante vitae fringilla. Pulvinar aliquam. Fringilla mollis facilisis.</span>
</td>
</tr>
```
And my css for now is:
```
table.ForumThreadViewer td.Date {
text-align: left;
vertical-align: top;
font-size: xx-small;
border-bottom: solid 1 black;
height: 20px;
}
table.ForumThreadViewer td.Body {
text-align: left;
vertical-align: top;
border-top: solid 1 black;
}
table.ForumThreadViewer td.Author {
vertical-align: top;
text-align: left;
}
```
It's working for FF but not for IE. :( | Oli is right! Give then screenshot you posted, you are using the wrong markup. You could use something more like this:
```
<div class="post">
<div class="author">
<a href="#">Claude</a><br />
<a href="#"><img src="Users/4/Avatar.jpeg" /></a>
</div>
<div class="content">
<div class="date">Sent: 18.08.2008 20:49:28</div>
<div class="body">
This is the content of the message.
</div>
</div>
<div class="clear"> </div>
</div>
```
with css like this:
```
div.post {
border: 1px solid #999;
margin-bottom: -1px; /* collapse the borders between posts */
}
div.author {
float: left;
width: 150px;
border-right: 1px solid #999;
}
div.content {
border-left: 1px solid #999;
margin-left: 150px;
}
div.date {
border-bottom: 1px solid #999;
}
div.clear {
clear: both;
height: 0;
line-height: 0;
}
``` |
123,235 | <p>I was trying to remove all the lines of a file except the last line but the following command did not work, although file.txt is not empty.</p>
<pre><code>$cat file.txt |tail -1 > file.txt
$cat file.txt
</code></pre>
<p>Why is it so?</p>
| [
{
"answer_id": 123249,
"author": "Lewis Baumstark",
"author_id": 12000,
"author_profile": "https://Stackoverflow.com/users/12000",
"pm_score": 0,
"selected": false,
"text": "<p>It seems to not like the fact you're writing it back to the same filename. If you do the following it works:</... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I was trying to remove all the lines of a file except the last line but the following command did not work, although file.txt is not empty.
```
$cat file.txt |tail -1 > file.txt
$cat file.txt
```
Why is it so? | Redirecting from a file through a pipeline back to the same file is unsafe; if `file.txt` is overwritten by the shell when setting up the last stage of the pipeline before `tail` starts reading off the first stage, you end up with empty output.
Do the following instead:
```
tail -1 file.txt >file.txt.new && mv file.txt.new file.txt
```
...well, actually, don't do that in production code; particularly if you're in a security-sensitive environment and running as root, the following is more appropriate:
```
tempfile="$(mktemp file.txt.XXXXXX)"
chown --reference=file.txt -- "$tempfile"
chmod --reference=file.txt -- "$tempfile"
tail -1 file.txt >"$tempfile" && mv -- "$tempfile" file.txt
```
Another approach (avoiding temporary files, unless `<<<` implicitly creates them on your platform) is the following:
```
lastline="$(tail -1 file.txt)"; cat >file.txt <<<"$lastline"
```
(The above implementation is bash-specific, but works in cases where echo does not -- such as when the last line contains "--version", for instance).
Finally, one can use sponge from [moreutils](http://kitenet.net/~joey/code/moreutils/):
```
tail -1 file.txt | sponge file.txt
``` |
123,236 | <p>We have a customer requesting data in XML format. Normally this is not required as we usually just hand off an Access database or csv files and that is sufficient. However in this case I need to automate the exporting of proper XML from a dozen tables.</p>
<p>If I can do it out of SQL Server 2005, that would be preferred. However I can't for the life of me find a way to do this. I can dump out raw xml data but this is just a tag per row with attribute values. We need something that represents the structure of the tables. Access has an export in xml format that meets our needs. However I'm not sure how this can be automated. It doesn't appear to be available in any way through SQL so I'm trying to track down the necessary code to export the XML through a macro or vbscript.</p>
<p>Any suggestions?</p>
| [
{
"answer_id": 123282,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 0,
"selected": false,
"text": "<p>There's an outline <a href=\"http://www.microsoft.com/technet/scriptcenter/resources/officetips/oct05/tips1020.mspx\" rel... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8345/"
] | We have a customer requesting data in XML format. Normally this is not required as we usually just hand off an Access database or csv files and that is sufficient. However in this case I need to automate the exporting of proper XML from a dozen tables.
If I can do it out of SQL Server 2005, that would be preferred. However I can't for the life of me find a way to do this. I can dump out raw xml data but this is just a tag per row with attribute values. We need something that represents the structure of the tables. Access has an export in xml format that meets our needs. However I'm not sure how this can be automated. It doesn't appear to be available in any way through SQL so I'm trying to track down the necessary code to export the XML through a macro or vbscript.
Any suggestions? | Look into using FOR XML AUTO. Depending on your requirements, you might need to use EXPLICIT.
As a quick example:
```
SELECT
*
FROM
Customers
INNER JOIN Orders ON Orders.CustID = Customers.CustID
FOR XML AUTO
```
This will generate a nested XML document with the orders inside the customers. You could then use SSIS to export that out into a file pretty easily I would think. I haven't tried it myself though. |
123,239 | <p>This is a sample (edited slightly, but you get the idea) of my XML file:</p>
<pre><code><HostCollection>
<ApplicationInfo />
<Hosts>
<Host>
<Name>Test</Name>
<IP>192.168.1.1</IP>
</Host>
<Host>
<Name>Test</Name>
<IP>192.168.1.2</IP>
</Host>
</Hosts>
</HostCollection>
</code></pre>
<p>When my application (VB.NET app) loads, I want to loop through the list of hosts and their attributes and add them to a collection. I was hoping I could use the XPathNodeIterator for this. The examples I found online seemed a little muddied, and I'm hoping someone here can clear things up a bit.</p>
| [
{
"answer_id": 123275,
"author": "kitsune",
"author_id": 13466,
"author_profile": "https://Stackoverflow.com/users/13466",
"pm_score": 3,
"selected": true,
"text": "<p>You could load them into an XmlDocument and use an XPath statement to fill a NodeList...</p>\n\n<pre><code>Dim doc As Xm... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5473/"
] | This is a sample (edited slightly, but you get the idea) of my XML file:
```
<HostCollection>
<ApplicationInfo />
<Hosts>
<Host>
<Name>Test</Name>
<IP>192.168.1.1</IP>
</Host>
<Host>
<Name>Test</Name>
<IP>192.168.1.2</IP>
</Host>
</Hosts>
</HostCollection>
```
When my application (VB.NET app) loads, I want to loop through the list of hosts and their attributes and add them to a collection. I was hoping I could use the XPathNodeIterator for this. The examples I found online seemed a little muddied, and I'm hoping someone here can clear things up a bit. | You could load them into an XmlDocument and use an XPath statement to fill a NodeList...
```
Dim doc As XmlDocument = New XmlDocument()
doc.Load("hosts.xml")
Dim nodeList as XmlNodeList
nodeList = doc.SelectNodes("/HostCollectionInfo/Hosts/Host")
```
Then loop through the nodes |
123,263 | <p>I'm reading text from a flat file in c# and need to test whether certain values are dates. They could be in either YYYYMMDD format or MM/DD/YY format. What is the simplest way to do this in .Net?</p>
| [
{
"answer_id": 123270,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx\" rel=\"nofollow noreferrer\">DateTime.TryParse</a... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625/"
] | I'm reading text from a flat file in c# and need to test whether certain values are dates. They could be in either YYYYMMDD format or MM/DD/YY format. What is the simplest way to do this in .Net? | ```cs
string[] formats = {"yyyyMMdd", "MM/dd/yy"};
var Result = DateTime.ParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None);
```
or
```cs
DateTime result;
string[] formats = {"yyyyMMdd", "MM/dd/yy"};
DateTime.TryParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out result);
```
More info in the MSDN documentation on [ParseExact](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parseexact) and [TryParseExact](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact). |
123,334 | <p>NOTE: I am not set on using VI, it is just the first thing that came to mind that might be able to do what I need. Feel free to suggest any other program.</p>
<p>I have a form with nearly 100 fields that I would like to auto-fill with PHP. I know how to do the autofill, but I would like to avoid manually adding the needed text to 100 fields.</p>
<p>Is there an automated way I can take the text:</p>
<pre><code><input name="riskRating" id="riskRating" type="text" />
</code></pre>
<p>and change it to:</p>
<pre><code><input name="riskRating" id="riskRating" type="text" value="<?php echo $data['riskRating']; ?>" />
</code></pre>
<p>Remember that I am wanting to do this to almost 100 fields. I am trying to avoid going to each field, pasting in the PHP code and changing the variable name manually.</p>
<p>I'm hoping some VI guru out there knows off the top of his/her head.</p>
| [
{
"answer_id": 123373,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 2,
"selected": false,
"text": "<p><code>:%s:\\(<input name=\"\\([^\"]\\+\\)\" id=\"[^\"]\\+\" type=\"text\" \\)/>:\\1value=\"<?php echo $d... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16292/"
] | NOTE: I am not set on using VI, it is just the first thing that came to mind that might be able to do what I need. Feel free to suggest any other program.
I have a form with nearly 100 fields that I would like to auto-fill with PHP. I know how to do the autofill, but I would like to avoid manually adding the needed text to 100 fields.
Is there an automated way I can take the text:
```
<input name="riskRating" id="riskRating" type="text" />
```
and change it to:
```
<input name="riskRating" id="riskRating" type="text" value="<?php echo $data['riskRating']; ?>" />
```
Remember that I am wanting to do this to almost 100 fields. I am trying to avoid going to each field, pasting in the PHP code and changing the variable name manually.
I'm hoping some VI guru out there knows off the top of his/her head. | Taking some ideas from Zsolt Botykai and Mark Biek:
```
:%s:<input\(.* id="\([^"]*\)".*\) />:<input \1 value="<?php echo $data['\2']; ?> />:g
``` |
123,336 | <p>How can you strip non-ASCII characters from a string? (in C#)</p>
| [
{
"answer_id": 123340,
"author": "philcruz",
"author_id": 3784,
"author_profile": "https://Stackoverflow.com/users/3784",
"pm_score": 10,
"selected": true,
"text": "<pre><code>string s = \"søme string\";\ns = Regex.Replace(s, @\"[^\\u0000-\\u007F]+\", string.Empty);\n</code></pre>\n"
}... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3784/"
] | How can you strip non-ASCII characters from a string? (in C#) | ```
string s = "søme string";
s = Regex.Replace(s, @"[^\u0000-\u007F]+", string.Empty);
``` |
123,378 | <p>Is there a good command-line UNIX charting / graphing / plotting tool out there? I'm looking for something that will plot xy points on an ASCII graph.</p>
<p>Just to clarify, I'm looking for something that will output a graph in ASCII (like ascii-art style), so I can use it over an interactive shell session without needing X.</p>
| [
{
"answer_id": 123396,
"author": "Palmin",
"author_id": 5949,
"author_profile": "https://Stackoverflow.com/users/5949",
"pm_score": 8,
"selected": true,
"text": "<p>Try <a href=\"http://www.gnuplot.info/\" rel=\"noreferrer\">gnuplot</a>. It has very powerful graphing possibilities.</p>\n... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21339/"
] | Is there a good command-line UNIX charting / graphing / plotting tool out there? I'm looking for something that will plot xy points on an ASCII graph.
Just to clarify, I'm looking for something that will output a graph in ASCII (like ascii-art style), so I can use it over an interactive shell session without needing X. | Try [gnuplot](http://www.gnuplot.info/). It has very powerful graphing possibilities.
It can output to your terminal in the following way:
```
gnuplot> set terminal dumb
Terminal type set to 'dumb'
Options are 'feed 79 24'
gnuplot> plot sin(x)
1 ++----------------**---------------+----**-----------+--------**-----++
+ *+ * + * * + sin(x) ****** +
0.8 ++ * * * * * * ++
| * * * * * * |
0.6 ++ * * * * * * ++
* * * * * * * |
0.4 +* * * * * * * ++
|* * * * * * * |
0.2 +* * * * * * * ++
| * * * * * * * |
0 ++* * * * * * *++
| * * * * * * *|
-0.2 ++ * * * * * * *+
| * * * * * * *|
-0.4 ++ * * * * * * *+
| * * * * * * *
-0.6 ++ * * * * * * ++
| * * * * * * |
-0.8 ++ * * * * * * ++
+ * * + * * + * * +
-1 ++-----**---------+----------**----+---------------**+---------------++
-10 -5 0 5 10
``` |
123,391 | <p>I would like to know how to unload an assembly that is loaded into the main AppDomain.</p>
<p>I have the following code:</p>
<pre><code>var assembly = Assembly.LoadFrom( FilePathHere );
</code></pre>
<p>I need/want to be able to unload this assembly when I am done.</p>
<p>Thanks for your help.</p>
| [
{
"answer_id": 123397,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 5,
"selected": false,
"text": "<p><strong>For .net versions core 3.0 and later:</strong></p>\n<p>You can now unload assemblies. Note that appdomain... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14164/"
] | I would like to know how to unload an assembly that is loaded into the main AppDomain.
I have the following code:
```
var assembly = Assembly.LoadFrom( FilePathHere );
```
I need/want to be able to unload this assembly when I am done.
Thanks for your help. | **For .net versions core 3.0 and later:**
You can now unload assemblies. Note that appdomains are no longer available in .net core. Instead, you can create one or more AssemblyLoadContext, load your assemblies via that context, then unload that context. See [AssemblyLoadContext](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.loader.assemblyloadcontext?view=netcore-3.0), or [this tutorial that simulates loading a plugin then unloading it](https://github.com/dotnet/samples/tree/master/core/tutorials/Unloading).
**For .net versions before .net core 3, including netframework 4 and lower**
You can not unload an assembly from an appdomain. You can destroy appdomains, but once an assembly is loaded into an appdomain, it's there for the life of the appdomain.
See Jason Zander's explanation of [Why isn't there an Assembly.Unload method?](https://learn.microsoft.com/en-us/archive/blogs/jasonz/why-isnt-there-an-assembly-unload-method)
If you are using 3.5, you can use the AddIn Framework to make it easier to manage/call into different AppDomains (which you *can* unload, unloading all the assemblies). If you are using versions before that, you need to create a new appdomain yourself to unload it. |
123,394 | <p>I know I can do this:</p>
<pre><code>IDateTimeFactory dtf = MockRepository.GenerateStub<IDateTimeFactory>();
dtf.Now = new DateTime();
DoStuff(dtf); // dtf.Now can be called arbitrary number of times, will always return the same value
dtf.Now = new DateTime()+new TimeSpan(0,1,0); // 1 minute later
DoStuff(dtf); //ditto from above
</code></pre>
<p>What if instead of <strong>IDateTimeFactory.Now</strong> being a property it is a method <strong>IDateTimeFactory.GetNow()</strong>, how do I do the same thing?</p>
<p>As per Judah's suggestion below I have rewritten my SetDateTime helper method as follows:</p>
<pre><code> private void SetDateTime(DateTime dt) {
Expect.Call(_now_factory.GetNow()).Repeat.Any();
LastCall.Do((Func<DateTime>)delegate() { return dt; });
}
</code></pre>
<p>but it still throws "The result for ICurrentDateTimeFactory.GetNow(); has already been setup." errors.</p>
<p>Plus its still not going to work with a stub....</p>
| [
{
"answer_id": 123515,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 0,
"selected": false,
"text": "<p>You can use Expect.Call to accomplish this. Here's an example using the record/playback model:</p>\n\n<pre><c... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | I know I can do this:
```
IDateTimeFactory dtf = MockRepository.GenerateStub<IDateTimeFactory>();
dtf.Now = new DateTime();
DoStuff(dtf); // dtf.Now can be called arbitrary number of times, will always return the same value
dtf.Now = new DateTime()+new TimeSpan(0,1,0); // 1 minute later
DoStuff(dtf); //ditto from above
```
What if instead of **IDateTimeFactory.Now** being a property it is a method **IDateTimeFactory.GetNow()**, how do I do the same thing?
As per Judah's suggestion below I have rewritten my SetDateTime helper method as follows:
```
private void SetDateTime(DateTime dt) {
Expect.Call(_now_factory.GetNow()).Repeat.Any();
LastCall.Do((Func<DateTime>)delegate() { return dt; });
}
```
but it still throws "The result for ICurrentDateTimeFactory.GetNow(); has already been setup." errors.
Plus its still not going to work with a stub.... | George,
Using your updated code, I got this to work:
```
MockRepository mocks = new MockRepository();
[Test]
public void Test()
{
IDateTimeFactory dtf = mocks.DynamicMock<IDateTimeFactory>();
DateTime desiredNowTime = DateTime.Now;
using (mocks.Record())
{
SetupResult.For(dtf.GetNow()).Do((Func<DateTime>)delegate { return desiredNowTime; });
}
using (mocks.Playback())
{
DoStuff(dtf); // Prints the current time
desiredNowTime += TimeSpan.FromMinutes(1); // 1 minute later
DoStuff(dtf); // Prints the time 1 minute from now
}
}
void DoStuff(IDateTimeFactory factory)
{
DateTime time = factory.GetNow();
Console.WriteLine(time);
}
```
FWIW, I don't believe you can accomplish this using stubs; you need to use a mock instead. |
123,401 | <p>Using jQuery, how do you bind a click event to a table cell (below, <code>class="expand"</code>) that will change the <code>image src</code> (which is in the clicked cell - original will be plus.gif, alternating with minus.gif) and <code>hide/show</code> the row immediately below it based on whether that row has a class of <code>hide</code>. (show it if it has a class of "hide" and hide if it does not have a class of "hide"). I am flexible with changing ids and classes in the markup.</p>
<p>Thanks</p>
<p>Table rows</p>
<pre><code><tr>
<td class="expand"><img src="plus.gif"/></td>
<td>Data1</td><td>Data2</td><td>Data3</td>
</tr>
<tr class="show hide">
<td> </td>
<td>Data4</td><td>Data5</td><td>Data6</td>
</tr>
</code></pre>
| [
{
"answer_id": 123518,
"author": "neuroguy123",
"author_id": 12529,
"author_profile": "https://Stackoverflow.com/users/12529",
"pm_score": 5,
"selected": true,
"text": "<p>You don't need the show and hide tags:</p>\n\n<pre><code>$(document).ready(function(){ \n $('.expand').click(fu... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
] | Using jQuery, how do you bind a click event to a table cell (below, `class="expand"`) that will change the `image src` (which is in the clicked cell - original will be plus.gif, alternating with minus.gif) and `hide/show` the row immediately below it based on whether that row has a class of `hide`. (show it if it has a class of "hide" and hide if it does not have a class of "hide"). I am flexible with changing ids and classes in the markup.
Thanks
Table rows
```
<tr>
<td class="expand"><img src="plus.gif"/></td>
<td>Data1</td><td>Data2</td><td>Data3</td>
</tr>
<tr class="show hide">
<td> </td>
<td>Data4</td><td>Data5</td><td>Data6</td>
</tr>
``` | You don't need the show and hide tags:
```
$(document).ready(function(){
$('.expand').click(function() {
if( $(this).hasClass('hidden') )
$('img', this).attr("src", "plus.jpg");
else
$('img', this).attr("src", "minus.jpg");
$(this).toggleClass('hidden');
$(this).parent().next().toggle();
});
});
```
edit: Okay, I added the code for changing the image. That's just one way to do it. I added a class to the expand attribute as a tag when the row that follows is hidden and removed it when the row was shown. |
123,489 | <p>I am using REPLACE in an SQL view to remove the spaces from a property number. The function is setup like this REPLACE(pin, ' ', ''). On the green-screen the query looked fine. In anything else we get the hex values of the characters in the field. I am sure it is an encoding thing, but how do I fix it?</p>
<p>Here is the statement I used to create the view:</p>
<pre><code>CREATE VIEW RLIC2GIS AS SELECT REPLACE(RCAPIN, ' ', '') AS
RCAPIN13 , RLICNO, RONAME, ROADR1, ROADR2, ROCITY, ROSTAT, ROZIP1,
ROZIP2, RGRID, RRADR1, RRADR2, RANAME, RAADR1, RAADR2, RACITY,
RASTAT, RAZIP1, RAZIP2, REGRES, RPENDI, RBLDGT, ROWNOC, RRCODE,
RROOMS, RUNITS, RTUNIT, RPAID, RAMTPD, RMDYPD, RRFUSE, RNUMCP,
RDATCP, RINSP, RCAUKY, RCAPIN, RAMTYR, RYREXP, RDELET, RVARIA,
RMDYIN, RDTLKI, ROPHN1, ROPHN2, ROCOM1, ROCOM2, RAPHN1, RAPHN2,
RACOM1, RACOM2, RNOTES FROM RLIC2
</code></pre>
<p>UPDATE: I posted the answer below.</p>
| [
{
"answer_id": 123498,
"author": "Mike McAllister",
"author_id": 16247,
"author_profile": "https://Stackoverflow.com/users/16247",
"pm_score": 0,
"selected": false,
"text": "<p>Try using NULL rather than an empty string. i.e. REPLACE(RCAPIN, ' ', NULL)</p>\n"
},
{
"answer_id": 12... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2535/"
] | I am using REPLACE in an SQL view to remove the spaces from a property number. The function is setup like this REPLACE(pin, ' ', ''). On the green-screen the query looked fine. In anything else we get the hex values of the characters in the field. I am sure it is an encoding thing, but how do I fix it?
Here is the statement I used to create the view:
```
CREATE VIEW RLIC2GIS AS SELECT REPLACE(RCAPIN, ' ', '') AS
RCAPIN13 , RLICNO, RONAME, ROADR1, ROADR2, ROCITY, ROSTAT, ROZIP1,
ROZIP2, RGRID, RRADR1, RRADR2, RANAME, RAADR1, RAADR2, RACITY,
RASTAT, RAZIP1, RAZIP2, REGRES, RPENDI, RBLDGT, ROWNOC, RRCODE,
RROOMS, RUNITS, RTUNIT, RPAID, RAMTPD, RMDYPD, RRFUSE, RNUMCP,
RDATCP, RINSP, RCAUKY, RCAPIN, RAMTYR, RYREXP, RDELET, RVARIA,
RMDYIN, RDTLKI, ROPHN1, ROPHN2, ROCOM1, ROCOM2, RAPHN1, RAPHN2,
RACOM1, RACOM2, RNOTES FROM RLIC2
```
UPDATE: I posted the answer below. | We ended up using concat and substring to get the results we wanted.
```
CREATE VIEW RLIC2GIS AS
SELECT CONCAT(SUBSTR(RCAPIN,1,3),CONCAT(SUBSTR(RCAPIN,5,2),
CONCAT(SUBSTR(RCAPIN,8,2), CONCAT(SUBSTR(RCAPIN,11,3),
SUBSTR(RCAPIN, 15,3))))) AS CAPIN13, RLICNO, RONAME, ROADR1,
ROADR2, ROCITY, ROSTAT, ROZIP1, ROZIP2, RGRID, RRADR1, RRADR2,
RANAME, RAADR1, RAADR2, RACITY, RASTAT, RAZIP1, RAZIP2, REGRES,
RPENDI, RBLDGT, ROWNOC, RRCODE, RROOMS, RUNITS, RTUNIT, RPAID,
RAMTPD, RMDYPD, RRFUSE, RNUMCP, RDATCP, RINSP, RCAUKY, RCAPIN,
RAMTYR, RYREXP, RDELET, RVARIA, RMDYIN, RDTLKI, ROPHN1, ROPHN2,
ROCOM1, ROCOM2, RAPHN1, RAPHN2, RACOM1, RACOM2, RNOTES FROM RLIC2
``` |
123,499 | <p>I've got the directive</p>
<pre><code><VirtualHost *>
<Location />
AuthType Digest
AuthName "global"
AuthDigestDomain /
AuthUserFile /root/apache_users
<Limit GET>
Require valid-user
</Limit>
</Location>
WSGIScriptAlias / /some/script.wsgi
WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25
WSGIProcessGroup mywsgi
ServerName some.example.org
</VirtualHost>
</code></pre>
<p>I'd like to know in the /some/script.wsgi</p>
<pre><code>def application(environ, start_response):
start_response('200 OK', [
('Content-Type', 'text/plain'),
])
return ['Hello']
</code></pre>
<p>What user is logged in.</p>
<p>How do I do that?</p>
| [
{
"answer_id": 123526,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 5,
"selected": true,
"text": "<p>add <code>WSGIPassAuthorization On</code>:</p>\n\n<pre><code><VirtualHost *>\n <Location />\n AuthT... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19435/"
] | I've got the directive
```
<VirtualHost *>
<Location />
AuthType Digest
AuthName "global"
AuthDigestDomain /
AuthUserFile /root/apache_users
<Limit GET>
Require valid-user
</Limit>
</Location>
WSGIScriptAlias / /some/script.wsgi
WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25
WSGIProcessGroup mywsgi
ServerName some.example.org
</VirtualHost>
```
I'd like to know in the /some/script.wsgi
```
def application(environ, start_response):
start_response('200 OK', [
('Content-Type', 'text/plain'),
])
return ['Hello']
```
What user is logged in.
How do I do that? | add `WSGIPassAuthorization On`:
```
<VirtualHost *>
<Location />
AuthType Digest
AuthName "global"
AuthDigestDomain /
AuthUserFile /root/apache_users
<Limit GET>
Require valid-user
</Limit>
</Location>
WSGIPassAuthorization On
WSGIScriptAlias / /some/script.wsgi
WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25
WSGIProcessGroup mywsgi
ServerName some.example.org
</VirtualHost>
```
Then just read `environ['REMOTE_USER']`:
```
def application(environ, start_response):
start_response('200 OK', [
('Content-Type', 'text/plain'),
])
return ['Hello %s' % environ['REMOTE_USER']]
```
More information at [mod\_wsgi documentation](http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#User_Authentication "User Authentication on WSGI applications"). |
123,503 | <p>I'm writing an iPhone app with Cocoa in xcode. I can't find any tutorials or sample code that shows how to take photos with the built in camera. How do I do this? Where can I find good info?</p>
<p>Thanks!</p>
| [
{
"answer_id": 123590,
"author": "jblocksom",
"author_id": 20626,
"author_profile": "https://Stackoverflow.com/users/20626",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>UIImagePickerController</code> class lets you take pictures or choose them from the photo library. Specify... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm writing an iPhone app with Cocoa in xcode. I can't find any tutorials or sample code that shows how to take photos with the built in camera. How do I do this? Where can I find good info?
Thanks! | Just Copy and paste following code into your project to get fully implemented functionality.
where **takePhoto** and **chooseFromLibrary** are my own method names which will be called on button touch.
Make sure to reference outlets of appropriate buttons to these methods.
```
-(IBAction)takePhoto :(id)sender
{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
[imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];
}
// image picker needs a delegate,
[imagePickerController setDelegate:self];
// Place image picker on the screen
[self presentModalViewController:imagePickerController animated:YES];
}
-(IBAction)chooseFromLibrary:(id)sender
{
UIImagePickerController *imagePickerController= [[UIImagePickerController alloc] init];
[imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
// image picker needs a delegate so we can respond to its messages
[imagePickerController setDelegate:self];
// Place image picker on the screen
[self presentModalViewController:imagePickerController animated:YES];
}
//delegate methode will be called after picking photo either from camera or library
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self dismissModalViewControllerAnimated:YES];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
[myImageView setImage:image]; // "myImageView" name of any UIImageView.
}
``` |
123,504 | <p>In wxWidgets, how can you find the pixels per inch on a wxDC? I'd like to be able to scale things by a real world number like inches. That often makes it easier to use the same code for printing to the screen and the printer.</p>
| [
{
"answer_id": 123590,
"author": "jblocksom",
"author_id": 20626,
"author_profile": "https://Stackoverflow.com/users/20626",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>UIImagePickerController</code> class lets you take pictures or choose them from the photo library. Specify... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17693/"
] | In wxWidgets, how can you find the pixels per inch on a wxDC? I'd like to be able to scale things by a real world number like inches. That often makes it easier to use the same code for printing to the screen and the printer. | Just Copy and paste following code into your project to get fully implemented functionality.
where **takePhoto** and **chooseFromLibrary** are my own method names which will be called on button touch.
Make sure to reference outlets of appropriate buttons to these methods.
```
-(IBAction)takePhoto :(id)sender
{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
[imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];
}
// image picker needs a delegate,
[imagePickerController setDelegate:self];
// Place image picker on the screen
[self presentModalViewController:imagePickerController animated:YES];
}
-(IBAction)chooseFromLibrary:(id)sender
{
UIImagePickerController *imagePickerController= [[UIImagePickerController alloc] init];
[imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
// image picker needs a delegate so we can respond to its messages
[imagePickerController setDelegate:self];
// Place image picker on the screen
[self presentModalViewController:imagePickerController animated:YES];
}
//delegate methode will be called after picking photo either from camera or library
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self dismissModalViewControllerAnimated:YES];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
[myImageView setImage:image]; // "myImageView" name of any UIImageView.
}
``` |
123,506 | <p>I have a ASP.NET application running on a remote web server and I just started getting this error:</p>
<pre><code>Method not found: 'Void System.Collections.Generic.ICollection`1..ctor()'.
</code></pre>
<p>I disassembled the code in the DLL and it seems like the compiler is incorrectly optimizing the code. (Note that Set is a class that implements a set of unique objects. It inherits from IEnumerable.) This line:</p>
<pre><code>Set<int> set = new Set<int>();
</code></pre>
<p>Is compiled into this line:</p>
<pre><code>Set<int> set = (Set<int>) new ICollection<CalendarModule>();
</code></pre>
<p>The CalendarModule class is a totally unrelated class!! Has anyone ever noticed .NET incorrectly compiling code like this before?</p>
<p><strong>Update #1:</strong> This problem seems to be introduced by Microsoft's <a href="http://research.microsoft.com/~mbarnett/ILMerge.aspx" rel="nofollow noreferrer">ILMerge</a> tool. We are currently investigating how to overcome it.</p>
<p><strong>Update #2:</strong> We found two ways to solve this problem so far. We don't quite understand what the underlying problem is, but both of these fix it:</p>
<ol>
<li><p>Turn off optimization.</p></li>
<li><p>Merge the assemblie with ILMerge on a different machine.</p></li>
</ol>
<p>So we are left wondering if the build machine is misconfigured somehow (which is strange considering that we have been using the machine to build releases for over a year now) or if it is some other problem.</p>
| [
{
"answer_id": 123538,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 1,
"selected": false,
"text": "<p>Are you sure that the assembly you're looking at was actually generated from the source code in question? Are you... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10475/"
] | I have a ASP.NET application running on a remote web server and I just started getting this error:
```
Method not found: 'Void System.Collections.Generic.ICollection`1..ctor()'.
```
I disassembled the code in the DLL and it seems like the compiler is incorrectly optimizing the code. (Note that Set is a class that implements a set of unique objects. It inherits from IEnumerable.) This line:
```
Set<int> set = new Set<int>();
```
Is compiled into this line:
```
Set<int> set = (Set<int>) new ICollection<CalendarModule>();
```
The CalendarModule class is a totally unrelated class!! Has anyone ever noticed .NET incorrectly compiling code like this before?
**Update #1:** This problem seems to be introduced by Microsoft's [ILMerge](http://research.microsoft.com/~mbarnett/ILMerge.aspx) tool. We are currently investigating how to overcome it.
**Update #2:** We found two ways to solve this problem so far. We don't quite understand what the underlying problem is, but both of these fix it:
1. Turn off optimization.
2. Merge the assemblie with ILMerge on a different machine.
So we are left wondering if the build machine is misconfigured somehow (which is strange considering that we have been using the machine to build releases for over a year now) or if it is some other problem. | Ahh, ILMerge - that extra info in your question really helps with your problem. While I wouldn't ever expect the .net compiler to fail in this way I would expect to occasionally see this sort of thing with ILMerge (given what it's doing).
My guess is that two of your assemblies are using the same optimisation 'trick', and once merged you get the conflict.
Have you raised the bug with Microsoft?
A workaround in the meantime is to recompile the assemblies from source as a single assembly, saving the need for ILMerge. As the csproj files are just XML lists they're basically easy to merge, and you could automate that as an extra MSBuild step. |
123,557 | <p>I need to select a bunch of data into a temp table to then do some secondary calculations; To help make it work more efficiently, I would like to have an IDENTITY column on that table. I know I could declare the table first with an identity, then insert the rest of the data into it, but is there a way to do it in 1 step?</p>
| [
{
"answer_id": 123642,
"author": "Hector Sosa Jr",
"author_id": 12829,
"author_profile": "https://Stackoverflow.com/users/12829",
"pm_score": -1,
"selected": false,
"text": "<p>IIRC, the INSERT INTO command uses the schema of the source table to create the temp table. That's part of the ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19305/"
] | I need to select a bunch of data into a temp table to then do some secondary calculations; To help make it work more efficiently, I would like to have an IDENTITY column on that table. I know I could declare the table first with an identity, then insert the rest of the data into it, but is there a way to do it in 1 step? | Oh ye of little faith:
```
SELECT *, IDENTITY( int ) AS idcol
INTO #newtable
FROM oldtable
```
<http://msdn.microsoft.com/en-us/library/aa933208(SQL.80).aspx> |
123,558 | <p>Is it possible to disable a trigger for a batch of commands and then enable it when the batch is done?</p>
<p>I'm sure I could drop the trigger and re-add it but I was wondering if there was another way.</p>
| [
{
"answer_id": 123566,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 7,
"selected": true,
"text": "<pre><code>DISABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL }\nON { object_name | DATABASE | ALL SERVER }... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4068/"
] | Is it possible to disable a trigger for a batch of commands and then enable it when the batch is done?
I'm sure I could drop the trigger and re-add it but I was wondering if there was another way. | ```
DISABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL }
ON { object_name | DATABASE | ALL SERVER } [ ; ]
```
<http://msdn.microsoft.com/en-us/library/ms189748(SQL.90).aspx>
followed by the inverse:
```
ENABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL }
ON { object_name | DATABASE | ALL SERVER } [ ; ]
```
<http://msdn.microsoft.com/en-us/library/ms182706(SQL.90).aspx> |
123,559 | <p>I'm trying to put together a comprehensive regex to validate phone numbers. Ideally it would handle international formats, but it must handle US formats, including the following:</p>
<ul>
<li><code>1-234-567-8901</code></li>
<li><code>1-234-567-8901 x1234</code></li>
<li><code>1-234-567-8901 ext1234</code></li>
<li><code>1 (234) 567-8901</code></li>
<li><code>1.234.567.8901</code></li>
<li><code>1/234/567/8901</code></li>
<li><code>12345678901</code></li>
</ul>
<p>I'll answer with my current attempt, but I'm hoping somebody has something better and/or more elegant.</p>
| [
{
"answer_id": 123565,
"author": "Nicholas Trandem",
"author_id": 765,
"author_profile": "https://Stackoverflow.com/users/765",
"pm_score": 4,
"selected": false,
"text": "<p>Here's my best try so far. It handles the formats above but I'm sure I'm missing some other possible formats.</p>\... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/765/"
] | I'm trying to put together a comprehensive regex to validate phone numbers. Ideally it would handle international formats, but it must handle US formats, including the following:
* `1-234-567-8901`
* `1-234-567-8901 x1234`
* `1-234-567-8901 ext1234`
* `1 (234) 567-8901`
* `1.234.567.8901`
* `1/234/567/8901`
* `12345678901`
I'll answer with my current attempt, but I'm hoping somebody has something better and/or more elegant. | Better option... just strip all non-digit characters on input (except 'x' and leading '+' signs), taking care because of the British tendency to write numbers in the non-standard form `+44 (0) ...` when asked to use the international prefix (in that specific case, you should discard the `(0)` entirely).
Then, you end up with values like:
```
12345678901
12345678901x1234
345678901x1234
12344678901
12345678901
12345678901
12345678901
+4112345678
+441234567890
```
Then when you display, reformat to your hearts content. e.g.
```
1 (234) 567-8901
1 (234) 567-8901 x1234
``` |
123,598 | <p>I have an Enum called Status defined as such:</p>
<pre><code>public enum Status {
VALID("valid"), OLD("old");
private final String val;
Status(String val) {
this.val = val;
}
public String getStatus() {
return val;
}
}
</code></pre>
<p>I would like to access the value of <code>VALID</code> from a JSTL tag. Specifically the <code>test</code> attribute of the <code><c:when></code> tag. E.g.</p>
<pre><code><c:when test="${dp.status eq Status.VALID">
</code></pre>
<p>I'm not sure if this is possible.</p>
| [
{
"answer_id": 130002,
"author": "IaCoder",
"author_id": 17337,
"author_profile": "https://Stackoverflow.com/users/17337",
"pm_score": 5,
"selected": false,
"text": "\n\n<p>So to get my problem fully resolved I needed to do the following:</p>\n\n<pre class=\"lang-xml prettyprint-override... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17337/"
] | I have an Enum called Status defined as such:
```
public enum Status {
VALID("valid"), OLD("old");
private final String val;
Status(String val) {
this.val = val;
}
public String getStatus() {
return val;
}
}
```
I would like to access the value of `VALID` from a JSTL tag. Specifically the `test` attribute of the `<c:when>` tag. E.g.
```
<c:when test="${dp.status eq Status.VALID">
```
I'm not sure if this is possible. | A simple comparison against string works:
```xml
<c:when test="${someModel.status == 'OLD'}">
``` |
123,632 | <pre><code>devenv mysolution.sln /build "Release|Win32" /project myproject
</code></pre>
<p>When building from the command line, it seems I have the option of doing a <code>/build</code> or <code>/rebuild</code>, but no way of saying I want to do "project only" (i.e. not build or rebuild the specified project's dependencies as well). Does anyone know of a way?</p>
| [
{
"answer_id": 123649,
"author": "Ben Straub",
"author_id": 1319,
"author_profile": "https://Stackoverflow.com/users/1319",
"pm_score": 2,
"selected": false,
"text": "<p>Don't call <code>devenv</code>, use the genericized build tool instead:</p>\n\n<pre><code>vcbuild subproject.vcproj \"... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
] | ```
devenv mysolution.sln /build "Release|Win32" /project myproject
```
When building from the command line, it seems I have the option of doing a `/build` or `/rebuild`, but no way of saying I want to do "project only" (i.e. not build or rebuild the specified project's dependencies as well). Does anyone know of a way? | Depending on the structure of your build system, this may be what you're looking for:
```
msbuild /p:BuildProjectReferences=false project.proj
``` |
123,639 | <p>Suppose I use the [RemoteClass] tag to endow a custom Flex class with serialization intelligence. </p>
<p>What happens when I need to change my object (add a new field, remove a field, rename a field, etc)?</p>
<p>Is there a design pattern for handling this in an elegant way?</p>
| [
{
"answer_id": 127521,
"author": "Marc Hughes",
"author_id": 6791,
"author_profile": "https://Stackoverflow.com/users/6791",
"pm_score": 1,
"selected": false,
"text": "<p>Adding or removing generally works. </p>\n\n<p>You'll get runtime warnings in your trace about properties either bei... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1750627/"
] | Suppose I use the [RemoteClass] tag to endow a custom Flex class with serialization intelligence.
What happens when I need to change my object (add a new field, remove a field, rename a field, etc)?
Is there a design pattern for handling this in an elegant way? | Your best bet is to do code generation against your backend classes to generation ActionScript counterparts for them. If you generate a base class with all of your object properties and then create a subclass for it which is never modified, you can still add custom code while regenerating only the parts of your class that change. Example:
```
java:
public class User {
public Long id;
public String firstName;
public String lastName;
}
as3:
public class UserBase {
public var id : Number;
public var firstName : String;
public var lastName : String;
}
[Bindable] [RemoteClass(...)]
public class User extends UserBase {
public function getFullName() : String {
return firstName + " " + lastName;
}
}
```
Check out the Granite Data Services project for Java -> AS3 code generation.
<http://www.graniteds.org> |
123,648 | <p>I know that a SQL Server full text index can not index more than one table. But, I have relationships in tables that I would like to implement full text indexes on.</p>
<p>Take the 3 tables below...</p>
<pre><code>Vehicle
Veh_ID - int (Primary Key)
FK_Atr_VehicleColor - int
Veh_Make - nvarchar(20)
Veh_Model - nvarchar(50)
Veh_LicensePlate - nvarchar(10)
Attributes
Atr_ID - int (Primary Key)
FK_Aty_ID - int
Atr_Name - nvarchar(50)
AttributeTypes
Aty_ID - int (Primary key)
Aty_Name - nvarchar(50)
</code></pre>
<p>The Attributes and AttributeTypes tables hold values that can be used in drop down lists throughout the application being built. For example, Attribute Type of "Vehicle Color" with Attributes of "Black", "Blue", "Red", etc...</p>
<p>Ok, so the problem comes when a user is trying to search for a "Blue Ford Mustang". So what is the best solution considering that tables like Vehicle will get rather large?</p>
<p>Do I create another field in the "Vehicle" table that is "Veh Color" that holds the text value of what is selected in the drop down in addition to "FK Atr VehicleColor"?</p>
<p>Or, do I drop "FK Atr VehicleColor" altogether and add "Veh Color"? I can use text value of "Veh Color" to match against "Atr Name" when the drop down is populated in an update form. With this approach I will have to handle if Attributes are dropped from the database.</p>
<p>-- Note: could not use underscore outside of code view as everything between two underscores is <em>italicized</em>.</p>
| [
{
"answer_id": 123814,
"author": "Cowan",
"author_id": 17041,
"author_profile": "https://Stackoverflow.com/users/17041",
"pm_score": 0,
"selected": false,
"text": "<p>As I understand it (I've used SQL Server a lot but never full-text indexing) SQL Server 2005 allows you to create full te... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/576/"
] | I know that a SQL Server full text index can not index more than one table. But, I have relationships in tables that I would like to implement full text indexes on.
Take the 3 tables below...
```
Vehicle
Veh_ID - int (Primary Key)
FK_Atr_VehicleColor - int
Veh_Make - nvarchar(20)
Veh_Model - nvarchar(50)
Veh_LicensePlate - nvarchar(10)
Attributes
Atr_ID - int (Primary Key)
FK_Aty_ID - int
Atr_Name - nvarchar(50)
AttributeTypes
Aty_ID - int (Primary key)
Aty_Name - nvarchar(50)
```
The Attributes and AttributeTypes tables hold values that can be used in drop down lists throughout the application being built. For example, Attribute Type of "Vehicle Color" with Attributes of "Black", "Blue", "Red", etc...
Ok, so the problem comes when a user is trying to search for a "Blue Ford Mustang". So what is the best solution considering that tables like Vehicle will get rather large?
Do I create another field in the "Vehicle" table that is "Veh Color" that holds the text value of what is selected in the drop down in addition to "FK Atr VehicleColor"?
Or, do I drop "FK Atr VehicleColor" altogether and add "Veh Color"? I can use text value of "Veh Color" to match against "Atr Name" when the drop down is populated in an update form. With this approach I will have to handle if Attributes are dropped from the database.
-- Note: could not use underscore outside of code view as everything between two underscores is *italicized*. | I believe it's a common practice to have separate denormalized table specifically for full-text indexing. This table is then updated by triggers or, as it was in our case, by SQL Server's scheduled task.
This was SQL Server 2000. In SQL Server you can have an [indexed view](http://www.microsoft.com/technet/prodtechnol/sql/2005/impprfiv.mspx) with full-text index: <http://msdn.microsoft.com/en-us/library/ms187317.aspx>. But note that there are many restrictions on indexed views; for instance, *you can't index a view that uses OUTER join*. |
123,657 | <p>I would like to know if there is some way to share a variable or an object between two or more Servlets, I mean some "standard" way. I suppose that this is not a good practice but is a easier way to build a prototype.</p>
<p>I don't know if it depends on the technologies used, but I'll use Tomcat 5.5</p>
<hr>
<p>I want to share a Vector of objects of a simple class (just public attributes, strings, ints, etc). My intention is to have a static data like in a DB, obviously it will be lost when the Tomcat is stopped. (it's just for Testing)</p>
| [
{
"answer_id": 123696,
"author": "yalestar",
"author_id": 2177,
"author_profile": "https://Stackoverflow.com/users/2177",
"pm_score": 1,
"selected": false,
"text": "<p>Couldn't you just put the object in the HttpSession and then refer to it by its attribute name in each of the servlets?<... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19689/"
] | I would like to know if there is some way to share a variable or an object between two or more Servlets, I mean some "standard" way. I suppose that this is not a good practice but is a easier way to build a prototype.
I don't know if it depends on the technologies used, but I'll use Tomcat 5.5
---
I want to share a Vector of objects of a simple class (just public attributes, strings, ints, etc). My intention is to have a static data like in a DB, obviously it will be lost when the Tomcat is stopped. (it's just for Testing) | I think what you're looking for here is request, session or application data.
In a servlet you can add an object as an attribute to the request object, session object or servlet context object:
```
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
String shared = "shared";
request.setAttribute("sharedId", shared); // add to request
request.getSession().setAttribute("sharedId", shared); // add to session
this.getServletConfig().getServletContext().setAttribute("sharedId", shared); // add to application context
request.getRequestDispatcher("/URLofOtherServlet").forward(request, response);
}
```
If you put it in the request object it will be available to the servlet that is forwarded to until the request is finished:
```
request.getAttribute("sharedId");
```
If you put it in the session it will be available to all the servlets going forward but the value will be tied to the user:
```
request.getSession().getAttribute("sharedId");
```
Until the session expires based on inactivity from the user.
Is reset by you:
```
request.getSession().invalidate();
```
Or one servlet removes it from scope:
```
request.getSession().removeAttribute("sharedId");
```
If you put it in the servlet context it will be available while the application is running:
```
this.getServletConfig().getServletContext().getAttribute("sharedId");
```
Until you remove it:
```
this.getServletConfig().getServletContext().removeAttribute("sharedId");
``` |
123,661 | <p>Consider a <em>hypothetical</em> method of an object that does stuff for you:</p>
<pre><code>public class DoesStuff
{
BackgroundWorker _worker = new BackgroundWorker();
...
public void CancelDoingStuff()
{
_worker.CancelAsync();
//todo: Figure out a way to wait for BackgroundWorker to be cancelled.
}
}
</code></pre>
<p>How can one wait for a BackgroundWorker to be done?</p>
<hr>
<p>In the past people have tried:</p>
<pre><code>while (_worker.IsBusy)
{
Sleep(100);
}
</code></pre>
<p>But <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1819196&SiteID=1" rel="noreferrer">this deadlocks</a>, because <code>IsBusy</code> is not cleared until after the <code>RunWorkerCompleted</code> event is handled, and that event can't get handled until the application goes idle. The application won't go idle until the worker is done. (Plus, it's a busy loop - disgusting.)</p>
<p>Others have add suggested kludging it into:</p>
<pre><code>while (_worker.IsBusy)
{
Application.DoEvents();
}
</code></pre>
<p>The problem with that is that is <code>Application.DoEvents()</code> causes messages currently in the queue to be processed, which cause re-entrancy problems (.NET isn't re-entrant).</p>
<p>I would hope to use some solution involving Event synchronization objects, where the code <strong>waits</strong> for an event - that the worker's <code>RunWorkerCompleted</code> event handlers sets. Something like:</p>
<pre><code>Event _workerDoneEvent = new WaitHandle();
public void CancelDoingStuff()
{
_worker.CancelAsync();
_workerDoneEvent.WaitOne();
}
private void RunWorkerCompletedEventHandler(sender object, RunWorkerCompletedEventArgs e)
{
_workerDoneEvent.SetEvent();
}
</code></pre>
<p>But I'm back to the deadlock: the event handler can't run until the application goes idle, and the application won't go idle because it's waiting for an Event.</p>
<p>So how can you wait for an BackgroundWorker to finish?</p>
<hr>
<p><strong>Update</strong>
People seem to be confused by this question. They seem to think that I will be using the BackgroundWorker as:</p>
<pre><code>BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += MyWork;
worker.RunWorkerAsync();
WaitForWorkerToFinish(worker);
</code></pre>
<p>That is <em>not</em> it, that is <em>not</em> what I'm doing, and that is <em>not</em> what is being asked here. If that were the case, there would be no point in using a background worker.</p>
| [
{
"answer_id": 123684,
"author": "Seb Nilsson",
"author_id": 2429,
"author_profile": "https://Stackoverflow.com/users/2429",
"pm_score": 2,
"selected": false,
"text": "<p>You can check into the <strong>RunWorkerCompletedEventArgs</strong> in the <strong>RunWorkerCompletedEventHandler</st... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] | Consider a *hypothetical* method of an object that does stuff for you:
```
public class DoesStuff
{
BackgroundWorker _worker = new BackgroundWorker();
...
public void CancelDoingStuff()
{
_worker.CancelAsync();
//todo: Figure out a way to wait for BackgroundWorker to be cancelled.
}
}
```
How can one wait for a BackgroundWorker to be done?
---
In the past people have tried:
```
while (_worker.IsBusy)
{
Sleep(100);
}
```
But [this deadlocks](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1819196&SiteID=1), because `IsBusy` is not cleared until after the `RunWorkerCompleted` event is handled, and that event can't get handled until the application goes idle. The application won't go idle until the worker is done. (Plus, it's a busy loop - disgusting.)
Others have add suggested kludging it into:
```
while (_worker.IsBusy)
{
Application.DoEvents();
}
```
The problem with that is that is `Application.DoEvents()` causes messages currently in the queue to be processed, which cause re-entrancy problems (.NET isn't re-entrant).
I would hope to use some solution involving Event synchronization objects, where the code **waits** for an event - that the worker's `RunWorkerCompleted` event handlers sets. Something like:
```
Event _workerDoneEvent = new WaitHandle();
public void CancelDoingStuff()
{
_worker.CancelAsync();
_workerDoneEvent.WaitOne();
}
private void RunWorkerCompletedEventHandler(sender object, RunWorkerCompletedEventArgs e)
{
_workerDoneEvent.SetEvent();
}
```
But I'm back to the deadlock: the event handler can't run until the application goes idle, and the application won't go idle because it's waiting for an Event.
So how can you wait for an BackgroundWorker to finish?
---
**Update**
People seem to be confused by this question. They seem to think that I will be using the BackgroundWorker as:
```
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += MyWork;
worker.RunWorkerAsync();
WaitForWorkerToFinish(worker);
```
That is *not* it, that is *not* what I'm doing, and that is *not* what is being asked here. If that were the case, there would be no point in using a background worker. | If I understand your requirement right, you could do something like this (code not tested, but shows the general idea):
```
private BackgroundWorker worker = new BackgroundWorker();
private AutoResetEvent _resetEvent = new AutoResetEvent(false);
public Form1()
{
InitializeComponent();
worker.DoWork += worker_DoWork;
}
public void Cancel()
{
worker.CancelAsync();
_resetEvent.WaitOne(); // will block until _resetEvent.Set() call made
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
while(!e.Cancel)
{
// do something
}
_resetEvent.Set(); // signal that worker is done
}
``` |
123,672 | <p>In <a href="http://msdn.microsoft.com/en-us/library/ms155365%28SQL.90%29.aspx" rel="nofollow noreferrer">this MSDN article</a>, MS explains how to specify other delimiters besides commas for csv-type exports from SSRS 2005, however, literal tab characters are stripped by the config file parser, and it doesn't appear that MS has provided a workaround.<br>
<a href="http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=357527" rel="nofollow noreferrer">This entry</a> on Microsoft Connect seems to confirm this.<br>
Has anyone developed a way to export tab-delimited files from SSRS 2005?<br>
Or perhaps developed an open-source custom renderer to get the job done? </p>
<p>Note: I've heard of manually appending <code>&rc:FieldDelimiter=%09</code> via URL access, but that's not an acceptable workaround for my users and doesn't appear to work anyways.</p>
| [
{
"answer_id": 124523,
"author": "Leo Moore",
"author_id": 6336,
"author_profile": "https://Stackoverflow.com/users/6336",
"pm_score": 1,
"selected": false,
"text": "<p>I used a select query to format the data and BCP to extract the data out into a file. In my case I encapsulated it all ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19239/"
] | In [this MSDN article](http://msdn.microsoft.com/en-us/library/ms155365%28SQL.90%29.aspx), MS explains how to specify other delimiters besides commas for csv-type exports from SSRS 2005, however, literal tab characters are stripped by the config file parser, and it doesn't appear that MS has provided a workaround.
[This entry](http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=357527) on Microsoft Connect seems to confirm this.
Has anyone developed a way to export tab-delimited files from SSRS 2005?
Or perhaps developed an open-source custom renderer to get the job done?
Note: I've heard of manually appending `&rc:FieldDelimiter=%09` via URL access, but that's not an acceptable workaround for my users and doesn't appear to work anyways. | In case anyone needs it this is working very well for me.
```
<Extension Name="Tabs" Type="Microsoft.ReportingServices.Rendering.DataRenderer.CsvReport,Microsoft.ReportingServices.DataRendering">
<OverrideNames>
<Name Language="en-US">Tab-delimited</Name>
</OverrideNames>
<Configuration>
<DeviceInfo>
<OutputFormat>TXT</OutputFormat>
<Encoding>ASCII</Encoding>
<FieldDelimiter>	</FieldDelimiter>
<!-- or as this -->
<!-- <FieldDelimiter xml:space="preserve">[TAB]</FieldDelimiter> -->
<FileExtension>txt</FileExtension>
</DeviceInfo>
</Configuration>
</Extension>
``` |
123,718 | <p>How can i check to see if a static class has been declared?
ex
Given the class</p>
<pre><code>class bob {
function yippie() {
echo "skippie";
}
}
</code></pre>
<p>later in code how do i check:</p>
<pre><code>if(is_a_valid_static_object(bob)) {
bob::yippie();
}
</code></pre>
<p>so i don't get:
Fatal error: Class 'bob' not found in file.php on line 3</p>
| [
{
"answer_id": 123731,
"author": "Don Neufeld",
"author_id": 13097,
"author_profile": "https://Stackoverflow.com/users/13097",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://us2.php.net/class_exists\" rel=\"nofollow noreferrer\"><code>bool class_exists( string $class_name... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5261/"
] | How can i check to see if a static class has been declared?
ex
Given the class
```
class bob {
function yippie() {
echo "skippie";
}
}
```
later in code how do i check:
```
if(is_a_valid_static_object(bob)) {
bob::yippie();
}
```
so i don't get:
Fatal error: Class 'bob' not found in file.php on line 3 | You can also check for existence of a specific method, even without instantiating the class
```
echo method_exists( bob, 'yippie' ) ? 'yes' : 'no';
```
If you want to go one step further and verify that "yippie" is actually static, use the [Reflection API](http://us3.php.net/language.oop5.reflection) (PHP5 only)
```
try {
$method = new ReflectionMethod( 'bob::yippie' );
if ( $method->isStatic() )
{
// verified that bob::yippie is defined AND static, proceed
}
}
catch ( ReflectionException $e )
{
// method does not exist
echo $e->getMessage();
}
```
or, you could combine the two approaches
```
if ( method_exists( bob, 'yippie' ) )
{
$method = new ReflectionMethod( 'bob::yippie' );
if ( $method->isStatic() )
{
// verified that bob::yippie is defined AND static, proceed
}
}
``` |
123,758 | <p>Let's say I have the following <code>class X</code> where I want to return access to an internal member:</p>
<pre><code>class Z
{
// details
};
class X
{
std::vector<Z> vecZ;
public:
Z& Z(size_t index)
{
// massive amounts of code for validating index
Z& ret = vecZ[index];
// even more code for determining that the Z instance
// at index is *exactly* the right sort of Z (a process
// which involves calculating leap years in which
// religious holidays fall on Tuesdays for
// the next thousand years or so)
return ret;
}
const Z& Z(size_t index) const
{
// identical to non-const X::Z(), except printed in
// a lighter shade of gray since
// we're running low on toner by this point
}
};
</code></pre>
<p>The two member functions <code>X::Z()</code> and <code>X::Z() const</code> have identical code inside the braces. This is duplicate code <strong>and can cause maintenance problems for long functions with complex logic</strong>. </p>
<p>Is there a way to avoid this code duplication?</p>
| [
{
"answer_id": 123765,
"author": "Kevin",
"author_id": 6386,
"author_profile": "https://Stackoverflow.com/users/6386",
"pm_score": 7,
"selected": true,
"text": "<p>Yes, it is possible to avoid the code duplication. You need to use the const member function to have the logic and have the... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6386/"
] | Let's say I have the following `class X` where I want to return access to an internal member:
```
class Z
{
// details
};
class X
{
std::vector<Z> vecZ;
public:
Z& Z(size_t index)
{
// massive amounts of code for validating index
Z& ret = vecZ[index];
// even more code for determining that the Z instance
// at index is *exactly* the right sort of Z (a process
// which involves calculating leap years in which
// religious holidays fall on Tuesdays for
// the next thousand years or so)
return ret;
}
const Z& Z(size_t index) const
{
// identical to non-const X::Z(), except printed in
// a lighter shade of gray since
// we're running low on toner by this point
}
};
```
The two member functions `X::Z()` and `X::Z() const` have identical code inside the braces. This is duplicate code **and can cause maintenance problems for long functions with complex logic**.
Is there a way to avoid this code duplication? | Yes, it is possible to avoid the code duplication. You need to use the const member function to have the logic and have the non-const member function call the const member function and re-cast the return value to a non-const reference (or pointer if the functions returns a pointer):
```
class X
{
std::vector<Z> vecZ;
public:
const Z& z(size_t index) const
{
// same really-really-really long access
// and checking code as in OP
// ...
return vecZ[index];
}
Z& z(size_t index)
{
// One line. One ugly, ugly line - but just one line!
return const_cast<Z&>( static_cast<const X&>(*this).z(index) );
}
#if 0 // A slightly less-ugly version
Z& Z(size_t index)
{
// Two lines -- one cast. This is slightly less ugly but takes an extra line.
const X& constMe = *this;
return const_cast<Z&>( constMe.z(index) );
}
#endif
};
```
**NOTE:** It is important that you do **NOT** put the logic in the non-const function and have the const-function call the non-const function -- it may result in undefined behavior. The reason is that a constant class instance gets cast as a non-constant instance. The non-const member function may accidentally modify the class, which the C++ standard states will result in undefined behavior. |
123,773 | <p>I will choose Java as an example, most people know it, though every other OO language was working as well.</p>
<p>Java, like many other languages, has interface inheritance and implementation inheritance. E.g. a Java class can inherit from another one and every method that has an implementation there (assuming the parent is not abstract) is inherited, too. That means the interface is inherited and the implementation for this method as well. I can overwrite it, but I don't have to. If I don't overwrite it, I have inherited the implementation.</p>
<p>However, my class can also "inherit" (not in Java terms) just an interface, without implementation. Actually interfaces are really named that way in Java, they provide interface inheritance, but without inheriting any implementation, since all methods of an interface have no implementation.</p>
<p>Now there was this <a href="http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html" rel="noreferrer">article, saying it's better to inherit interfaces than implementations</a>, you may like to read it (at least the first half of the first page), it's pretty interesting. It avoids issues like the <a href="http://en.wikipedia.org/wiki/Fragile_base_class" rel="noreferrer">fragile base class problem</a>. So far this makes all a lot of sense and many other things said in the article make a lot of sense to me.</p>
<p>What bugs me about this, is that implementation inheritance means <strong>code reuse</strong>, one of the most important properties of OO languages. Now if Java had no classes (like James Gosling, the godfather of Java has wished according to this article), it solves all problems of implementation inheritance, but how would you make code reuse possible then?</p>
<p>E.g. if I have a class Car and Car has a method move(), which makes the Car move. Now I can sub-class Car for different type of cars, that are all cars, but are all specialized versions of Car. Some may move in a different way, these need to overwrite move() anyway, but most would simply keep the inherited move, as they move alike just like the abstract parent Car. Now assume for a second that there are only interfaces in Java, only interfaces may inherit from each other, a class may implement interfaces, but all classes are always final, so no class can inherit from any other class.</p>
<p>How would you avoid that when you have an Interface Car and hundred Car classes, that you need to implement an identical move() method for each of them? What concepts for code reuse other than implementation inheritance exist in the the OO world?</p>
<p>Some languages have Mixins. Are Mixins the answer to my question? I read about them, but I cannot really imagine how Mixins would work in a Java world and if they can really solve the problem here.</p>
<p>Another idea was that there is a class that only implements the Car interface, let's call it AbstractCar, and implements the move() method. Now other cars implement the Car interface as well, internally they create an instance of AbstractCar and they implement their own move() method by calling move() on their internal abstract Car. But wouldn't this be wasting resources for nothing (a method calling just another method - okay, JIT could inline the code, but still) and using extra memory for keeping internal objects, you wouldn't even need with implementation inheritance? (after all every object needs more memory than just the sum of the encapsulated data) Also isn't it awkward for a programmer to write dummy methods like</p>
<pre><code>public void move() {
abstractCarObject.move();
}
</code></pre>
<p>?</p>
<p>Anyone can imagine a better idea how to avoid implementation inheritance and still be able to re-use code in an easy fashion?</p>
| [
{
"answer_id": 123800,
"author": "Xian",
"author_id": 4642,
"author_profile": "https://Stackoverflow.com/users/4642",
"pm_score": 2,
"selected": false,
"text": "<p>You could also use composition and the strategy pattern.<a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofo... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15809/"
] | I will choose Java as an example, most people know it, though every other OO language was working as well.
Java, like many other languages, has interface inheritance and implementation inheritance. E.g. a Java class can inherit from another one and every method that has an implementation there (assuming the parent is not abstract) is inherited, too. That means the interface is inherited and the implementation for this method as well. I can overwrite it, but I don't have to. If I don't overwrite it, I have inherited the implementation.
However, my class can also "inherit" (not in Java terms) just an interface, without implementation. Actually interfaces are really named that way in Java, they provide interface inheritance, but without inheriting any implementation, since all methods of an interface have no implementation.
Now there was this [article, saying it's better to inherit interfaces than implementations](http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html), you may like to read it (at least the first half of the first page), it's pretty interesting. It avoids issues like the [fragile base class problem](http://en.wikipedia.org/wiki/Fragile_base_class). So far this makes all a lot of sense and many other things said in the article make a lot of sense to me.
What bugs me about this, is that implementation inheritance means **code reuse**, one of the most important properties of OO languages. Now if Java had no classes (like James Gosling, the godfather of Java has wished according to this article), it solves all problems of implementation inheritance, but how would you make code reuse possible then?
E.g. if I have a class Car and Car has a method move(), which makes the Car move. Now I can sub-class Car for different type of cars, that are all cars, but are all specialized versions of Car. Some may move in a different way, these need to overwrite move() anyway, but most would simply keep the inherited move, as they move alike just like the abstract parent Car. Now assume for a second that there are only interfaces in Java, only interfaces may inherit from each other, a class may implement interfaces, but all classes are always final, so no class can inherit from any other class.
How would you avoid that when you have an Interface Car and hundred Car classes, that you need to implement an identical move() method for each of them? What concepts for code reuse other than implementation inheritance exist in the the OO world?
Some languages have Mixins. Are Mixins the answer to my question? I read about them, but I cannot really imagine how Mixins would work in a Java world and if they can really solve the problem here.
Another idea was that there is a class that only implements the Car interface, let's call it AbstractCar, and implements the move() method. Now other cars implement the Car interface as well, internally they create an instance of AbstractCar and they implement their own move() method by calling move() on their internal abstract Car. But wouldn't this be wasting resources for nothing (a method calling just another method - okay, JIT could inline the code, but still) and using extra memory for keeping internal objects, you wouldn't even need with implementation inheritance? (after all every object needs more memory than just the sum of the encapsulated data) Also isn't it awkward for a programmer to write dummy methods like
```
public void move() {
abstractCarObject.move();
}
```
?
Anyone can imagine a better idea how to avoid implementation inheritance and still be able to re-use code in an easy fashion? | Short answer: Yes it is possible. But you have to do it on purpose and no by chance ( using final, abstract and design with inheritance in mind, etc. )
Long answer:
Well, inheritance is not actually for "code re-use", it is for class "specialization", I think this is a misinterpretation.
For instance is it a very bad idea to create a Stack from a Vector, just because they are alike. Or properties from HashTable just because they store values. See [Effective].
The "code reuse" was more a "business view" of the OO characteristics, meaning that you objects were easily distributable among nodes; and were portable and didn't not have the problems of previous programming languages generation. This has been proved half rigth. We now have libraries that can be easily distributed; for instance in java the jar files can be used in any project saving thousands of hours of development. OO still has some problems with portability and things like that, that is the reason now WebServices are so popular ( as before it was CORBA ) but that's another thread.
This is one aspect of "code reuse". The other is effectively, the one that has to do with programming. But in this case is not just to "save" lines of code and creating fragile monsters, but designing with inheritance in mind. This is the item 17 in the book previously mentioned; **Item 17: Design and document for inheritance or else prohibit it.** See [Effective]
Of course you may have a Car class and tons of subclasses. And yes, the approach you mention about Car interface, AbstractCar and CarImplementation is a correct way to go.
You define the "contract" the Car should adhere and say these are the methods I would expect to have when talking about cars. The abstract car that has the base functionality that every car but leaving and documenting the methods the subclasses are responsible to handle. In java you do this by marking the method as abstract.
When you proceed this way, there is not a problem with the "fragile" class ( or at least the designer is conscious or the threat ) and the subclasses do complete only those parts the designer allow them.
Inheritance is more to "specialize" the classes, in the same fashion a Truck is an specialized version of Car, and MosterTruck an specialized version of Truck.
It does not make sanse to create a "ComputerMouse" subclase from a Car just because it has a Wheel ( scroll wheel ) like a car, it moves, and has a wheel below just to save lines of code. It belongs to a different domain, and it will be used for other purposes.
The way to prevent "implementation" inheritance is in the programming language since the beginning, you should use the final keyword on the class declaration and this way you are prohibiting subclasses.
Subclassing is not evil if it's done on purpose. If it's done uncarefully it may become a nightmare. I would say that you should start as private and "final" as possible and if needed make things more public and extend-able. This is also widely explained in the presentation"How to design good API's and why it matters" See [Good API]
Keep reading articles and with time and practice ( and a lot of patience ) this thing will come clearer. Although sometime you just need to do the work and copy/paste some code :P . This is ok, as long you try to do it well first.
Here are the references both from Joshua Bloch ( formerly working in Sun at the core of java now working for Google )
---
[Effective]
Effective Java. Definitely the best java book a non beginner should learn, understand and practice. A must have.
[Effective Java](http://java.sun.com/docs/books/effective)
---
[Good API]Presentation that talks on API's design, reusability and related topics.
It is a little lengthy but it worth every minute.
[How To Design A Good API and Why it Matters](http://www.youtube.com/watch?v=aAb7hSCtvGw)
Regards.
---
Update: Take a look at minute 42 of the video link I sent you. It talks about this topic:
"When you have two classes in a public API and you think to make one a subclass of another, like Foo is a subclass of Bar, ask your self , is Every Foo a Bar?... "
And in the minute previous it talks about "code reuse" while talking about TimeTask. |
123,783 | <p>Many websites have the concept of sending messages from user to user. When you send a message to another user, the message would show up in their inbox. You could respond to the message, and it would show up as a new entry in that message thread. </p>
<p>You should be able to see if you've read a given message already, and messages that have got a new response should be able to be at the top.</p>
<p>How would you design the classes (or tables or whatever) to support such a system?</p>
| [
{
"answer_id": 123799,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 2,
"selected": true,
"text": "<pre><code>user\n id\n name\n\nmessages\n id\n to_user_id\n from_user_id\n title\n date\n\nmessage_post\n id\n message_id\n user... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17076/"
] | Many websites have the concept of sending messages from user to user. When you send a message to another user, the message would show up in their inbox. You could respond to the message, and it would show up as a new entry in that message thread.
You should be able to see if you've read a given message already, and messages that have got a new response should be able to be at the top.
How would you design the classes (or tables or whatever) to support such a system? | ```
user
id
name
messages
id
to_user_id
from_user_id
title
date
message_post
id
message_id
user_id
message
date
```
classes would reflect this sort of schema |
123,809 | <p>If my code throws an exception, sometimes - not everytime - the jsf presents a blank page. I´m using facelets for layout.
A similar error were reported at this <a href="http://forums.sun.com/thread.jspa?messageID=10237827" rel="nofollow noreferrer">Sun forumn´s post</a>, but without answers.
Anyone else with the same problem, or have a solution?
;)</p>
<p>Due to some requests. Here follow more datails:</p>
<p>web.xml</p>
<pre><code> <error-page>
<exception-type>com.company.ApplicationResourceException</exception-type>
<location>/error.faces</location>
</error-page>
</code></pre>
<p>And the stack related to jsf is printed after the real exception:</p>
<pre><code>####<Sep 23, 2008 5:42:55 PM GMT-03:00> <Error> <HTTP> <comp141> <AdminServer> <[ACTIVE] ExecuteThread: '3' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1222202575662> <BEA-101107> <[weblogic.servlet.internal.WebAppServletContext@6d46b9 - appName: 'ControlPanelEAR', name: 'ControlPanelWeb', context-path: '/Web'] Problem occurred while serving the error page.
javax.servlet.ServletException: viewId:/error.xhtml - View /error.xhtml could not be restored.
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:249)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:226)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:124)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:283)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175)
at weblogic.servlet.internal.RequestDispatcherImpl.invokeServlet(RequestDispatcherImpl.java:525)
at weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:261)
at weblogic.servlet.internal.ForwardAction.run(ForwardAction.java:22)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(Unknown Source)
at weblogic.servlet.internal.ErrorManager.handleException(ErrorManager.java:144)
at weblogic.servlet.internal.WebAppServletContext.handleThrowableFromInvocation(WebAppServletContext.java:2201)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2053)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1366)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:200)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:172)
javax.faces.application.ViewExpiredException: viewId:/error.xhtml - View /error.xhtml could not be restored.
at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:180)
at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:248)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:244)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:226)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:124)
</code></pre>
<p>I´m using the jsf version <code>Mojarra 1.2_09</code>, <code>richfaces 3.2.1.GA</code> and <code>facelets 1.1.13</code>.</p>
<p>Hope some help :(</p>
| [
{
"answer_id": 123932,
"author": "William",
"author_id": 9193,
"author_profile": "https://Stackoverflow.com/users/9193",
"pm_score": 3,
"selected": true,
"text": "<p>I think this largely depends on your JSF implementation. I've heard that some will render blank screens.</p>\n\n<p>The one... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21370/"
] | If my code throws an exception, sometimes - not everytime - the jsf presents a blank page. I´m using facelets for layout.
A similar error were reported at this [Sun forumn´s post](http://forums.sun.com/thread.jspa?messageID=10237827), but without answers.
Anyone else with the same problem, or have a solution?
;)
Due to some requests. Here follow more datails:
web.xml
```
<error-page>
<exception-type>com.company.ApplicationResourceException</exception-type>
<location>/error.faces</location>
</error-page>
```
And the stack related to jsf is printed after the real exception:
```
####<Sep 23, 2008 5:42:55 PM GMT-03:00> <Error> <HTTP> <comp141> <AdminServer> <[ACTIVE] ExecuteThread: '3' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1222202575662> <BEA-101107> <[weblogic.servlet.internal.WebAppServletContext@6d46b9 - appName: 'ControlPanelEAR', name: 'ControlPanelWeb', context-path: '/Web'] Problem occurred while serving the error page.
javax.servlet.ServletException: viewId:/error.xhtml - View /error.xhtml could not be restored.
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:249)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:226)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:124)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:283)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175)
at weblogic.servlet.internal.RequestDispatcherImpl.invokeServlet(RequestDispatcherImpl.java:525)
at weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:261)
at weblogic.servlet.internal.ForwardAction.run(ForwardAction.java:22)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(Unknown Source)
at weblogic.servlet.internal.ErrorManager.handleException(ErrorManager.java:144)
at weblogic.servlet.internal.WebAppServletContext.handleThrowableFromInvocation(WebAppServletContext.java:2201)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2053)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1366)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:200)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:172)
javax.faces.application.ViewExpiredException: viewId:/error.xhtml - View /error.xhtml could not be restored.
at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:180)
at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:248)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:244)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:226)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:124)
```
I´m using the jsf version `Mojarra 1.2_09`, `richfaces 3.2.1.GA` and `facelets 1.1.13`.
Hope some help :( | I think this largely depends on your JSF implementation. I've heard that some will render blank screens.
The one we were using would throw error 500's with a stack trace. Other times out buttons wouldn't work without any error for the user. This was all during our development phase.
But the best advice I can give you is to catch the exceptions and log them in an error log so you have the stack trace for debugging later. For messages that we couldn't do anything about like a backend failing we would just add a fatal message to the FacesContext that gets displayed on the screen and log the stack trace. |
123,838 | <p>Our clients will be uploading images to be printed on their documents and we have been asked to come up with a way to get the resolution of the image in order to warn them if the image has too low of a resolution and will look pixalated in the end-product</p>
<p>If it comes to it we could also go with the dimensions if anyone knows how to get those but the resolution would be preferred</p>
<p>Thank you</p>
| [
{
"answer_id": 123854,
"author": "Xian",
"author_id": 4642,
"author_profile": "https://Stackoverflow.com/users/4642",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.image.aspx\" rel=\"noreferrer\">System.Drawing.Image</a></p>... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] | Our clients will be uploading images to be printed on their documents and we have been asked to come up with a way to get the resolution of the image in order to warn them if the image has too low of a resolution and will look pixalated in the end-product
If it comes to it we could also go with the dimensions if anyone knows how to get those but the resolution would be preferred
Thank you | [System.Drawing.Image](http://msdn.microsoft.com/en-us/library/system.drawing.image.aspx)
```
Image newImage = Image.FromFile("SampImag.jpg");
newImage.HorizontalResolution
``` |
123,902 | <p>I have a self-signed root certificate with just the code signing extension (no other extensions) in my Mac keychain; I use it to sign all code coming out of ∞labs using Apple's codesign tool and it works great.</p>
<p>I was looking to expand myself a little and doing some Java development. I know Apple provides a KeyStore implementation that reads from the Keychain, and I can list all certificates I have in the 'chain with:</p>
<pre><code>keytool -list -provider com.apple.crypto.provider.Apple -storetype KeychainStore -keystore NONE -v
</code></pre>
<p>However, whenever I try to use jarsigner to sign a simple test JAR file, I end up with:</p>
<pre><code>$ jarsigner -keystore NONE -storetype KeychainStore -providerName Apple a.jar infinitelabs_codesigning_2
Enter Passphrase for keystore: <omitted>
jarsigner: Certificate chain not found for: infinitelabs_codesigning_2. infinitelabs_codesigning_2 must reference a valid KeyStore key entry containing a private key and corresponding public key certificate chain.
</code></pre>
<p>What am I doing wrong?</p>
<p>(The certificate was created following <a href="http://developer.apple.com/documentation/Security/Conceptual/CodeSigningGuide/Procedures/chapter_3_section_2.html#//apple_ref/doc/uid/TP40005929-CH4-SW1" rel="noreferrer">Apple's instructions for obtaining a signing identity</a>.)</p>
| [
{
"answer_id": 137559,
"author": "bd808",
"author_id": 8171,
"author_profile": "https://Stackoverflow.com/users/8171",
"pm_score": 1,
"selected": false,
"text": "<p>I think that your keystore entry alias must be wrong. Are you using the alias name of a keystore object with an entry type ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6061/"
] | I have a self-signed root certificate with just the code signing extension (no other extensions) in my Mac keychain; I use it to sign all code coming out of ∞labs using Apple's codesign tool and it works great.
I was looking to expand myself a little and doing some Java development. I know Apple provides a KeyStore implementation that reads from the Keychain, and I can list all certificates I have in the 'chain with:
```
keytool -list -provider com.apple.crypto.provider.Apple -storetype KeychainStore -keystore NONE -v
```
However, whenever I try to use jarsigner to sign a simple test JAR file, I end up with:
```
$ jarsigner -keystore NONE -storetype KeychainStore -providerName Apple a.jar infinitelabs_codesigning_2
Enter Passphrase for keystore: <omitted>
jarsigner: Certificate chain not found for: infinitelabs_codesigning_2. infinitelabs_codesigning_2 must reference a valid KeyStore key entry containing a private key and corresponding public key certificate chain.
```
What am I doing wrong?
(The certificate was created following [Apple's instructions for obtaining a signing identity](http://developer.apple.com/documentation/Security/Conceptual/CodeSigningGuide/Procedures/chapter_3_section_2.html#//apple_ref/doc/uid/TP40005929-CH4-SW1).) | I think that your keystore entry alias must be wrong. Are you using the alias name of a keystore object with an entry type of "keyEntry"? The same command works perfectly for me.
From the jarsigner man page:
>
> When using jarsigner to sign a JAR file, you must specify the alias for the keystore entry containing the private key needed to generate the signature.
>
>
> |
123,918 | <p>System.IO.BinaryReader reads values in a little-endian format.</p>
<p>I have a C# application connecting to a proprietary networking library on the server side. The server-side sends everything down in network byte order, as one would expect, but I find that dealing with this on the client side is awkward, particularly for unsigned values.</p>
<pre><code>UInt32 length = (UInt32)IPAddress.NetworkToHostOrder(reader.ReadInt32());
</code></pre>
<p>is the only way I've come up with to get a correct unsigned value out of the stream, but this seems both awkward and ugly, and I have yet to test if that's just going to clip off high-order values so that I have to do fun BitConverter stuff.</p>
<p>Is there some way I'm missing short of writing a wrapper around the whole thing to avoid these ugly conversions on every read? It seems like there should be an endian-ness option on the reader to make things like this simpler, but I haven't come across anything.</p>
| [
{
"answer_id": 123942,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 1,
"selected": false,
"text": "<p>I built a custom BinaryReader to handle all of this. It's available as <a href=\"http://www.assembla.com/wiki/... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21374/"
] | System.IO.BinaryReader reads values in a little-endian format.
I have a C# application connecting to a proprietary networking library on the server side. The server-side sends everything down in network byte order, as one would expect, but I find that dealing with this on the client side is awkward, particularly for unsigned values.
```
UInt32 length = (UInt32)IPAddress.NetworkToHostOrder(reader.ReadInt32());
```
is the only way I've come up with to get a correct unsigned value out of the stream, but this seems both awkward and ugly, and I have yet to test if that's just going to clip off high-order values so that I have to do fun BitConverter stuff.
Is there some way I'm missing short of writing a wrapper around the whole thing to avoid these ugly conversions on every read? It seems like there should be an endian-ness option on the reader to make things like this simpler, but I haven't come across anything. | There is no built-in converter. Here's my wrapper (as you can see, I only implemented the functionality I needed but the structure is pretty easy to change to your liking):
```
/// <summary>
/// Utilities for reading big-endian files
/// </summary>
public class BigEndianReader
{
public BigEndianReader(BinaryReader baseReader)
{
mBaseReader = baseReader;
}
public short ReadInt16()
{
return BitConverter.ToInt16(ReadBigEndianBytes(2), 0);
}
public ushort ReadUInt16()
{
return BitConverter.ToUInt16(ReadBigEndianBytes(2), 0);
}
public uint ReadUInt32()
{
return BitConverter.ToUInt32(ReadBigEndianBytes(4), 0);
}
public byte[] ReadBigEndianBytes(int count)
{
byte[] bytes = new byte[count];
for (int i = count - 1; i >= 0; i--)
bytes[i] = mBaseReader.ReadByte();
return bytes;
}
public byte[] ReadBytes(int count)
{
return mBaseReader.ReadBytes(count);
}
public void Close()
{
mBaseReader.Close();
}
public Stream BaseStream
{
get { return mBaseReader.BaseStream; }
}
private BinaryReader mBaseReader;
}
```
Basically, ReadBigEndianBytes does the grunt work, and this is passed to a BitConverter. There will be a definite problem if you read a large number of bytes since this will cause a large memory allocation. |
123,927 | <p>I'm writing a setup program to install an application to a USB drive. The application is meant to be used only from USB drives, so it would save an extra step for the user by automatically selecting USB drive to install to.</p>
<p>I might explore using Nullsoft or MSI for install, but since I'm mostly familiar with .NET I initially plan to try either custom .NET installer or setup component on .NET.</p>
<p>Is it possible to determine the drive letter of a USB flash drive on Windows using .NET? How?</p>
| [
{
"answer_id": 123948,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 5,
"selected": true,
"text": "<p>You could use:</p>\n\n<pre><code>from driveInfo in DriveInfo.GetDrives()\nwhere driveInfo.DriveType == DriveType.Rem... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19124/"
] | I'm writing a setup program to install an application to a USB drive. The application is meant to be used only from USB drives, so it would save an extra step for the user by automatically selecting USB drive to install to.
I might explore using Nullsoft or MSI for install, but since I'm mostly familiar with .NET I initially plan to try either custom .NET installer or setup component on .NET.
Is it possible to determine the drive letter of a USB flash drive on Windows using .NET? How? | You could use:
```
from driveInfo in DriveInfo.GetDrives()
where driveInfo.DriveType == DriveType.Removable && driveInfo.IsReady
select driveInfo.RootDirectory.FullName
``` |
123,936 | <p>Some of my colleagues use special comments on their bug fixes, for example:</p>
<pre><code>// 2008-09-23 John Doe - bug 12345
// <short description>
</code></pre>
<p>Does this make sense?<br>
Do you comment bug fixes in a special way?</p>
<p>Please let me know.</p>
| [
{
"answer_id": 123949,
"author": "perimosocordiae",
"author_id": 10601,
"author_profile": "https://Stackoverflow.com/users/10601",
"pm_score": 2,
"selected": false,
"text": "<p>Only if the solution was particularly clever or hard to understand.</p>\n"
},
{
"answer_id": 123952,
... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2012356/"
] | Some of my colleagues use special comments on their bug fixes, for example:
```
// 2008-09-23 John Doe - bug 12345
// <short description>
```
Does this make sense?
Do you comment bug fixes in a special way?
Please let me know. | I don't put in comments like that, the source control system already maintains that history and I am already able to log the history of a file.
I do put in comments that describe why something non-obvious is being done though. So if the bug fix makes the code less predictable and clear, then I explain why. |
123,958 | <p>In python is it possible to get or set a logical directory (as opposed to an absolute one).</p>
<p>For example if I have:</p>
<pre><code>/real/path/to/dir
</code></pre>
<p>and I have</p>
<pre><code>/linked/path/to/dir
</code></pre>
<p>linked to the same directory.</p>
<p>using os.getcwd and os.chdir will always use the absolute path</p>
<pre><code>>>> import os
>>> os.chdir('/linked/path/to/dir')
>>> print os.getcwd()
/real/path/to/dir
</code></pre>
<p>The only way I have found to get around this at all is to launch 'pwd' in another process and read the output. However, this only works until you call os.chdir for the first time.</p>
| [
{
"answer_id": 123985,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 5,
"selected": true,
"text": "<p>The underlying operational system / shell reports real paths to python. </p>\n\n<p>So, there really is no way around it, ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3051/"
] | In python is it possible to get or set a logical directory (as opposed to an absolute one).
For example if I have:
```
/real/path/to/dir
```
and I have
```
/linked/path/to/dir
```
linked to the same directory.
using os.getcwd and os.chdir will always use the absolute path
```
>>> import os
>>> os.chdir('/linked/path/to/dir')
>>> print os.getcwd()
/real/path/to/dir
```
The only way I have found to get around this at all is to launch 'pwd' in another process and read the output. However, this only works until you call os.chdir for the first time. | The underlying operational system / shell reports real paths to python.
So, there really is no way around it, since `os.getcwd()` is a wrapped call to C Library `getcwd()` function.
There are some workarounds in the spirit of the one that you already know which is launching `pwd`.
Another one would involve using `os.environ['PWD']`. If that environmnent variable is set you can make some `getcwd` function that respects it.
The solution below combines both:
```
import os
from subprocess import Popen, PIPE
class CwdKeeper(object):
def __init__(self):
self._cwd = os.environ.get("PWD")
if self._cwd is None: # no environment. fall back to calling pwd on shell
self._cwd = Popen('pwd', stdout=PIPE).communicate()[0].strip()
self._os_getcwd = os.getcwd
self._os_chdir = os.chdir
def chdir(self, path):
if not self._cwd:
return self._os_chdir(path)
p = os.path.normpath(os.path.join(self._cwd, path))
result = self._os_chdir(p)
self._cwd = p
os.environ["PWD"] = p
return result
def getcwd(self):
if not self._cwd:
return self._os_getcwd()
return self._cwd
cwd = CwdKeeper()
print cwd.getcwd()
# use only cwd.chdir and cwd.getcwd from now on.
# monkeypatch os if you want:
os.chdir = cwd.chdir
os.getcwd = cwd.getcwd
# now you can use os.chdir and os.getcwd as normal.
``` |
123,979 | <p>I have created a bunch of movie clips which all have similar names and then after some other event I have built up a string like:</p>
<pre><code>var clipName = "barLeft42"
</code></pre>
<p>which is held inside another movie clip called 'thing'.</p>
<p>I have been able to get hold of a reference using:</p>
<pre><code>var movieClip = Eval( "_root.thing." + clipName )
</code></pre>
<p>But that feels bad - is there a better way?</p>
| [
{
"answer_id": 124010,
"author": "Ronnie",
"author_id": 193,
"author_profile": "https://Stackoverflow.com/users/193",
"pm_score": 3,
"selected": true,
"text": "<p>Movie clips are collections in actionscript (like most and similar to javascript, everything is basically key-value pairs). Y... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21214/"
] | I have created a bunch of movie clips which all have similar names and then after some other event I have built up a string like:
```
var clipName = "barLeft42"
```
which is held inside another movie clip called 'thing'.
I have been able to get hold of a reference using:
```
var movieClip = Eval( "_root.thing." + clipName )
```
But that feels bad - is there a better way? | Movie clips are collections in actionscript (like most and similar to javascript, everything is basically key-value pairs). You can index into the collection using square brackets and a string for the key name like:
```
_root.thing[ "barLeft42" ]
```
That should do the trick for you... |
123,986 | <p>I need my program to work only with certain USB Flash drives (from a single manufacturer) and ignore all other USB Flash drives (from any other manufacturers).</p>
<p>is it possible to check that specific USB card is inserted on windows using .NET 2.0? how?</p>
<p>if I find it through WMI, can I somehow determine which drive letter the USB drive is on?</p>
| [
{
"answer_id": 124087,
"author": "fryguybob",
"author_id": 4592,
"author_profile": "https://Stackoverflow.com/users/4592",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps #usblib:</p>\n\n<p><a href=\"http://www.icsharpcode.net/OpenSource/SharpUSBLib/\" rel=\"nofollow noreferrer\">h... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19124/"
] | I need my program to work only with certain USB Flash drives (from a single manufacturer) and ignore all other USB Flash drives (from any other manufacturers).
is it possible to check that specific USB card is inserted on windows using .NET 2.0? how?
if I find it through WMI, can I somehow determine which drive letter the USB drive is on? | **EDIT:** Added code to print drive letter.
---
Check if this example works for you. It uses WMI.
```
Console.WriteLine("Manufacturer: {0}", queryObj["Manufacturer"]);
...
Console.WriteLine(" Name: {0}", c["Name"]); // here it will print drive letter
```
The full code sample:
```
namespace WMISample
{
using System;
using System.Management;
public class MyWMIQuery
{
public static void Main()
{
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("DeviceID: {0}", queryObj["DeviceID"]);
Console.WriteLine("PNPDeviceID: {0}", queryObj["PNPDeviceID"]);
Console.WriteLine("Manufacturer: {0}", queryObj["Manufacturer"]);
Console.WriteLine("Model: {0}", queryObj["Model"]);
foreach (ManagementObject b in queryObj.GetRelated("Win32_DiskPartition"))
{
Console.WriteLine(" Name: {0}", b["Name"]);
foreach (ManagementBaseObject c in b.GetRelated("Win32_LogicalDisk"))
{
Console.WriteLine(" Name: {0}", c["Name"]); // here it will print drive letter
}
}
// ...
Console.WriteLine("--------------------------------------------");
}
}
catch (ManagementException e)
{
Console.WriteLine(e.StackTrace);
}
Console.ReadLine();
}
}
}
```
I think those properties should help you distinguish genuine USB drives from the others. Test with several pen drives to check if the values are the same. See full reference for **Win32\_DiskDrive** properties here:
<http://msdn.microsoft.com/en-us/library/aa394132(VS.85).aspx>
Check if this article is also of any help to you:
<http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/48a9758c-d4db-4144-bad1-e87f2e9fc979> |
123,994 | <p>I'm trying to pass in a Base64 string into a C#.Net web application via the QueryString. When the string arrives the "+" (plus) sign is being replaced by a space. It appears that the automatic URLDecode process is doing this. I have no control over what is being passed via the QueryString. Is there any way to handle this server side?</p>
<p>Example:</p>
<pre><code>http://localhost:3399/Base64.aspx?VLTrap=VkxUcmFwIHNldCB0byAiRkRTQT8+PE0iIHBsdXMgb3IgbWludXMgNSBwZXJjZW50Lg==
</code></pre>
<p>Produces:</p>
<pre><code>VkxUcmFwIHNldCB0byAiRkRTQT8 PE0iIHBsdXMgb3IgbWludXMgNSBwZXJjZW50Lg==
</code></pre>
<p>People have suggested URLEncoding the querystring:</p>
<pre><code>System.Web.HttpUtility.UrlEncode(yourString)
</code></pre>
<p>I can't do that as I have no control over the calling routine (which is working fine with other languages).</p>
<p>There was also the suggestion of replacing spaces with a plus sign:</p>
<pre><code>Request.QueryString["VLTrap"].Replace(" ", "+");
</code></pre>
<p>I had though of this but my concern with it, and I should have mentioned this to start, is that I don't know what <em>other</em> characters might be malformed in addition to the plus sign.</p>
<p><strong><em>My main goal is to intercept the QueryString before it is run through the decoder.</em></strong></p>
<p>To this end I tried looking at Request.QueryString.toString() but this contained the same malformed information. Is there any way to look at the raw QueryString <em>before</em> it is URLDecoded?</p>
<p>After further testing it appears that .Net expects everything coming in from the QuerString to be URL encoded but the browser does not automatically URL encode GET requests.</p>
| [
{
"answer_id": 124004,
"author": "Nir",
"author_id": 3509,
"author_profile": "https://Stackoverflow.com/users/3509",
"pm_score": 1,
"selected": false,
"text": "<p>If you URLEncode the string before adding it to the URL you will not have any of those problems (the automatic URLDecode will... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7819/"
] | I'm trying to pass in a Base64 string into a C#.Net web application via the QueryString. When the string arrives the "+" (plus) sign is being replaced by a space. It appears that the automatic URLDecode process is doing this. I have no control over what is being passed via the QueryString. Is there any way to handle this server side?
Example:
```
http://localhost:3399/Base64.aspx?VLTrap=VkxUcmFwIHNldCB0byAiRkRTQT8+PE0iIHBsdXMgb3IgbWludXMgNSBwZXJjZW50Lg==
```
Produces:
```
VkxUcmFwIHNldCB0byAiRkRTQT8 PE0iIHBsdXMgb3IgbWludXMgNSBwZXJjZW50Lg==
```
People have suggested URLEncoding the querystring:
```
System.Web.HttpUtility.UrlEncode(yourString)
```
I can't do that as I have no control over the calling routine (which is working fine with other languages).
There was also the suggestion of replacing spaces with a plus sign:
```
Request.QueryString["VLTrap"].Replace(" ", "+");
```
I had though of this but my concern with it, and I should have mentioned this to start, is that I don't know what *other* characters might be malformed in addition to the plus sign.
***My main goal is to intercept the QueryString before it is run through the decoder.***
To this end I tried looking at Request.QueryString.toString() but this contained the same malformed information. Is there any way to look at the raw QueryString *before* it is URLDecoded?
After further testing it appears that .Net expects everything coming in from the QuerString to be URL encoded but the browser does not automatically URL encode GET requests. | You could manually replace the value (`argument.Replace(' ', '+')`) or consult the `HttpRequest.ServerVariables["QUERY_STRING"]` (even better the HttpRequest.Url.Query) and parse it yourself.
You should however try to solve the problem where the URL is given; a plus sign needs to get encoded as "%2B" in the URL because a plus otherwise represents a space.
If you don't control the inbound URLs, the first option would be preferred as you avoid the most errors this way. |
123,999 | <p>Is there an efficient way to tell if a DOM element (in an HTML document) is currently visible (appears in the <strong>viewport</strong>)?</p>
<p>(The question refers to Firefox.)</p>
| [
{
"answer_id": 125106,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 10,
"selected": true,
"text": "<p><strong>Update:</strong> Time marches on and so have our browsers. <strong>This technique is no longer recommended</stro... | 2008/09/23 | [
"https://Stackoverflow.com/questions/123999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21290/"
] | Is there an efficient way to tell if a DOM element (in an HTML document) is currently visible (appears in the **viewport**)?
(The question refers to Firefox.) | **Update:** Time marches on and so have our browsers. **This technique is no longer recommended** and you should use [Dan's solution](https://stackoverflow.com/questions/123999/how-can-i-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433) if you do not need to support version of Internet Explorer before 7.
**Original solution (now outdated):**
This will check if the element is entirely visible in the current viewport:
```
function elementInViewport(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top >= window.pageYOffset &&
left >= window.pageXOffset &&
(top + height) <= (window.pageYOffset + window.innerHeight) &&
(left + width) <= (window.pageXOffset + window.innerWidth)
);
}
```
You could modify this simply to determine if any part of the element is visible in the viewport:
```
function elementInViewport2(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
}
``` |
124,035 | <p>I recently converted a ruby library to a gem, which seemed to break the command line usability</p>
<p>Worked fine as a library</p>
<pre><code> $ ruby -r foobar -e 'p FooBar.question' # => "answer"
</code></pre>
<p>And as a gem, irb knows how to require a gem from command-line switches</p>
<pre><code> $ irb -rubygems -r foobar
irb(main):001:0> FooBar.question # => "answer"
</code></pre>
<p>But the same fails for ruby itself:</p>
<pre><code> $ ruby -rubygems -r foobar -e 'p FooBar.question'
ruby: no such file to load -- foobar (LoadError)
</code></pre>
<p>must I now do this, which seems ugly: </p>
<pre><code> ruby -rubygems -e 'require "foobar"; p FooBar.question' # => "answer"
</code></pre>
<p>Or is there a way to make the 2 switches work?</p>
<p><em>Note</em>: I know the gem could add a bin/program for every useful method but I don't like to pollute the command line namespace unnecessarily</p>
| [
{
"answer_id": 124069,
"author": "JasonTrue",
"author_id": 13433,
"author_profile": "https://Stackoverflow.com/users/13433",
"pm_score": 4,
"selected": true,
"text": "<p>-rubygems is actually the same as -r ubygems.</p>\n\n<p>It doesn't mess with your search path, as far as I understand,... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4615/"
] | I recently converted a ruby library to a gem, which seemed to break the command line usability
Worked fine as a library
```
$ ruby -r foobar -e 'p FooBar.question' # => "answer"
```
And as a gem, irb knows how to require a gem from command-line switches
```
$ irb -rubygems -r foobar
irb(main):001:0> FooBar.question # => "answer"
```
But the same fails for ruby itself:
```
$ ruby -rubygems -r foobar -e 'p FooBar.question'
ruby: no such file to load -- foobar (LoadError)
```
must I now do this, which seems ugly:
```
ruby -rubygems -e 'require "foobar"; p FooBar.question' # => "answer"
```
Or is there a way to make the 2 switches work?
*Note*: I know the gem could add a bin/program for every useful method but I don't like to pollute the command line namespace unnecessarily | -rubygems is actually the same as -r ubygems.
It doesn't mess with your search path, as far as I understand, but I think it doesn't add anything to your -r search path either. I was able to do something like this:
```
ruby -rubygems -r /usr/lib/ruby/gems/myhelpfulclass-0.0.1/lib/MyHelpfulClass -e "puts MyHelpfulClass"
```
MyHelpfulClass.rb exists in the lib directory specified above.
That kind of sucks, but it at least demonstrates that you can have multiple -r equire directives.
As a slightly less ugly workaround, you can add additional items to the ruby library search path (colon delimited in \*nix, semicolon delimited in windows).
```
export RUBYLIB=/usr/lib/ruby/gems/1.8/gems/myhelpfulclass-0.0.1/lib
ruby -rubygems -r MyHelpfulClass -e "puts MyHelpfulClass"
```
If you don't want to mess with the environment variable, you can add something to the load path yourself:
```
ruby -I /usr/lib/ruby/gems/1.8/gems/myhelpfulclass-0.0.1/lib \
-rubygems -r MyHelpfulClass -e "puts MyHelpfulClass"
``` |
124,067 | <p>In languages like Java and C#, strings are immutable and it can be computationally expensive to build a string one character at a time. In said languages, there are library classes to reduce this cost such as C# <code>System.Text.StringBuilder</code> and Java <code>java.lang.StringBuilder</code>.</p>
<p>Does php (4 or 5; I'm interested in both) share this limitation? If so, are there similar solutions to the problem available?</p>
| [
{
"answer_id": 124084,
"author": "paan",
"author_id": 2976,
"author_profile": "https://Stackoverflow.com/users/2976",
"pm_score": -1,
"selected": false,
"text": "<p>no such limitation in php,\nphp can concatenate strng with the dot(.) operator</p>\n\n<pre><code>$a=\"hello \";\n$b=\"world... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21388/"
] | In languages like Java and C#, strings are immutable and it can be computationally expensive to build a string one character at a time. In said languages, there are library classes to reduce this cost such as C# `System.Text.StringBuilder` and Java `java.lang.StringBuilder`.
Does php (4 or 5; I'm interested in both) share this limitation? If so, are there similar solutions to the problem available? | No, there is no type of stringbuilder class in PHP, since strings are mutable.
That being said, there are different ways of building a string, depending on what you're doing.
echo, for example, will accept comma-separated tokens for output.
```
// This...
echo 'one', 'two';
// Is the same as this
echo 'one';
echo 'two';
```
What this means is that you can output a complex string without actually using concatenation, which would be slower
```
// This...
echo 'one', 'two';
// Is faster than this...
echo 'one' . 'two';
```
If you need to capture this output in a variable, you can do that with the [output buffering functions](http://us3.php.net/outcontrol).
Also, PHP's array performance is really good. If you want to do something like a comma-separated list of values, just use implode()
```
$values = array( 'one', 'two', 'three' );
$valueList = implode( ', ', $values );
```
Lastly, make sure you familiarize yourself with [PHP's string type](http://us3.php.net/types.string) and it's different delimiters, and the implications of each. |
124,079 | <p>I'd like to slice and dice large datafiles, up to a gig, in a fairly quick and efficient manner. If I use something like UNIX's "CUT", it's extremely fast, even in a CYGWIN environment. </p>
<p>I've tried developing and benchmarking various Ruby scripts to process these files, and always end up with glacial results. </p>
<p>What would you do in Ruby to make this not so dog slow?</p>
| [
{
"answer_id": 124088,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p>This question reminds me of Tim Bray's <a href=\"http://www.tbray.org/ongoing/When/200x/2007/09/20/Wide-Finder\" rel=... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21275/"
] | I'd like to slice and dice large datafiles, up to a gig, in a fairly quick and efficient manner. If I use something like UNIX's "CUT", it's extremely fast, even in a CYGWIN environment.
I've tried developing and benchmarking various Ruby scripts to process these files, and always end up with glacial results.
What would you do in Ruby to make this not so dog slow? | Why not combine them together - using cut to do what it does best and ruby to provide the glue/value add with the results from CUT? you can run shell scripts by putting them in backticks like this:
```
puts `cut somefile > foo.fil`
# process each line of the output from cut
f = File.new("foo.fil")
f.each{|line|
}
``` |
124,118 | <p>We want to switch a web server from Windows 2003 to Windows 2003 Enterprise (64 bits) to use 8GB of RAM. Will IIS 6.0 and an ASPNET 1.1 application be able to benefit from the change?</p>
| [
{
"answer_id": 124338,
"author": "Pseudo Masochist",
"author_id": 8529,
"author_profile": "https://Stackoverflow.com/users/8529",
"pm_score": 0,
"selected": false,
"text": "<p>My understanding is that there was a virtual address space limitation of 3 GB in ASP.NET 1.1, and that it was ne... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7277/"
] | We want to switch a web server from Windows 2003 to Windows 2003 Enterprise (64 bits) to use 8GB of RAM. Will IIS 6.0 and an ASPNET 1.1 application be able to benefit from the change? | Since ASP.Net 1.1 has no x64 support, you are limited to running IIS 6 using 32 bit worker processes. The /3GB switch doesn't do anything on x64, but x64 natively gives 32bit processes 4 GB instead of 2GB, so you will have more memory available for your worker proces.
You will need to set the AppPools to 32 bit:
```
cscript %SystemDrive%\inetpub\AdminScripts\adsutil.vbs set w3svc/AppPools/Enable32bitAppOnWin64 1
```
You could consider tweaking the ASP.net memory from 60% of the application to 80%, which we've had some success.
```
<system.web>
<processModel memoryLimit="80" />
</system.web>
```
This can stress the app pool when you get up into the 1.2GB to 1.6 GB range.
Other things to consider is that most ASP.Net 1.1 applications have no issues when run in a 2.0 application pool, allowing you to easily convert your 1.1 32 bit application to a 2.0 64 bit application. This doesn't require any recompilation, just change the app pool to 2.0, then switch to x64 using the above ADSUTIL.VBS script (set to 0 rather than 1). |
124,121 | <p>I saw an article on creating Excel UDFs in VSTO managed code, using VBA: <a href="http://blogs.msdn.com/pstubbs/archive/2004/12/31/344964.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/pstubbs/archive/2004/12/31/344964.aspx</a>. </p>
<p>However I want to get this working in a C# Excel add-in using VSTO 2005 SE, can any one help?</p>
<p>I tried the technique Romain pointed out but when trying to load Excel I get the following exception:</p>
<blockquote>
<p>The customization assembly could not
be found or could not be loaded. You
can still edit and save the
document.....</p>
</blockquote>
<p>Details:</p>
<pre><code>Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))
************** Exception Text **************
System.Runtime.InteropServices.COMException (0x80020005): Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))
at Microsoft.Office.Interop.Excel._Application.Run(Object Macro, Object Arg1, Object Arg2, Object Arg3, Object Arg4, Object Arg5, Object Arg6, Object Arg7, Object Arg8, Object Arg9, Object Arg10, Object Arg11, Object Arg12, Object Arg13, Object Arg14, Object Arg15, Object Arg16, Object Arg17, Object Arg18, Object Arg19, Object Arg20, Object Arg21, Object Arg22, Object Arg23, Object Arg24, Object Arg25, Object Arg26, Object Arg27, Object Arg28, Object Arg29, Object Arg30)
at ExcelWorkbook4.ThisWorkbook.ThisWorkbook_Startup(Object sender, EventArgs e) in C:\projects\ExcelWorkbook4\ExcelWorkbook4\ThisWorkbook.cs:line 42
at Microsoft.Office.Tools.Excel.Workbook.OnStartup()
at ExcelWorkbook4.ThisWorkbook.FinishInitialization() in C:\projects\ExcelWorkbook4\ExcelWorkbook4\ThisWorkbook.Designer.cs:line 66
at Microsoft.VisualStudio.Tools.Applications.Runtime.AppDomainManagerInternal.ExecutePhase(String methodName)
at Microsoft.VisualStudio.Tools.Applications.Runtime.AppDomainManagerInternal.ExecuteCustomizationStartupCode()
at Microsoft.VisualStudio.Tools.Applications.Runtime.AppDomainManagerInternal.ExecuteCustomization(IHostServiceProvider serviceProvider)
************** Loaded Assemblies **************
</code></pre>
| [
{
"answer_id": 125984,
"author": "Romain Verdier",
"author_id": 4687,
"author_profile": "https://Stackoverflow.com/users/4687",
"pm_score": 1,
"selected": false,
"text": "<p>Creating UDF using a simple automation addin is quite easy. You will have to create a dedicated assembly and make ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17584/"
] | I saw an article on creating Excel UDFs in VSTO managed code, using VBA: <http://blogs.msdn.com/pstubbs/archive/2004/12/31/344964.aspx>.
However I want to get this working in a C# Excel add-in using VSTO 2005 SE, can any one help?
I tried the technique Romain pointed out but when trying to load Excel I get the following exception:
>
> The customization assembly could not
> be found or could not be loaded. You
> can still edit and save the
> document.....
>
>
>
Details:
```
Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))
************** Exception Text **************
System.Runtime.InteropServices.COMException (0x80020005): Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))
at Microsoft.Office.Interop.Excel._Application.Run(Object Macro, Object Arg1, Object Arg2, Object Arg3, Object Arg4, Object Arg5, Object Arg6, Object Arg7, Object Arg8, Object Arg9, Object Arg10, Object Arg11, Object Arg12, Object Arg13, Object Arg14, Object Arg15, Object Arg16, Object Arg17, Object Arg18, Object Arg19, Object Arg20, Object Arg21, Object Arg22, Object Arg23, Object Arg24, Object Arg25, Object Arg26, Object Arg27, Object Arg28, Object Arg29, Object Arg30)
at ExcelWorkbook4.ThisWorkbook.ThisWorkbook_Startup(Object sender, EventArgs e) in C:\projects\ExcelWorkbook4\ExcelWorkbook4\ThisWorkbook.cs:line 42
at Microsoft.Office.Tools.Excel.Workbook.OnStartup()
at ExcelWorkbook4.ThisWorkbook.FinishInitialization() in C:\projects\ExcelWorkbook4\ExcelWorkbook4\ThisWorkbook.Designer.cs:line 66
at Microsoft.VisualStudio.Tools.Applications.Runtime.AppDomainManagerInternal.ExecutePhase(String methodName)
at Microsoft.VisualStudio.Tools.Applications.Runtime.AppDomainManagerInternal.ExecuteCustomizationStartupCode()
at Microsoft.VisualStudio.Tools.Applications.Runtime.AppDomainManagerInternal.ExecuteCustomization(IHostServiceProvider serviceProvider)
************** Loaded Assemblies **************
``` | You should also have a look at ExcelDna - <http://www.codeplex.com/exceldna>. ExcelDna allows managed assemblies to expose user-defined functions (UDFs) and macros to Excel through the native .xll interface. The project is open-source and freely allows commercial use.
Your user-defined functions can be written in C#, Visual Basic, F#, Java (using IKVM.NET), and can be compiled to a .dll or exposed through a text-based script file. Excel versions from Excel 97 to Excel 2007 are supported.
Some advantages of using the .xll interface rather than making automation add-ins include:
* older versions of Excel are supported,
* deployment is much easier since COM registration is not required and references to user-defined functions in worksheet formulae do not bind to the location of the add-in, and
* the performance of UDF functions exposed through ExcelDna is excellent. |
124,123 | <p>Imagine I have the folling XML file:</p>
<p><a>before<b>middle</b>after</a></p>
<p>I want to convert it into something like this:</p>
<p><a>beforemiddleafter</a></p>
<p>In other words I want to get all the child nodes of a certain node, and move them to the parent node in order. This is like doing this command: "mv ./directory/* .", but for xml nodes.</p>
<p>I'd like to do this in using unix command line tools. I've been trying with xmlstarlet, which is a powerful command line XML manipulator. I tried doing something like this, but it doesn't work</p>
<p>echo "<a>before<b>middle</b>after</a>" | xmlstarlet ed -m "//b/*" ".."</p>
<p>Update: XSLT templates are fine, since they can be called from the command line.</p>
<p>My goal here is 'remove the links from an XHTML page', in other words replace where the link was, with the contents of the link tag.</p>
| [
{
"answer_id": 124215,
"author": "Rahul",
"author_id": 16308,
"author_profile": "https://Stackoverflow.com/users/16308",
"pm_score": 2,
"selected": false,
"text": "<p>In XSLT, you could just write:</p>\n\n<pre><code><xsl:template match=\"a\"><a><xsl:apply-templates />&l... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/161922/"
] | Imagine I have the folling XML file:
<a>before<b>middle</b>after</a>
I want to convert it into something like this:
<a>beforemiddleafter</a>
In other words I want to get all the child nodes of a certain node, and move them to the parent node in order. This is like doing this command: "mv ./directory/\* .", but for xml nodes.
I'd like to do this in using unix command line tools. I've been trying with xmlstarlet, which is a powerful command line XML manipulator. I tried doing something like this, but it doesn't work
echo "<a>before<b>middle</b>after</a>" | xmlstarlet ed -m "//b/\*" ".."
Update: XSLT templates are fine, since they can be called from the command line.
My goal here is 'remove the links from an XHTML page', in other words replace where the link was, with the contents of the link tag. | If your actual goal is to remove the links from a web page, then you should use a stylesheet like this, which matches all XHTML `<a>` elements (I'm assuming you're using XHTML?) and simply applies templates to their content:
```
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:h="http://www.w3.org/1999/xhtml"
exclude-result-prefixes="h">
<!-- Don't copy the <a> elements, just process their content -->
<xsl:template match="h:a">
<xsl:apply-templates />
</xsl:template>
<!-- identity template; copies everything by default -->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
```
This stylesheet will deal with a situation where you have something nested *within* the `<a>` element that you want to retain, such as:
```
<p>Here is <a href="....">some <em>linked</em> text</a>.</p>
```
which you will want to come out as:
```
<p>Here is some <em>linked</em> text.</p>
```
And it will deal with the situation where you have the link nested within an unexpected element between the usual parent (the `<p>` element) and the `<a>` element, such as:
```
<p>Here is <em>some <a href="...">linked</a> text</em>.</p>
``` |
124,143 | <p>I know Googling I can find an appropriate answer, but I prefer listening to your personal (and maybe technical) opinions.<br/>
<strong>What is the main reason of the difference between Java and C# in throwing exceptions?</strong><br/>
In Java the signature of a method that throws an exception has to use the "throws" keyword, while in C# you don't know in compilation time if an exception could be thrown.</p>
| [
{
"answer_id": 124173,
"author": "Derek Slager",
"author_id": 18636,
"author_profile": "https://Stackoverflow.com/users/18636",
"pm_score": 4,
"selected": false,
"text": "<p>The basic design philosophy of C# is that actually catching exceptions is rarely useful, whereas cleaning up resou... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68336/"
] | I know Googling I can find an appropriate answer, but I prefer listening to your personal (and maybe technical) opinions.
**What is the main reason of the difference between Java and C# in throwing exceptions?**
In Java the signature of a method that throws an exception has to use the "throws" keyword, while in C# you don't know in compilation time if an exception could be thrown. | Because the response to checked exceptions is almost always:
```
try {
// exception throwing code
} catch(Exception e) {
// either
log.error("Error fooing bar",e);
// OR
throw new RuntimeException(e);
}
```
If you actually know that there is something you can do if a particular exception is thrown, then you can catch it and then handle it, but otherwise it's just incantations to appease the compiler. |
124,148 | <p>Mixing the use of primitive data types and their respective wrapper classes, in Java, can lead to a lot of bugs. The following example illustrates the issue:</p>
<pre><code>int i = 4;
...
if (i == 10)
doStuff();
</code></pre>
<p>Later on you figure that you want the variable <em>i</em> to be either defined or undefined, so you change the above instantiation to:</p>
<pre><code>Integer i = null;
</code></pre>
<p>Now the equality check fails.</p>
<p>Is it good Java practise to always use the primitive wrapper classes? It obviously would get some bugs out of the way early, but what are the downsides to this? Does it impact performance or the application's memory footprint? Are there any sneaky gotchas?</p>
| [
{
"answer_id": 124190,
"author": "rmeador",
"author_id": 10861,
"author_profile": "https://Stackoverflow.com/users/10861",
"pm_score": 3,
"selected": false,
"text": "<p>Firstly, switching from using a primitive to using an object just to get the ability to set it to null is probably a ba... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8683/"
] | Mixing the use of primitive data types and their respective wrapper classes, in Java, can lead to a lot of bugs. The following example illustrates the issue:
```
int i = 4;
...
if (i == 10)
doStuff();
```
Later on you figure that you want the variable *i* to be either defined or undefined, so you change the above instantiation to:
```
Integer i = null;
```
Now the equality check fails.
Is it good Java practise to always use the primitive wrapper classes? It obviously would get some bugs out of the way early, but what are the downsides to this? Does it impact performance or the application's memory footprint? Are there any sneaky gotchas? | Using the boxed types *does* have both performance and memory issues.
When doing comparisons (eg `(i == 10)` ), java has to unbox the type before doing the comparison. Even using `i.equals(TEN)` uses a method call, which is costlier and (IMO) uglier than the == syntax.
Re memory, the object has to be stored on the heap (which also takes a hit on performance) as well as storing the value itself.
A sneaky gotcha? `i.equals(j)` when i is `null`.
I always use the primitives, except when it *may* be `null`, but always check for `null` before comparison in those cases. |
124,167 | <p>Please explain to me why the very last <code>echo</code> statement is blank? I expect that <code>XCODE</code> is incremented in the while loop to a value of 1:</p>
<pre><code>#!/bin/bash
OUTPUT="name1 ip ip status" # normally output of another command with multi line output
if [ -z "$OUTPUT" ]
then
echo "Status WARN: No messages from SMcli"
exit $STATE_WARNING
else
echo "$OUTPUT"|while read NAME IP1 IP2 STATUS
do
if [ "$STATUS" != "Optimal" ]
then
echo "CRIT: $NAME - $STATUS"
echo $((++XCODE))
else
echo "OK: $NAME - $STATUS"
fi
done
fi
echo $XCODE
</code></pre>
<p>I've tried using the following statement instead of the <code>++XCODE</code> method</p>
<pre><code>XCODE=`expr $XCODE + 1`
</code></pre>
<p>and it too won't print outside of the while statement. I think I'm missing something about variable scope here, but the ol' man page isn't showing it to me.</p>
| [
{
"answer_id": 124211,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 2,
"selected": false,
"text": "<pre><code> #!/bin/bash\n OUTPUT=\"name1 ip ip status\"\n+export XCODE=0;\n if [ -z \"$OUTPUT\" ]\n----\n\n ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14230/"
] | Please explain to me why the very last `echo` statement is blank? I expect that `XCODE` is incremented in the while loop to a value of 1:
```
#!/bin/bash
OUTPUT="name1 ip ip status" # normally output of another command with multi line output
if [ -z "$OUTPUT" ]
then
echo "Status WARN: No messages from SMcli"
exit $STATE_WARNING
else
echo "$OUTPUT"|while read NAME IP1 IP2 STATUS
do
if [ "$STATUS" != "Optimal" ]
then
echo "CRIT: $NAME - $STATUS"
echo $((++XCODE))
else
echo "OK: $NAME - $STATUS"
fi
done
fi
echo $XCODE
```
I've tried using the following statement instead of the `++XCODE` method
```
XCODE=`expr $XCODE + 1`
```
and it too won't print outside of the while statement. I think I'm missing something about variable scope here, but the ol' man page isn't showing it to me. | Because you're piping into the while loop, a sub-shell is created to run the while loop.
Now this child process has its own copy of the environment and can't pass any
variables back to its parent (as in any unix process).
Therefore you'll need to restructure so that you're not piping into the loop.
Alternatively you could run in a function, for example, and `echo` the value you
want returned from the sub-process.
<http://tldp.org/LDP/abs/html/subshells.html#SUBSHELL> |
124,205 | <p>I would like to do a lookup of tables in my SQL Server 2005 Express database based on table name. In <code>MySQL</code> I would use <code>SHOW TABLES LIKE "Datasheet%"</code>, but in <code>T-SQL</code> this throws an error (it tries to look for a <code>SHOW</code> stored procedure and fails).</p>
<p>Is this possible, and if so, how?</p>
| [
{
"answer_id": 124216,
"author": "Mladen",
"author_id": 21404,
"author_profile": "https://Stackoverflow.com/users/21404",
"pm_score": 3,
"selected": false,
"text": "<p>Try this :</p>\n\n<pre><code>select * from information_schema.columns\nwhere table_name = 'yourTableName'\n</code></pre>... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21402/"
] | I would like to do a lookup of tables in my SQL Server 2005 Express database based on table name. In `MySQL` I would use `SHOW TABLES LIKE "Datasheet%"`, but in `T-SQL` this throws an error (it tries to look for a `SHOW` stored procedure and fails).
Is this possible, and if so, how? | This will give you a list of the tables in the current database:
```
Select Table_name as "Table name"
From Information_schema.Tables
Where Table_type = 'BASE TABLE' and Objectproperty
(Object_id(Table_name), 'IsMsShipped') = 0
```
Some other useful T-SQL bits can be found here: <http://www.devx.com/tips/Tip/28529> |
124,207 | <p>I currently filter some message from my inbox with these steps:</p>
<pre><code>select inbox
pick messages
set \Deleted tag
</code></pre>
<p>and then repeat the process after selecting Trash.</p>
<p>Is there a more direct way of disposing of these messages? Or is it just the feature of the Mail server that deleting a message puts it in the trash, and deleting from the trash permantently disposes of it?</p>
| [
{
"answer_id": 124245,
"author": "mopoke",
"author_id": 14054,
"author_profile": "https://Stackoverflow.com/users/14054",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure exactly where you're doing these operations. IMAP itself doesn't specify that you move things to a Trash folder... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] | I currently filter some message from my inbox with these steps:
```
select inbox
pick messages
set \Deleted tag
```
and then repeat the process after selecting Trash.
Is there a more direct way of disposing of these messages? Or is it just the feature of the Mail server that deleting a message puts it in the trash, and deleting from the trash permantently disposes of it? | I believe you have to call EXPUNGE after setting the tag Deleted.
[RFC 3501](http://www.faqs.org/rfcs/rfc3501.html) |
124,240 | <p>Been using <strong>PHP/MySQL</strong> for a little while now, and I'm wondering if there are any specific advantages (performance or otherwise) to using <code>mysql_fetch_object()</code> vs <code>mysql_fetch_assoc()</code> / <code>mysql_fetch_array()</code>.</p>
| [
{
"answer_id": 124262,
"author": "Steve Paulo",
"author_id": 9414,
"author_profile": "https://Stackoverflow.com/users/9414",
"pm_score": 2,
"selected": false,
"text": "<p>Fetching an array with <code>mysql_fetch_array()</code> lets you loop through the result set via either a foreach loo... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2227/"
] | Been using **PHP/MySQL** for a little while now, and I'm wondering if there are any specific advantages (performance or otherwise) to using `mysql_fetch_object()` vs `mysql_fetch_assoc()` / `mysql_fetch_array()`. | Performance-wise it doesn't matter what you use. The difference is that mysql\_fetch\_object returns object:
```
while ($row = mysql_fetch_object($result)) {
echo $row->user_id;
echo $row->fullname;
}
```
mysql\_fetch\_assoc() returns associative array:
```
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
}
```
and mysql\_fetch\_array() returns array:
```
while ($row = mysql_fetch_array($result)) {
echo $row[0];
echo $row[1] ;
}
``` |
124,266 | <p>What is an elegant way to sort objects in PHP? I would love to accomplish something similar to this.</p>
<pre><code>$sortedObjectArary = sort($unsortedObjectArray, $Object->weight);
</code></pre>
<p>Basically specify the array I want to sort as well as the field I want to sort on. I looked into multidimensional array sorting and there might be something useful there, but I don't see anything elegant or obvious.</p>
| [
{
"answer_id": 124283,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 7,
"selected": true,
"text": "<p>Almost verbatim from the manual: </p>\n\n<pre><code>function compare_weights($a, $b) { \n if($a->weight == $b... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8880/"
] | What is an elegant way to sort objects in PHP? I would love to accomplish something similar to this.
```
$sortedObjectArary = sort($unsortedObjectArray, $Object->weight);
```
Basically specify the array I want to sort as well as the field I want to sort on. I looked into multidimensional array sorting and there might be something useful there, but I don't see anything elegant or obvious. | Almost verbatim from the manual:
```
function compare_weights($a, $b) {
if($a->weight == $b->weight) {
return 0;
}
return ($a->weight < $b->weight) ? -1 : 1;
}
usort($unsortedObjectArray, 'compare_weights');
```
If you want objects to be able to sort themselves, see example 3 here: <http://php.net/usort> |
124,269 | <p>What is the simplest SOAP example using Javascript?</p>
<p>To be as useful as possible, the answer should:</p>
<ul>
<li>Be functional (in other words actually work)</li>
<li>Send at least one parameter that can be set elsewhere in the code</li>
<li>Process at least one result value that can be read elsewhere in the code</li>
<li>Work with most modern browser versions</li>
<li>Be as clear and as short as possible, without using an external library</li>
</ul>
| [
{
"answer_id": 124663,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 1,
"selected": false,
"text": "<p>Simplest example would consist of:</p>\n\n<ol>\n<li>Getting user input.</li>\n<li><p>Composing XML SOAP message simi... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15985/"
] | What is the simplest SOAP example using Javascript?
To be as useful as possible, the answer should:
* Be functional (in other words actually work)
* Send at least one parameter that can be set elsewhere in the code
* Process at least one result value that can be read elsewhere in the code
* Work with most modern browser versions
* Be as clear and as short as possible, without using an external library | This is the simplest JavaScript SOAP Client I can create.
```
<html>
<head>
<title>SOAP JavaScript Client Test</title>
<script type="text/javascript">
function soap() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'https://somesoapurl.com/', true);
// build SOAP request
var sr =
'<?xml version="1.0" encoding="utf-8"?>' +
'<soapenv:Envelope ' +
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
'xmlns:api="http://127.0.0.1/Integrics/Enswitch/API" ' +
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soapenv:Body>' +
'<api:some_api_call soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
'<username xsi:type="xsd:string">login_username</username>' +
'<password xsi:type="xsd:string">password</password>' +
'</api:some_api_call>' +
'</soapenv:Body>' +
'</soapenv:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
// alert('done. use firebug/console to see network response');
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(sr);
// send request
// ...
}
</script>
</head>
<body>
<form name="Demo" action="" method="post">
<div>
<input type="button" value="Soap" onclick="soap();" />
</div>
</form>
</body>
</html> <!-- typo -->
``` |
124,275 | <p>I'm tired of using: </p>
<pre><code>tail -f development.log
</code></pre>
<p>To keep track of my rails logs. Instead I would like something that displays the info in a grid and allows my to sort, filter and look at stack traces per log message.</p>
<p>Does anyone know of a GUI tool for displaying rails logs. Ideally I would like a standalone app (not something in Netbeans or Eclipse) </p>
| [
{
"answer_id": 124287,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 2,
"selected": true,
"text": "<p>FWIW I started <a href=\"http://github.com/SamSaffron/logviewer/tree/master\" rel=\"nofollow noreferrer\">this proje... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17174/"
] | I'm tired of using:
```
tail -f development.log
```
To keep track of my rails logs. Instead I would like something that displays the info in a grid and allows my to sort, filter and look at stack traces per log message.
Does anyone know of a GUI tool for displaying rails logs. Ideally I would like a standalone app (not something in Netbeans or Eclipse) | FWIW I started [this project](http://github.com/SamSaffron/logviewer/tree/master) at GitHub to try and solve this problem, its far from functional. |
124,291 | <p>I need to do some simple timezone calculation in mod_perl. DateTime isn't an option. What I need to do is easily accomplished by setting $ENV{TZ} and using localtime and POSIX::mktime, but under a threaded MPM, I'd need to make sure only one thread at a time was mucking with the environment. (I'm not concerned about other uses of localtime, etc.)</p>
<p>How can I use a mutex or other locking strategy to serialize (in the non-marshalling sense) access to the environment? The <a href="http://perl.apache.org/docs/2.0/api/APR/ThreadMutex.html" rel="nofollow noreferrer">docs</a> I've looked at don't explain well enough how I would create a mutex for just this use. Maybe there's something I'm just not getting about how you create mutexes in general.</p>
<p>Update: yes, I am aware of the need for using Env::C to set TZ.</p>
| [
{
"answer_id": 125010,
"author": "pjf",
"author_id": 19422,
"author_profile": "https://Stackoverflow.com/users/19422",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using apache 1.3, then you shouldn't need to resort to mutexes. Apache 1.3 spawns of a number of worker processe... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17389/"
] | I need to do some simple timezone calculation in mod\_perl. DateTime isn't an option. What I need to do is easily accomplished by setting $ENV{TZ} and using localtime and POSIX::mktime, but under a threaded MPM, I'd need to make sure only one thread at a time was mucking with the environment. (I'm not concerned about other uses of localtime, etc.)
How can I use a mutex or other locking strategy to serialize (in the non-marshalling sense) access to the environment? The [docs](http://perl.apache.org/docs/2.0/api/APR/ThreadMutex.html) I've looked at don't explain well enough how I would create a mutex for just this use. Maybe there's something I'm just not getting about how you create mutexes in general.
Update: yes, I am aware of the need for using Env::C to set TZ. | (repeating what I said over at PerlMonks...)
```
BEGIN {
my $mutex;
sub that {
$mutex ||= APR::ThreadMutex->new( $r->pool() );
$mutex->lock();
$ENV{TZ}= ...;
...
$mutex->unlock();
}
}
```
But, of course, lock() should happen in a c'tor and unlock() should happen in a d'tor except for one-off hacks.
Update: Note that there is a race condition in how $mutex is initialized in the subroutine (two threads could call that() for the first time nearly simultaneously). You'd most likely want to initialize $mutex before (additional) threads are created but I'm unclear on the details on the 'worker' Apache MPM and how you would accomplish that easily. If there is some code that gets run "early", simply calling that() from there would eliminate the race.
Which all suggests a much safer interface to APR::ThreadMutex:
```
BEGIN {
my $mutex;
sub that {
my $autoLock= APR::ThreadMutex->autoLock( \$mutex );
...
# Mutex automatically released when $autoLock destroyed
}
}
```
Note that autoLock() getting a reference to undef would cause it to use a mutex to prevent a race when it initializes $mutex. |
124,295 | <p>Everything I have read says that when making a managed stored procedure, to right click in Visual Studio and choose deploy. That works fine, but what if I want to deploy it outside of Visual Studio to a number of different locations? I tried creating the assembly with the dll the project built in SQL, and while it did add the assembly, it did not create the procedures out of the assembly. Has anyone figured out how to do this in SQL directly, without using Visual Studio?</p>
| [
{
"answer_id": 124528,
"author": "Kevin Crumley",
"author_id": 1818,
"author_profile": "https://Stackoverflow.com/users/1818",
"pm_score": 4,
"selected": true,
"text": "<p>Copy your assembly DLL file to the local drive on your various servers. Then register your assembly with the databa... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4539/"
] | Everything I have read says that when making a managed stored procedure, to right click in Visual Studio and choose deploy. That works fine, but what if I want to deploy it outside of Visual Studio to a number of different locations? I tried creating the assembly with the dll the project built in SQL, and while it did add the assembly, it did not create the procedures out of the assembly. Has anyone figured out how to do this in SQL directly, without using Visual Studio? | Copy your assembly DLL file to the local drive on your various servers. Then register your assembly with the database:
```
create assembly [YOUR_ASSEMBLY]
from '(PATH_TO_DLL)'
```
...then you create a function referencing the appropriate public method in the DLL:
```
create proc [YOUR_FUNCTION]
as
external name [YOUR_ASSEMBLY].[NAME_SPACE].[YOUR_METHOD]
```
Be sure to use the [ brackets, especially around the NAME\_SPACE. Namespaces can have any number of dots in them, but SQL identifiers can't, unless the parts are explicitly set apart by square brackets. This was a source of many headaches when I was first using SQL CLR.
To be clear, [YOUR\_ASSEMBLY] is the name you defined in SQL; [NAME\_SPACE] is the .NET namespace inside the DLL where your method can be found; and [YOUR\_METHOD] is simply the name of the method within that namespace. |
124,313 | <p>I'm working on an application that is supposed to create products (like shipping insurance policies) when PayPal Instant Payment Notifications are received. Unfortunately, PayPal sometimes sends duplicate notifications. Furthermore, there is another third-party that is performing web-service updates simultaneously when they get updates from PayPal as well.</p>
<p>Here is a basic diagram of the database tables involved.</p>
<pre><code>// table "package"
// columns packageID, policyID, other data...
//
// table "insurancepolicy"
// columns policyID, coverageAmount, other data...
</code></pre>
<p>Here is a basic diagram of what I want to do:</p>
<pre><code>using (SqlConnection conn = new SqlConnection(...))
{
sqlTransaction sqlTrans = conn.BeginTransaction(IsolationLevel.RepeatableRead);
// Calls a stored procedure that checks if the foreign key in the transaction table has a value.
if (PackageDB.HasInsurancePolicy(packageID, conn))
{
sqlTrans.Commit();
return false;
}
// Insert row in foreign table.
int policyID = InsurancePolicyDB.Insert(coverageAmount, conn);
if (policyID <= 0)
{
sqlTrans.Rollback();
return false;
}
// Assign foreign key to parent table. If this fails, roll back everything.
bool assigned = PackageDB.AssignPolicyID(packageID, policyID, conn);
if (!assigned)
{
sqlTrans.Rollback();
return false;
}
}
</code></pre>
<p>If there are two (or more) threads (or processes or applications) doing this at the same time, I want the first thread to lock the "package" row while it has no policyID, until the policy is created and the policyID is assigned to the package table. Then the lock would be released after the policyID is assigned to the package table. It is my hope that the other thread which is calling this same code will pause when it reads the package row to make sure it doesn't have a policyID first. When the first transaction's lock is released, it is my hope that the second transaction will see the policyID is there and therefore return without inserting any rows into the policy table.</p>
<p>Note: Because of the CRUD database design, each the stored procedures involved either Read (select), Create (insert), or Update.</p>
<p>Is this the right use of RepeatableRead transaction isolation?</p>
<p>Thanks.</p>
| [
{
"answer_id": 124601,
"author": "Aaron Jensen",
"author_id": 11229,
"author_profile": "https://Stackoverflow.com/users/11229",
"pm_score": 1,
"selected": false,
"text": "<p>I believe you're actually wanting Serializable isolation level. The problem is that two threads can get past the H... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16454/"
] | I'm working on an application that is supposed to create products (like shipping insurance policies) when PayPal Instant Payment Notifications are received. Unfortunately, PayPal sometimes sends duplicate notifications. Furthermore, there is another third-party that is performing web-service updates simultaneously when they get updates from PayPal as well.
Here is a basic diagram of the database tables involved.
```
// table "package"
// columns packageID, policyID, other data...
//
// table "insurancepolicy"
// columns policyID, coverageAmount, other data...
```
Here is a basic diagram of what I want to do:
```
using (SqlConnection conn = new SqlConnection(...))
{
sqlTransaction sqlTrans = conn.BeginTransaction(IsolationLevel.RepeatableRead);
// Calls a stored procedure that checks if the foreign key in the transaction table has a value.
if (PackageDB.HasInsurancePolicy(packageID, conn))
{
sqlTrans.Commit();
return false;
}
// Insert row in foreign table.
int policyID = InsurancePolicyDB.Insert(coverageAmount, conn);
if (policyID <= 0)
{
sqlTrans.Rollback();
return false;
}
// Assign foreign key to parent table. If this fails, roll back everything.
bool assigned = PackageDB.AssignPolicyID(packageID, policyID, conn);
if (!assigned)
{
sqlTrans.Rollback();
return false;
}
}
```
If there are two (or more) threads (or processes or applications) doing this at the same time, I want the first thread to lock the "package" row while it has no policyID, until the policy is created and the policyID is assigned to the package table. Then the lock would be released after the policyID is assigned to the package table. It is my hope that the other thread which is calling this same code will pause when it reads the package row to make sure it doesn't have a policyID first. When the first transaction's lock is released, it is my hope that the second transaction will see the policyID is there and therefore return without inserting any rows into the policy table.
Note: Because of the CRUD database design, each the stored procedures involved either Read (select), Create (insert), or Update.
Is this the right use of RepeatableRead transaction isolation?
Thanks. | It would be safer and cleaner if `insert into Policy` just hit some uniqueness table constraint on attempt to insert duplicate. Raising isolation level can lower concurrency and lead to other nasty issues like deadlocks.
Another way is to always insert Policy row, then roll it back if Package has been attached to a Policy already:
```
begin tran (read committed)
/* tentatively insert new Policy */
insert Policy
/* attach Package to Policy if it's still free */
update Package
set Package.policy_id = @policy_id
where Package.package_id = @package_id and Package.policy_id is null
if @@rowcount > 0
commit
else
rollback
```
This works best when conflicts are rare, which seems to be your case. |
124,314 | <p>I have a table that holds information about cities in a game, you can build one building each turn and this is recorded with the value "usedBuilding".</p>
<p>Each turn I will run a script that alters usedBuilding to 0, the question is, which of the following two ways is faster and does it actually matter which way is used?</p>
<pre><code>UPDATE cities SET usedBuilding = 0;
UPDATE cities SET usedBuilding = 0 WHERE usedBuilding = 1;
</code></pre>
| [
{
"answer_id": 124324,
"author": "mopoke",
"author_id": 14054,
"author_profile": "https://Stackoverflow.com/users/14054",
"pm_score": 2,
"selected": false,
"text": "<p>If usedBuilding is indexed, it will be quicker to use the where clause since it will only access/update rows where usedB... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] | I have a table that holds information about cities in a game, you can build one building each turn and this is recorded with the value "usedBuilding".
Each turn I will run a script that alters usedBuilding to 0, the question is, which of the following two ways is faster and does it actually matter which way is used?
```
UPDATE cities SET usedBuilding = 0;
UPDATE cities SET usedBuilding = 0 WHERE usedBuilding = 1;
``` | In general, the 2nd case (with the WHERE) clause would be faster - as it won't cause trigger evaluation, transaction logging, index updating, etc. on the unused rows.
Potentially - depending on the distribution of 0/1 values, it could actually be faster to update all rows rather than doing the comparison - but that's a pretty degenerate case.
Since ~95% of your query costs are I/O, using the WHERE clause will either make no difference (since the column is not indexed, and you're doing a table scan) or a huge difference (if the column is indexed, or the table partitioned, etc.). Either way, it doesn't hurt.
I'd suspect that for the amount of data you're talking, you won't notice a difference in either execution plans or speed - which makes it academic at best, premature optimization at worst. So, I'd advise to go with whatever logically makes sense for your app. |
124,325 | <p>I'm trying to grasp the concept of .NET Generics and actually use them in my own code but I keep running into a problem.</p>
<p>Can someone try to explain to me why the following setup does not compile?</p>
<pre><code>public class ClassA
{
ClassB b = new ClassB();
public void MethodA<T>(IRepo<T> repo) where T : ITypeEntity
{
b.MethodB(repo);
}
}
public class ClassB
{
IRepo<ITypeEntity> repo;
public void MethodB(IRepo<ITypeEntity> repo)
{
this.repo = repo;
}
}
</code></pre>
<p>I get the following error:<br>
cannot convert from IRepo<'T> to IRepo<'ITypeEntity></p>
<p>MethodA gets called with a IRepo<'DetailType> object parameter where DetailType inherits from ITypeEntity.</p>
<p>I keep thinking that this should compile as I'm constraining T within MethodA to be of type ITypeEntity.</p>
<p>Any thoughts or feedback would be extremely helpful.</p>
<p>Thanks.</p>
<p><b>Edit:</b> Nick R has a great suggestion but unfortunately in my context, I don't have the option of making ClassA Generic. ClassB could be though.</p>
| [
{
"answer_id": 124382,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 2,
"selected": false,
"text": "<p>The problem is a tricky one to get your head around. DetailType may inherit from ITypeEntity, but isn't actually ITyp... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384853/"
] | I'm trying to grasp the concept of .NET Generics and actually use them in my own code but I keep running into a problem.
Can someone try to explain to me why the following setup does not compile?
```
public class ClassA
{
ClassB b = new ClassB();
public void MethodA<T>(IRepo<T> repo) where T : ITypeEntity
{
b.MethodB(repo);
}
}
public class ClassB
{
IRepo<ITypeEntity> repo;
public void MethodB(IRepo<ITypeEntity> repo)
{
this.repo = repo;
}
}
```
I get the following error:
cannot convert from IRepo<'T> to IRepo<'ITypeEntity>
MethodA gets called with a IRepo<'DetailType> object parameter where DetailType inherits from ITypeEntity.
I keep thinking that this should compile as I'm constraining T within MethodA to be of type ITypeEntity.
Any thoughts or feedback would be extremely helpful.
Thanks.
**Edit:** Nick R has a great suggestion but unfortunately in my context, I don't have the option of making ClassA Generic. ClassB could be though. | Inheritance doesn't work the same when using generics. As Smashery points out, even if TypeA inherits from TypeB, myType<TypeA> doesn't inherit from myType<TypeB>.
As such, you can't make a call to a method defined as MethodA(myType<TypeB> b) expecting a myType<TypeB> and give it a myType<TypeA> instead. The types in question have to match exactly. Thus, the following won't compile:
```
myType<TypeA> a; // This should be a myType<TypeB>, even if it contains only TypeA's
public void MethodB(myType<TypeB> b){ /* do stuff */ }
public void Main()
{
MethodB(a);
}
```
So in your case, you would need to pass in an IRepo<ITypeEntity> to MethodB, even if it only contains DetailTypes. You'd need to do some conversion between the two. If you were using a generic IList, you might do the following:
```
public void MethodA<T>(IList<T> list) where T : ITypeEntity
{
IList<T> myIList = new List<T>();
foreach(T item in list)
{
myIList.Add(item);
}
b.MethodB(myIList);
}
```
I hope this is helpful. |
124,326 | <p>JavaScript allows functions to be treated as objects--if you first define a variable as a function, you can subsequently add properties to that function. How do you do the reverse, and add a function to an "object"?</p>
<p>This works:</p>
<pre><code>var foo = function() { return 1; };
foo.baz = "qqqq";
</code></pre>
<p>At this point, <code>foo()</code> calls the function, and <code>foo.baz</code> has the value "qqqq".</p>
<p>However, if you do the property assignment part first, how do you subsequently assign a function to the variable?</p>
<pre><code>var bar = { baz: "qqqq" };
</code></pre>
<p>What can I do now to arrange for <code>bar.baz</code> to have the value "qqqq" <em>and</em> <code>bar()</code> to call the function?</p>
| [
{
"answer_id": 124359,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>JavaScript allows functions to be\n treated as objects--you can add a\n property to a function. How do you... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11543/"
] | JavaScript allows functions to be treated as objects--if you first define a variable as a function, you can subsequently add properties to that function. How do you do the reverse, and add a function to an "object"?
This works:
```
var foo = function() { return 1; };
foo.baz = "qqqq";
```
At this point, `foo()` calls the function, and `foo.baz` has the value "qqqq".
However, if you do the property assignment part first, how do you subsequently assign a function to the variable?
```
var bar = { baz: "qqqq" };
```
What can I do now to arrange for `bar.baz` to have the value "qqqq" *and* `bar()` to call the function? | It's easy to be confused here, but you can't (easily or clearly or as far as I know) do what you want. Hopefully this will help clear things up.
First, every object in Javascript inherits from the Object object.
```
//these do the same thing
var foo = new Object();
var bar = {};
```
Second, functions **ARE** objects in Javascript. Specifically, they're a Function object. The Function object inherits from the Object object. Checkout the [Function constructor](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function)
```
var foo = new Function();
var bar = function(){};
function baz(){};
```
Once you declare a variable to be an "Object" you can't (easily or clearly or as far as I know) convert it to a Function object. You'd need to declare a new Object of type Function (with the function constructor, assigning a variable an anonymous function etc.), and copy over any properties of methods from your old object.
Finally, anticipating a possible question, even once something is declared as a function, you can't (as far as I know) change the functionBody/source. |
124,332 | <p>I am using the RSA Algorithm for encryption/decryption, and in order to decrypt the files you have to deal with some pretty big values. More specifically, things like </p>
<pre><code>P = C^d % n
= 62^65 % 133
</code></pre>
<p>Now that is really the only calculations that ill be doing. I have tried using Matt McCutchen's BigInteger Library, but I am getting a lot of compiler errors during linking, such as:</p>
<pre><code>encryption.o(.text+0x187):encryption.cpp: undefined reference to `BigInteger::BigInteger(int)'
encryption.o(.text+0x302):encryption.cpp: undefined reference to `operator<<(std::ostream&, BigInteger const&)'
encryption.o(.text$_ZNK10BigIntegermlERKS_[BigInteger::operator*(BigInteger const&) const]+0x63):encryption.cpp: undefined reference to `BigInteger::multiply(BigInteger const&, BigInteger const&)'
</code></pre>
<p>So I was wondering what would be the best way to go about handling the really big integers that come out of the RSA Algorithm.</p>
<p>I heard that a possibility would be to declare your variables as a double long, so...</p>
<pre><code>long long decryptedCharacter;
</code></pre>
<p>but I'm not sure exactly how big of an integer that can store.</p>
<hr>
<p>Well for example, I try to compile and run the following program using dev C++:</p>
<pre><code>#include iostream
#include "bigint\BigIntegerLibrary.hh"
using namespace std;
int main()
{
BigInteger a = 65536;
cout << (a * a * a * a * a * a * a * a);
return 0;
}
</code></pre>
<p>then I get those errors.</p>
<p>Derek, I thought that by including the <code>BigIntegerLibrary.hh</code> file, that the compiler would go through and compile all the necessary files that it will use.</p>
<p>How should I try and compile the program above in order to resolve the linking errors?</p>
| [
{
"answer_id": 124344,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 1,
"selected": false,
"text": "<p>A long int is typically 64 bits which would probably not be enough to handle an integer that large. You'll probably n... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am using the RSA Algorithm for encryption/decryption, and in order to decrypt the files you have to deal with some pretty big values. More specifically, things like
```
P = C^d % n
= 62^65 % 133
```
Now that is really the only calculations that ill be doing. I have tried using Matt McCutchen's BigInteger Library, but I am getting a lot of compiler errors during linking, such as:
```
encryption.o(.text+0x187):encryption.cpp: undefined reference to `BigInteger::BigInteger(int)'
encryption.o(.text+0x302):encryption.cpp: undefined reference to `operator<<(std::ostream&, BigInteger const&)'
encryption.o(.text$_ZNK10BigIntegermlERKS_[BigInteger::operator*(BigInteger const&) const]+0x63):encryption.cpp: undefined reference to `BigInteger::multiply(BigInteger const&, BigInteger const&)'
```
So I was wondering what would be the best way to go about handling the really big integers that come out of the RSA Algorithm.
I heard that a possibility would be to declare your variables as a double long, so...
```
long long decryptedCharacter;
```
but I'm not sure exactly how big of an integer that can store.
---
Well for example, I try to compile and run the following program using dev C++:
```
#include iostream
#include "bigint\BigIntegerLibrary.hh"
using namespace std;
int main()
{
BigInteger a = 65536;
cout << (a * a * a * a * a * a * a * a);
return 0;
}
```
then I get those errors.
Derek, I thought that by including the `BigIntegerLibrary.hh` file, that the compiler would go through and compile all the necessary files that it will use.
How should I try and compile the program above in order to resolve the linking errors? | I'd suggest using [gmp](http://gmplib.org/), it can handle arbitrarily long ints and has decent C++ bindings.
afaik on current hardware/sofware long longs are 64bit, so unsigned can handle numbers up to (2\*\*64)-1 == 18446744073709551615 which is quite a bit smaller than numbers you'd have to deal with with RSA. |
124,336 | <p>I'm not sure if this is a strange thing to do or not, or if it is some how code smell...but I was wondering if there was a way (some sort of oop pattern would be nice) to "cast" a base type to a form of its derived type. I know this makes little sense as the derived type will have additional functionality that the parent doesn't offer which is in its self not fundamentally sound. But is there some way to do this? Here is a code example to so I can better explain what I"m asking.</p>
<pre><code>public class SomeBaseClass {
public string GetBaseClassName {get;set;}
public bool BooleanEvaluator {get;set;}
}
public class SomeDerivedClass : SomeBaseClass {
public void Insert(SqlConnection connection) {
//...random connection stuff
cmd.Parameters["IsItTrue"].Value = this.BooleanEvalutar;
//...
}
}
public static void Main(object[] args) {
SomeBaseClass baseClass = new SomeBaseClass();
SomeDerivedClass derClass = (SomeDerivedClass)baseClass;
derClass.Insert(new sqlConnection());
}
</code></pre>
<p>I know this seems goofy but is there any way to accomplish something of this sort?</p>
| [
{
"answer_id": 124347,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 6,
"selected": true,
"text": "<p>Not soundly, in \"managed\" languages. This is <em>downcasting</em>, and there is no sane down way to handle it, for e... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13688/"
] | I'm not sure if this is a strange thing to do or not, or if it is some how code smell...but I was wondering if there was a way (some sort of oop pattern would be nice) to "cast" a base type to a form of its derived type. I know this makes little sense as the derived type will have additional functionality that the parent doesn't offer which is in its self not fundamentally sound. But is there some way to do this? Here is a code example to so I can better explain what I"m asking.
```
public class SomeBaseClass {
public string GetBaseClassName {get;set;}
public bool BooleanEvaluator {get;set;}
}
public class SomeDerivedClass : SomeBaseClass {
public void Insert(SqlConnection connection) {
//...random connection stuff
cmd.Parameters["IsItTrue"].Value = this.BooleanEvalutar;
//...
}
}
public static void Main(object[] args) {
SomeBaseClass baseClass = new SomeBaseClass();
SomeDerivedClass derClass = (SomeDerivedClass)baseClass;
derClass.Insert(new sqlConnection());
}
```
I know this seems goofy but is there any way to accomplish something of this sort? | Not soundly, in "managed" languages. This is *downcasting*, and there is no sane down way to handle it, for exactly the reason you described (subclasses provide more than base classes - where does this "more" come from?). If you really want a similar behaviour for a particular hierarchy, you could use constructors for derived types that will take the base type as a prototype.
One could build something with reflection that handled the simple cases (more specific types that have no addition state). In general, just redesign to avoid the problem.
Edit: Woops, can't write conversion operators between base/derived types. An oddity of Microsoft trying to "protect you" against yourself. Ah well, at least they're no where near as bad as Sun. |
124,358 | <p>Although my question might seem abstract I hope it's not. Suppose I develop an application, an ASP.NET MVC site and later I am tasked to build an Winforms client for this application how much and how can I reuse from the existing application?</p>
<p>I defined the models, I defined controllers and views. They all work well.</p>
<p>Now the boss comes asking for a Winforms client and I am hoping I can reuse the models and the controllers (provided I put them in different assemblies) and not reuse just the views (ASPX views).</p>
<p>Can this be done? How?</p>
| [
{
"answer_id": 124452,
"author": "zadam",
"author_id": 410357,
"author_profile": "https://Stackoverflow.com/users/410357",
"pm_score": 4,
"selected": true,
"text": "<p>I have done this previously, not with asp.net MVC but with pure asp.net web forms. I used a home-grown MVP (Model-View-... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1796/"
] | Although my question might seem abstract I hope it's not. Suppose I develop an application, an ASP.NET MVC site and later I am tasked to build an Winforms client for this application how much and how can I reuse from the existing application?
I defined the models, I defined controllers and views. They all work well.
Now the boss comes asking for a Winforms client and I am hoping I can reuse the models and the controllers (provided I put them in different assemblies) and not reuse just the views (ASPX views).
Can this be done? How? | I have done this previously, not with asp.net MVC but with pure asp.net web forms. I used a home-grown MVP (Model-View-Presenter) pattern, and the absolute most important thing to allow the Presenter (== Controller in your case) to be used in a WinForms app was to not reference *anything* to do with system.web
So the first thing you need to do is introduce interface(s) to wrap any request, response, web etc stuff, and have every Presenter accept these interfaces via Dependency Injection (or make them available to the Presenters by some other technique), then if the Presenter uses those rather than the actual system.web stuff.
Example:
Imagine you want to transfer control from Page A to Page B (which in your winforms app you might want to close form A then open form B).
Interface:
```
public interface IRuntimeContext
{
void TransferTo(string destination);
}
```
web implementation:
```
public class AspNetRuntimeContext
{
public void TransferTo(string destination)
{
Response.Redirect(destination);
}
}
```
winforms implementation:
```
public class WinformsRuntimeContext
{
public void TransferTo(string destination)
{
var r = GetFormByName(destination);
r.Show();
}
}
```
Now the Presenter (Controller in your case):
```
public class SomePresenter
{
private readonly runtimeContext;
public SomePresenter(IRuntimeContext runtimeContext)
{
this.runtimeContext = runtimeContext;
}
public void SomeAction()
{
// do some work
// then transfer control to another page/form
runtimeContext.TransferTo("somewhereElse");
}
}
```
I haven't looked at the asp.net MVC implementation in detail but I hope this gives you some indication that it will probably be a lot of work to enable the scenario you are after.
You may instead want to consider accepting that you will have to re-code the View and Controller for the different platforms, and instead concentrate on keeping your controllers extremely thin and putting the bulk of your code in a service layer that can be shared.
Good Luck! |
124,374 | <p>I need to recursively search directories and replace a string (say <a href="http://development:port/URI" rel="nofollow noreferrer">http://development:port/URI</a>) with another (say <a href="http://production:port/URI" rel="nofollow noreferrer">http://production:port/URI</a>) in all the files where ever it's found. Can anyone help?</p>
<p>It would be much better if that script can print out the files that it modified and takes the search/replace patterns as input parameters.</p>
<p>Regards.</p>
| [
{
"answer_id": 124400,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like you would benefit from a layer of indirection. (But then, who wouldn't?) </p>\n\n<p>I'm thinking that... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1408/"
] | I need to recursively search directories and replace a string (say <http://development:port/URI>) with another (say <http://production:port/URI>) in all the files where ever it's found. Can anyone help?
It would be much better if that script can print out the files that it modified and takes the search/replace patterns as input parameters.
Regards. | Try this:
```
find . -type f | xargs grep -l development | xargs perl -i.bak -p -e 's(http://development)(http://production)g'
```
Another approach with slightly more feedback:
```
find . -type f | while read file
do
grep development $file && echo "modifying $file" && perl -i.bak -p -e 's(http://development)(http://prodution)g' $file
done
```
Hope this helps. |
124,378 | <p>I'm running my workstation on Server 2008 and a few servers in Hyper-V VM's on that server. I connect to my corporate LAN using VPN from the main OS (the host) but my VM's aren't seeing the servers in the corporate LAN. Internet and local access to my home network work fine. Each of the VMs has one virtual network adapter. </p>
<p>What should I try to make it work?</p>
<p>Maybe I need to provide more details, please ask if needed.</p>
<p><strong>More details:</strong></p>
<ul>
<li>cannot start multiple VPN connections </li>
<li>not using NAT through the host</li>
<li>VM gets IP address from the home network router (DHCP)</li>
</ul>
| [
{
"answer_id": 124495,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 0,
"selected": false,
"text": "<p>Setup some routes in your routing tablke. It really depends on how its setup but if you can access your corp network f... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21420/"
] | I'm running my workstation on Server 2008 and a few servers in Hyper-V VM's on that server. I connect to my corporate LAN using VPN from the main OS (the host) but my VM's aren't seeing the servers in the corporate LAN. Internet and local access to my home network work fine. Each of the VMs has one virtual network adapter.
What should I try to make it work?
Maybe I need to provide more details, please ask if needed.
**More details:**
* cannot start multiple VPN connections
* not using NAT through the host
* VM gets IP address from the home network router (DHCP) | Like I said you need to setup some routes. Add a route to your Corp LAN via your Host as the gateway. Just the fact alone you telling me that it gets it from home DHCPP tells me that is the issue. Your VM's only see 1 default gateway, and that is to the internet. The VM's have no idea whatsoever that the Host has a VPN on it. Adding that route (on VM machines) causes any requests that your VM's make to the subnet of your corp network to route through your host rather than the home router.
Adding something like this:
```
route ADD 10.0.0.0 MASK 255.0.0.0 192.168.1.30
```
on your VM'S would do this: Any requests made to the 10.*.*.\* network would route through the computer with the IP address of 192.168.1.30. So replace the 10.0.0.0 and subnet with your corp lan, and the 192 ip with your hosts IP. That should take care of the issue. |
124,411 | <p>But here's an example:</p>
<pre><code>Dim desiredType as Type
if IsNumeric(desiredType) then ...
</code></pre>
<p><strong>EDIT:</strong> I only know the Type, not the Value as a string.</p>
<p>Ok, so unfortunately I have to cycle through the TypeCode.</p>
<p>But this is a nice way to do it:</p>
<pre><code> if ((desiredType.IsArray))
return 0;
switch (Type.GetTypeCode(desiredType))
{
case 3:
case 6:
case 7:
case 9:
case 11:
case 13:
case 14:
case 15:
return 1;
}
;return 0;
</code></pre>
| [
{
"answer_id": 124443,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 5,
"selected": false,
"text": "<p>You can find out if a variable is numeric using the <code>Type.GetTypeCode()</code> method:</p>\n\n<pre><code>TypeCode t... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14484/"
] | But here's an example:
```
Dim desiredType as Type
if IsNumeric(desiredType) then ...
```
**EDIT:** I only know the Type, not the Value as a string.
Ok, so unfortunately I have to cycle through the TypeCode.
But this is a nice way to do it:
```
if ((desiredType.IsArray))
return 0;
switch (Type.GetTypeCode(desiredType))
{
case 3:
case 6:
case 7:
case 9:
case 11:
case 13:
case 14:
case 15:
return 1;
}
;return 0;
``` | A few years late here, but here's my solution (you can choose whether to include boolean). Solves for the Nullable case. XUnit test included
```
/// <summary>
/// Determines if a type is numeric. Nullable numeric types are considered numeric.
/// </summary>
/// <remarks>
/// Boolean is not considered numeric.
/// </remarks>
public static bool IsNumericType( Type type )
{
if (type == null)
{
return false;
}
switch (Type.GetTypeCode(type))
{
case TypeCode.Byte:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.SByte:
case TypeCode.Single:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
case TypeCode.Object:
if ( type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return IsNumericType(Nullable.GetUnderlyingType(type));
}
return false;
}
return false;
}
/// <summary>
/// Tests the IsNumericType method.
/// </summary>
[Fact]
public void IsNumericTypeTest()
{
// Non-numeric types
Assert.False(TypeHelper.IsNumericType(null));
Assert.False(TypeHelper.IsNumericType(typeof(object)));
Assert.False(TypeHelper.IsNumericType(typeof(DBNull)));
Assert.False(TypeHelper.IsNumericType(typeof(bool)));
Assert.False(TypeHelper.IsNumericType(typeof(char)));
Assert.False(TypeHelper.IsNumericType(typeof(DateTime)));
Assert.False(TypeHelper.IsNumericType(typeof(string)));
// Arrays of numeric and non-numeric types
Assert.False(TypeHelper.IsNumericType(typeof(object[])));
Assert.False(TypeHelper.IsNumericType(typeof(DBNull[])));
Assert.False(TypeHelper.IsNumericType(typeof(bool[])));
Assert.False(TypeHelper.IsNumericType(typeof(char[])));
Assert.False(TypeHelper.IsNumericType(typeof(DateTime[])));
Assert.False(TypeHelper.IsNumericType(typeof(string[])));
Assert.False(TypeHelper.IsNumericType(typeof(byte[])));
Assert.False(TypeHelper.IsNumericType(typeof(decimal[])));
Assert.False(TypeHelper.IsNumericType(typeof(double[])));
Assert.False(TypeHelper.IsNumericType(typeof(short[])));
Assert.False(TypeHelper.IsNumericType(typeof(int[])));
Assert.False(TypeHelper.IsNumericType(typeof(long[])));
Assert.False(TypeHelper.IsNumericType(typeof(sbyte[])));
Assert.False(TypeHelper.IsNumericType(typeof(float[])));
Assert.False(TypeHelper.IsNumericType(typeof(ushort[])));
Assert.False(TypeHelper.IsNumericType(typeof(uint[])));
Assert.False(TypeHelper.IsNumericType(typeof(ulong[])));
// numeric types
Assert.True(TypeHelper.IsNumericType(typeof(byte)));
Assert.True(TypeHelper.IsNumericType(typeof(decimal)));
Assert.True(TypeHelper.IsNumericType(typeof(double)));
Assert.True(TypeHelper.IsNumericType(typeof(short)));
Assert.True(TypeHelper.IsNumericType(typeof(int)));
Assert.True(TypeHelper.IsNumericType(typeof(long)));
Assert.True(TypeHelper.IsNumericType(typeof(sbyte)));
Assert.True(TypeHelper.IsNumericType(typeof(float)));
Assert.True(TypeHelper.IsNumericType(typeof(ushort)));
Assert.True(TypeHelper.IsNumericType(typeof(uint)));
Assert.True(TypeHelper.IsNumericType(typeof(ulong)));
// Nullable non-numeric types
Assert.False(TypeHelper.IsNumericType(typeof(bool?)));
Assert.False(TypeHelper.IsNumericType(typeof(char?)));
Assert.False(TypeHelper.IsNumericType(typeof(DateTime?)));
// Nullable numeric types
Assert.True(TypeHelper.IsNumericType(typeof(byte?)));
Assert.True(TypeHelper.IsNumericType(typeof(decimal?)));
Assert.True(TypeHelper.IsNumericType(typeof(double?)));
Assert.True(TypeHelper.IsNumericType(typeof(short?)));
Assert.True(TypeHelper.IsNumericType(typeof(int?)));
Assert.True(TypeHelper.IsNumericType(typeof(long?)));
Assert.True(TypeHelper.IsNumericType(typeof(sbyte?)));
Assert.True(TypeHelper.IsNumericType(typeof(float?)));
Assert.True(TypeHelper.IsNumericType(typeof(ushort?)));
Assert.True(TypeHelper.IsNumericType(typeof(uint?)));
Assert.True(TypeHelper.IsNumericType(typeof(ulong?)));
// Testing with GetType because of handling with non-numerics. See:
// http://msdn.microsoft.com/en-us/library/ms366789.aspx
// Using GetType - non-numeric
Assert.False(TypeHelper.IsNumericType((new object()).GetType()));
Assert.False(TypeHelper.IsNumericType(DBNull.Value.GetType()));
Assert.False(TypeHelper.IsNumericType(true.GetType()));
Assert.False(TypeHelper.IsNumericType('a'.GetType()));
Assert.False(TypeHelper.IsNumericType((new DateTime(2009, 1, 1)).GetType()));
Assert.False(TypeHelper.IsNumericType(string.Empty.GetType()));
// Using GetType - numeric types
// ReSharper disable RedundantCast
Assert.True(TypeHelper.IsNumericType((new byte()).GetType()));
Assert.True(TypeHelper.IsNumericType(43.2m.GetType()));
Assert.True(TypeHelper.IsNumericType(43.2d.GetType()));
Assert.True(TypeHelper.IsNumericType(((short)2).GetType()));
Assert.True(TypeHelper.IsNumericType(((int)2).GetType()));
Assert.True(TypeHelper.IsNumericType(((long)2).GetType()));
Assert.True(TypeHelper.IsNumericType(((sbyte)2).GetType()));
Assert.True(TypeHelper.IsNumericType(2f.GetType()));
Assert.True(TypeHelper.IsNumericType(((ushort)2).GetType()));
Assert.True(TypeHelper.IsNumericType(((uint)2).GetType()));
Assert.True(TypeHelper.IsNumericType(((ulong)2).GetType()));
// ReSharper restore RedundantCast
// Using GetType - nullable non-numeric types
bool? nullableBool = true;
Assert.False(TypeHelper.IsNumericType(nullableBool.GetType()));
char? nullableChar = ' ';
Assert.False(TypeHelper.IsNumericType(nullableChar.GetType()));
DateTime? nullableDateTime = new DateTime(2009, 1, 1);
Assert.False(TypeHelper.IsNumericType(nullableDateTime.GetType()));
// Using GetType - nullable numeric types
byte? nullableByte = 12;
Assert.True(TypeHelper.IsNumericType(nullableByte.GetType()));
decimal? nullableDecimal = 12.2m;
Assert.True(TypeHelper.IsNumericType(nullableDecimal.GetType()));
double? nullableDouble = 12.32;
Assert.True(TypeHelper.IsNumericType(nullableDouble.GetType()));
short? nullableInt16 = 12;
Assert.True(TypeHelper.IsNumericType(nullableInt16.GetType()));
short? nullableInt32 = 12;
Assert.True(TypeHelper.IsNumericType(nullableInt32.GetType()));
short? nullableInt64 = 12;
Assert.True(TypeHelper.IsNumericType(nullableInt64.GetType()));
sbyte? nullableSByte = 12;
Assert.True(TypeHelper.IsNumericType(nullableSByte.GetType()));
float? nullableSingle = 3.2f;
Assert.True(TypeHelper.IsNumericType(nullableSingle.GetType()));
ushort? nullableUInt16 = 12;
Assert.True(TypeHelper.IsNumericType(nullableUInt16.GetType()));
ushort? nullableUInt32 = 12;
Assert.True(TypeHelper.IsNumericType(nullableUInt32.GetType()));
ushort? nullableUInt64 = 12;
Assert.True(TypeHelper.IsNumericType(nullableUInt64.GetType()));
}
``` |
124,417 | <p>I want to write a query like this:</p>
<pre><code>SELECT o.OrderId, MAX(o.NegotiatedPrice, o.SuggestedPrice)
FROM Order o
</code></pre>
<p>But this isn't how the <code>MAX</code> function works, right? It is an aggregate function so it expects a single parameter and then returns the MAX of all rows. </p>
<p>Does anyone know how to do it my way?</p>
| [
{
"answer_id": 124441,
"author": "Scott Langham",
"author_id": 11898,
"author_profile": "https://Stackoverflow.com/users/11898",
"pm_score": 7,
"selected": false,
"text": "<p>I don't think so. I wanted this the other day. The closest I got was:</p>\n\n<pre><code>SELECT\n o.OrderId,\n C... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14101/"
] | I want to write a query like this:
```
SELECT o.OrderId, MAX(o.NegotiatedPrice, o.SuggestedPrice)
FROM Order o
```
But this isn't how the `MAX` function works, right? It is an aggregate function so it expects a single parameter and then returns the MAX of all rows.
Does anyone know how to do it my way? | You'd need to make a `User-Defined Function` if you wanted to have syntax similar to your example, but could you do what you want to do, inline, fairly easily with a `CASE` statement, as the others have said.
The `UDF` could be something like this:
```
create function dbo.InlineMax(@val1 int, @val2 int)
returns int
as
begin
if @val1 > @val2
return @val1
return isnull(@val2,@val1)
end
```
... and you would call it like so ...
```
SELECT o.OrderId, dbo.InlineMax(o.NegotiatedPrice, o.SuggestedPrice)
FROM Order o
``` |
124,455 | <p>I've got a Lua program that seems to be slower than it ought to be. I suspect the issue is that I'm adding values to an associative array one at a time and the table has to allocate new memory each time. </p>
<p>There did seem to be a table.setn function, but it fails under Lua 5.1.3:</p>
<pre><code>stdin:1: 'setn' is obsolete
stack traceback:
[C]: in function 'setn'
stdin:1: in main chunk
[C]: ?
</code></pre>
<p>I gather from the Google searching I've done that this function was depreciated in Lua 5.1, but I can't find what (if anything) replaced the functionality.</p>
<p>Do you know how to pre-size a table in Lua?</p>
<p>Alternatively, is there some other way to avoid memory allocation when you add an object to a table?</p>
| [
{
"answer_id": 124536,
"author": "Mike G.",
"author_id": 18901,
"author_profile": "https://Stackoverflow.com/users/18901",
"pm_score": 3,
"selected": false,
"text": "<p>I don't think you can - it's not an array, it's an associative array, like a perl hash or an awk array.</p>\n\n<p><a hr... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1438/"
] | I've got a Lua program that seems to be slower than it ought to be. I suspect the issue is that I'm adding values to an associative array one at a time and the table has to allocate new memory each time.
There did seem to be a table.setn function, but it fails under Lua 5.1.3:
```
stdin:1: 'setn' is obsolete
stack traceback:
[C]: in function 'setn'
stdin:1: in main chunk
[C]: ?
```
I gather from the Google searching I've done that this function was depreciated in Lua 5.1, but I can't find what (if anything) replaced the functionality.
Do you know how to pre-size a table in Lua?
Alternatively, is there some other way to avoid memory allocation when you add an object to a table? | Let me focus more on your question:
>
> adding values to an associative array
> one at a time
>
>
>
Tables in Lua are associative, but using them in an array form (1..N) is optimized. They have double faces, internally.
So.. If you indeed are adding values associatively, follow the rules above.
If you are using indices 1..N, you can force a one-time size readjust by setting t[100000]= something. This should work until the limit of optimized array size, specified within Lua sources (2^26 = 67108864). After that, everything is associative.
p.s. The old 'setn' method handled the array part only, so it's no use for associative usage (ignore those answers).
p.p.s. Have you studied general tips for keeping Lua performance high? i.e. know table creation and rather reuse a table than create a new one, use of 'local print=print' and such to avoid global accesses. |
124,457 | <p>I have limited experience with .net. My app throws an error this.dateTimeFormat is undefined which I tracked down to a known ajax bug. The workaround posted said to:</p>
<p>"Register the following as a startup script:"</p>
<pre><code>Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value)
{
if (!this._upperAbbrMonths) {
this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames);
}
return Array.indexOf(this._upperAbbrMonths, this._toUpper(value));
};
</code></pre>
<p>So how do I do this? Do I add the script to the bottom of my aspx file?</p>
| [
{
"answer_id": 124466,
"author": "Chris Ballance",
"author_id": 1551,
"author_profile": "https://Stackoverflow.com/users/1551",
"pm_score": 0,
"selected": false,
"text": "<p>Put it in the header portion of the page</p>\n"
},
{
"answer_id": 124470,
"author": "Wayne",
"auth... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5234/"
] | I have limited experience with .net. My app throws an error this.dateTimeFormat is undefined which I tracked down to a known ajax bug. The workaround posted said to:
"Register the following as a startup script:"
```
Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value)
{
if (!this._upperAbbrMonths) {
this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames);
}
return Array.indexOf(this._upperAbbrMonths, this._toUpper(value));
};
```
So how do I do this? Do I add the script to the bottom of my aspx file? | You would use [ClientScriptManager.RegisterStartupScript()](http://msdn.microsoft.com/en-us/library/z9h4dk8y.aspx)
```
string str = @"Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value) {
if (!this._upperAbbrMonths) {
this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames);
}
return Array.indexOf(this._upperAbbrMonths, this._toUpper(value));
};";
if(!ClientScriptManager.IsStartupScriptRegistered("MyScript"){
ClientScriptManager.RegisterStartupScript(this.GetType(), "MyScript", str, true)
}
``` |
124,462 | <p>Is there a way in PHP to make asynchronous HTTP calls? I don't care about the response, I just want to do something like <code>file_get_contents()</code>, but not wait for the request to finish before executing the rest of my code. This would be super useful for setting off "events" of a sort in my application, or triggering long processes.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 124557,
"author": "Internet Friend",
"author_id": 18037,
"author_profile": "https://Stackoverflow.com/users/18037",
"pm_score": 5,
"selected": false,
"text": "<p>You can do trickery by using exec() to invoke something that can do HTTP requests, like <code>wget</code>, but ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10680/"
] | Is there a way in PHP to make asynchronous HTTP calls? I don't care about the response, I just want to do something like `file_get_contents()`, but not wait for the request to finish before executing the rest of my code. This would be super useful for setting off "events" of a sort in my application, or triggering long processes.
Any ideas? | The answer I'd previously accepted didn't work. It still waited for responses. This does work though, taken from [How do I make an asynchronous GET request in PHP?](https://stackoverflow.com/questions/962915/how-do-i-make-an-asynchronous-get-request-in-php)
```
function post_without_wait($url, $params)
{
foreach ($params as $key => &$val) {
if (is_array($val)) $val = implode(',', $val);
$post_params[] = $key.'='.urlencode($val);
}
$post_string = implode('&', $post_params);
$parts=parse_url($url);
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($post_string)."\r\n";
$out.= "Connection: Close\r\n\r\n";
if (isset($post_string)) $out.= $post_string;
fwrite($fp, $out);
fclose($fp);
}
``` |
124,492 | <p>I need a short code snippet to get a directory listing from an HTTP server.</p>
<p>Thanks</p>
| [
{
"answer_id": 124498,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Basic understanding:</strong></p>\n\n<p>Directory listings are just HTML pages generated by a web server.\... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I need a short code snippet to get a directory listing from an HTTP server.
Thanks | A few important considerations before the code:
1. The HTTP Server has to be configured to allow directories listing for the directories you want;
2. Because directory listings are normal HTML pages there is no standard that defines the format of a directory listing;
3. Due to consideration **2** you are in the land where you have to put specific code for each server.
My choice is to use regular expressions. This allows for rapid parsing and customization. You can get specific regular expressions pattern per site and that way you have a very modular approach. Use an external source for mapping URL to regular expression patterns if you plan to enhance the parsing module with new sites support without changing the source code.
Example to print directory listing from <http://www.ibiblio.org/pub/>
```
namespace Example
{
using System;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
public class MyExample
{
public static string GetDirectoryListingRegexForUrl(string url)
{
if (url.Equals("http://www.ibiblio.org/pub/"))
{
return "<a href=\".*\">(?<name>.*)</a>";
}
throw new NotSupportedException();
}
public static void Main(String[] args)
{
string url = "http://www.ibiblio.org/pub/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string html = reader.ReadToEnd();
Regex regex = new Regex(GetDirectoryListingRegexForUrl(url));
MatchCollection matches = regex.Matches(html);
if (matches.Count > 0)
{
foreach (Match match in matches)
{
if (match.Success)
{
Console.WriteLine(match.Groups["name"]);
}
}
}
}
}
Console.ReadLine();
}
}
}
``` |
124,585 | <p>This question is specifically related to overriding the equals() method for objects with a large number of fields. First off, let me say that this large object cannot be broken down into multiple components without violating OO principles, so telling me "no class should have more than x fields" won't help. </p>
<p>Moving on, the problem came to fruition when I forgot to check one of the fields for equality. Therefore, my equals method was incorrect. Then I thought to use reflection:</p>
<pre><code>--code removed because it was too distracting--
</code></pre>
<p>The purpose of this post isn't necessarily to refactor the code (this isn't even the code I am using), but instead to get input on whether or not this is a good idea. </p>
<p><strong>Pros:</strong></p>
<ul>
<li>If a new field is added, it is automatically included<br> </li>
<li>The method is much more terse than 30 if statements</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li>If a new field is added, it is automatically included, sometimes this is undesirable</li>
<li>Performance: This has to be slower, I don't feel the need to break out a profiler</li>
<li>Whitelisting certain fields to ignore in the comparison is a little ugly<br></li>
</ul>
<p>Any thoughts?</p>
| [
{
"answer_id": 124598,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 5,
"selected": true,
"text": "<p>If you did want to whitelist for performance reasons, consider using an annotation to indicate which fields to compare. A... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402777/"
] | This question is specifically related to overriding the equals() method for objects with a large number of fields. First off, let me say that this large object cannot be broken down into multiple components without violating OO principles, so telling me "no class should have more than x fields" won't help.
Moving on, the problem came to fruition when I forgot to check one of the fields for equality. Therefore, my equals method was incorrect. Then I thought to use reflection:
```
--code removed because it was too distracting--
```
The purpose of this post isn't necessarily to refactor the code (this isn't even the code I am using), but instead to get input on whether or not this is a good idea.
**Pros:**
* If a new field is added, it is automatically included
* The method is much more terse than 30 if statements
**Cons:**
* If a new field is added, it is automatically included, sometimes this is undesirable
* Performance: This has to be slower, I don't feel the need to break out a profiler
* Whitelisting certain fields to ignore in the comparison is a little ugly
Any thoughts? | If you did want to whitelist for performance reasons, consider using an annotation to indicate which fields to compare. Also, this implementation won't work if your fields don't have good implementations for `equals()`.
P.S. If you go this route for `equals()`, don't forget to do something similar for `hashCode()`.
P.P.S. I trust you already considered [HashCodeBuilder](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html) and [EqualsBuilder](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/EqualsBuilder.html). |
124,606 | <p>I have a function that I use called sqlf(), it emulates prepared statements. For instance I can do things like:</p>
<pre>
$sql = sqlf("SELECT * FROM Users WHERE name= :1 AND email= :2",'Big "John"','bj@example.com') ;
</pre>
<p>For various reasons, I cannot use prepared statements, but I would like to emulate them. The problem that I run into is with queries like</p>
<pre>
$sql = sqlf("SELECT * FROM Users WHERE id IN (:1)",array(1,2,3) );
</pre>
<p>My code works, but it fails with empty arrays, e.g. the following throws a mysql error:</p>
<pre>
SELECT * FROM Users WHERE id IN ();
</pre>
<p>Does anyone have any suggestions? How should I translate and empty array into sql that can be injected into an IN clause? Substituting NULL will not work. </p>
| [
{
"answer_id": 124611,
"author": "neouser99",
"author_id": 10669,
"author_profile": "https://Stackoverflow.com/users/10669",
"pm_score": 4,
"selected": true,
"text": "<p>Null is the only value that you can guarantee is not in the set. How come it is not an option? Anything else can be se... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20512/"
] | I have a function that I use called sqlf(), it emulates prepared statements. For instance I can do things like:
```
$sql = sqlf("SELECT * FROM Users WHERE name= :1 AND email= :2",'Big "John"','bj@example.com') ;
```
For various reasons, I cannot use prepared statements, but I would like to emulate them. The problem that I run into is with queries like
```
$sql = sqlf("SELECT * FROM Users WHERE id IN (:1)",array(1,2,3) );
```
My code works, but it fails with empty arrays, e.g. the following throws a mysql error:
```
SELECT * FROM Users WHERE id IN ();
```
Does anyone have any suggestions? How should I translate and empty array into sql that can be injected into an IN clause? Substituting NULL will not work. | Null is the only value that you can guarantee is not in the set. How come it is not an option? Anything else can be seen as part of the potential set, they are all values. |
124,615 | <p>Lets say I have a class that stores user information complete with getters and setters, and it is populated with data from an XML file. How would I iterate over all of the instances of that class like you would do with java beans and tag libraries?</p>
| [
{
"answer_id": 124783,
"author": "Ta01",
"author_id": 7280,
"author_profile": "https://Stackoverflow.com/users/7280",
"pm_score": 0,
"selected": false,
"text": "<p>This assumes you can acquire all instances of your class and add them to a Generic List.</p>\n\n<pre><code>List<YourClass... | 2008/09/23 | [
"https://Stackoverflow.com/questions/124615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2066/"
] | Lets say I have a class that stores user information complete with getters and setters, and it is populated with data from an XML file. How would I iterate over all of the instances of that class like you would do with java beans and tag libraries? | For outputting formatted HTML, you have a few choices. What I would probably do is make a property on the code-behind that accesses the collection of objects you want to iterate over. Then, I'd write the logic for iterating and formatting them on the .aspx page itself. For example, the .aspx page:
```
[snip]
<body>
<form id="form1" runat="server">
<% Somethings.ForEach(s => { %>
<h1><%=s.Name %></h1>
<h2><%=s.Id %></h2>
<% }); %>
</form>
</body>
</html>
```
And then the code-behind:
```
[snip]
public partial class _Default : System.Web.UI.Page
{
protected List<Something> Somethings { get; private set; }
protected void Page_Load(object sender, EventArgs e)
{
Somethings = GetSomethings(); // Or whatever populates the collection
}
[snip]
```
You could also look at using a repeater control and set the DataSource to your collection. It's pretty much the same idea as the code above, but I think this way is clearer (in my opinion). |
124,630 | <p>I'm currently turning an array of pixel values (originally created with a java.awt.image.PixelGrabber object) into an Image object using the following code:</p>
<pre><code>public Image getImageFromArray(int[] pixels, int width, int height) {
MemoryImageSource mis = new MemoryImageSource(width, height, pixels, 0, width);
Toolkit tk = Toolkit.getDefaultToolkit();
return tk.createImage(mis);
}
</code></pre>
<p><em>Is it possible to achieve the same result using classes from the ImageIO package(s) so I don't have to use the AWT Toolkit?</em></p>
<p>Toolkit.getDefaultToolkit() does not seem to be 100% reliable and will sometimes throw an AWTError, whereas the ImageIO classes should always be available, which is why I'm interested in changing my method.</p>
| [
{
"answer_id": 124957,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": 2,
"selected": false,
"text": "<p>I've had good success using java.awt.Robot to grab a screen shot (or a segment of the screen), but to work with Ima... | 2008/09/24 | [
"https://Stackoverflow.com/questions/124630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1119/"
] | I'm currently turning an array of pixel values (originally created with a java.awt.image.PixelGrabber object) into an Image object using the following code:
```
public Image getImageFromArray(int[] pixels, int width, int height) {
MemoryImageSource mis = new MemoryImageSource(width, height, pixels, 0, width);
Toolkit tk = Toolkit.getDefaultToolkit();
return tk.createImage(mis);
}
```
*Is it possible to achieve the same result using classes from the ImageIO package(s) so I don't have to use the AWT Toolkit?*
Toolkit.getDefaultToolkit() does not seem to be 100% reliable and will sometimes throw an AWTError, whereas the ImageIO classes should always be available, which is why I'm interested in changing my method. | You can create the image without using ImageIO. Just create a BufferedImage using an image type matching the contents of the pixel array.
```
public static Image getImageFromArray(int[] pixels, int width, int height) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
WritableRaster raster = (WritableRaster) image.getData();
raster.setPixels(0,0,width,height,pixels);
return image;
}
```
When working with the PixelGrabber, don't forget to extract the RGBA info from the pixel array before calling `getImageFromArray`. There's an example of this in the [handlepixelmethod](http://java.sun.com/javase/6/docs/api/java/awt/image/PixelGrabber.html) in the PixelGrabber javadoc. Once you do that, make sure the image type in the BufferedImage constructor to `BufferedImage.TYPE_INT_ARGB`. |
124,638 | <p>I found an article on getting active tcp/udp connections on a machine.</p>
<p><a href="http://www.codeproject.com/KB/IP/iphlpapi.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/IP/iphlpapi.aspx</a></p>
<p>My issue however is I need to be able to determine active connections remotely - to see if a particular port is running or listening without tampering with the machine.</p>
<p>Is this possible?</p>
<p>Doesn't seem like it natively, otherwise it could pose a security issue. The alternative would be to query a remoting service which could then make the necessary calls on the local machine.</p>
<p>Any thoughts?</p>
| [
{
"answer_id": 124641,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 2,
"selected": false,
"text": "<p>There is no way to know which ports are open without the remote computer knowing it. But you can determine the in... | 2008/09/24 | [
"https://Stackoverflow.com/questions/124638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I found an article on getting active tcp/udp connections on a machine.
<http://www.codeproject.com/KB/IP/iphlpapi.aspx>
My issue however is I need to be able to determine active connections remotely - to see if a particular port is running or listening without tampering with the machine.
Is this possible?
Doesn't seem like it natively, otherwise it could pose a security issue. The alternative would be to query a remoting service which could then make the necessary calls on the local machine.
Any thoughts? | There is no way to know which ports are open without the remote computer knowing it. But you can determine the information without the program running on the port knowing it (i.e. without interfering with the program).
**Use SYN scanning:**
To establish a connection, TCP uses a three-way handshake. This can be exploited to find out if a port is open or not without the program knowing.
The handshake works as follows:
1. The client performs an active open by sending a SYN to the server.
2. The server replies with a SYN-ACK.
3. Normally, the client sends an ACK back to the server. But this step is skipped.
>
> SYN scan is the most popular form of
> TCP scanning. Rather than use the
> operating system's network functions,
> the port scanner generates raw IP
> packets itself, and monitors for
> responses. This scan type is also
> known as "half-open scanning", because
> it never actually opens a full TCP
> connection. The port scanner generates
> a SYN packet. If the target port is
> open, it will respond with a SYN-ACK
> packet. The scanner host responds with
> a RST packet, closing the connection
> before the handshake is completed.
>
>
> The use of raw networking has several
> advantages, giving the scanner full
> control of the packets sent and the
> timeout for responses, and allowing
> detailed reporting of the responses.
> There is debate over which scan is
> less intrusive on the target host. SYN
> scan has the advantage that the
> individual services never actually
> receive a connection while some
> services can be crashed with a connect
> scan. However, the RST during the
> handshake can cause problems for some
> network stacks, particularly simple
> devices like printers. There are no
> conclusive arguments either way.
>
>
>
[Source Wikipedia](http://en.wikipedia.org/wiki/Port_scanner)
As is mentioned below, I think [nmap](http://nmap.org/) can do SYN scanning.
**Using sockets for TCP port scanning:**
One way to determine which ports are open is to open a socket to that port. Or to a different port which finds out the information for you like you mentioned.
For example from command prompt or a terminal:
```
telnet google.com 80
```
**UDP Port scanning:**
if a UDP packet is sent to a port that is not open, the system will respond with an ICMP port unreachable message. You can use this method to determine if a port is open or close. But the receiving program will know. |
124,647 | <p>Say I have an array that represents a set of points:</p>
<pre><code>x = [2, 5, 8, 33, 58]
</code></pre>
<p>How do I generate an array of all the pairwise distances? </p>
| [
{
"answer_id": 124734,
"author": "Lucas Oman",
"author_id": 6726,
"author_profile": "https://Stackoverflow.com/users/6726",
"pm_score": 4,
"selected": true,
"text": "<pre><code>x = [2, 5, 8, 33, 58]\nprint x.collect {|n| x.collect {|i| (n-i).abs}}.flatten\n</code></pre>\n\n<p>I think tha... | 2008/09/24 | [
"https://Stackoverflow.com/questions/124647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] | Say I have an array that represents a set of points:
```
x = [2, 5, 8, 33, 58]
```
How do I generate an array of all the pairwise distances? | ```
x = [2, 5, 8, 33, 58]
print x.collect {|n| x.collect {|i| (n-i).abs}}.flatten
```
I think that would do it. |
124,649 | <p>In my Silverlight application, I can't seem to bring focus to a TextBox control. On the recommendation of various posts, I've set the IsTabStop property to True and I'm using TextBox.Focus(). Though the UserControl_Loaded event is firing, the TextBox control isn't getting focus. I've included my very simple code below. What am I missing? Thanks.</p>
<p><strong><em>Page.xaml</em></strong> </p>
<pre><code><UserControl x:Class="TextboxFocusTest.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Loaded="UserControl_Loaded"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel Width="150" VerticalAlignment="Center">
<TextBox x:Name="RegularTextBox" IsTabStop="True" />
</StackPanel>
</Grid>
</UserControl>
</code></pre>
<p><strong><em>Page.xaml.cs</em></strong></p>
<pre><code>using System.Windows;
using System.Windows.Controls;
namespace PasswordTextboxTest
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
RegularTextBox.Focus();
}
}
}
</code></pre>
| [
{
"answer_id": 124778,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 1,
"selected": false,
"text": "<p>You code to set the focus is correct since if you add a button that calls the same code it works perfectly:</p>\n\n<pre>... | 2008/09/24 | [
"https://Stackoverflow.com/questions/124649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4115/"
] | In my Silverlight application, I can't seem to bring focus to a TextBox control. On the recommendation of various posts, I've set the IsTabStop property to True and I'm using TextBox.Focus(). Though the UserControl\_Loaded event is firing, the TextBox control isn't getting focus. I've included my very simple code below. What am I missing? Thanks.
***Page.xaml***
```
<UserControl x:Class="TextboxFocusTest.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Loaded="UserControl_Loaded"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel Width="150" VerticalAlignment="Center">
<TextBox x:Name="RegularTextBox" IsTabStop="True" />
</StackPanel>
</Grid>
</UserControl>
```
***Page.xaml.cs***
```
using System.Windows;
using System.Windows.Controls;
namespace PasswordTextboxTest
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
RegularTextBox.Focus();
}
}
}
``` | I found this on silverlight.net, and was able to get it to work for me by adding a call to System.Windows.Browser.HtmlPage.Plugin.Focus() prior to calling RegularTextBox.Focus():
```
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
System.Windows.Browser.HtmlPage.Plugin.Focus();
RegularTextBox.Focus();
}
``` |
124,671 | <p>How do I pick a random element from a set?
I'm particularly interested in picking a random element from a
HashSet or a LinkedHashSet, in Java.
Solutions for other languages are also welcome. </p>
| [
{
"answer_id": 124687,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 1,
"selected": false,
"text": "<p>Since you said \"Solutions for other languages are also welcome\", here's the version for Python:</p>\n\n<pre><code>&... | 2008/09/24 | [
"https://Stackoverflow.com/questions/124671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21445/"
] | How do I pick a random element from a set?
I'm particularly interested in picking a random element from a
HashSet or a LinkedHashSet, in Java.
Solutions for other languages are also welcome. | ```
int size = myHashSet.size();
int item = new Random().nextInt(size); // In real life, the Random object should be rather more shared than this
int i = 0;
for(Object obj : myhashSet)
{
if (i == item)
return obj;
i++;
}
``` |
124,682 | <p>Can you have custom client-side javascript Validation for standard ASP.NET Web Form Validators?</p>
<p>For instance use a asp:RequiredFieldValidator leave the server side code alone but implement your own client notification using jQuery to highlight the field or background color for example.</p>
| [
{
"answer_id": 125127,
"author": "sontek",
"author_id": 17176,
"author_profile": "https://Stackoverflow.com/users/17176",
"pm_score": 1,
"selected": false,
"text": "<p>What you can do is hook into the validator and assign a new evaluate method, like this:</p>\n\n<pre><code> <script t... | 2008/09/24 | [
"https://Stackoverflow.com/questions/124682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] | Can you have custom client-side javascript Validation for standard ASP.NET Web Form Validators?
For instance use a asp:RequiredFieldValidator leave the server side code alone but implement your own client notification using jQuery to highlight the field or background color for example. | The standard **CustomValidator** has a **[ClientValidationFunction](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.clientvalidationfunction.aspx)** property for that:
```
<asp:CustomValidator ControlToValidate="Text1"
ClientValidationFunction="onValidate" />
<script type='text/javascript'>
function onValidate(validatorSpan, eventArgs)
{ eventArgs.IsValid = (eventArgs.Value.length > 0);
if (!eventArgs.IsValid) highlight(validatorSpan);
}
</script>
``` |
124,742 | <p>Is there a documented max to the length of the string data you can use in the send method of an <code>XMLHttpRequest</code> for the major browser implementations?</p>
<p>I am running into an issue with a JavaScript <code>XMLHttpRequest</code> Post failing in FireFox 3 when the data is over approx 3k. I was assuming the Post would behave the same as a conventional Form Post.</p>
<p>The W3C docs mention the data param of the send method is a DOMString but I am not sure how the major browsers implement that.</p>
<p>Here is a simplified version of my JavaScript, if bigText is over about 3k it fails, otherwise it works...</p>
<pre><code>var xhReq = createXMLHttpRequest();
function createXMLHttpRequest() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
try { return new XMLHttpRequest(); } catch(e) {}
alert("XMLHttpRequest not supported");
return null;
}
function mySubmit(id, bigText) {
var url = "SubmitPost.cfm";
var params = "id=" + id + "&bigtext=" + encodeURI(bigText);
xhReq.open("POST", url, true);
//Send the header information along with the request
xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhReq.setRequestHeader("Content-length", params.length);
xhReq.setRequestHeader("Connection", "close");
xhReq.onreadystatechange = onPostSubmit;
xhReq.send(params);
}
function onPostSubmit() {
if (xhReq.readyState==4 || xhReq.readyState=="complete")
{
if (xhReq.status != 200)
{
alert('BadStatus');
return;
}
}
}
</code></pre>
| [
{
"answer_id": 124766,
"author": "Zack The Human",
"author_id": 18265,
"author_profile": "https://Stackoverflow.com/users/18265",
"pm_score": 4,
"selected": true,
"text": "<p>I believe the maximum length depends not only on the browser, but also on the web server. For example, the Apache... | 2008/09/24 | [
"https://Stackoverflow.com/questions/124742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7121/"
] | Is there a documented max to the length of the string data you can use in the send method of an `XMLHttpRequest` for the major browser implementations?
I am running into an issue with a JavaScript `XMLHttpRequest` Post failing in FireFox 3 when the data is over approx 3k. I was assuming the Post would behave the same as a conventional Form Post.
The W3C docs mention the data param of the send method is a DOMString but I am not sure how the major browsers implement that.
Here is a simplified version of my JavaScript, if bigText is over about 3k it fails, otherwise it works...
```
var xhReq = createXMLHttpRequest();
function createXMLHttpRequest() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
try { return new XMLHttpRequest(); } catch(e) {}
alert("XMLHttpRequest not supported");
return null;
}
function mySubmit(id, bigText) {
var url = "SubmitPost.cfm";
var params = "id=" + id + "&bigtext=" + encodeURI(bigText);
xhReq.open("POST", url, true);
//Send the header information along with the request
xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhReq.setRequestHeader("Content-length", params.length);
xhReq.setRequestHeader("Connection", "close");
xhReq.onreadystatechange = onPostSubmit;
xhReq.send(params);
}
function onPostSubmit() {
if (xhReq.readyState==4 || xhReq.readyState=="complete")
{
if (xhReq.status != 200)
{
alert('BadStatus');
return;
}
}
}
``` | I believe the maximum length depends not only on the browser, but also on the web server. For example, the Apache HTTP server has a [LimitRequestBody directive](http://httpd.apache.org/docs/2.0/mod/core.html#limitrequestbody) which allows anywhere from 0 bytes to 2GB worth of data. |
124,786 | <p>I was just tinkering around with calling GetPrivateProfileString and GetPrivateProfileSection in kernel32 from .NET and came across something odd I don't understand.</p>
<p>Let's start with this encantation:</p>
<pre><code> Private Declare Unicode Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringW" ( _
ByVal lpApplicationName As String, _
ByVal lpKeyName As String, _
ByVal lpDefault As String, _
ByVal lpReturnedString() As Char, _
ByVal nSize As Int32, _
ByVal lpFileName As String) As Int32
</code></pre>
<p>If I pass an lpApplicationName (section), no lpKeyName and no lpDefault, I should get all of the keys for that section, and indeed I do: 50% of the time.</p>
<p>If the ini file has the lpApplicationName starting on the first line, the buffer returns nothing. If lpApplicationName stats on the second line in the file, it returns the expected values.</p>
<p>At first I though it was a matter of using the W version and Unicode in the Declare, but changing those seems to have no effect.</p>
<p>What am I missing?</p>
| [
{
"answer_id": 124823,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 4,
"selected": true,
"text": "<p>Check to see if the file you are opening has a <a href=\"http://en.wikipedia.org/wiki/Byte-order_mark\" rel=\"noreferre... | 2008/09/24 | [
"https://Stackoverflow.com/questions/124786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91911/"
] | I was just tinkering around with calling GetPrivateProfileString and GetPrivateProfileSection in kernel32 from .NET and came across something odd I don't understand.
Let's start with this encantation:
```
Private Declare Unicode Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringW" ( _
ByVal lpApplicationName As String, _
ByVal lpKeyName As String, _
ByVal lpDefault As String, _
ByVal lpReturnedString() As Char, _
ByVal nSize As Int32, _
ByVal lpFileName As String) As Int32
```
If I pass an lpApplicationName (section), no lpKeyName and no lpDefault, I should get all of the keys for that section, and indeed I do: 50% of the time.
If the ini file has the lpApplicationName starting on the first line, the buffer returns nothing. If lpApplicationName stats on the second line in the file, it returns the expected values.
At first I though it was a matter of using the W version and Unicode in the Declare, but changing those seems to have no effect.
What am I missing? | Check to see if the file you are opening has a [byte order mark](http://en.wikipedia.org/wiki/Byte-order_mark) (a few bytes marking the type of text encoding).
These Windows API calls don't seem to grok byte order marks and is causes them to miss the first section (hence everything works fine if there is a blank line). |
124,841 | <p>I have written the following simple test in trying to learn Castle Windsor's Fluent Interface:</p>
<pre><code>using NUnit.Framework;
using Castle.Windsor;
using System.Collections;
using Castle.MicroKernel.Registration;
namespace WindsorSample {
public class MyComponent : IMyComponent {
public MyComponent(int start_at) {
this.Value = start_at;
}
public int Value { get; private set; }
}
public interface IMyComponent {
int Value { get; }
}
[TestFixture]
public class ConcreteImplFixture {
[Test]
public void ResolvingConcreteImplShouldInitialiseValue() {
IWindsorContainer container = new WindsorContainer();
container.Register(Component.For<IMyComponent>().ImplementedBy<MyComponent>().Parameters(Parameter.ForKey("start_at").Eq("1")));
IMyComponent resolvedComp = container.Resolve<IMyComponent>();
Assert.AreEqual(resolvedComp.Value, 1);
}
}
}
</code></pre>
<p>When I execute the test through TestDriven.NET I get the following error:</p>
<pre><code>System.TypeLoadException : Could not load type 'Castle.MicroKernel.Registration.IRegistration' from assembly 'Castle.MicroKernel, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc'.
at WindsorSample.ConcreteImplFixture.ResolvingConcreteImplShouldInitialiseValue()
</code></pre>
<p>When I execute the test through the NUnit GUI I get:</p>
<pre><code>WindsorSample.ConcreteImplFixture.ResolvingConcreteImplShouldInitialiseValue:
System.IO.FileNotFoundException : Could not load file or assembly 'Castle.Windsor, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc' or one of its dependencies. The system cannot find the file specified.
</code></pre>
<p>If I open the Assembly that I am referencing in Reflector I can see its information is:</p>
<pre><code>Castle.MicroKernel, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc
</code></pre>
<p>and that it definitely contains <strong>Castle.MicroKernel.Registration.IRegistration</strong></p>
<p>What could be going on? </p>
<p>I should mention that the binaries are taken from the <a href="http://builds.castleproject.org/cruise/DownloadBuild.castle?number=956" rel="noreferrer">latest build of Castle</a> though I have never worked with nant so I didn't bother re-compiling from source and just took the files in the bin directory. I should also point out that my project compiles with no problem.</p>
| [
{
"answer_id": 124846,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 8,
"selected": true,
"text": "<p>Is the assembly in the Global Assembly Cache (GAC) or any place the might be overriding the assembly that you thin... | 2008/09/24 | [
"https://Stackoverflow.com/questions/124841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | I have written the following simple test in trying to learn Castle Windsor's Fluent Interface:
```
using NUnit.Framework;
using Castle.Windsor;
using System.Collections;
using Castle.MicroKernel.Registration;
namespace WindsorSample {
public class MyComponent : IMyComponent {
public MyComponent(int start_at) {
this.Value = start_at;
}
public int Value { get; private set; }
}
public interface IMyComponent {
int Value { get; }
}
[TestFixture]
public class ConcreteImplFixture {
[Test]
public void ResolvingConcreteImplShouldInitialiseValue() {
IWindsorContainer container = new WindsorContainer();
container.Register(Component.For<IMyComponent>().ImplementedBy<MyComponent>().Parameters(Parameter.ForKey("start_at").Eq("1")));
IMyComponent resolvedComp = container.Resolve<IMyComponent>();
Assert.AreEqual(resolvedComp.Value, 1);
}
}
}
```
When I execute the test through TestDriven.NET I get the following error:
```
System.TypeLoadException : Could not load type 'Castle.MicroKernel.Registration.IRegistration' from assembly 'Castle.MicroKernel, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc'.
at WindsorSample.ConcreteImplFixture.ResolvingConcreteImplShouldInitialiseValue()
```
When I execute the test through the NUnit GUI I get:
```
WindsorSample.ConcreteImplFixture.ResolvingConcreteImplShouldInitialiseValue:
System.IO.FileNotFoundException : Could not load file or assembly 'Castle.Windsor, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc' or one of its dependencies. The system cannot find the file specified.
```
If I open the Assembly that I am referencing in Reflector I can see its information is:
```
Castle.MicroKernel, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc
```
and that it definitely contains **Castle.MicroKernel.Registration.IRegistration**
What could be going on?
I should mention that the binaries are taken from the [latest build of Castle](http://builds.castleproject.org/cruise/DownloadBuild.castle?number=956) though I have never worked with nant so I didn't bother re-compiling from source and just took the files in the bin directory. I should also point out that my project compiles with no problem. | Is the assembly in the Global Assembly Cache (GAC) or any place the might be overriding the assembly that you think is being loaded? This is usually the result of an incorrect assembly being loaded, for me it means I usually have something in the GAC overriding the version I have in bin/Debug. |
124,854 | <p>I have an <code><img></code> in an HTML document that I would like to highlight as though the user had highlighted it using the mouse. Is there a way to do that using JavaScript?</p>
<p>I only need it to work in Mozilla, but any and all information is welcome.</p>
<p><em>EDIT: The reason I want to select the image is actually not so that it appears highlighted, but so that I can then copy the selected image to the clipboard using XPCOM. So the img actually has to be selected for this to work.</em></p>
| [
{
"answer_id": 124867,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": -1,
"selected": false,
"text": "<p>You can swap the source of the image, as in img.src = \"otherimage.png\";</p>\n\n<p>I actually did this at one point, a... | 2008/09/24 | [
"https://Stackoverflow.com/questions/124854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7441/"
] | I have an `<img>` in an HTML document that I would like to highlight as though the user had highlighted it using the mouse. Is there a way to do that using JavaScript?
I only need it to work in Mozilla, but any and all information is welcome.
*EDIT: The reason I want to select the image is actually not so that it appears highlighted, but so that I can then copy the selected image to the clipboard using XPCOM. So the img actually has to be selected for this to work.* | Here's an example which selects the first image on the page (which will be the Stack Overflow logo if you test it out on this page in Firebug):
```
var s = window.getSelection()
var r = document.createRange();
r.selectNode(document.images[0]);
s.addRange(r)
```
Relevant documentation:
* <http://developer.mozilla.org/en/DOM/window.getSelection>
* <http://developer.mozilla.org/en/DOM/range.selectNode>
* <http://developer.mozilla.org/en/DOM/Selection/addRange> |
124,856 | <p>I'd like to ensure my RAII class is always allocated on the stack.</p>
<p>How do I prevent a class from being allocated via the 'new' operator?</p>
| [
{
"answer_id": 124857,
"author": "Kevin",
"author_id": 6386,
"author_profile": "https://Stackoverflow.com/users/6386",
"pm_score": 6,
"selected": false,
"text": "<p>All you need to do is declare the class' new operator private:</p>\n\n<pre><code>class X\n{\n private: \n // Preven... | 2008/09/24 | [
"https://Stackoverflow.com/questions/124856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6386/"
] | I'd like to ensure my RAII class is always allocated on the stack.
How do I prevent a class from being allocated via the 'new' operator? | All you need to do is declare the class' new operator private:
```
class X
{
private:
// Prevent heap allocation
void * operator new (size_t);
void * operator new[] (size_t);
void operator delete (void *);
void operator delete[] (void*);
// ...
// The rest of the implementation for X
// ...
};
```
Making 'operator new' private effectively prevents code outside the class from using 'new' to create an instance of X.
To complete things, you should hide 'operator delete' and the array versions of both operators.
Since C++11 you can also explicitly delete the functions:
```
class X
{
// public, protected, private ... does not matter
static void *operator new (size_t) = delete;
static void *operator new[] (size_t) = delete;
static void operator delete (void*) = delete;
static void operator delete[](void*) = delete;
};
```
**Related Question:** [Is it possible to prevent stack allocation of an object and only allow it to be instiated with ‘new’?](https://stackoverflow.com/questions/124880/is-it-possible-to-prevent-stack-allocation-of-an-object-and-only-allow-it-to-be) |
124,865 | <p>At the office we are currently writing an application that will generate XML files against a schema that we were given. We have the schema in an .XSD file.</p>
<p>Are there tool or libraries that we can use for automated testing to check that the generated XML matches the schema?</p>
<p>We would prefer free tools that are appropriate for commercial use although we won't be bundling the schema checker so it only needs to be usable by devs during development.</p>
<p>Our development language is C++ if that makes any difference, although I don't think it should as we could generate the xml file and then do validation by calling a separate program in the test.</p>
| [
{
"answer_id": 124933,
"author": "John",
"author_id": 13895,
"author_profile": "https://Stackoverflow.com/users/13895",
"pm_score": 2,
"selected": false,
"text": "<p>I use Xerces:</p>\n\n<p><a href=\"http://xerces.apache.org/xerces-c/\" rel=\"nofollow noreferrer\">http://xerces.apache.or... | 2008/09/24 | [
"https://Stackoverflow.com/questions/124865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5113/"
] | At the office we are currently writing an application that will generate XML files against a schema that we were given. We have the schema in an .XSD file.
Are there tool or libraries that we can use for automated testing to check that the generated XML matches the schema?
We would prefer free tools that are appropriate for commercial use although we won't be bundling the schema checker so it only needs to be usable by devs during development.
Our development language is C++ if that makes any difference, although I don't think it should as we could generate the xml file and then do validation by calling a separate program in the test. | After some research, I think the best answer is [Xerces](http://xerces.apache.org/), as it implements all of XSD, is cross-platform and widely used. I've created a [small Java project on github](https://github.com/amouat/xsd-validator) to validate from the command line using the default JRE parser, which is normally Xerces. This can be used on Windows/Mac/Linux.
There is also a [C++ version of Xerces](https://xerces.apache.org/xerces-c/) available if you'd rather use that. The [StdInParse utility](http://xerces.apache.org/xerces-c/stdinparse-3.html) can be used to call it from the command line. Also, a commenter below points to this [more complete wrapper utility](http://jmvanel.free.fr/xsd/).
You could also use xmllint, which is part of [libxml](http://xmlsoft.org/). You may well already have it installed. Example usage:
```
xmllint --noout --schema XSD_FILE XML_FILE
```
One problem is that libxml doesn't implement all of the specification, so you may run into issues :(
Alternatively, if you are on Windows, you can use [msxml](http://msdn.microsoft.com/en-us/library/ms763742.aspx), but you will need some sort of wrapper to call it, such as the GUI one described in this [DDJ article](http://www.ddj.com/architect/184416391). However, it seems most people on Windows use an XML Editor, such as Notepad++ (as described in [Nate's answer](https://stackoverflow.com/a/1088659/4332)) or [XML Notepad 2007](http://www.microsoft.com/en-us/download/details.aspx?id=7973) as [suggested by SteveC](https://stackoverflow.com/a/3915105/4332) (there are also several commercial editors which I won't mention here).
Finally, you'll find different programs will, unfortunately, give different results. This is largely due to the complexity of the XSD spec. You may want to test your schema with several tools.
**UPDATE**: I've expanded on this in a [blog post](http://www.adrianmouat.com/bit-bucket/2013/11/xml-schema-validation/). |
124,880 | <p>Is it possible to prevent stack allocation of an object and only allow it to be instiated with 'new' on the heap?</p>
| [
{
"answer_id": 124903,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 4,
"selected": false,
"text": "<p>You could make the constructor <code>private</code>, then provide a <code>public</code> static factory method to crea... | 2008/09/24 | [
"https://Stackoverflow.com/questions/124880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Is it possible to prevent stack allocation of an object and only allow it to be instiated with 'new' on the heap? | One way you could do this would be to make the constructors private and only allow construction through a static method that returns a pointer. For example:
```
class Foo
{
public:
~Foo();
static Foo* createFoo()
{
return new Foo();
}
private:
Foo();
Foo(const Foo&);
Foo& operator=(const Foo&);
};
``` |
124,935 | <p>I'm using scriptaculous's Ajax.Autocompleter for a search with different filters. </p>
<p><a href="http://github.com/madrobby/scriptaculous/wikis/ajax-autocompleter" rel="nofollow noreferrer">http://github.com/madrobby/scriptaculous/wikis/ajax-autocompleter</a></p>
<p>The filters are requiring me to pass data into the autocompleter dynamically, which I've successfully learned to do from the following link. </p>
<p><a href="http://www.simpltry.com/2007/01/30/ajaxautocompleter-dynamic-parameters/" rel="nofollow noreferrer">http://www.simpltry.com/2007/01/30/ajaxautocompleter-dynamic-parameters/</a></p>
<p>Now, I have multiple filters and one search box. How do I get the autocompleter to make the request <em>without</em> typing into the input, but by clicking a new filter?</p>
<p>Here's a use case to clarify. The page loads, there are multiple filters (just links with onclicks), and one input field with the autocompleter attached. I type a query and the autocompleter request is performed. Then, I click on a different filter, and I'd like another request to be performed with the same query, but different filter. </p>
<p>Or more succinctly, how do I make the autocompleter perform the request <em>when I want</em>, instead of depending on typing to trigger it?</p>
| [
{
"answer_id": 125027,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 1,
"selected": false,
"text": "<p>Having looked at the Scriptaculous source to see <a href=\"http://github.com/madrobby/scriptaculous/tree/master/sr... | 2008/09/24 | [
"https://Stackoverflow.com/questions/124935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21456/"
] | I'm using scriptaculous's Ajax.Autocompleter for a search with different filters.
<http://github.com/madrobby/scriptaculous/wikis/ajax-autocompleter>
The filters are requiring me to pass data into the autocompleter dynamically, which I've successfully learned to do from the following link.
<http://www.simpltry.com/2007/01/30/ajaxautocompleter-dynamic-parameters/>
Now, I have multiple filters and one search box. How do I get the autocompleter to make the request *without* typing into the input, but by clicking a new filter?
Here's a use case to clarify. The page loads, there are multiple filters (just links with onclicks), and one input field with the autocompleter attached. I type a query and the autocompleter request is performed. Then, I click on a different filter, and I'd like another request to be performed with the same query, but different filter.
Or more succinctly, how do I make the autocompleter perform the request *when I want*, instead of depending on typing to trigger it? | To answer my own question: fake a key press. It ensures that the request is made, and that the dropdown box becomes visible. Here's my function to fake the key press, which takes into account the differences in IE and Firefox.
```
function fakeKeyPress(input_id) {
var input = $(input_id);
if(input.fireEvent) {
// ie stuff
var evt = document.createEventObject();
evt.keyCode = 67;
$(input_id).fireEvent("onKeyDown", evt);
} else {
// firefox stuff
var evt = document.createEvent("KeyboardEvent");
evt.initKeyEvent('keydown', true, true, null, false, false, false, false, 27, 0);
var canceled = !$(input_id).dispatchEvent(evt);
}
}
``` |
124,946 | <p>My question is based off of inheriting a great deal of legacy code that I can't do very much about. Basically, I have a device that will produce a block of data. A library which will call the device to create that block of data, for some reason I don't entirely understand and cannot change even if I wanted to, writes that block of data to disk.</p>
<p>This write is not instantaneous, but can take up to 90 seconds. In that time, the user wants to get a partial view of the data that's being produced, so I want to have a consumer thread which reads the data that the other library is writing to disk.</p>
<p>Before I even touch this legacy code, I want to mimic the problem using code I entirely control. I'm using C#, ostensibly because it provides a lot of the functionality I want.</p>
<p>In the producer class, I have this code creating a random block of data:</p>
<pre><code>FileStream theFS = new FileStream(this.ScannerRawFileName,
FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
//note that I need to be able to read this elsewhere...
BinaryWriter theBinaryWriter = new BinaryWriter(theFS);
int y, x;
for (y = 0; y < imheight; y++){
ushort[] theData= new ushort[imwidth];
for(x = 0; x < imwidth;x++){
theData[x] = (ushort)(2*y+4*x);
}
byte[] theNewArray = new byte[imwidth * 2];
Buffer.BlockCopy(theImage, 0, theNewArray, 0, imwidth * 2);
theBinaryWriter.Write(theNewArray);
Thread.Sleep(mScanThreadWait); //sleep for 50 milliseconds
Progress = (float)(y-1 >= 0 ? y-1 : 0) / (float)imheight;
}
theFS.Close();
</code></pre>
<p>So far, so good. This code works. The current version (using FileStream and BinaryWriter) appears to be equivalent (though slower, because of the copy) to using File.Open with the same options and a BinaryFormatter on the ushort[] being written to disk.</p>
<p>But then I add a consumer thread:</p>
<pre><code>FileStream theFS;
if (!File.Exists(theFileName)) {
//do error handling
return;
}
else {
theFS = new FileStream(theFileName, FileMode.Open,
FileAccess.Read, FileShare.Read);
//very relaxed file opening
}
BinaryReader theReader = new BinaryReader(theFS);
//gotta do this copying in order to handle byte array swaps
//frustrating, but true.
byte[] theNewArray = theReader.ReadBytes(
(int)(imheight * imwidth * inBase.Progress) * 2);
ushort[] theData = new ushort[((int)(theNewArray.Length/2))];
Buffer.BlockCopy(theNewArray, 0, theData, 0, theNewArray.Length);
</code></pre>
<p>Now, it's possible that the declaration of theNewArray is broken, and will cause some kind of read overflow. However, this code never gets that far, because it always always always breaks on trying to open the new FileStream with a System.IO.IOException that states that another process has opened the file.</p>
<p>I'm setting the FileAccess and FileShare enumerations as stated in the FileStream documentation on MSDN, but it appears that I just can't do what I want to do (ie, write in one thread, read in another). I realize that this application is a bit unorthodox, but when I get the actual device involved, I'm going to have to do the same thing, but using MFC.</p>
<p>In any event, What am I forgetting? Is what I'm wanting to do possible, since it's specified as possible in the documentation? </p>
<p>Thanks!
mmr</p>
| [
{
"answer_id": 125059,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I haven't had time to test this but I think you may need to call the Flush method of the BinaryWriter</p>\n\n<pre><code>Fil... | 2008/09/24 | [
"https://Stackoverflow.com/questions/124946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | My question is based off of inheriting a great deal of legacy code that I can't do very much about. Basically, I have a device that will produce a block of data. A library which will call the device to create that block of data, for some reason I don't entirely understand and cannot change even if I wanted to, writes that block of data to disk.
This write is not instantaneous, but can take up to 90 seconds. In that time, the user wants to get a partial view of the data that's being produced, so I want to have a consumer thread which reads the data that the other library is writing to disk.
Before I even touch this legacy code, I want to mimic the problem using code I entirely control. I'm using C#, ostensibly because it provides a lot of the functionality I want.
In the producer class, I have this code creating a random block of data:
```
FileStream theFS = new FileStream(this.ScannerRawFileName,
FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
//note that I need to be able to read this elsewhere...
BinaryWriter theBinaryWriter = new BinaryWriter(theFS);
int y, x;
for (y = 0; y < imheight; y++){
ushort[] theData= new ushort[imwidth];
for(x = 0; x < imwidth;x++){
theData[x] = (ushort)(2*y+4*x);
}
byte[] theNewArray = new byte[imwidth * 2];
Buffer.BlockCopy(theImage, 0, theNewArray, 0, imwidth * 2);
theBinaryWriter.Write(theNewArray);
Thread.Sleep(mScanThreadWait); //sleep for 50 milliseconds
Progress = (float)(y-1 >= 0 ? y-1 : 0) / (float)imheight;
}
theFS.Close();
```
So far, so good. This code works. The current version (using FileStream and BinaryWriter) appears to be equivalent (though slower, because of the copy) to using File.Open with the same options and a BinaryFormatter on the ushort[] being written to disk.
But then I add a consumer thread:
```
FileStream theFS;
if (!File.Exists(theFileName)) {
//do error handling
return;
}
else {
theFS = new FileStream(theFileName, FileMode.Open,
FileAccess.Read, FileShare.Read);
//very relaxed file opening
}
BinaryReader theReader = new BinaryReader(theFS);
//gotta do this copying in order to handle byte array swaps
//frustrating, but true.
byte[] theNewArray = theReader.ReadBytes(
(int)(imheight * imwidth * inBase.Progress) * 2);
ushort[] theData = new ushort[((int)(theNewArray.Length/2))];
Buffer.BlockCopy(theNewArray, 0, theData, 0, theNewArray.Length);
```
Now, it's possible that the declaration of theNewArray is broken, and will cause some kind of read overflow. However, this code never gets that far, because it always always always breaks on trying to open the new FileStream with a System.IO.IOException that states that another process has opened the file.
I'm setting the FileAccess and FileShare enumerations as stated in the FileStream documentation on MSDN, but it appears that I just can't do what I want to do (ie, write in one thread, read in another). I realize that this application is a bit unorthodox, but when I get the actual device involved, I'm going to have to do the same thing, but using MFC.
In any event, What am I forgetting? Is what I'm wanting to do possible, since it's specified as possible in the documentation?
Thanks!
mmr | Your consumer must specify FileShare.ReadWrite.
By trying to open the file as FileShare.Read in the consumer you are saying "I want to open the file and let others read it at the same time" ... since there is **already** a writer that call fails, you have to allow concurrent writes with the reader. |
124,958 | <p>I'm trying to display an array of files in order of date (last modified).</p>
<p>I have done this buy looping through the array and sorting it into another array, but is there an easier (more efficient) way to do this?</p>
| [
{
"answer_id": 125047,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 8,
"selected": true,
"text": "<blockquote>\n <p><strong>Warning</strong> <code>create_function()</code> has been DEPRECATED as of PHP 7.2.0. Relying on this... | 2008/09/24 | [
"https://Stackoverflow.com/questions/124958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/910/"
] | I'm trying to display an array of files in order of date (last modified).
I have done this buy looping through the array and sorting it into another array, but is there an easier (more efficient) way to do this? | >
> **Warning** `create_function()` has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.
>
>
>
For the sake of posterity, in case the forum post linked in the accepted answer is lost or unclear to some, the relevant code needed is:
```
<?php
$myarray = glob("*.*");
usort($myarray, create_function('$a,$b', 'return filemtime($a) - filemtime($b);'));
?>
```
Tested this on my system and verified it does sort by file mtime as desired. I used a similar approach (written in Python) for determining the last updated files on my website as well. |
124,959 | <p>Whats the available solutions for PHP to create word document in linux environment?</p>
| [
{
"answer_id": 125009,
"author": "Sergey Kornilov",
"author_id": 10969,
"author_profile": "https://Stackoverflow.com/users/10969",
"pm_score": 5,
"selected": false,
"text": "<h3>real Word documents</h3>\n\n<p>If you need to produce \"real\" Word documents you need a Windows-based web ser... | 2008/09/24 | [
"https://Stackoverflow.com/questions/124959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Whats the available solutions for PHP to create word document in linux environment? | ### real Word documents
If you need to produce "real" Word documents you need a Windows-based web server and COM automation. I highly recommend [Joel's article](http://www.joelonsoftware.com/items/2008/02/19.html) on this subject.
### *fake* HTTP headers for tricking Word into opening raw HTML
A rather common (but unreliable) alternative is:
```
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment; filename=document_name.doc");
echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<b>Fake word document</b>";
echo "</body>";
echo "</html>"
```
Make sure you don't use external stylesheets. Everything should be in the same file.
Note that this does **not** send an actual Word document. It merely tricks browsers into offering it as download and defaulting to a `.doc` file extension. Older versions of Word may often open this without any warning/security message, and just import the raw HTML into Word. PHP sending sending that misleading `Content-Type` header along does not constitute a real file format conversion. |
124,975 | <p>I'm looking for a free winforms component for an application I'm writing. I basicly need a textbox that contains line numbers in a side column. Being able to tabulate data within it would be a major plus too.</p>
<p>Does anyone know of a premade component that could do this?</p>
| [
{
"answer_id": 125051,
"author": "ine",
"author_id": 4965,
"author_profile": "https://Stackoverflow.com/users/4965",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at the <a href=\"http://www.icsharpcode.net/OpenSource/SD/\" rel=\"noreferrer\">SharpDevelop</a> C# compiler/IDE ... | 2008/09/24 | [
"https://Stackoverflow.com/questions/124975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | I'm looking for a free winforms component for an application I'm writing. I basicly need a textbox that contains line numbers in a side column. Being able to tabulate data within it would be a major plus too.
Does anyone know of a premade component that could do this? | Referencing [Wayne's post](https://stackoverflow.com/questions/124975/windows-forms-textbox-that-has-line-numbers#125093), here is the relevant code. It is using GDI to draw line numbers next to the text box.
```
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
SetStyle(ControlStyles.UserPaint, True)
SetStyle(ControlStyles.AllPaintingInWmPaint, True)
SetStyle(ControlStyles.DoubleBuffer, True)
SetStyle(ControlStyles.ResizeRedraw, True)
End Sub
Private Sub RichTextBox1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.SelectionChanged
FindLine()
Invalidate()
End Sub
Private Sub FindLine()
Dim intChar As Integer
intChar = RichTextBox1.GetCharIndexFromPosition(New Point(0, 0))
intLine = RichTextBox1.GetLineFromCharIndex(intChar)
End Sub
Private Sub DrawLines(ByVal g As Graphics, ByVal intLine As Integer)
Dim intCounter As Integer, intY As Integer
g.Clear(Color.Black)
intCounter = intLine + 1
intY = 2
Do
g.DrawString(intCounter.ToString(), Font, Brushes.White, 3, intY)
intCounter += 1
intY += Font.Height + 1
If intY > ClientRectangle.Height - 15 Then Exit Do
Loop
End Sub
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
DrawLines(e.Graphics, intLine)
End Sub
Private Sub RichTextBox1_VScroll(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.VScroll
FindLine()
Invalidate()
End Sub
Private Sub RichTextBox1_UserScroll() Handles RichTextBox1.UserScroll
FindLine()
Invalidate()
End Sub
```
The RichTextBox is overridden like this:
```
Public Class UserControl1
Inherits System.Windows.Forms.RichTextBox
Public Event UserScroll()
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If m.Msg = &H115 Then
RaiseEvent UserScroll()
End If
MyBase.WndProc(m)
End Sub
End Class
```
(Code by divil on the xtremedotnettalk.com forum.) |
125,034 | <p>In Python, I want to make <strong>selected</strong> instance attributes of a class be readonly to code outside of the class. I want there to be no way outside code can alter the attribute, except indirectly by invoking methods on the instance. I want the syntax to be concise. What is the best way? (I give my current best answer below...)</p>
| [
{
"answer_id": 125053,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 1,
"selected": false,
"text": "<p>There is no real way to do this. There are ways to make it more 'difficult', but there's no concept of completely hidd... | 2008/09/24 | [
"https://Stackoverflow.com/questions/125034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14028/"
] | In Python, I want to make **selected** instance attributes of a class be readonly to code outside of the class. I want there to be no way outside code can alter the attribute, except indirectly by invoking methods on the instance. I want the syntax to be concise. What is the best way? (I give my current best answer below...) | You should use the `@property` decorator.
```
>>> class a(object):
... def __init__(self, x):
... self.x = x
... @property
... def xval(self):
... return self.x
...
>>> b = a(5)
>>> b.xval
5
>>> b.xval = 6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
``` |
125,050 | <p>...or are they the same thing? I notice that each has its own Wikipedia entry: <a href="http://en.wikipedia.org/wiki/Polymorphism_(computer_science)" rel="noreferrer">Polymorphism</a>, <a href="http://en.wikipedia.org/wiki/Multiple_dispatch" rel="noreferrer">Multiple Dispatch</a>, but I'm having trouble seeing how the concepts differ.</p>
<p><strong>Edit:</strong> And how does <a href="http://en.wikipedia.org/wiki/Overloaded" rel="noreferrer">Overloading</a> fit into all this?</p>
| [
{
"answer_id": 125064,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 0,
"selected": false,
"text": "<p>Multiple Dispatch is a kind of polymorphism. In Java/C#/C++, there is polymorphism through inheritance and overriding... | 2008/09/24 | [
"https://Stackoverflow.com/questions/125050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
] | ...or are they the same thing? I notice that each has its own Wikipedia entry: [Polymorphism](http://en.wikipedia.org/wiki/Polymorphism_(computer_science)), [Multiple Dispatch](http://en.wikipedia.org/wiki/Multiple_dispatch), but I'm having trouble seeing how the concepts differ.
**Edit:** And how does [Overloading](http://en.wikipedia.org/wiki/Overloaded) fit into all this? | Polymorphism is the facility that allows a language/program to make decisions during runtime on which method to invoke based on the types of the parameters sent to that method.
The number of parameters used by the language/runtime determines the 'type' of polymorphism supported by a language.
Single dispatch is a type of polymorphism where only one parameter is used (the receiver of the message - `this`, or `self`) to determine the call.
Multiple dispatch is a type of polymorphism where in multiple parameters are used in determining which method to call. In this case, the reciever as well as the types of the method parameters are used to tell which method to invoke.
So you can say that polymorphism is the general term and multiple and single dispatch are specific types of polymorphism.
Addendum: Overloading happens during compile time. It uses the type information available during compilation to determine which type of method to call. Single/multiple dispatch happens during runtime.
Sample code:
```
using NUnit.Framework;
namespace SanityCheck.UnitTests.StackOverflow
{
[TestFixture]
public class DispatchTypes
{
[Test]
public void Polymorphism()
{
Baz baz = new Baz();
Foo foo = new Foo();
// overloading - parameter type is known during compile time
Assert.AreEqual("zap object", baz.Zap("hello"));
Assert.AreEqual("zap foo", baz.Zap(foo));
// virtual call - single dispatch. Baz is used.
Zapper zapper = baz;
Assert.AreEqual("zap object", zapper.Zap("hello"));
Assert.AreEqual("zap foo", zapper.Zap(foo));
// C# has doesn't support multiple dispatch so it doesn't
// know that oFoo is actually of type Foo.
//
// In languages with multiple dispatch, the type of oFoo will
// also be used in runtime so Baz.Zap(Foo) will be called
// instead of Baz.Zap(object)
object oFoo = foo;
Assert.AreEqual("zap object", zapper.Zap(oFoo));
}
public class Zapper
{
public virtual string Zap(object o) { return "generic zapper" ; }
public virtual string Zap(Foo f) { return "generic zapper"; }
}
public class Baz : Zapper
{
public override string Zap(object o) { return "zap object"; }
public override string Zap(Foo f) { return "zap foo"; }
}
public class Foo { }
}
}
``` |